@robota-sdk/agent-framework 3.0.0-beta.101 → 3.0.0-beta.106
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 +86 -0
- package/dist/node/{createInteractiveRuntime-BEeaSsQH.d.ts → createInteractiveRuntime-B4laJ8IC.d.ts} +178 -3779
- package/dist/node/{createInteractiveRuntime-BEeaSsQH.d.ts.map → createInteractiveRuntime-B4laJ8IC.d.ts.map} +1 -1
- package/dist/node/{createInteractiveRuntime-C1T56vBM.d.cts → createInteractiveRuntime-CpJLlJRl.d.cts} +178 -3779
- package/dist/node/{createInteractiveRuntime-C1T56vBM.d.cts.map → createInteractiveRuntime-CpJLlJRl.d.cts.map} +1 -1
- package/dist/node/index.cjs +1 -1
- package/dist/node/index.d.cts +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.js +1 -1
- package/dist/node/{interactive-Cbr5fae5.cjs → interactive-D5RQkohO.cjs} +1 -1
- package/dist/node/{interactive-CQ7kqxsV.js → interactive-DommsJxu.js} +2 -2
- package/dist/node/{interactive-CQ7kqxsV.js.map → interactive-DommsJxu.js.map} +1 -1
- package/dist/node/testing/index.cjs +1 -1
- package/dist/node/testing/index.d.cts +1 -1
- package/dist/node/testing/index.d.ts +1 -1
- package/dist/node/testing/index.js +1 -1
- package/package.json +20 -20
|
@@ -101,7 +101,7 @@ Do not use emojis.`}function $n(){return`You are a worker subagent executing a s
|
|
|
101
101
|
`)[0]?.trim()===`---`?void 0:{path:t,reason:`frontmatter-missing`}:{path:t,reason:i.diagnostics[0].code===`unterminated`?`frontmatter-unterminated`:`frontmatter-invalid`,detail:new uu(i.diagnostics).message}}function ld(e,t,n){let i={sourceDisplayName:e.displayName,root:t};if(e.inspectKind(t,`inspect skill directory`)!==`directory`)return{...i,present:!1,discovered:[],skipped:[]};let a=[],o=[];for(let i of e.listDirectory(t,`inspect skills`)){let s;if(n===`skills`){if(i.kind!==`directory`)continue;if(s=(0,r.join)(t,i.name,`SKILL.md`),e.inspectKind(s,`inspect skill definition`)!==`file`){o.push({path:(0,r.join)(t,i.name),reason:`missing-skill-file`});continue}}else{if(i.kind!==`file`||!i.name.endsWith(`.md`))continue;s=(0,r.join)(t,i.name)}let c=e.readText(s,`inspect skill definition`);if(c===void 0){o.push({path:s,reason:`unreadable`});continue}let l=cd(e,s,c);l!==void 0&&o.push(l),(l===void 0||l.reason===`frontmatter-missing`)&&a.push(n===`skills`?(0,r.basename)((0,r.join)(s,`..`)):(0,r.basename)(i.name,`.md`))}return{...i,present:!0,discovered:a,skipped:o}}function ud(e,t=[]){return{roots:e.flatMap(e=>t.map(({root:t,kind:n})=>ld(e,t,n)))}}function dd(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function fd(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function pd(e,t){return e.some(e=>fd(e.name)===t)}function md(e,t){return!t||Object.keys(t).length===0||Object.values(e??{}).some(e=>e?.some(e=>e.hooks.some(e=>e.type===`guardrail`)))?e:{...e,PreToolUse:[...e?.PreToolUse??[],{matcher:``,hooks:[{type:`guardrail`}]}]}}async function hd(e,n=[]){if(!e.provider)throw Error(`provider is required. SDK is provider-neutral — consumer must create and pass a provider instance.`);let r=e.provider,i=e.cwd??process.cwd(),a=e.sessionId??gd(),o=new sd(e.contributionSources??[],e.skillRoots??[]),s=dd(e.commandDescriptors),l=s.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,u=l?gr(s,e.modelCommandToolPrefix):void 0,d=pd(s,e.commandSemanticRoles?.skillActivation??``)?od(o.getCommands(),e.pluginSkills??[]).filter(e=>e.disableModelInvocation!==!0):[],f,{tools:p,wrapAdded:m}=await Zl(e,i,()=>f===void 0?void 0:In(f,e.onUsageRecorded));l&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&p.push(...yr({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:s,toolNamePrefix:e.modelCommandToolPrefix}));let h=nu(e),g=md(e.config.hooks,e.guardrails);ed(g,h,n);let{agentToolDeps:_,agentDefinitions:v,backgroundTaskManager:y}=gu(e,a,i,r,p,h),{backgroundProcessToolDeps:b}=qu(e,y,a,i,p);Ju(e,y,a,i,p);let{finalSystemMessage:ee,rebuildSystemMessage:x}=Xu(e,i,s,u,b,d,v,p),S=u?u.commandTools.filter(e=>!e.requiresPermission).map(e=>e.toolName):[],C={allow:[...e.baselinePermissionAllow??[],...S,...e.config.permissions.allow??[]],deny:e.config.permissions.deny??[]},w={...(0,t.applyPresetToolLists)(C,e),ask:[...e.config.permissions.ask??[]]},te=e.persistProjectPermission,ne=te?e=>{te(e.includes(`(`)?e:`${e}(*)`)}:void 0,T=new c.Session({pathProtection:e.pathProtection,tools:p,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},wrapAddedTools:m,provider:r,systemMessage:ee,terminal:e.terminal,cwd:i,permissions:w,presetFreePermissions:C,hooks:g,permissionMode:e.permissionMode,defaultTrustLevel:e.config.defaultTrustLevel,model:e.model??e.config.provider.model,providerTimeout:e.config.provider.timeout??12e4,maxTurns:e.maxTurns,sessionStore:e.sessionStore,checkpointHistory:e.checkpointHistory,sessionId:a,permissionHandler:e.permissionHandler,...e.sandboxClient?.autoApproves===void 0?{}:{commandSandbox:Or(e.sandboxClient)},...e.disableAutoMode===!0?{}:{permissionClassifier:Zn(r,{cwd:i,model:e.model??e.config.provider.model})},...e.ask?{ask:e.ask}:{},...ne===void 0?{}:{onProjectAllowTool:ne},onTextDelta:e.onTextDelta,onThinkingDelta:e.onThinkingDelta,onContextUpdate:e.onContextUpdate,onToolExecution:e.onToolExecution,promptForApproval:e.promptForApproval,onCompact:e.onCompact,onCompactEvent:e.onCompactEvent,compactInstructions:e.compactInstructions??e.context.compactInstructions,contextCapacityHint:e.contextCapacityHint,autoCompactThreshold:e.autoCompactThreshold??e.config.autoCompactThreshold,sessionLogger:e.sessionLogger,transcriptPath:e.transcriptPath,hookTypeExecutors:h,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens}});return f=T,Zu(T,_,b,y),{session:T,rebuildSystemMessage:x}}function gd(){return`session_${(0,n.randomUUID)()}`}function _d(e){let t=new Date().toISOString();return{id:gd(),name:e.name,cwd:e.cwd,createdAt:t,updatedAt:t,messages:[...e.source.getHistory()],history:[...e.source.getFullHistory()],systemPrompt:e.source.getSystemMessage(),toolSchemas:[...e.source.getToolSchemas()]}}function vd(e,t){return!t.isFork||t.restoredSystemPrompt===void 0||t.explicitSystemPrompt!==void 0?!1:(e.updateSystemMessage(t.restoredSystemPrompt),!0)}function yd(e){let t=new Set;for(let n of e.list())n.outcome.status===`valid`&&n.outcome.record.name!==void 0&&t.add(n.outcome.record.name);return t}function bd(e,t,n,r){let i=e?.trim();if(i!==void 0&&i.length>0){if(i===t)throw Error(`A fork cannot be named "${i}": that is the source session's name, and a name lookup could then resolve to either record.`);if(r.has(i))throw Error(`A fork cannot be named "${i}": another session already answers to that name, and a name lookup could then resolve to either record.`);return i}let a=`${t??n} (fork)`;if(!r.has(a))return a;let o=e=>`${t??n} (fork ${e})`,s=2;for(;r.has(o(s));)s+=1;return o(s)}function xd(e){let t=bd(e.requestedName,e.sourceName,e.sourceId,yd(e.sessionStore)),n=_d({source:{getHistory:()=>e.source.getHistory(),getSystemMessage:()=>e.source.getSystemMessage(),getToolSchemas:()=>e.source.getToolSchemas(),getFullHistory:e.fullHistory},name:t,cwd:e.cwd});return e.sessionStore.save(n),{sessionId:n.id,name:t}}function Sd(e,t){let n=e.name??e.id,r=yd(t),i=n;for(let e=1;r.has(i);e+=1)i=e===1?`${n} (moved)`:`${n} (moved ${e})`;return{...e,name:i}}function Cd(e,t,n){let r=M(n),i=r?.customAgentRegistry?.(e)??(r?.builtInAgents?r.builtInAgents.find(t=>t.name===e):Tn(e));if(!i)throw Error(`Unknown agent type: ${e}`);let a=t.effort??i.effort??n.getModelEffort();return{...i,...t.model?{model:t.model}:{},...t.allowedTools?{tools:t.allowedTools}:{},...a===`auto`?{}:{effort:a}}}async function wd(e,t,n){t.signal?.throwIfAborted();let r=M(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);let i=Cd(t.agent??`general-purpose`,t,n),a=Er({pathProtection:r.pathProtection,agentDefinition:i,parentConfig:Hr(r),parentContext:r.context,parentTools:r.tools,provider:r.provider,terminal:r.terminal,cwd:n.getCwd(),isForkWorker:!0,permissionMode:n.getPermissionMode(),...r.commandSemanticRoles?{commandSemanticRoles:r.commandSemanticRoles}:{},...r.modelCommandToolPrefix?{modelCommandToolPrefix:r.modelCommandToolPrefix}:{},permissionHandler:r.permissionHandler,...Ur(r.sandboxClient),hooks:r.hooks,hookTypeExecutors:r.hookTypeExecutors,onTextDelta:r.onTextDelta,onToolExecution:r.onToolExecution});return t.signal?a.run(e,void 0,{signal:t.signal}):a.run(e)}function Td(e,t){return e===`~`?t:e.startsWith(`~/`)?`${t}/${e.slice(2)}`:e}function Ed(e){if(e.executing)throw Error(`Finish or cancel the current turn before moving to another directory.`);if(e.liveBackgroundTasks>0)throw Error(`${e.liveBackgroundTasks} background task(s) are still running in this directory and would not survive the move. Wait for them or cancel them first.`);let n=e.requestedPath.trim();if(n===``)throw Error(`Usage: /cd <directory>`);let i=Td(n,e.homeDirectory??(0,h.homedir)()),a=(0,r.isAbsolute)(i)?i:(0,r.resolve)(e.workspace.cwd,i),o;try{o=(0,d.realpathSync)(a)}catch{throw Error(`No such directory: ${a}`)}if(!(0,d.statSync)(o).isDirectory())throw Error(`Not a directory: ${o}`);if(o===(0,d.realpathSync)(e.workspace.cwd))throw Error(`Already in ${o}.`);if((0,t.evaluatePermission)(`Cd`,{path:o},e.permissionMode,e.rules)===`deny`)throw Error(`Moving to ${o} is denied by a permission rule.`);return{fromCwd:e.workspace.cwd,targetCwd:o,record:_d({source:e.source,name:e.sessionName,cwd:o}),restricted:e.workspace.projectAccess.status===`restricted`}}function Dd(e){let t=[`<workspace-move>`,`The working directory has moved from ${e.fromCwd} to ${e.toCwd}. This supersedes the working directory stated earlier in this conversation and in the system prompt; tools now resolve paths against ${e.toCwd}.`];if(e.restricted)t.push(`This project is not trusted, so no project instructions, settings or skills were loaded for it. Instructions loaded for the previous directory no longer apply.`);else if(e.instructions.length===0)t.push(`No project instructions were found for ${e.toCwd}. Instructions loaded for the previous directory no longer apply.`);else{t.push(`Project instructions for ${e.toCwd}, which replace any loaded for the previous directory:`);for(let n of e.instructions)t.push(``,`## ${n.filePath}`,n.content.trim())}return t.push(`</workspace-move>`),t.join(`
|
|
102
102
|
`)}async function Od(e,t,n,i){if(n.status!==`trusted`)throw new N(`Adding a project context reference requires explicit workspace project authority.`);let a=await vc([t],{reader:B(n.authority),startRelativeDirectory:(0,r.relative)(n.identity.worktreeRoot,i),reason:`manual`});if(dc(a.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[fc(a.diagnostics)]}};let o=a.references[0];if(!o)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let s=qs(pc([o])[0],`manual`,`active`),c=Js(e,s);return{references:c.references,result:{reference:s,evicted:c.evicted,diagnostics:[]}}}function kd(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=qs(e,n.loadType,n.status,r);i=Js(i,t).references}return i}function Ad(e,t){let n=new Date().toISOString();return e.map(e=>{let i=(0,r.isAbsolute)(e.filePath)?(0,r.relative)(t,e.filePath):e.filePath;return{id:`system:${i}`,sourcePath:e.filePath,relativePath:i,originalReference:i,loadType:`system`,status:`active`,byteLength:Buffer.byteLength(e.content,`utf-8`),loadedAt:n,lastUsedAt:n}})}const jd=`main`;var Md=class extends Error{checkpointDir;snapshotFile;constructor(e,t){super(`Checkpoint manifest names a snapshot outside its checkpoint directory: ${JSON.stringify(t)} (checkpoint ${e})`),this.name=`EditCheckpointManifestEscapeError`,this.checkpointDir=e,this.snapshotFile=t}};function Nd(e,t){if(t.length===0||(0,r.isAbsolute)(t))throw new Md(e,t);let n=(0,r.join)(e,t),i=(0,r.relative)(e,n);if(i.length===0||i===`..`||i.startsWith(`../`)||i.startsWith(`..\\`)||(0,r.isAbsolute)(i))throw new Md(e,t);return n}function Pd(e){return e.map((t,n)=>{if(t.version===2&&t.branchId!==void 0)return t;let r=n>0?e[n-1]:void 0;return{...t,version:2,branchId:jd,...r?{parentId:r.id}:{}}})}function Fd(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}const Id={create:`checkpoint_created`,fork:`branch_forked`,switch:`branch_switched`,restore:`checkpoint_restored`,rollback:`checkpoint_rolled_back`,resume_pointer:`non_event`};var Ld=class{getStore;getSessionId;persistSession;emitEvent;onError;constructor(e,t,n,r,i){this.getStore=e,this.getSessionId=t,this.persistSession=n,this.emitEvent=r,this.onError=i}emit(e,t){let n=Id[e],r=this.getStore().getActiveBranchPointer(this.getSessionId())?.branchId??`main`;this.emitEvent({kind:n,checkpointId:t,branchId:r})}async finalize(){try{let e=await this.getStore().finalizeTurn();if(!e)return;this.persistSession(),this.emit(`create`,e.id)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.onError(t),t}}};function Rd(e){return e.source===`plugin`?`plugin`:`skill`}function zd(e){return e.context===`fork`?`fork`:`inject`}function Bd(e){return{type:`skill-activation`,skillName:e.skill.name,source:Rd(e.skill),invocation:e.invocation,mode:zd(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function Vd(e){let t=e.source===`plugin`?`plugin skill`:`skill`;return e.status===`failed`?`Skill failed: ${e.skillName}${e.error?` (${e.error})`:``}`:e.status===`completed`?`Skill completed: ${e.skillName}`:`Invoking ${t}: ${e.skillName}`}const Hd=new Set([`memory_candidate_saved`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`]);function Ud(e){let t=e.topic?`: ${e.topic}`:``;switch(e.type){case`memory_candidate_saved`:return`Memory saved${t}`;case`memory_candidate_approved`:return`Memory approved${t}`;case`memory_candidate_rejected`:return`Memory rejected${t}${e.reason?` (${e.reason})`:``}`;case`memory_retrieved`:return`Memory recalled${t}`;case`memory_candidate_extracted`:return`Memory candidate extracted${t}`;case`memory_candidate_queued`:return`Memory candidate queued${t}`;case`memory_candidate_skipped`:return`Memory candidate skipped${t}${e.reason?` (${e.reason})`:``}`}}const Wd={"host-cannot-write-project":`Rewind isn't available on this computer yet.`,"restricted-workspace":`Edit checkpoints need a trusted workspace; this one is restricted, so nothing is saved under it.`,"no-checkpoint-store":`Edit checkpoints are off: this session was built without a checkpoint store.`};var Gd=class extends N{reason;name=`EditCheckpointsUnavailableError`;constructor(e){super(Wd[e]),this.reason=e}},Kd=class{workspace;getSessionId;getExecuting;persistSession;emitSkillActivation;emitMemoryEvent;history=[];editCheckpointStore=null;branchEvents;pendingActiveBranch=void 0;memoryEvents=[];usedMemoryReferences=[];contextReferences=[];systemContextReferences=[];skillActivationEvents=[];constructor(e,n,r,i,a,o,s=null,c=()=>void 0){this.workspace=e,this.getSessionId=n,this.getExecuting=r,this.persistSession=i,this.emitSkillActivation=a,this.emitMemoryEvent=o,this.editCheckpointStore=s,this.branchEvents=new Ld(()=>this.getCheckpointStore(),n,i,c,e=>this.history.push((0,t.messageToHistoryEntry)((0,t.createSystemMessage)(`Checkpoint error: ${e.message}`))))}restoreState(e){this.history=e.history,this.memoryEvents=e.memoryEvents,this.usedMemoryReferences=e.usedMemoryReferences,this.contextReferences=e.contextReferences,this.skillActivationEvents=e.skillActivationEvents}getState(){return{history:this.history,memoryEvents:this.memoryEvents,usedMemoryReferences:this.usedMemoryReferences,contextReferences:this.contextReferences,skillActivationEvents:this.skillActivationEvents}}append(e){this.history.push(e)}getHistory(){return this.history}clearHistory(){this.history=[],this.memoryEvents=[],this.usedMemoryReferences=[]}resetUsedMemoryReferences(){this.usedMemoryReferences=[]}recordContextReferenceUsage(e){this.contextReferences=kd(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=kd(this.contextReferences,e,{loadType:`prompt-reference`,status:`observed`}),this.persistSession()}listEditCheckpoints(){let e=this.getSessionId();return this.getCheckpointStore().list(e)}inspectEditCheckpoint(e){let t=this.getSessionId();return this.getCheckpointStore().inspect(t,e)}async restoreEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot restore edit checkpoint while a prompt is running.`);let n=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push((0,t.messageToHistoryEntry)((0,t.createSystemMessage)(`Restored edit checkpoint: ${e}`))),this.persistSession(),this.branchEvents.emit(`restore`,e),n}async rollbackEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot rollback edit checkpoint while a prompt is running.`);let n=await this.getCheckpointStore().rollbackThroughCheckpoint(this.getSessionId(),e);return this.history.push((0,t.messageToHistoryEntry)((0,t.createSystemMessage)(`Rolled back edit checkpoint: ${e}`))),this.persistSession(),this.branchEvents.emit(`rollback`,e),n}listCheckpointBranches(){return this.getCheckpointStore().listCheckpointBranches(this.getSessionId())}async forkCheckpointBranch(e){if(this.getExecuting())throw Error(`Cannot fork edit checkpoint while a prompt is running.`);let n=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push((0,t.messageToHistoryEntry)((0,t.createSystemMessage)(`Forked new branch from checkpoint: ${e}`))),this.persistSession(),this.branchEvents.emit(`fork`,e),n}switchCheckpointBranch(e){if(this.getExecuting())throw Error(`Cannot switch edit checkpoint branch while a prompt is running.`);this.getCheckpointStore().switchToCheckpoint(this.getSessionId(),e),this.history.push((0,t.messageToHistoryEntry)((0,t.createSystemMessage)(`Switched to checkpoint branch: ${e}`))),this.persistSession(),this.branchEvents.emit(`switch`,e)}getActiveBranchPointer(){if(this.editCheckpointStore)return this.applyPendingActiveBranch(),this.editCheckpointStore.getActiveBranchPointer(this.getSessionId())}restoreActiveBranch(e){e!==void 0&&(this.pendingActiveBranch=e)}applyPendingActiveBranch(){this.pendingActiveBranch===void 0||!this.editCheckpointStore||(this.editCheckpointStore.restoreActiveBranch(this.getSessionId(),this.pendingActiveBranch),this.pendingActiveBranch=void 0)}async beginEditCheckpointTurn(e){this.editCheckpointStore&&(this.applyPendingActiveBranch(),await this.editCheckpointStore.beginTurn({sessionId:this.getSessionId(),prompt:e}))}async finalizeEditCheckpointTurn(){this.editCheckpointStore&&await this.branchEvents.finalize()}setEditCheckpointStore(e){this.editCheckpointStore=e}getUsedMemoryReferences(){return[...this.usedMemoryReferences]}recordUsedMemoryReferences(e){e.length!==0&&(this.usedMemoryReferences=[...this.usedMemoryReferences,...e],this.persistSession())}recordMemoryEvent(e){this.memoryEvents.push(e),Hd.has(e.type)&&this.history.push({id:(0,n.randomUUID)(),timestamp:new Date(e.at),category:`event`,type:`memory-event`,data:{...e,message:Ud(e)}}),this.emitMemoryEvent(e),this.persistSession()}recordSystemContextFiles(e){this.systemContextReferences=Ad(e,this.workspace.cwd)}listContextReferences(){return[...this.systemContextReferences,...this.contextReferences]}listInjectionContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await Od(this.contextReferences,e,this.workspace.projectAccess,this.workspace.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=Ys(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=Xs(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,t){this.skillActivationEvents.push(e),t&&this.history.push({id:(0,n.randomUUID)(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:Vd(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){if(!this.editCheckpointStore)throw new Gd(this.noStoreReason());return this.applyPendingActiveBranch(),this.editCheckpointStore}noStoreReason(){return Ba()?this.workspace.projectAccess.status===`trusted`?`no-checkpoint-store`:`restricted-workspace`:`host-cannot-write-project`}},qd=class extends Error{filePath;constructor(e){super(`Settings file ${e} has no active provider profile ("currentProvider" + "providers"); the model cannot be updated. Run provider setup first.`),this.name=`NoCurrentProviderProfileError`,this.filePath=e}};function Jd(e){if(!(0,d.existsSync)(e))return{};let t=(0,d.readFileSync)(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new Uc(e,t instanceof Error?t.message:String(t))}}function Yd(e,t){(0,u.ensureOwnerOnlyDirectory)((0,r.dirname)(e)),(0,u.tightenExistingFile)(e),(0,d.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
103
103
|
`,{encoding:`utf8`,mode:384})}function Xd(e,t){let n=Jd(e),r=n.currentProvider,i=n.providers;if(typeof r!=`string`||!Zd(i))throw new qd(e);let a=i;a[r]={...Zd(a[r])?a[r]:{},model:t},n.providers=a,Yd(e,n)}function Zd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Qd(e){return(0,d.existsSync)(e)?((0,d.unlinkSync)(e),!0):!1}const G=Object.freeze({theme:`theme`,syntaxHighlighting:`syntaxHighlighting`,reducedMotion:`reducedMotion`}),$d=Object.freeze({theme:`dark`,syntaxHighlighting:!0,reducedMotion:!1});function ef(e){let t=new Set(Object.values(G));return!Object.keys(e).some(e=>!t.has(e))&&(e.theme===void 0||typeof e.theme==`string`&&e.theme.length>0)&&(e.syntaxHighlighting===void 0||typeof e.syntaxHighlighting==`boolean`)&&(e.reducedMotion===void 0||typeof e.reducedMotion==`boolean`)}function tf(e){let t=e[G.theme],n=e[G.syntaxHighlighting],r=e[G.reducedMotion];return{theme:typeof t==`string`&&t.length>0?t:$d.theme,syntaxHighlighting:typeof n==`boolean`?n:$d.syntaxHighlighting,reducedMotion:typeof r==`boolean`?r:$d.reducedMotion}}function nf(e,t){let n=Jd(e),r={...tf(n),...t};return n[G.theme]=r.theme,n[G.syntaxHighlighting]=r.syntaxHighlighting,n[G.reducedMotion]=r.reducedMotion,Yd(e,n),r}var rf=class extends Error{filePath;constructor(e,t){super(`Organization policy file ${e} could not be read as a policy: ${t}. Policy is NOT applied while this file is unreadable. Fix or remove the file.`),this.name=`OrgPolicyParseError`,this.filePath=e}};function af(e){if(typeof e!=`string`||e.trim()===``)throw TypeError(`Organization policy path is required`);if(!(0,d.existsSync)(e))return null;let t;try{t=JSON.parse((0,d.readFileSync)(e,`utf8`))}catch(t){throw new rf(e,t instanceof Error?t.message:String(t))}let n=of(t);if(n!==void 0)throw new rf(e,n);return t}function of(e){if(typeof e!=`object`||!e||Array.isArray(e))return`expected a JSON object, found ${Array.isArray(e)?`an array`:typeof e}`;let t=e;for(let e of[`allowedProviders`,`blockedCommands`]){let n=t[e];if(n!==void 0&&(!Array.isArray(n)||n.some(e=>typeof e!=`string`)))return`\`${e}\` must be an array of strings`}for(let e of[`requireApiKeyFromEnv`,`disableAutoMode`])if(t[e]!==void 0&&typeof t[e]!=`boolean`)return`\`${e}\` must be a boolean`;if(t.adminContact!==void 0&&typeof t.adminContact!=`string`)return"`adminContact` must be a string"}function sf(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function cf(e){return e?!e.startsWith(`$ENV:`):!1}const lf={enabled:!0,gitBranch:!0};function uf(e=`statusline`){return[{name:`on`,description:`Show the status line`,source:e},{name:`off`,description:`Hide the status line`,source:e},{name:`reset`,description:`Restore default status-line fields`,source:e},{name:`git`,description:`Show or hide git branch field`,source:e}]}function df(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function ff(e){let t=e.statusline;return mf(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:lf.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:lf.gitBranch}:{...lf}}function pf(e,t){let n=Jd(e),r={...ff(n),...t};return n.statusline=r,Yd(e,n),r}function mf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function K(e,t){return{success:!1,message:`Cannot apply '${e}': ${t} is not available in this environment.`}}function hf(e,t){return{success:!1,message:`Failed to apply '${e}': ${t instanceof Error?t.message:String(t)}`}}async function gf(e,t){if(!e.success)return{result:e,uiIntents:[]};let n=e.hostActions??[],r=e.uiIntents??[],i=[];for(let e of n){let n=await _f(e,t,i);if(n)return{result:n,uiIntents:[]}}return n.length===0&&r.length===0?{result:e,uiIntents:[]}:{result:{message:i.length>0?[e.message,...i].filter(e=>e.length>0).join(`
|
|
104
|
-
`):e.message,success:e.success,...e.data===void 0?{}:{data:e.data}},uiIntents:r}}async function _f(e,t,n){let r=t.getAdapters();try{switch(e.type){case`provider-hot-swap`:{let{orgPolicy:n}=t;return n?.allowedProviders&&!n.allowedProviders.includes(e.profileName)?{message:sf(`Provider "${e.profileName}" is not allowed by your organization policy. Allowed: ${n.allowedProviders.join(`, `)}.`,n.adminContact),success:!1}:(await t.switchProvider(e.profileName),null)}case`output-style-change`:{let i=r.outputStyleRegistry;if(!i)return K(e.type,`an output-style registry adapter`);let a=i.getOutputStyle(e.styleId);if(!a){let t=i.listOutputStyles().map(e=>e.id).join(`, `);return{success:!1,message:`Unknown output style "${e.styleId}". Available: ${t||`(none)`}`}}let o=r.settings;return o?(o.write({...o.read(),outputStyle:e.styleId}),t.applyOutputStyle(a),n.push(`Output style: ${a.name}`),null):K(e.type,`a settings adapter`)}case`language-change`:{let t=r.settings;return t?r.process?(t.write({...t.read(),language:e.language}),n.push(`Restarting...`),r.process.requestRestart(`other`,`Language change restart`),null):K(e.type,`a process adapter (restart)`):K(e.type,`a settings adapter`)}case`settings-reset`:{let t=r.settings;if(!t?.delete)return K(e.type,`a settings adapter with delete()`);if(!r.process)return K(e.type,`a process adapter (exit)`);let i=t.delete();return n.push(i?`User settings deleted. Exiting...`:`No user settings found. Exiting...`),r.process.requestExit(`other`),null}case`session-exit`:return r.process?(r.process.requestExit(e.reason??`prompt_input_exit`),null):K(e.type,`a process adapter`);case`session-restart`:return r.process?(r.process.requestRestart(e.reason,e.message),null):K(e.type,`a process adapter`);case`session-rename`:return t.renameSession(e.name),null;case`workspace-move`:return r.workspace?(n.push(await t.moveWorkspace(e.path)),null):K(e.type,`a host that can start a session elsewhere`);case`statusline-settings-patch`:{let t=r.settings;if(!t)return K(e.type,`a settings adapter`);if(!df(e.patch))return hf(e.type,Error(`invalid statusline settings patch`));let n=t.read(),i={...ff(n),...e.patch};return t.write({...n,statusline:i}),null}case`appearance-settings-patch`:{let t=r.settings;if(!t)return K(e.type,`a settings adapter`);if(!ef(e.patch))return hf(e.type,Error(`invalid appearance settings patch`));let n=t.read(),i={...tf(n),...e.patch};return t.write({...n,theme:i.theme,syntaxHighlighting:i.syntaxHighlighting,reducedMotion:i.reducedMotion}),null}case`remote-control-enable`:{if(t.invocationSource!==`user`)return{success:!1,message:"Cannot apply 'remote-control-enable': only the operator at this terminal can pair a device. Run `/remote-control` on the host terminal."};let i=r.remoteControl?.enable;return i?(n.push(await i.call(r.remoteControl)),null):K(e.type,`a remote-control adapter with enable()`)}case`remote-control-stop`:{let t=r.remoteControl?.stop;return t?(n.push(await t.call(r.remoteControl)),null):K(e.type,`a remote-control adapter with stop()`)}}}catch(t){return hf(e.type,t)}}function vf(e,t,n){return t===void 0?e===`model`?n??void 0:e===`user`?i.OWNER_DRIVER_ID:void 0:t}function yf(e,t,n){for(let r of e)n({intent:r,...t===void 0?{}:{requesterDriverId:t}})}function bf(e,t){let n=Wc(e,t);return Object.freeze({kind:`host`,scope:e,displayName:t,source:n,read:()=>{if(!(0,d.existsSync)(t))return{};let e=(0,d.readFileSync)(t,`utf8`);try{return JSON.parse(e)}catch(e){throw new Uc(t,e instanceof Error?e.message:String(e))}},write:e=>{(0,u.ensureOwnerOnlyDirectory)((0,r.dirname)(t)),(0,u.tightenExistingFile)(t),(0,d.writeFileSync)(t,`${JSON.stringify(e,null,2)}\n`,{encoding:`utf8`,mode:384})}})}function xf(e,t){let n=io(t,e),r=B(e),i=n.target,a=n.relativePath,o=Object.freeze({kind:`project`,scope:i,displayName:a,relativePath:a,reader:r});return Object.freeze({kind:`project`,scope:i,displayName:a,source:o,read:()=>{let e=r.readText(a,`read project settings for update`);if(e===void 0)return{};try{return JSON.parse(e)}catch(e){throw new Uc(a,e instanceof Error?e.message:String(e))}},write:e=>{n.writeText(`${JSON.stringify(e,null,2)}\n`)}})}function Sf(e,t){if(process.platform!==`linux`||e?.status!==`trusted`)return;let n=t?.find(e=>e.scope===`project-local`);if(n!==void 0)return t=>{let r=no(e.authority,{status:`approved`,target:`project-local`,relativePath:n.relativePath,purpose:`persist user-approved project permission`}),i=xf(e.authority,r),a=i.read(),o=typeof a.permissions==`object`&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{},s=Array.isArray(o.allow)?o.allow:[];s.includes(t)||i.write({...a,permissions:{...o,allow:[...s,t]}})}}function Cf(e){return e.commandSemanticRoles?e.commandSemanticRoles:(e.commandModules?.flatMap(e=>e.systemCommands??[])??[]).reduce((e,t)=>t.semanticRole?{...e,[t.semanticRole]:t.name}:e,{})}function wf(e,t){let{mergedConfig:n,cwd:r,context:i,projectInfo:a,sessionId:o,contextCapacityHint:s,contributionSources:l,skillRoots:u}=t,d=Sf(e.projectAccess,e.projectSettingsPaths);return{config:n,cwd:r,context:i,contributionSources:l,skillRoots:u,...e.pluginSkills===void 0?{}:{pluginSkills:e.pluginSkills},projectInfo:a,permissionMode:e.permissionMode,baselinePermissionAllow:e.baselinePermissionAllow,maxTurns:e.maxTurns,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},terminal:Ue,sessionLogger:e.sessionLogSink===void 0?new c.SilentSessionLogger:new c.FileSessionLogger(e.sessionLogSink),...e.transcriptPath===void 0?{}:{transcriptPath:e.transcriptPath},permissionHandler:e.permissionHandler,...d===void 0?{}:{persistProjectPermission:d},...e.askHandler?{ask:e.askHandler}:{},provider:e.provider,onTextDelta:e.onTextDelta,...e.onThinkingDelta===void 0?{}:{onThinkingDelta:e.onThinkingDelta},onContextUpdate:e.onContextUpdate,onCompactEvent:e.onCompactEvent,...e.onUsageRecorded===void 0?{}:{onUsageRecorded:e.onUsageRecorded},onToolExecution:e.onToolExecution,checkpointHistory:e.checkpointHistory,sessionId:o,allowedTools:e.allowedTools,deniedTools:e.deniedTools,disableBuiltInHookExecutors:e.disableBuiltInHookExecutors,commandHookShell:e.commandHookShell,model:e.model,...e.effort===void 0?{}:{effort:e.effort},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},appendSystemPrompt:e.appendSystemPrompt,...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},...e.persona===void 0?{}:{persona:e.persona},...e.systemPrompt?{systemPromptBuilder:()=>e.systemPrompt}:{},...e.guardrails===void 0?{}:{guardrails:e.guardrails},...e.retrievalAdapter===void 0?{}:{retrievalAdapter:e.retrievalAdapter},backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.resumeSessionStore===void 0?{}:{resumeSessionStore:e.resumeSessionStore},...e.agentDefinitions?{agentDefinitions:e.agentDefinitions}:{},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.commandModules?.some(e=>e.sessionRequirements?.includes(`runtime`))?{enableAgentRuntime:!0}:{},...e.enableParallelSubagents===void 0?{}:{enableParallelSubagents:e.enableParallelSubagents},...e.selfVerification===void 0?{}:{selfVerification:e.selfVerification},...e.commandModules||e.commandDescriptors?{commandDescriptors:[...e.commandDescriptors??[],...e.commandModules?.flatMap(e=>e.commandDescriptors??[])??[]]}:{},commandSemanticRoles:Cf(e),modelCommandExecutor:e.modelCommandExecutor,modelCommandToolPrefix:e.modelCommandToolPrefix,subagentHookEnvironmentNames:e.subagentHookEnvironmentNames,observerFailureWarningCode:e.observerFailureWarningCode,isModelCommandInvocable:e.isModelCommandInvocable,editCheckpointRecorder:e.editCheckpointRecorder,reversibleExecution:e.reversibleExecution,sandboxClient:e.sandboxClient,...e.disableAutoMode===!0?{disableAutoMode:!0}:{},sandboxType:e.sandboxType,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.defaultTools?{defaultTools:e.defaultTools}:{},includeGoalTool:!0,includeSessionLoopDecisionTool:!0,...e.peerReply?{peerReply:e.peerReply}:{},...e.peerSendFile?{peerSendFile:e.peerSendFile}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},...s===void 0?{}:{contextCapacityHint:s}}}function Tf(e,t){return{...e.sandboxClient?{sandboxClient:e.sandboxClient}:{},...e.sandboxType?{sandboxType:e.sandboxType}:{},...e.workspaceManifest?{workspaceManifest:e.workspaceManifest}:{},...e.sandboxWorkspaceRoot?{sandboxWorkspaceRoot:e.sandboxWorkspaceRoot}:{},...t?{sandboxSnapshotId:t}:{}}}async function Ef(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await(0,o.applyWorkspaceManifest)(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function Df(e){if(!e.sandboxSnapshotId)return!1;if(!e.sandboxClient?.restore)throw Error(`sandboxSnapshotId requires sandboxClient with restore().`);return await e.sandboxClient.restore(e.sandboxSnapshotId),!0}function Of(e){return{...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt}}}const kf=Object.freeze({defaultTrustLevel:`most-restrictive`,disabledHooks:`accumulate`,provider:`object-merge`,"permissions.allow":`union`,"permissions.deny":`union`,"permissions.ask":`union`,env:`object-merge`,providers:`object-merge`,enabledPlugins:`object-merge`,extraKnownMarketplaces:`replace`,autoCompactThreshold:`replace`,hooks:`per-event`,taskContext:`object-merge`,sandbox:`object-merge`});function Af(e){let t=jf(e);return{settings:t.settings,hookSources:t.hookSources}}function jf(e){let t=new Set,n={},r=[];for(let{settings:i,source:a}of e){let e=Vf(i.hooks,t);a!==void 0&&Mf(e,a,r);for(let e of i.disabledHooks??[])t.add(e);n=Nf(n,{...i,hooks:e},t)}return{settings:n,hookSources:r}}function Mf(e,t,n){for(let[r,i]of Object.entries(e??{}))for(let e of i??[])for(let i of e.hooks)n.push({event:r,type:i.type,source:t})}function Nf(e,t,n){return{...e,...t,defaultTrustLevel:Wf(e.defaultTrustLevel,t.defaultTrustLevel),disabledHooks:Pf(n),provider:Gf(e.provider,t.provider),permissions:Ff(e.permissions,t.permissions),env:{...e.env??{},...t.env??{}},providers:Lf(e.providers,t.providers),enabledPlugins:If(e.enabledPlugins,t.enabledPlugins),extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold,hooks:Rf(e.hooks,t.hooks),taskContext:If(e.taskContext,t.taskContext),sandbox:If(e.sandbox,t.sandbox)}}function Pf(e){return e.size===0?void 0:[...e]}function Ff(e,t){if(e!==void 0||t!==void 0)return{allow:Bf(e?.allow,t?.allow),deny:Bf(e?.deny,t?.deny),ask:Bf(e?.ask,t?.ask)}}function If(e,t){if(e!==void 0||t!==void 0)return{...e,...t}}function Lf(e,t){if(e!==void 0||t!==void 0)return Hf(e,t)}function Rf(e,t){if(e!==void 0||t!==void 0)return zf(e,t)}function zf(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{})){if(r===void 0)continue;let t=e,i=n[t];n[t]=i===void 0?[...r]:[...i,...r]}return n}function Bf(e,t){return e===void 0?t===void 0?void 0:[...t]:t===void 0?[...e]:[...new Set([...e,...t])]}function Vf(e,t){if(e===void 0||t.size===0)return e;let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=r;n[e]=i.filter(e=>e.id===void 0||!t.has(e.id))}return n}function Hf(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]=Gf(n[e],r);return n}const Uf={safe:0,moderate:1,full:2};function Wf(e,t){return e===void 0?t:t===void 0||Uf[e]<=Uf[t]?e:t}function Gf(e,t){if(e===void 0&&t===void 0)return;if(t?.apiKeyRef!==void 0&&(t.apiKey!==void 0||t.apiKeyEnv!==void 0))throw Error(`Provider settings have conflicting credential origins`);let n={...e,...t};return t?.apiKeyRef===void 0?(t?.apiKey!==void 0||t?.apiKeyEnv!==void 0)&&delete n.apiKeyRef:(delete n.apiKey,delete n.apiKeyEnv),t?.baseURL!==void 0&&t.baseURL!==e?.baseURL&&(t?.apiKeyRef===void 0?t?.apiKey===void 0?t?.apiKeyEnv===void 0?(delete n.apiKey,delete n.apiKeyEnv,delete n.apiKeyRef,e?.apiKeyRef!==void 0&&(n.apiKey=``)):delete n.apiKey:delete n.apiKeyEnv:(delete n.apiKey,delete n.apiKeyEnv)),n}const Kf=s.z.lazy(()=>s.z.union([s.z.string(),s.z.number(),s.z.boolean(),s.z.null(),s.z.undefined(),s.z.date(),s.z.array(Kf),s.z.record(Kf)])),qf=s.z.object({service:s.z.string().min(1),account:s.z.string().min(1)}).strict(),Jf=s.z.object({name:s.z.string().optional(),model:s.z.string().optional(),apiKey:s.z.string().optional(),apiKeyRef:qf.optional(),baseURL:s.z.string().optional(),timeout:s.z.number().optional(),options:s.z.record(Kf).optional()}),Yf=s.z.object({type:s.z.string().optional(),model:s.z.string().optional(),apiKey:s.z.string().optional(),apiKeyRef:qf.optional(),baseURL:s.z.string().optional(),timeout:s.z.number().optional(),options:s.z.record(Kf).optional()}),Xf=s.z.object({allow:s.z.array(s.z.string()).optional(),deny:s.z.array(s.z.string()).optional(),ask:s.z.array(s.z.string()).optional()}),Zf=s.z.record(s.z.string()).optional(),Qf=s.z.object({type:s.z.literal(`command`),command:s.z.string(),timeout:s.z.number().optional()}),$f=s.z.object({type:s.z.literal(`http`),url:s.z.string(),headers:s.z.record(s.z.string()).optional(),timeout:s.z.number().optional()}),ep=s.z.object({type:s.z.literal(`prompt`),prompt:s.z.string(),model:s.z.string().optional()}),tp=s.z.object({type:s.z.literal(`agent`),agent:s.z.string(),maxTurns:s.z.number().optional(),timeout:s.z.number().optional()}),np=s.z.object({type:s.z.literal(`guardrail`),guardrails:s.z.array(s.z.string()).optional()}),rp=s.z.discriminatedUnion(`type`,[Qf,$f,ep,tp,np]),q=s.z.object({id:s.z.string().optional(),matcher:s.z.string(),hooks:s.z.array(rp)}),ip=s.z.object({PreToolUse:s.z.array(q).optional(),PostToolUse:s.z.array(q).optional(),SessionStart:s.z.array(q).optional(),SessionEnd:s.z.array(q).optional(),Stop:s.z.array(q).optional(),StopFailure:s.z.array(q).optional(),PreCompact:s.z.array(q).optional(),PostCompact:s.z.array(q).optional(),UserPromptSubmit:s.z.array(q).optional(),SubagentStart:s.z.array(q).optional(),SubagentStop:s.z.array(q).optional(),WorktreeCreate:s.z.array(q).optional(),WorktreeRemove:s.z.array(q).optional(),PreModelCall:s.z.array(q).optional(),PostModelCall:s.z.array(q).optional(),PermissionDecision:s.z.array(q).optional()}).optional(),ap=s.z.record(s.z.boolean()).optional(),op=s.z.object({source:s.z.object({type:s.z.enum([`github`,`git`,`local`,`url`]),repo:s.z.string().optional(),url:s.z.string().optional(),path:s.z.string().optional(),ref:s.z.string().optional()})}),sp=s.z.record(op).optional().catch(void 0),cp=s.z.union([s.z.number().gt(0).lte(1),s.z.literal(!1)]).optional(),lp=s.z.object({enabled:s.z.boolean().optional(),options:s.z.record(Kf).optional()}),up=s.z.object({enabled:s.z.boolean().optional(),autoAllowBashIfSandboxed:s.z.boolean().optional(),excludedCommands:s.z.array(s.z.string()).optional(),failIfUnavailable:s.z.boolean().optional(),filesystem:s.z.object({allowWrite:s.z.array(s.z.string()).optional(),denyRead:s.z.array(s.z.string()).optional()}).optional(),network:s.z.object({enabled:s.z.boolean().optional()}).optional()}),dp=s.z.object({defaultTrustLevel:s.z.enum([`safe`,`moderate`,`full`]).optional(),language:s.z.string().optional(),preset:s.z.string().optional(),currentProvider:s.z.string().optional(),providers:s.z.record(Yf).optional(),provider:Jf.optional(),permissions:Xf.optional(),env:Zf,commandEnvAllow:s.z.array(s.z.string()).optional(),hooks:ip,disabledHooks:s.z.array(s.z.string()).optional(),enabledPlugins:ap,extraKnownMarketplaces:sp,autoCompactThreshold:cp,transports:s.z.record(lp).optional(),sandbox:up.optional(),taskContext:s.z.object({enabled:s.z.boolean().optional(),dir:s.z.string().min(1).optional()}).optional()}),fp=/position (\d+)/;function pp(e){let t=fp.exec(e.message);return t===null?void 0:Number(t[1])}function mp(e){let t=e.code;return typeof t==`string`?t:void 0}function hp(e){let t;try{t=qc(e,`load configuration settings`)}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`unreadable`,cause:{state:`unreadable`,errno:mp(n)},error:n}}if(t===void 0)return{source:e,state:`absent`};let n=t.trim();if(n.length===0)return{source:e,state:`empty`,cause:{state:`empty`}};try{return{source:e,state:`ok`,raw:JSON.parse(n)}}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`invalid-json`,cause:{state:`invalid-json`,offset:pp(n)},error:n}}}function gp(e){if(e.state!==`ok`)return e;let t=dp.safeParse(e.raw);return t.success?{...e,settings:t.data}:{...e,state:`schema-invalid`,cause:{state:`schema-invalid`,issues:t.error.issues.map(e=>({path:e.path.map(String).join(`.`),code:e.code}))},schemaMessage:t.error.message}}function _p(e){return e.map(hp).map(gp)}function vp(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0){if(n===`permissions`&&typeof r==`object`&&r){for(let e of[`allow`,`deny`,`ask`])r[e]!==void 0&&t.push(`permissions.${e}`);continue}t.push(n)}return t}function yp(e){let t=new Map;for(let n of e)if(n.settings!==void 0)for(let e of vp(n.settings)){let r=t.get(e)??[];r.push(n.displayName),t.set(e,r)}return[...t.entries()].map(([e,t])=>({key:e,rule:kf[e]??`replace`,contributors:t}))}function bp(e){let t=_p(e).map(e=>({source:e.source,displayName:e.source.displayName,kind:e.source.kind,scope:e.source.scope,state:e.state,...e.cause===void 0?{}:{cause:e.cause},...e.settings===void 0?{}:{settings:e.settings}})),n=t.some(e=>e.state!==`ok`&&e.state!==`absent`),r=Af(t.flatMap(e=>e.settings===void 0?[]:[{settings:e.settings,source:e.displayName}]));return{layers:t,merged:r.settings,partial:n,provenance:yp(t),hookSources:r.hookSources}}const J={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[],ask:[]},env:{}};function xp(e){if(e.state===`empty`)throw new Uc(e.source.displayName,`the settings file is empty`);if(e.state===`invalid-json`)throw new Uc(e.source.displayName,e.error?.message??`invalid JSON`);if(e.state===`unreadable`)throw e.error}function Sp(e,t){return e.startsWith(`$ENV:`)?t[e.slice(5)]??e:e}function Cp(e,t){let n=e.provider?.apiKey===void 0?e.provider:wp(e.provider,t);if(e.providers!==void 0){let r=Object.fromEntries(Object.entries(e.providers).map(([e,n])=>[e,wp(n,t)]));return{...e,provider:n,providers:r}}return{...e,provider:n}}function wp(e,t){if(e.apiKey===void 0)return e;let n=e.apiKey.startsWith(`$ENV:`);return{...e,apiKey:Sp(e.apiKey,t),...n&&{apiKeyEnv:e.apiKey.slice(5)}}}function Tp(e){if(e.currentProvider!==void 0)return Ep(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...J.provider}}function Ep(e){let t=e.currentProvider;if(t===void 0)throw Error(`currentProvider is required`);let n=e.providers?.[t];if(n===void 0)throw Error(`currentProvider "${t}" was not found in providers`);if(n.type===void 0)throw Error(`Provider profile "${t}" is missing type`);return{name:n.type,model:n.model??J.provider.model,apiKey:n.apiKeyRef===void 0?n.apiKey??J.provider.apiKey:void 0,...n.apiKeyRef!==void 0&&{apiKeyRef:n.apiKeyRef},...n.apiKeyEnv!==void 0&&{apiKeyEnv:n.apiKeyEnv},...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function Dp(e){return{defaultTrustLevel:e.defaultTrustLevel??J.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:Tp(e),permissions:{allow:e.permissions?.allow??J.permissions.allow,deny:e.permissions?.deny??J.permissions.deny,ask:e.permissions?.ask??J.permissions.ask},env:e.env??J.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold,taskContext:e.taskContext??void 0,...e.sandbox===void 0?{}:{sandbox:e.sandbox}}}async function Op(e,t={}){let n=_p(e);for(let e of n)xp(e);let r=[];for(let e of n)if(e.state!==`absent`){if(e.state===`schema-invalid`||e.settings===void 0)throw Error(`Invalid settings in ${e.source.displayName}: ${e.schemaMessage}`);r.push({settings:Cp(e.settings,t),source:e.source.displayName})}let i=Af(r);return{config:Dp(i.settings),hookSources:i.hookSources}}const kp={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function Ap(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function jp(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||(0,r.basename)(t,`.md`)}function Mp(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function Np(e,t){let n=e.split(/\r?\n/),r=RegExp(`^(#{2,6})\\s+${t}\\b`,`i`),i=n.findIndex(e=>r.test(e));if(i<0)return;let a=[];for(let e of n.slice(i+1)){if(/^##\s+/.test(e))break;a.push(e)}let o=a.join(`
|
|
104
|
+
`):e.message,success:e.success,...e.data===void 0?{}:{data:e.data}},uiIntents:r}}async function _f(e,t,n){let r=t.getAdapters();try{switch(e.type){case`provider-hot-swap`:{let{orgPolicy:n}=t;return n?.allowedProviders&&!n.allowedProviders.includes(e.profileName)?{message:sf(`Provider "${e.profileName}" is not allowed by your organization policy. Allowed: ${n.allowedProviders.join(`, `)}.`,n.adminContact),success:!1}:(await t.switchProvider(e.profileName),null)}case`output-style-change`:{let i=r.outputStyleRegistry;if(!i)return K(e.type,`an output-style registry adapter`);let a=i.getOutputStyle(e.styleId);if(!a){let t=i.listOutputStyles().map(e=>e.id).join(`, `);return{success:!1,message:`Unknown output style "${e.styleId}". Available: ${t||`(none)`}`}}let o=r.settings;return o?(o.write({...o.read(),outputStyle:e.styleId}),t.applyOutputStyle(a),n.push(`Output style: ${a.name}`),null):K(e.type,`a settings adapter`)}case`language-change`:{let t=r.settings;return t?r.process?(t.write({...t.read(),language:e.language}),n.push(`Restarting...`),r.process.requestRestart(`other`,`Language change restart`),null):K(e.type,`a process adapter (restart)`):K(e.type,`a settings adapter`)}case`settings-reset`:{let t=r.settings;if(!t?.delete)return K(e.type,`a settings adapter with delete()`);if(!r.process)return K(e.type,`a process adapter (exit)`);let i=t.delete();return n.push(i?`User settings deleted. Exiting...`:`No user settings found. Exiting...`),r.process.requestExit(`other`),null}case`session-exit`:return r.process?(r.process.requestExit(e.reason??`prompt_input_exit`),null):K(e.type,`a process adapter`);case`session-restart`:return r.process?(r.process.requestRestart(e.reason,e.message),null):K(e.type,`a process adapter`);case`session-rename`:return t.renameSession(e.name),null;case`workspace-move`:return r.workspace?(n.push(await t.moveWorkspace(e.path)),null):K(e.type,`a host that can start a session elsewhere`);case`statusline-settings-patch`:{let t=r.settings;if(!t)return K(e.type,`a settings adapter`);if(!df(e.patch))return hf(e.type,Error(`invalid statusline settings patch`));let n=t.read(),i={...ff(n),...e.patch};return t.write({...n,statusline:i}),null}case`appearance-settings-patch`:{let t=r.settings;if(!t)return K(e.type,`a settings adapter`);if(!ef(e.patch))return hf(e.type,Error(`invalid appearance settings patch`));let n=t.read(),i={...tf(n),...e.patch};return t.write({...n,theme:i.theme,syntaxHighlighting:i.syntaxHighlighting,reducedMotion:i.reducedMotion}),null}case`remote-control-enable`:{if(t.invocationSource!==`user`)return{success:!1,message:"Cannot apply 'remote-control-enable': only the operator at this terminal can pair a device. Run `/remote-control` on the host terminal."};let i=r.remoteControl?.enable;return i?(n.push(await i.call(r.remoteControl)),null):K(e.type,`a remote-control adapter with enable()`)}case`remote-control-stop`:{let t=r.remoteControl?.stop;return t?(n.push(await t.call(r.remoteControl)),null):K(e.type,`a remote-control adapter with stop()`)}}}catch(t){return hf(e.type,t)}}function vf(e,t,n){return t===void 0?e===`model`?n??void 0:e===`user`?i.OWNER_DRIVER_ID:void 0:t}function yf(e,t,n){for(let r of e)n({intent:r,...t===void 0?{}:{requesterDriverId:t}})}function bf(e,t){let n=Wc(e,t);return Object.freeze({kind:`host`,scope:e,displayName:t,source:n,read:()=>{if(!(0,d.existsSync)(t))return{};let e=(0,d.readFileSync)(t,`utf8`);try{return JSON.parse(e)}catch(e){throw new Uc(t,e instanceof Error?e.message:String(e))}},write:e=>{(0,u.ensureOwnerOnlyDirectory)((0,r.dirname)(t)),(0,u.tightenExistingFile)(t),(0,d.writeFileSync)(t,`${JSON.stringify(e,null,2)}\n`,{encoding:`utf8`,mode:384})}})}function xf(e,t){let n=io(t,e),r=B(e),i=n.target,a=n.relativePath,o=Object.freeze({kind:`project`,scope:i,displayName:a,relativePath:a,reader:r});return Object.freeze({kind:`project`,scope:i,displayName:a,source:o,read:()=>{let e=r.readText(a,`read project settings for update`);if(e===void 0)return{};try{return JSON.parse(e)}catch(e){throw new Uc(a,e instanceof Error?e.message:String(e))}},write:e=>{n.writeText(`${JSON.stringify(e,null,2)}\n`)}})}function Sf(e,t){if(process.platform!==`linux`||e?.status!==`trusted`)return;let n=t?.find(e=>e.scope===`project-local`);if(n!==void 0)return t=>{let r=no(e.authority,{status:`approved`,target:`project-local`,relativePath:n.relativePath,purpose:`persist user-approved project permission`}),i=xf(e.authority,r),a=i.read(),o=typeof a.permissions==`object`&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{},s=Array.isArray(o.allow)?o.allow:[];s.includes(t)||i.write({...a,permissions:{...o,allow:[...s,t]}})}}function Cf(e){return e.commandSemanticRoles?e.commandSemanticRoles:(e.commandModules?.flatMap(e=>e.systemCommands??[])??[]).reduce((e,t)=>t.semanticRole?{...e,[t.semanticRole]:t.name}:e,{})}function wf(e,t){let{mergedConfig:n,cwd:r,context:i,projectInfo:a,sessionId:o,contextCapacityHint:s,contributionSources:l,skillRoots:u}=t,d=Sf(e.projectAccess,e.projectSettingsPaths);return{config:n,cwd:r,context:i,contributionSources:l,skillRoots:u,...e.pluginSkills===void 0?{}:{pluginSkills:e.pluginSkills},projectInfo:a,permissionMode:e.permissionMode,baselinePermissionAllow:e.baselinePermissionAllow,maxTurns:e.maxTurns,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},terminal:Ue,sessionLogger:e.sessionLogSink===void 0?new c.SilentSessionLogger:new c.FileSessionLogger(e.sessionLogSink),...e.transcriptPath===void 0?{}:{transcriptPath:e.transcriptPath},permissionHandler:e.permissionHandler,...d===void 0?{}:{persistProjectPermission:d},...e.askHandler?{ask:e.askHandler}:{},provider:e.provider,onTextDelta:e.onTextDelta,...e.onThinkingDelta===void 0?{}:{onThinkingDelta:e.onThinkingDelta},onContextUpdate:e.onContextUpdate,onCompactEvent:e.onCompactEvent,...e.onUsageRecorded===void 0?{}:{onUsageRecorded:e.onUsageRecorded},onToolExecution:e.onToolExecution,checkpointHistory:e.checkpointHistory,sessionId:o,allowedTools:e.allowedTools,deniedTools:e.deniedTools,disableBuiltInHookExecutors:e.disableBuiltInHookExecutors,commandHookShell:e.commandHookShell,model:e.model,...e.effort===void 0?{}:{effort:e.effort},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},appendSystemPrompt:e.appendSystemPrompt,...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},...e.persona===void 0?{}:{persona:e.persona},...e.systemPrompt?{systemPromptBuilder:()=>e.systemPrompt}:{},...e.guardrails===void 0?{}:{guardrails:e.guardrails},...e.retrievalAdapter===void 0?{}:{retrievalAdapter:e.retrievalAdapter},backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.resumeSessionStore===void 0?{}:{resumeSessionStore:e.resumeSessionStore},...e.agentDefinitions?{agentDefinitions:e.agentDefinitions}:{},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.commandModules?.some(e=>e.sessionRequirements?.includes(`runtime`))?{enableAgentRuntime:!0}:{},...e.enableParallelSubagents===void 0?{}:{enableParallelSubagents:e.enableParallelSubagents},...e.selfVerification===void 0?{}:{selfVerification:e.selfVerification},...e.commandModules||e.commandDescriptors?{commandDescriptors:[...e.commandDescriptors??[],...e.commandModules?.flatMap(e=>e.commandDescriptors??[])??[]]}:{},commandSemanticRoles:Cf(e),modelCommandExecutor:e.modelCommandExecutor,modelCommandToolPrefix:e.modelCommandToolPrefix,subagentHookEnvironmentNames:e.subagentHookEnvironmentNames,observerFailureWarningCode:e.observerFailureWarningCode,isModelCommandInvocable:e.isModelCommandInvocable,editCheckpointRecorder:e.editCheckpointRecorder,reversibleExecution:e.reversibleExecution,sandboxClient:e.sandboxClient,...e.disableAutoMode===!0?{disableAutoMode:!0}:{},sandboxType:e.sandboxType,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.defaultTools?{defaultTools:e.defaultTools}:{},includeGoalTool:!0,includeSessionLoopDecisionTool:!0,...e.peerReply?{peerReply:e.peerReply}:{},...e.peerSendFile?{peerSendFile:e.peerSendFile}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},...s===void 0?{}:{contextCapacityHint:s}}}function Tf(e,t){return{...e.sandboxClient?{sandboxClient:e.sandboxClient}:{},...e.sandboxType?{sandboxType:e.sandboxType}:{},...e.workspaceManifest?{workspaceManifest:e.workspaceManifest}:{},...e.sandboxWorkspaceRoot?{sandboxWorkspaceRoot:e.sandboxWorkspaceRoot}:{},...t?{sandboxSnapshotId:t}:{}}}async function Ef(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await(0,o.applyWorkspaceManifest)(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function Df(e){if(!e.sandboxSnapshotId)return!1;if(!e.sandboxClient?.restore)throw Error(`sandboxSnapshotId requires sandboxClient with restore().`);return await e.sandboxClient.restore(e.sandboxSnapshotId),!0}function Of(e){return{...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt}}}const kf=Object.freeze({defaultTrustLevel:`most-restrictive`,disabledHooks:`accumulate`,provider:`object-merge`,"permissions.allow":`union`,"permissions.deny":`union`,"permissions.ask":`union`,env:`object-merge`,providers:`object-merge`,enabledPlugins:`object-merge`,extraKnownMarketplaces:`replace`,autoCompactThreshold:`replace`,hooks:`per-event`,taskContext:`object-merge`,sandbox:`object-merge`});function Af(e){let t=jf(e);return{settings:t.settings,hookSources:t.hookSources}}function jf(e){let t=new Set,n={},r=[];for(let{settings:i,source:a}of e){let e=Vf(i.hooks,t);a!==void 0&&Mf(e,a,r);for(let e of i.disabledHooks??[])t.add(e);n=Nf(n,{...i,hooks:e},t)}return{settings:n,hookSources:r}}function Mf(e,t,n){for(let[r,i]of Object.entries(e??{}))for(let e of i??[])for(let i of e.hooks)n.push({event:r,type:i.type,source:t})}function Nf(e,t,n){return{...e,...t,defaultTrustLevel:Wf(e.defaultTrustLevel,t.defaultTrustLevel),disabledHooks:Pf(n),provider:Gf(e.provider,t.provider),permissions:Ff(e.permissions,t.permissions),env:{...e.env??{},...t.env??{}},providers:Lf(e.providers,t.providers),enabledPlugins:If(e.enabledPlugins,t.enabledPlugins),extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold,hooks:Rf(e.hooks,t.hooks),taskContext:If(e.taskContext,t.taskContext),sandbox:If(e.sandbox,t.sandbox)}}function Pf(e){return e.size===0?void 0:[...e]}function Ff(e,t){if(e!==void 0||t!==void 0)return{allow:Bf(e?.allow,t?.allow),deny:Bf(e?.deny,t?.deny),ask:Bf(e?.ask,t?.ask)}}function If(e,t){if(e!==void 0||t!==void 0)return{...e,...t}}function Lf(e,t){if(e!==void 0||t!==void 0)return Hf(e,t)}function Rf(e,t){if(e!==void 0||t!==void 0)return zf(e,t)}function zf(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{})){if(r===void 0)continue;let t=e,i=n[t];n[t]=i===void 0?[...r]:[...i,...r]}return n}function Bf(e,t){return e===void 0?t===void 0?void 0:[...t]:t===void 0?[...e]:[...new Set([...e,...t])]}function Vf(e,t){if(e===void 0||t.size===0)return e;let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=r;n[e]=i.filter(e=>e.id===void 0||!t.has(e.id))}return n}function Hf(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]=Gf(n[e],r);return n}const Uf={safe:0,moderate:1,full:2};function Wf(e,t){return e===void 0?t:t===void 0||Uf[e]<=Uf[t]?e:t}function Gf(e,t){if(e===void 0&&t===void 0)return;if(t?.apiKeyRef!==void 0&&(t.apiKey!==void 0||t.apiKeyEnv!==void 0))throw Error(`Provider settings have conflicting credential origins`);let n={...e,...t};return t?.apiKeyRef===void 0?(t?.apiKey!==void 0||t?.apiKeyEnv!==void 0)&&delete n.apiKeyRef:(delete n.apiKey,delete n.apiKeyEnv),t?.baseURL!==void 0&&t.baseURL!==e?.baseURL&&(t?.apiKeyRef===void 0?t?.apiKey===void 0?t?.apiKeyEnv===void 0?(delete n.apiKey,delete n.apiKeyEnv,delete n.apiKeyRef,e?.apiKeyRef!==void 0&&(n.apiKey=``)):delete n.apiKey:delete n.apiKeyEnv:(delete n.apiKey,delete n.apiKeyEnv)),n}const Kf=s.z.lazy(()=>s.z.union([s.z.string(),s.z.number(),s.z.boolean(),s.z.null(),s.z.undefined(),s.z.date(),s.z.array(Kf),s.z.record(s.z.string(),Kf)])),qf=s.z.object({service:s.z.string().min(1),account:s.z.string().min(1)}).strict(),Jf=s.z.object({name:s.z.string().optional(),model:s.z.string().optional(),apiKey:s.z.string().optional(),apiKeyRef:qf.optional(),baseURL:s.z.string().optional(),timeout:s.z.number().optional(),options:s.z.record(s.z.string(),Kf).optional()}),Yf=s.z.object({type:s.z.string().optional(),model:s.z.string().optional(),apiKey:s.z.string().optional(),apiKeyRef:qf.optional(),baseURL:s.z.string().optional(),timeout:s.z.number().optional(),options:s.z.record(s.z.string(),Kf).optional()}),Xf=s.z.object({allow:s.z.array(s.z.string()).optional(),deny:s.z.array(s.z.string()).optional(),ask:s.z.array(s.z.string()).optional()}),Zf=s.z.record(s.z.string(),s.z.string()).optional(),Qf=s.z.object({type:s.z.literal(`command`),command:s.z.string(),timeout:s.z.number().optional()}),$f=s.z.object({type:s.z.literal(`http`),url:s.z.string(),headers:s.z.record(s.z.string(),s.z.string()).optional(),timeout:s.z.number().optional()}),ep=s.z.object({type:s.z.literal(`prompt`),prompt:s.z.string(),model:s.z.string().optional()}),tp=s.z.object({type:s.z.literal(`agent`),agent:s.z.string(),maxTurns:s.z.number().optional(),timeout:s.z.number().optional()}),np=s.z.object({type:s.z.literal(`guardrail`),guardrails:s.z.array(s.z.string()).optional()}),rp=s.z.discriminatedUnion(`type`,[Qf,$f,ep,tp,np]),q=s.z.object({id:s.z.string().optional(),matcher:s.z.string(),hooks:s.z.array(rp)}),ip=s.z.object({PreToolUse:s.z.array(q).optional(),PostToolUse:s.z.array(q).optional(),SessionStart:s.z.array(q).optional(),SessionEnd:s.z.array(q).optional(),Stop:s.z.array(q).optional(),StopFailure:s.z.array(q).optional(),PreCompact:s.z.array(q).optional(),PostCompact:s.z.array(q).optional(),UserPromptSubmit:s.z.array(q).optional(),SubagentStart:s.z.array(q).optional(),SubagentStop:s.z.array(q).optional(),WorktreeCreate:s.z.array(q).optional(),WorktreeRemove:s.z.array(q).optional(),PreModelCall:s.z.array(q).optional(),PostModelCall:s.z.array(q).optional(),PermissionDecision:s.z.array(q).optional()}).optional(),ap=s.z.record(s.z.string(),s.z.boolean()).optional(),op=s.z.object({source:s.z.object({type:s.z.enum([`github`,`git`,`local`,`url`]),repo:s.z.string().optional(),url:s.z.string().optional(),path:s.z.string().optional(),ref:s.z.string().optional()})}),sp=s.z.record(s.z.string(),op).optional().catch(void 0),cp=s.z.union([s.z.number().gt(0).lte(1),s.z.literal(!1)]).optional(),lp=s.z.object({enabled:s.z.boolean().optional(),options:s.z.record(s.z.string(),Kf).optional()}),up=s.z.object({enabled:s.z.boolean().optional(),autoAllowBashIfSandboxed:s.z.boolean().optional(),excludedCommands:s.z.array(s.z.string()).optional(),failIfUnavailable:s.z.boolean().optional(),filesystem:s.z.object({allowWrite:s.z.array(s.z.string()).optional(),denyRead:s.z.array(s.z.string()).optional()}).optional(),network:s.z.object({enabled:s.z.boolean().optional()}).optional()}),dp=s.z.object({defaultTrustLevel:s.z.enum([`safe`,`moderate`,`full`]).optional(),language:s.z.string().optional(),preset:s.z.string().optional(),currentProvider:s.z.string().optional(),providers:s.z.record(s.z.string(),Yf).optional(),provider:Jf.optional(),permissions:Xf.optional(),env:Zf,commandEnvAllow:s.z.array(s.z.string()).optional(),hooks:ip,disabledHooks:s.z.array(s.z.string()).optional(),enabledPlugins:ap,extraKnownMarketplaces:sp,autoCompactThreshold:cp,transports:s.z.record(s.z.string(),lp).optional(),sandbox:up.optional(),taskContext:s.z.object({enabled:s.z.boolean().optional(),dir:s.z.string().min(1).optional()}).optional()}),fp=/position (\d+)/;function pp(e){let t=fp.exec(e.message);return t===null?void 0:Number(t[1])}function mp(e){let t=e.code;return typeof t==`string`?t:void 0}function hp(e){let t;try{t=qc(e,`load configuration settings`)}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`unreadable`,cause:{state:`unreadable`,errno:mp(n)},error:n}}if(t===void 0)return{source:e,state:`absent`};let n=t.trim();if(n.length===0)return{source:e,state:`empty`,cause:{state:`empty`}};try{return{source:e,state:`ok`,raw:JSON.parse(n)}}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`invalid-json`,cause:{state:`invalid-json`,offset:pp(n)},error:n}}}function gp(e){if(e.state!==`ok`)return e;let t=dp.safeParse(e.raw);return t.success?{...e,settings:t.data}:{...e,state:`schema-invalid`,cause:{state:`schema-invalid`,issues:t.error.issues.map(e=>({path:e.path.map(String).join(`.`),code:e.code}))},schemaMessage:t.error.message}}function _p(e){return e.map(hp).map(gp)}function vp(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0){if(n===`permissions`&&typeof r==`object`&&r){for(let e of[`allow`,`deny`,`ask`])r[e]!==void 0&&t.push(`permissions.${e}`);continue}t.push(n)}return t}function yp(e){let t=new Map;for(let n of e)if(n.settings!==void 0)for(let e of vp(n.settings)){let r=t.get(e)??[];r.push(n.displayName),t.set(e,r)}return[...t.entries()].map(([e,t])=>({key:e,rule:kf[e]??`replace`,contributors:t}))}function bp(e){let t=_p(e).map(e=>({source:e.source,displayName:e.source.displayName,kind:e.source.kind,scope:e.source.scope,state:e.state,...e.cause===void 0?{}:{cause:e.cause},...e.settings===void 0?{}:{settings:e.settings}})),n=t.some(e=>e.state!==`ok`&&e.state!==`absent`),r=Af(t.flatMap(e=>e.settings===void 0?[]:[{settings:e.settings,source:e.displayName}]));return{layers:t,merged:r.settings,partial:n,provenance:yp(t),hookSources:r.hookSources}}const J={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[],ask:[]},env:{}};function xp(e){if(e.state===`empty`)throw new Uc(e.source.displayName,`the settings file is empty`);if(e.state===`invalid-json`)throw new Uc(e.source.displayName,e.error?.message??`invalid JSON`);if(e.state===`unreadable`)throw e.error}function Sp(e,t){return e.startsWith(`$ENV:`)?t[e.slice(5)]??e:e}function Cp(e,t){let n=e.provider?.apiKey===void 0?e.provider:wp(e.provider,t);if(e.providers!==void 0){let r=Object.fromEntries(Object.entries(e.providers).map(([e,n])=>[e,wp(n,t)]));return{...e,provider:n,providers:r}}return{...e,provider:n}}function wp(e,t){if(e.apiKey===void 0)return e;let n=e.apiKey.startsWith(`$ENV:`);return{...e,apiKey:Sp(e.apiKey,t),...n&&{apiKeyEnv:e.apiKey.slice(5)}}}function Tp(e){if(e.currentProvider!==void 0)return Ep(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...J.provider}}function Ep(e){let t=e.currentProvider;if(t===void 0)throw Error(`currentProvider is required`);let n=e.providers?.[t];if(n===void 0)throw Error(`currentProvider "${t}" was not found in providers`);if(n.type===void 0)throw Error(`Provider profile "${t}" is missing type`);return{name:n.type,model:n.model??J.provider.model,apiKey:n.apiKeyRef===void 0?n.apiKey??J.provider.apiKey:void 0,...n.apiKeyRef!==void 0&&{apiKeyRef:n.apiKeyRef},...n.apiKeyEnv!==void 0&&{apiKeyEnv:n.apiKeyEnv},...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function Dp(e){return{defaultTrustLevel:e.defaultTrustLevel??J.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:Tp(e),permissions:{allow:e.permissions?.allow??J.permissions.allow,deny:e.permissions?.deny??J.permissions.deny,ask:e.permissions?.ask??J.permissions.ask},env:e.env??J.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold,taskContext:e.taskContext??void 0,...e.sandbox===void 0?{}:{sandbox:e.sandbox}}}async function Op(e,t={}){let n=_p(e);for(let e of n)xp(e);let r=[];for(let e of n)if(e.state!==`absent`){if(e.state===`schema-invalid`||e.settings===void 0)throw Error(`Invalid settings in ${e.source.displayName}: ${e.schemaMessage}`);r.push({settings:Cp(e.settings,t),source:e.source.displayName})}let i=Af(r);return{config:Dp(i.settings),hookSources:i.hookSources}}const kp={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function Ap(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function jp(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||(0,r.basename)(t,`.md`)}function Mp(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function Np(e,t){let n=e.split(/\r?\n/),r=RegExp(`^(#{2,6})\\s+${t}\\b`,`i`),i=n.findIndex(e=>r.test(e));if(i<0)return;let a=[];for(let e of n.slice(i+1)){if(/^##\s+/.test(e))break;a.push(e)}let o=a.join(`
|
|
105
105
|
`).trim();return o.length>0?o:void 0}function Pp(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(\S.*)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function Fp(e,t){return t&&e.branch===t?0:kp[e.status]}function Ip(e){let t=[`### ${e.title}`,`- **Path:** \`${e.relativePath}\``];return t.push(`- **Status:** ${e.status}`),e.branch&&t.push(`- **Branch:** ${e.branch}`),e.scope&&t.push(`- **Scope:** ${e.scope}`),e.objective&&t.push(`- **Objective:** ${e.objective}`),e.openItems.length>0&&(t.push(`- **Open items:**`),t.push(...e.openItems.map(e=>` - ${e}`))),t.join(`
|
|
106
106
|
`)}function Lp(e,t){let n=(0,r.resolve)(e),i=!1;for(;!i;){let e=(0,r.join)(n,`.git`);if(t.existsSync(e)){if(t.statSync(e).isDirectory())return e;let i=t.readFileSync(e,`utf8`).trim().match(/^gitdir:\s*(\S.*)$/)?.[1];if(i)return(0,r.isAbsolute)(i)?i:(0,r.resolve)(n,i)}let a=(0,r.dirname)(n);i=a===n,n=a}}function Rp(e,t=new Ti){let n=Lp(e,t);if(!n)return;let i=(0,r.join)(n,`HEAD`);if(t.existsSync(i))return(t.readFileSync(i,`utf8`).trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1])?.trim()}function zp(e,t){return R(e).listDirectory(t,`discover project task context`).filter(e=>e.kind===`file`).map(e=>e.name).filter(e=>e!==`README.md`&&e.endsWith(`.md`)).sort((e,t)=>e.localeCompare(t)).map(e=>(0,r.join)(t,e))}function Bp(e,t){let n=R(t).readText(e,`load project task context`);if(n===void 0)throw Error(`Task context file is missing: ${e}`);return{path:e,relativePath:e,title:jp(n,e),status:Ap(Mp(n,`Status`)),branch:Mp(n,`Branch`),scope:Mp(n,`Scope`),objective:Np(n,`Objective`),openItems:Pp(n)}}function Vp(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>Fp(e,t.currentBranch)-Fp(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function Hp(e){return e.map(Ip).join(`
|
|
107
107
|
|
|
@@ -101,7 +101,7 @@ Do not use emojis.`}function ma(){return`You are a worker subagent executing a s
|
|
|
101
101
|
`)[0]?.trim()===`---`?void 0:{path:t,reason:`frontmatter-missing`}:{path:t,reason:r.diagnostics[0].code===`unterminated`?`frontmatter-unterminated`:`frontmatter-invalid`,detail:new Hf(r.diagnostics).message}}function Vp(e,t,n){let r={sourceDisplayName:e.displayName,root:t};if(e.inspectKind(t,`inspect skill directory`)!==`directory`)return{...r,present:!1,discovered:[],skipped:[]};let i=[],a=[];for(let r of e.listDirectory(t,`inspect skills`)){let o;if(n===`skills`){if(r.kind!==`directory`)continue;if(o=D(t,r.name,`SKILL.md`),e.inspectKind(o,`inspect skill definition`)!==`file`){a.push({path:D(t,r.name),reason:`missing-skill-file`});continue}}else{if(r.kind!==`file`||!r.name.endsWith(`.md`))continue;o=D(t,r.name)}let s=e.readText(o,`inspect skill definition`);if(s===void 0){a.push({path:o,reason:`unreadable`});continue}let c=Bp(e,o,s);c!==void 0&&a.push(c),(c===void 0||c.reason===`frontmatter-missing`)&&i.push(n===`skills`?T(D(o,`..`)):T(r.name,`.md`))}return{...r,present:!0,discovered:i,skipped:a}}function Hp(e,t=[]){return{roots:e.flatMap(e=>t.map(({root:t,kind:n})=>Vp(e,t,n)))}}function Up(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function Wp(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Gp(e,t){return e.some(e=>Wp(e.name)===t)}function Kp(e,t){return!t||Object.keys(t).length===0||Object.values(e??{}).some(e=>e?.some(e=>e.hooks.some(e=>e.type===`guardrail`)))?e:{...e,PreToolUse:[...e?.PreToolUse??[],{matcher:``,hooks:[{type:`guardrail`}]}]}}async function qp(e,t=[]){if(!e.provider)throw Error(`provider is required. SDK is provider-neutral — consumer must create and pass a provider instance.`);let n=e.provider,r=e.cwd??process.cwd(),i=e.sessionId??Jp(),a=new zp(e.contributionSources??[],e.skillRoots??[]),o=Up(e.commandDescriptors),s=o.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,c=s?ja(o,e.modelCommandToolPrefix):void 0,l=Gp(o,e.commandSemanticRoles?.skillActivation??``)?Rp(a.getCommands(),e.pluginSkills??[]).filter(e=>e.disableModelInvocation!==!0):[],u,{tools:d,wrapAdded:f}=await kf(e,r,()=>u===void 0?void 0:Zi(u,e.onUsageRecorded));s&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&d.push(...Pa({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:o,toolNamePrefix:e.modelCommandToolPrefix}));let p=Pf(e),m=Kp(e.config.hooks,e.guardrails);Mp(m,p,t);let{agentToolDeps:h,agentDefinitions:g,backgroundTaskManager:_}=Jf(e,i,r,n,d,p),{backgroundProcessToolDeps:v}=Tp(e,_,i,r,d);Ep(e,_,i,r,d);let{finalSystemMessage:y,rebuildSystemMessage:ee}=Op(e,r,o,c,v,l,g,d),b=c?c.commandTools.filter(e=>!e.requiresPermission).map(e=>e.toolName):[],x={allow:[...e.baselinePermissionAllow??[],...b,...e.config.permissions.allow??[]],deny:e.config.permissions.deny??[]},te={...ne(x,e),ask:[...e.config.permissions.ask??[]]},re=e.persistProjectPermission,ie=re?e=>{re(e.includes(`(`)?e:`${e}(*)`)}:void 0,ae=new ut({pathProtection:e.pathProtection,tools:d,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},wrapAddedTools:f,provider:n,systemMessage:y,terminal:e.terminal,cwd:r,permissions:te,presetFreePermissions:x,hooks:m,permissionMode:e.permissionMode,defaultTrustLevel:e.config.defaultTrustLevel,model:e.model??e.config.provider.model,providerTimeout:e.config.provider.timeout??12e4,maxTurns:e.maxTurns,sessionStore:e.sessionStore,checkpointHistory:e.checkpointHistory,sessionId:i,permissionHandler:e.permissionHandler,...e.sandboxClient?.autoApproves===void 0?{}:{commandSandbox:Ua(e.sandboxClient)},...e.disableAutoMode===!0?{}:{permissionClassifier:fa(n,{cwd:r,model:e.model??e.config.provider.model})},...e.ask?{ask:e.ask}:{},...ie===void 0?{}:{onProjectAllowTool:ie},onTextDelta:e.onTextDelta,onThinkingDelta:e.onThinkingDelta,onContextUpdate:e.onContextUpdate,onToolExecution:e.onToolExecution,promptForApproval:e.promptForApproval,onCompact:e.onCompact,onCompactEvent:e.onCompactEvent,compactInstructions:e.compactInstructions??e.context.compactInstructions,contextCapacityHint:e.contextCapacityHint,autoCompactThreshold:e.autoCompactThreshold??e.config.autoCompactThreshold,sessionLogger:e.sessionLogger,transcriptPath:e.transcriptPath,hookTypeExecutors:p,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens}});return u=ae,kp(ae,h,v,_),{session:ae,rebuildSystemMessage:ee}}function Jp(){return`session_${w()}`}function Yp(e){let t=new Date().toISOString();return{id:Jp(),name:e.name,cwd:e.cwd,createdAt:t,updatedAt:t,messages:[...e.source.getHistory()],history:[...e.source.getFullHistory()],systemPrompt:e.source.getSystemMessage(),toolSchemas:[...e.source.getToolSchemas()]}}function Xp(e,t){return!t.isFork||t.restoredSystemPrompt===void 0||t.explicitSystemPrompt!==void 0?!1:(e.updateSystemMessage(t.restoredSystemPrompt),!0)}function Zp(e){let t=new Set;for(let n of e.list())n.outcome.status===`valid`&&n.outcome.record.name!==void 0&&t.add(n.outcome.record.name);return t}function Qp(e,t,n,r){let i=e?.trim();if(i!==void 0&&i.length>0){if(i===t)throw Error(`A fork cannot be named "${i}": that is the source session's name, and a name lookup could then resolve to either record.`);if(r.has(i))throw Error(`A fork cannot be named "${i}": another session already answers to that name, and a name lookup could then resolve to either record.`);return i}let a=`${t??n} (fork)`;if(!r.has(a))return a;let o=e=>`${t??n} (fork ${e})`,s=2;for(;r.has(o(s));)s+=1;return o(s)}function $p(e){let t=Qp(e.requestedName,e.sourceName,e.sourceId,Zp(e.sessionStore)),n=Yp({source:{getHistory:()=>e.source.getHistory(),getSystemMessage:()=>e.source.getSystemMessage(),getToolSchemas:()=>e.source.getToolSchemas(),getFullHistory:e.fullHistory},name:t,cwd:e.cwd});return e.sessionStore.save(n),{sessionId:n.id,name:t}}function em(e,t){let n=e.name??e.id,r=Zp(t),i=n;for(let e=1;r.has(i);e+=1)i=e===1?`${n} (moved)`:`${n} (moved ${e})`;return{...e,name:i}}function tm(e,t,n){let r=mo(n),i=r?.customAgentRegistry?.(e)??(r?.builtInAgents?r.builtInAgents.find(t=>t.name===e):Bi(e));if(!i)throw Error(`Unknown agent type: ${e}`);let a=t.effort??i.effort??n.getModelEffort();return{...i,...t.model?{model:t.model}:{},...t.allowedTools?{tools:t.allowedTools}:{},...a===`auto`?{}:{effort:a}}}async function nm(e,t,n){t.signal?.throwIfAborted();let r=mo(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);let i=tm(t.agent??`general-purpose`,t,n),a=Va({pathProtection:r.pathProtection,agentDefinition:i,parentConfig:ro(r),parentContext:r.context,parentTools:r.tools,provider:r.provider,terminal:r.terminal,cwd:n.getCwd(),isForkWorker:!0,permissionMode:n.getPermissionMode(),...r.commandSemanticRoles?{commandSemanticRoles:r.commandSemanticRoles}:{},...r.modelCommandToolPrefix?{modelCommandToolPrefix:r.modelCommandToolPrefix}:{},permissionHandler:r.permissionHandler,...io(r.sandboxClient),hooks:r.hooks,hookTypeExecutors:r.hookTypeExecutors,onTextDelta:r.onTextDelta,onToolExecution:r.onToolExecution});return t.signal?a.run(e,void 0,{signal:t.signal}):a.run(e)}function rm(e,t){return e===`~`?t:e.startsWith(`~/`)?`${t}/${e.slice(2)}`:e}function im(e){if(e.executing)throw Error(`Finish or cancel the current turn before moving to another directory.`);if(e.liveBackgroundTasks>0)throw Error(`${e.liveBackgroundTasks} background task(s) are still running in this directory and would not survive the move. Wait for them or cancel them first.`);let t=e.requestedPath.trim();if(t===``)throw Error(`Usage: /cd <directory>`);let n=rm(t,e.homeDirectory??rn()),r=E(n)?n:O(e.workspace.cwd,n),i;try{i=N(r)}catch{throw Error(`No such directory: ${r}`)}if(!Bt(i).isDirectory())throw Error(`Not a directory: ${i}`);if(i===N(e.workspace.cwd))throw Error(`Already in ${i}.`);if(pe(`Cd`,{path:i},e.permissionMode,e.rules)===`deny`)throw Error(`Moving to ${i} is denied by a permission rule.`);return{fromCwd:e.workspace.cwd,targetCwd:i,record:Yp({source:e.source,name:e.sessionName,cwd:i}),restricted:e.workspace.projectAccess.status===`restricted`}}function am(e){let t=[`<workspace-move>`,`The working directory has moved from ${e.fromCwd} to ${e.toCwd}. This supersedes the working directory stated earlier in this conversation and in the system prompt; tools now resolve paths against ${e.toCwd}.`];if(e.restricted)t.push(`This project is not trusted, so no project instructions, settings or skills were loaded for it. Instructions loaded for the previous directory no longer apply.`);else if(e.instructions.length===0)t.push(`No project instructions were found for ${e.toCwd}. Instructions loaded for the previous directory no longer apply.`);else{t.push(`Project instructions for ${e.toCwd}, which replace any loaded for the previous directory:`);for(let n of e.instructions)t.push(``,`## ${n.filePath}`,n.content.trim())}return t.push(`</workspace-move>`),t.join(`
|
|
102
102
|
`)}async function om(e,t,n,r){if(n.status!==`trusted`)throw new z(`Adding a project context reference requires explicit workspace project authority.`);let i=await Ju([t],{reader:ac(n.authority),startRelativeDirectory:Be(n.identity.worktreeRoot,r),reason:`manual`});if(Vu(i.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[Hu(i.diagnostics)]}};let a=i.references[0];if(!a)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let o=Cu(Uu([a])[0],`manual`,`active`),s=wu(e,o);return{references:s.references,result:{reference:o,evicted:s.evicted,diagnostics:[]}}}function sm(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=Cu(e,n.loadType,n.status,r);i=wu(i,t).references}return i}function cm(e,t){let n=new Date().toISOString();return e.map(e=>{let r=E(e.filePath)?Be(t,e.filePath):e.filePath;return{id:`system:${r}`,sourcePath:e.filePath,relativePath:r,originalReference:r,loadType:`system`,status:`active`,byteLength:Buffer.byteLength(e.content,`utf-8`),loadedAt:n,lastUsedAt:n}})}const lm=`main`;var um=class extends Error{checkpointDir;snapshotFile;constructor(e,t){super(`Checkpoint manifest names a snapshot outside its checkpoint directory: ${JSON.stringify(t)} (checkpoint ${e})`),this.name=`EditCheckpointManifestEscapeError`,this.checkpointDir=e,this.snapshotFile=t}};function dm(e,t){if(t.length===0||E(t))throw new um(e,t);let n=D(e,t),r=Be(e,n);if(r.length===0||r===`..`||r.startsWith(`../`)||r.startsWith(`..\\`)||E(r))throw new um(e,t);return n}function fm(e){return e.map((t,n)=>{if(t.version===2&&t.branchId!==void 0)return t;let r=n>0?e[n-1]:void 0;return{...t,version:2,branchId:lm,...r?{parentId:r.id}:{}}})}function pm(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}const mm={create:`checkpoint_created`,fork:`branch_forked`,switch:`branch_switched`,restore:`checkpoint_restored`,rollback:`checkpoint_rolled_back`,resume_pointer:`non_event`};var hm=class{getStore;getSessionId;persistSession;emitEvent;onError;constructor(e,t,n,r,i){this.getStore=e,this.getSessionId=t,this.persistSession=n,this.emitEvent=r,this.onError=i}emit(e,t){let n=mm[e],r=this.getStore().getActiveBranchPointer(this.getSessionId())?.branchId??`main`;this.emitEvent({kind:n,checkpointId:t,branchId:r})}async finalize(){try{let e=await this.getStore().finalizeTurn();if(!e)return;this.persistSession(),this.emit(`create`,e.id)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.onError(t),t}}};function gm(e){return e.source===`plugin`?`plugin`:`skill`}function _m(e){return e.context===`fork`?`fork`:`inject`}function vm(e){return{type:`skill-activation`,skillName:e.skill.name,source:gm(e.skill),invocation:e.invocation,mode:_m(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function ym(e){let t=e.source===`plugin`?`plugin skill`:`skill`;return e.status===`failed`?`Skill failed: ${e.skillName}${e.error?` (${e.error})`:``}`:e.status===`completed`?`Skill completed: ${e.skillName}`:`Invoking ${t}: ${e.skillName}`}const bm=new Set([`memory_candidate_saved`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`]);function xm(e){let t=e.topic?`: ${e.topic}`:``;switch(e.type){case`memory_candidate_saved`:return`Memory saved${t}`;case`memory_candidate_approved`:return`Memory approved${t}`;case`memory_candidate_rejected`:return`Memory rejected${t}${e.reason?` (${e.reason})`:``}`;case`memory_retrieved`:return`Memory recalled${t}`;case`memory_candidate_extracted`:return`Memory candidate extracted${t}`;case`memory_candidate_queued`:return`Memory candidate queued${t}`;case`memory_candidate_skipped`:return`Memory candidate skipped${t}${e.reason?` (${e.reason})`:``}`}}const Sm={"host-cannot-write-project":`Rewind isn't available on this computer yet.`,"restricted-workspace":`Edit checkpoints need a trusted workspace; this one is restricted, so nothing is saved under it.`,"no-checkpoint-store":`Edit checkpoints are off: this session was built without a checkpoint store.`};var Cm=class extends z{reason;name=`EditCheckpointsUnavailableError`;constructor(e){super(Sm[e]),this.reason=e}},wm=class{workspace;getSessionId;getExecuting;persistSession;emitSkillActivation;emitMemoryEvent;history=[];editCheckpointStore=null;branchEvents;pendingActiveBranch=void 0;memoryEvents=[];usedMemoryReferences=[];contextReferences=[];systemContextReferences=[];skillActivationEvents=[];constructor(e,t,n,r,i,a,o=null,s=()=>void 0){this.workspace=e,this.getSessionId=t,this.getExecuting=n,this.persistSession=r,this.emitSkillActivation=i,this.emitMemoryEvent=a,this.editCheckpointStore=o,this.branchEvents=new hm(()=>this.getCheckpointStore(),t,r,s,e=>this.history.push(C(S(`Checkpoint error: ${e.message}`))))}restoreState(e){this.history=e.history,this.memoryEvents=e.memoryEvents,this.usedMemoryReferences=e.usedMemoryReferences,this.contextReferences=e.contextReferences,this.skillActivationEvents=e.skillActivationEvents}getState(){return{history:this.history,memoryEvents:this.memoryEvents,usedMemoryReferences:this.usedMemoryReferences,contextReferences:this.contextReferences,skillActivationEvents:this.skillActivationEvents}}append(e){this.history.push(e)}getHistory(){return this.history}clearHistory(){this.history=[],this.memoryEvents=[],this.usedMemoryReferences=[]}resetUsedMemoryReferences(){this.usedMemoryReferences=[]}recordContextReferenceUsage(e){this.contextReferences=sm(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=sm(this.contextReferences,e,{loadType:`prompt-reference`,status:`observed`}),this.persistSession()}listEditCheckpoints(){let e=this.getSessionId();return this.getCheckpointStore().list(e)}inspectEditCheckpoint(e){let t=this.getSessionId();return this.getCheckpointStore().inspect(t,e)}async restoreEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot restore edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push(C(S(`Restored edit checkpoint: ${e}`))),this.persistSession(),this.branchEvents.emit(`restore`,e),t}async rollbackEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot rollback edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().rollbackThroughCheckpoint(this.getSessionId(),e);return this.history.push(C(S(`Rolled back edit checkpoint: ${e}`))),this.persistSession(),this.branchEvents.emit(`rollback`,e),t}listCheckpointBranches(){return this.getCheckpointStore().listCheckpointBranches(this.getSessionId())}async forkCheckpointBranch(e){if(this.getExecuting())throw Error(`Cannot fork edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push(C(S(`Forked new branch from checkpoint: ${e}`))),this.persistSession(),this.branchEvents.emit(`fork`,e),t}switchCheckpointBranch(e){if(this.getExecuting())throw Error(`Cannot switch edit checkpoint branch while a prompt is running.`);this.getCheckpointStore().switchToCheckpoint(this.getSessionId(),e),this.history.push(C(S(`Switched to checkpoint branch: ${e}`))),this.persistSession(),this.branchEvents.emit(`switch`,e)}getActiveBranchPointer(){if(this.editCheckpointStore)return this.applyPendingActiveBranch(),this.editCheckpointStore.getActiveBranchPointer(this.getSessionId())}restoreActiveBranch(e){e!==void 0&&(this.pendingActiveBranch=e)}applyPendingActiveBranch(){this.pendingActiveBranch===void 0||!this.editCheckpointStore||(this.editCheckpointStore.restoreActiveBranch(this.getSessionId(),this.pendingActiveBranch),this.pendingActiveBranch=void 0)}async beginEditCheckpointTurn(e){this.editCheckpointStore&&(this.applyPendingActiveBranch(),await this.editCheckpointStore.beginTurn({sessionId:this.getSessionId(),prompt:e}))}async finalizeEditCheckpointTurn(){this.editCheckpointStore&&await this.branchEvents.finalize()}setEditCheckpointStore(e){this.editCheckpointStore=e}getUsedMemoryReferences(){return[...this.usedMemoryReferences]}recordUsedMemoryReferences(e){e.length!==0&&(this.usedMemoryReferences=[...this.usedMemoryReferences,...e],this.persistSession())}recordMemoryEvent(e){this.memoryEvents.push(e),bm.has(e.type)&&this.history.push({id:w(),timestamp:new Date(e.at),category:`event`,type:`memory-event`,data:{...e,message:xm(e)}}),this.emitMemoryEvent(e),this.persistSession()}recordSystemContextFiles(e){this.systemContextReferences=cm(e,this.workspace.cwd)}listContextReferences(){return[...this.systemContextReferences,...this.contextReferences]}listInjectionContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await om(this.contextReferences,e,this.workspace.projectAccess,this.workspace.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=Tu(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=Eu(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,t){this.skillActivationEvents.push(e),t&&this.history.push({id:w(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:ym(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){if(!this.editCheckpointStore)throw new Cm(this.noStoreReason());return this.applyPendingActiveBranch(),this.editCheckpointStore}noStoreReason(){return lc()?this.workspace.projectAccess.status===`trusted`?`no-checkpoint-store`:`restricted-workspace`:`host-cannot-write-project`}},Tm=class extends Error{filePath;constructor(e){super(`Settings file ${e} has no active provider profile ("currentProvider" + "providers"); the model cannot be updated. Run provider setup first.`),this.name=`NoCurrentProviderProfileError`,this.filePath=e}};function Em(e){if(!M(e))return{};let t=It(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new yd(e,t instanceof Error?t.message:String(t))}}function Dm(e,t){Et(ze(e)),Ot(e),Ht(e,JSON.stringify(t,null,2)+`
|
|
103
103
|
`,{encoding:`utf8`,mode:384})}function Om(e,t){let n=Em(e),r=n.currentProvider,i=n.providers;if(typeof r!=`string`||!km(i))throw new Tm(e);let a=i;a[r]={...km(a[r])?a[r]:{},model:t},n.providers=a,Dm(e,n)}function km(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Am(e){return M(e)?(Vt(e),!0):!1}const jm=Object.freeze({theme:`theme`,syntaxHighlighting:`syntaxHighlighting`,reducedMotion:`reducedMotion`}),Mm=Object.freeze({theme:`dark`,syntaxHighlighting:!0,reducedMotion:!1});function Nm(e){let t=new Set(Object.values(jm));return!Object.keys(e).some(e=>!t.has(e))&&(e.theme===void 0||typeof e.theme==`string`&&e.theme.length>0)&&(e.syntaxHighlighting===void 0||typeof e.syntaxHighlighting==`boolean`)&&(e.reducedMotion===void 0||typeof e.reducedMotion==`boolean`)}function Pm(e){let t=e[jm.theme],n=e[jm.syntaxHighlighting],r=e[jm.reducedMotion];return{theme:typeof t==`string`&&t.length>0?t:Mm.theme,syntaxHighlighting:typeof n==`boolean`?n:Mm.syntaxHighlighting,reducedMotion:typeof r==`boolean`?r:Mm.reducedMotion}}function Fm(e,t){let n=Em(e),r={...Pm(n),...t};return n[jm.theme]=r.theme,n[jm.syntaxHighlighting]=r.syntaxHighlighting,n[jm.reducedMotion]=r.reducedMotion,Dm(e,n),r}var Im=class extends Error{filePath;constructor(e,t){super(`Organization policy file ${e} could not be read as a policy: ${t}. Policy is NOT applied while this file is unreadable. Fix or remove the file.`),this.name=`OrgPolicyParseError`,this.filePath=e}};function Lm(e){if(typeof e!=`string`||e.trim()===``)throw TypeError(`Organization policy path is required`);if(!M(e))return null;let t;try{t=JSON.parse(It(e,`utf8`))}catch(t){throw new Im(e,t instanceof Error?t.message:String(t))}let n=Rm(t);if(n!==void 0)throw new Im(e,n);return t}function Rm(e){if(typeof e!=`object`||!e||Array.isArray(e))return`expected a JSON object, found ${Array.isArray(e)?`an array`:typeof e}`;let t=e;for(let e of[`allowedProviders`,`blockedCommands`]){let n=t[e];if(n!==void 0&&(!Array.isArray(n)||n.some(e=>typeof e!=`string`)))return`\`${e}\` must be an array of strings`}for(let e of[`requireApiKeyFromEnv`,`disableAutoMode`])if(t[e]!==void 0&&typeof t[e]!=`boolean`)return`\`${e}\` must be a boolean`;if(t.adminContact!==void 0&&typeof t.adminContact!=`string`)return"`adminContact` must be a string"}function zm(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function Bm(e){return e?!e.startsWith(`$ENV:`):!1}const Vm=`Configure TUI status-line visibility and fields such as model, context, tokens, session, and git branch.`,Hm=`on | off | reset | git on | git off`,Um={enabled:!0,gitBranch:!0};function Wm(e=`statusline`){return[{name:`on`,description:`Show the status line`,source:e},{name:`off`,description:`Hide the status line`,source:e},{name:`reset`,description:`Restore default status-line fields`,source:e},{name:`git`,description:`Show or hide git branch field`,source:e}]}function Gm(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function Km(e){let t=e.statusline;return Jm(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:Um.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:Um.gitBranch}:{...Um}}function qm(e,t){let n=Em(e),r={...Km(n),...t};return n.statusline=r,Dm(e,n),r}function Jm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Y(e,t){return{success:!1,message:`Cannot apply '${e}': ${t} is not available in this environment.`}}function Ym(e,t){return{success:!1,message:`Failed to apply '${e}': ${t instanceof Error?t.message:String(t)}`}}async function Xm(e,t){if(!e.success)return{result:e,uiIntents:[]};let n=e.hostActions??[],r=e.uiIntents??[],i=[];for(let e of n){let n=await Zm(e,t,i);if(n)return{result:n,uiIntents:[]}}return n.length===0&&r.length===0?{result:e,uiIntents:[]}:{result:{message:i.length>0?[e.message,...i].filter(e=>e.length>0).join(`
|
|
104
|
-
`):e.message,success:e.success,...e.data===void 0?{}:{data:e.data}},uiIntents:r}}async function Zm(e,t,n){let r=t.getAdapters();try{switch(e.type){case`provider-hot-swap`:{let{orgPolicy:n}=t;return n?.allowedProviders&&!n.allowedProviders.includes(e.profileName)?{message:zm(`Provider "${e.profileName}" is not allowed by your organization policy. Allowed: ${n.allowedProviders.join(`, `)}.`,n.adminContact),success:!1}:(await t.switchProvider(e.profileName),null)}case`output-style-change`:{let i=r.outputStyleRegistry;if(!i)return Y(e.type,`an output-style registry adapter`);let a=i.getOutputStyle(e.styleId);if(!a){let t=i.listOutputStyles().map(e=>e.id).join(`, `);return{success:!1,message:`Unknown output style "${e.styleId}". Available: ${t||`(none)`}`}}let o=r.settings;return o?(o.write({...o.read(),outputStyle:e.styleId}),t.applyOutputStyle(a),n.push(`Output style: ${a.name}`),null):Y(e.type,`a settings adapter`)}case`language-change`:{let t=r.settings;return t?r.process?(t.write({...t.read(),language:e.language}),n.push(`Restarting...`),r.process.requestRestart(`other`,`Language change restart`),null):Y(e.type,`a process adapter (restart)`):Y(e.type,`a settings adapter`)}case`settings-reset`:{let t=r.settings;if(!t?.delete)return Y(e.type,`a settings adapter with delete()`);if(!r.process)return Y(e.type,`a process adapter (exit)`);let i=t.delete();return n.push(i?`User settings deleted. Exiting...`:`No user settings found. Exiting...`),r.process.requestExit(`other`),null}case`session-exit`:return r.process?(r.process.requestExit(e.reason??`prompt_input_exit`),null):Y(e.type,`a process adapter`);case`session-restart`:return r.process?(r.process.requestRestart(e.reason,e.message),null):Y(e.type,`a process adapter`);case`session-rename`:return t.renameSession(e.name),null;case`workspace-move`:return r.workspace?(n.push(await t.moveWorkspace(e.path)),null):Y(e.type,`a host that can start a session elsewhere`);case`statusline-settings-patch`:{let t=r.settings;if(!t)return Y(e.type,`a settings adapter`);if(!Gm(e.patch))return Ym(e.type,Error(`invalid statusline settings patch`));let n=t.read(),i={...Km(n),...e.patch};return t.write({...n,statusline:i}),null}case`appearance-settings-patch`:{let t=r.settings;if(!t)return Y(e.type,`a settings adapter`);if(!Nm(e.patch))return Ym(e.type,Error(`invalid appearance settings patch`));let n=t.read(),i={...Pm(n),...e.patch};return t.write({...n,theme:i.theme,syntaxHighlighting:i.syntaxHighlighting,reducedMotion:i.reducedMotion}),null}case`remote-control-enable`:{if(t.invocationSource!==`user`)return{success:!1,message:"Cannot apply 'remote-control-enable': only the operator at this terminal can pair a device. Run `/remote-control` on the host terminal."};let i=r.remoteControl?.enable;return i?(n.push(await i.call(r.remoteControl)),null):Y(e.type,`a remote-control adapter with enable()`)}case`remote-control-stop`:{let t=r.remoteControl?.stop;return t?(n.push(await t.call(r.remoteControl)),null):Y(e.type,`a remote-control adapter with stop()`)}}}catch(t){return Ym(e.type,t)}}function Qm(e,t,n){return t===void 0?e===`model`?n??void 0:e===`user`?We:void 0:t}function $m(e,t,n){for(let r of e)n({intent:r,...t===void 0?{}:{requesterDriverId:t}})}function eh(e,t){let n=bd(e,t);return Object.freeze({kind:`host`,scope:e,displayName:t,source:n,read:()=>{if(!M(t))return{};let e=It(t,`utf8`);try{return JSON.parse(e)}catch(e){throw new yd(t,e instanceof Error?e.message:String(e))}},write:e=>{Et(ze(t)),Ot(t),Ht(t,`${JSON.stringify(e,null,2)}\n`,{encoding:`utf8`,mode:384})}})}function th(e,t){let n=Dc(t,e),r=ac(e),i=n.target,a=n.relativePath,o=Object.freeze({kind:`project`,scope:i,displayName:a,relativePath:a,reader:r});return Object.freeze({kind:`project`,scope:i,displayName:a,source:o,read:()=>{let e=r.readText(a,`read project settings for update`);if(e===void 0)return{};try{return JSON.parse(e)}catch(e){throw new yd(a,e instanceof Error?e.message:String(e))}},write:e=>{n.writeText(`${JSON.stringify(e,null,2)}\n`)}})}function nh(e,t){if(process.platform!==`linux`||e?.status!==`trusted`)return;let n=t?.find(e=>e.scope===`project-local`);if(n!==void 0)return t=>{let r=Tc(e.authority,{status:`approved`,target:`project-local`,relativePath:n.relativePath,purpose:`persist user-approved project permission`}),i=th(e.authority,r),a=i.read(),o=typeof a.permissions==`object`&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{},s=Array.isArray(o.allow)?o.allow:[];s.includes(t)||i.write({...a,permissions:{...o,allow:[...s,t]}})}}function rh(e){return e.commandSemanticRoles?e.commandSemanticRoles:(e.commandModules?.flatMap(e=>e.systemCommands??[])??[]).reduce((e,t)=>t.semanticRole?{...e,[t.semanticRole]:t.name}:e,{})}function ih(e,t){let{mergedConfig:n,cwd:r,context:i,projectInfo:a,sessionId:o,contextCapacityHint:s,contributionSources:c,skillRoots:l}=t,u=nh(e.projectAccess,e.projectSettingsPaths);return{config:n,cwd:r,context:i,contributionSources:c,skillRoots:l,...e.pluginSkills===void 0?{}:{pluginSkills:e.pluginSkills},projectInfo:a,permissionMode:e.permissionMode,baselinePermissionAllow:e.baselinePermissionAllow,maxTurns:e.maxTurns,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},terminal:ir,sessionLogger:e.sessionLogSink===void 0?new pt:new it(e.sessionLogSink),...e.transcriptPath===void 0?{}:{transcriptPath:e.transcriptPath},permissionHandler:e.permissionHandler,...u===void 0?{}:{persistProjectPermission:u},...e.askHandler?{ask:e.askHandler}:{},provider:e.provider,onTextDelta:e.onTextDelta,...e.onThinkingDelta===void 0?{}:{onThinkingDelta:e.onThinkingDelta},onContextUpdate:e.onContextUpdate,onCompactEvent:e.onCompactEvent,...e.onUsageRecorded===void 0?{}:{onUsageRecorded:e.onUsageRecorded},onToolExecution:e.onToolExecution,checkpointHistory:e.checkpointHistory,sessionId:o,allowedTools:e.allowedTools,deniedTools:e.deniedTools,disableBuiltInHookExecutors:e.disableBuiltInHookExecutors,commandHookShell:e.commandHookShell,model:e.model,...e.effort===void 0?{}:{effort:e.effort},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},appendSystemPrompt:e.appendSystemPrompt,...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},...e.persona===void 0?{}:{persona:e.persona},...e.systemPrompt?{systemPromptBuilder:()=>e.systemPrompt}:{},...e.guardrails===void 0?{}:{guardrails:e.guardrails},...e.retrievalAdapter===void 0?{}:{retrievalAdapter:e.retrievalAdapter},backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.resumeSessionStore===void 0?{}:{resumeSessionStore:e.resumeSessionStore},...e.agentDefinitions?{agentDefinitions:e.agentDefinitions}:{},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.commandModules?.some(e=>e.sessionRequirements?.includes(`runtime`))?{enableAgentRuntime:!0}:{},...e.enableParallelSubagents===void 0?{}:{enableParallelSubagents:e.enableParallelSubagents},...e.selfVerification===void 0?{}:{selfVerification:e.selfVerification},...e.commandModules||e.commandDescriptors?{commandDescriptors:[...e.commandDescriptors??[],...e.commandModules?.flatMap(e=>e.commandDescriptors??[])??[]]}:{},commandSemanticRoles:rh(e),modelCommandExecutor:e.modelCommandExecutor,modelCommandToolPrefix:e.modelCommandToolPrefix,subagentHookEnvironmentNames:e.subagentHookEnvironmentNames,observerFailureWarningCode:e.observerFailureWarningCode,isModelCommandInvocable:e.isModelCommandInvocable,editCheckpointRecorder:e.editCheckpointRecorder,reversibleExecution:e.reversibleExecution,sandboxClient:e.sandboxClient,...e.disableAutoMode===!0?{disableAutoMode:!0}:{},sandboxType:e.sandboxType,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.defaultTools?{defaultTools:e.defaultTools}:{},includeGoalTool:!0,includeSessionLoopDecisionTool:!0,...e.peerReply?{peerReply:e.peerReply}:{},...e.peerSendFile?{peerSendFile:e.peerSendFile}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},...s===void 0?{}:{contextCapacityHint:s}}}function ah(e,t){return{...e.sandboxClient?{sandboxClient:e.sandboxClient}:{},...e.sandboxType?{sandboxType:e.sandboxType}:{},...e.workspaceManifest?{workspaceManifest:e.workspaceManifest}:{},...e.sandboxWorkspaceRoot?{sandboxWorkspaceRoot:e.sandboxWorkspaceRoot}:{},...t?{sandboxSnapshotId:t}:{}}}async function oh(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await $e(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function sh(e){if(!e.sandboxSnapshotId)return!1;if(!e.sandboxClient?.restore)throw Error(`sandboxSnapshotId requires sandboxClient with restore().`);return await e.sandboxClient.restore(e.sandboxSnapshotId),!0}function ch(e){return{...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt}}}const lh=Object.freeze({defaultTrustLevel:`most-restrictive`,disabledHooks:`accumulate`,provider:`object-merge`,"permissions.allow":`union`,"permissions.deny":`union`,"permissions.ask":`union`,env:`object-merge`,providers:`object-merge`,enabledPlugins:`object-merge`,extraKnownMarketplaces:`replace`,autoCompactThreshold:`replace`,hooks:`per-event`,taskContext:`object-merge`,sandbox:`object-merge`});function uh(e){let t=dh(e);return{settings:t.settings,hookSources:t.hookSources}}function dh(e){let t=new Set,n={},r=[];for(let{settings:i,source:a}of e){let e=xh(i.hooks,t);a!==void 0&&fh(e,a,r);for(let e of i.disabledHooks??[])t.add(e);n=ph(n,{...i,hooks:e},t)}return{settings:n,hookSources:r}}function fh(e,t,n){for(let[r,i]of Object.entries(e??{}))for(let e of i??[])for(let i of e.hooks)n.push({event:r,type:i.type,source:t})}function ph(e,t,n){return{...e,...t,defaultTrustLevel:wh(e.defaultTrustLevel,t.defaultTrustLevel),disabledHooks:mh(n),provider:Th(e.provider,t.provider),permissions:hh(e.permissions,t.permissions),env:{...e.env??{},...t.env??{}},providers:_h(e.providers,t.providers),enabledPlugins:gh(e.enabledPlugins,t.enabledPlugins),extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold,hooks:vh(e.hooks,t.hooks),taskContext:gh(e.taskContext,t.taskContext),sandbox:gh(e.sandbox,t.sandbox)}}function mh(e){return e.size===0?void 0:[...e]}function hh(e,t){if(e!==void 0||t!==void 0)return{allow:bh(e?.allow,t?.allow),deny:bh(e?.deny,t?.deny),ask:bh(e?.ask,t?.ask)}}function gh(e,t){if(e!==void 0||t!==void 0)return{...e,...t}}function _h(e,t){if(e!==void 0||t!==void 0)return Sh(e,t)}function vh(e,t){if(e!==void 0||t!==void 0)return yh(e,t)}function yh(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{})){if(r===void 0)continue;let t=e,i=n[t];n[t]=i===void 0?[...r]:[...i,...r]}return n}function bh(e,t){return e===void 0?t===void 0?void 0:[...t]:t===void 0?[...e]:[...new Set([...e,...t])]}function xh(e,t){if(e===void 0||t.size===0)return e;let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=r;n[e]=i.filter(e=>e.id===void 0||!t.has(e.id))}return n}function Sh(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]=Th(n[e],r);return n}const Ch={safe:0,moderate:1,full:2};function wh(e,t){return e===void 0?t:t===void 0||Ch[e]<=Ch[t]?e:t}function Th(e,t){if(e===void 0&&t===void 0)return;if(t?.apiKeyRef!==void 0&&(t.apiKey!==void 0||t.apiKeyEnv!==void 0))throw Error(`Provider settings have conflicting credential origins`);let n={...e,...t};return t?.apiKeyRef===void 0?(t?.apiKey!==void 0||t?.apiKeyEnv!==void 0)&&delete n.apiKeyRef:(delete n.apiKey,delete n.apiKeyEnv),t?.baseURL!==void 0&&t.baseURL!==e?.baseURL&&(t?.apiKeyRef===void 0?t?.apiKey===void 0?t?.apiKeyEnv===void 0?(delete n.apiKey,delete n.apiKeyEnv,delete n.apiKeyRef,e?.apiKeyRef!==void 0&&(n.apiKey=``)):delete n.apiKey:delete n.apiKeyEnv:(delete n.apiKey,delete n.apiKeyEnv)),n}const Eh=k.lazy(()=>k.union([k.string(),k.number(),k.boolean(),k.null(),k.undefined(),k.date(),k.array(Eh),k.record(Eh)])),Dh=k.object({service:k.string().min(1),account:k.string().min(1)}).strict(),Oh=k.object({name:k.string().optional(),model:k.string().optional(),apiKey:k.string().optional(),apiKeyRef:Dh.optional(),baseURL:k.string().optional(),timeout:k.number().optional(),options:k.record(Eh).optional()}),kh=k.object({type:k.string().optional(),model:k.string().optional(),apiKey:k.string().optional(),apiKeyRef:Dh.optional(),baseURL:k.string().optional(),timeout:k.number().optional(),options:k.record(Eh).optional()}),Ah=k.object({allow:k.array(k.string()).optional(),deny:k.array(k.string()).optional(),ask:k.array(k.string()).optional()}),jh=k.record(k.string()).optional(),Mh=k.object({type:k.literal(`command`),command:k.string(),timeout:k.number().optional()}),Nh=k.object({type:k.literal(`http`),url:k.string(),headers:k.record(k.string()).optional(),timeout:k.number().optional()}),Ph=k.object({type:k.literal(`prompt`),prompt:k.string(),model:k.string().optional()}),Fh=k.object({type:k.literal(`agent`),agent:k.string(),maxTurns:k.number().optional(),timeout:k.number().optional()}),Ih=k.object({type:k.literal(`guardrail`),guardrails:k.array(k.string()).optional()}),Lh=k.discriminatedUnion(`type`,[Mh,Nh,Ph,Fh,Ih]),X=k.object({id:k.string().optional(),matcher:k.string(),hooks:k.array(Lh)}),Rh=k.object({PreToolUse:k.array(X).optional(),PostToolUse:k.array(X).optional(),SessionStart:k.array(X).optional(),SessionEnd:k.array(X).optional(),Stop:k.array(X).optional(),StopFailure:k.array(X).optional(),PreCompact:k.array(X).optional(),PostCompact:k.array(X).optional(),UserPromptSubmit:k.array(X).optional(),SubagentStart:k.array(X).optional(),SubagentStop:k.array(X).optional(),WorktreeCreate:k.array(X).optional(),WorktreeRemove:k.array(X).optional(),PreModelCall:k.array(X).optional(),PostModelCall:k.array(X).optional(),PermissionDecision:k.array(X).optional()}).optional(),zh=k.record(k.boolean()).optional(),Bh=k.object({source:k.object({type:k.enum([`github`,`git`,`local`,`url`]),repo:k.string().optional(),url:k.string().optional(),path:k.string().optional(),ref:k.string().optional()})}),Vh=k.record(Bh).optional().catch(void 0),Hh=k.union([k.number().gt(0).lte(1),k.literal(!1)]).optional(),Uh=k.object({enabled:k.boolean().optional(),options:k.record(Eh).optional()}),Wh=k.object({enabled:k.boolean().optional(),autoAllowBashIfSandboxed:k.boolean().optional(),excludedCommands:k.array(k.string()).optional(),failIfUnavailable:k.boolean().optional(),filesystem:k.object({allowWrite:k.array(k.string()).optional(),denyRead:k.array(k.string()).optional()}).optional(),network:k.object({enabled:k.boolean().optional()}).optional()}),Gh=k.object({defaultTrustLevel:k.enum([`safe`,`moderate`,`full`]).optional(),language:k.string().optional(),preset:k.string().optional(),currentProvider:k.string().optional(),providers:k.record(kh).optional(),provider:Oh.optional(),permissions:Ah.optional(),env:jh,commandEnvAllow:k.array(k.string()).optional(),hooks:Rh,disabledHooks:k.array(k.string()).optional(),enabledPlugins:zh,extraKnownMarketplaces:Vh,autoCompactThreshold:Hh,transports:k.record(Uh).optional(),sandbox:Wh.optional(),taskContext:k.object({enabled:k.boolean().optional(),dir:k.string().min(1).optional()}).optional()}),Kh=/position (\d+)/;function qh(e){let t=Kh.exec(e.message);return t===null?void 0:Number(t[1])}function Jh(e){let t=e.code;return typeof t==`string`?t:void 0}function Yh(e){let t;try{t=Cd(e,`load configuration settings`)}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`unreadable`,cause:{state:`unreadable`,errno:Jh(n)},error:n}}if(t===void 0)return{source:e,state:`absent`};let n=t.trim();if(n.length===0)return{source:e,state:`empty`,cause:{state:`empty`}};try{return{source:e,state:`ok`,raw:JSON.parse(n)}}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`invalid-json`,cause:{state:`invalid-json`,offset:qh(n)},error:n}}}function Xh(e){if(e.state!==`ok`)return e;let t=Gh.safeParse(e.raw);return t.success?{...e,settings:t.data}:{...e,state:`schema-invalid`,cause:{state:`schema-invalid`,issues:t.error.issues.map(e=>({path:e.path.map(String).join(`.`),code:e.code}))},schemaMessage:t.error.message}}function Zh(e){return e.map(Yh).map(Xh)}function Qh(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0){if(n===`permissions`&&typeof r==`object`&&r){for(let e of[`allow`,`deny`,`ask`])r[e]!==void 0&&t.push(`permissions.${e}`);continue}t.push(n)}return t}function $h(e){let t=new Map;for(let n of e)if(n.settings!==void 0)for(let e of Qh(n.settings)){let r=t.get(e)??[];r.push(n.displayName),t.set(e,r)}return[...t.entries()].map(([e,t])=>({key:e,rule:lh[e]??`replace`,contributors:t}))}function eg(e){let t=Zh(e).map(e=>({source:e.source,displayName:e.source.displayName,kind:e.source.kind,scope:e.source.scope,state:e.state,...e.cause===void 0?{}:{cause:e.cause},...e.settings===void 0?{}:{settings:e.settings}})),n=t.some(e=>e.state!==`ok`&&e.state!==`absent`),r=uh(t.flatMap(e=>e.settings===void 0?[]:[{settings:e.settings,source:e.displayName}]));return{layers:t,merged:r.settings,partial:n,provenance:$h(t),hookSources:r.hookSources}}const tg={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[],ask:[]},env:{}};function ng(e){if(e.state===`empty`)throw new yd(e.source.displayName,`the settings file is empty`);if(e.state===`invalid-json`)throw new yd(e.source.displayName,e.error?.message??`invalid JSON`);if(e.state===`unreadable`)throw e.error}function rg(e,t){return e.startsWith(`$ENV:`)?t[e.slice(5)]??e:e}function ig(e,t){let n=e.provider?.apiKey===void 0?e.provider:ag(e.provider,t);if(e.providers!==void 0){let r=Object.fromEntries(Object.entries(e.providers).map(([e,n])=>[e,ag(n,t)]));return{...e,provider:n,providers:r}}return{...e,provider:n}}function ag(e,t){if(e.apiKey===void 0)return e;let n=e.apiKey.startsWith(`$ENV:`);return{...e,apiKey:rg(e.apiKey,t),...n&&{apiKeyEnv:e.apiKey.slice(5)}}}function og(e){if(e.currentProvider!==void 0)return sg(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...tg.provider}}function sg(e){let t=e.currentProvider;if(t===void 0)throw Error(`currentProvider is required`);let n=e.providers?.[t];if(n===void 0)throw Error(`currentProvider "${t}" was not found in providers`);if(n.type===void 0)throw Error(`Provider profile "${t}" is missing type`);return{name:n.type,model:n.model??tg.provider.model,apiKey:n.apiKeyRef===void 0?n.apiKey??tg.provider.apiKey:void 0,...n.apiKeyRef!==void 0&&{apiKeyRef:n.apiKeyRef},...n.apiKeyEnv!==void 0&&{apiKeyEnv:n.apiKeyEnv},...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function cg(e){return{defaultTrustLevel:e.defaultTrustLevel??tg.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:og(e),permissions:{allow:e.permissions?.allow??tg.permissions.allow,deny:e.permissions?.deny??tg.permissions.deny,ask:e.permissions?.ask??tg.permissions.ask},env:e.env??tg.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold,taskContext:e.taskContext??void 0,...e.sandbox===void 0?{}:{sandbox:e.sandbox}}}async function lg(e,t={}){let n=Zh(e);for(let e of n)ng(e);let r=[];for(let e of n)if(e.state!==`absent`){if(e.state===`schema-invalid`||e.settings===void 0)throw Error(`Invalid settings in ${e.source.displayName}: ${e.schemaMessage}`);r.push({settings:ig(e.settings,t),source:e.source.displayName})}let i=uh(r);return{config:cg(i.settings),hookSources:i.hookSources}}const ug={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function dg(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function fg(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||T(t,`.md`)}function pg(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function mg(e,t){let n=e.split(/\r?\n/),r=RegExp(`^(#{2,6})\\s+${t}\\b`,`i`),i=n.findIndex(e=>r.test(e));if(i<0)return;let a=[];for(let e of n.slice(i+1)){if(/^##\s+/.test(e))break;a.push(e)}let o=a.join(`
|
|
104
|
+
`):e.message,success:e.success,...e.data===void 0?{}:{data:e.data}},uiIntents:r}}async function Zm(e,t,n){let r=t.getAdapters();try{switch(e.type){case`provider-hot-swap`:{let{orgPolicy:n}=t;return n?.allowedProviders&&!n.allowedProviders.includes(e.profileName)?{message:zm(`Provider "${e.profileName}" is not allowed by your organization policy. Allowed: ${n.allowedProviders.join(`, `)}.`,n.adminContact),success:!1}:(await t.switchProvider(e.profileName),null)}case`output-style-change`:{let i=r.outputStyleRegistry;if(!i)return Y(e.type,`an output-style registry adapter`);let a=i.getOutputStyle(e.styleId);if(!a){let t=i.listOutputStyles().map(e=>e.id).join(`, `);return{success:!1,message:`Unknown output style "${e.styleId}". Available: ${t||`(none)`}`}}let o=r.settings;return o?(o.write({...o.read(),outputStyle:e.styleId}),t.applyOutputStyle(a),n.push(`Output style: ${a.name}`),null):Y(e.type,`a settings adapter`)}case`language-change`:{let t=r.settings;return t?r.process?(t.write({...t.read(),language:e.language}),n.push(`Restarting...`),r.process.requestRestart(`other`,`Language change restart`),null):Y(e.type,`a process adapter (restart)`):Y(e.type,`a settings adapter`)}case`settings-reset`:{let t=r.settings;if(!t?.delete)return Y(e.type,`a settings adapter with delete()`);if(!r.process)return Y(e.type,`a process adapter (exit)`);let i=t.delete();return n.push(i?`User settings deleted. Exiting...`:`No user settings found. Exiting...`),r.process.requestExit(`other`),null}case`session-exit`:return r.process?(r.process.requestExit(e.reason??`prompt_input_exit`),null):Y(e.type,`a process adapter`);case`session-restart`:return r.process?(r.process.requestRestart(e.reason,e.message),null):Y(e.type,`a process adapter`);case`session-rename`:return t.renameSession(e.name),null;case`workspace-move`:return r.workspace?(n.push(await t.moveWorkspace(e.path)),null):Y(e.type,`a host that can start a session elsewhere`);case`statusline-settings-patch`:{let t=r.settings;if(!t)return Y(e.type,`a settings adapter`);if(!Gm(e.patch))return Ym(e.type,Error(`invalid statusline settings patch`));let n=t.read(),i={...Km(n),...e.patch};return t.write({...n,statusline:i}),null}case`appearance-settings-patch`:{let t=r.settings;if(!t)return Y(e.type,`a settings adapter`);if(!Nm(e.patch))return Ym(e.type,Error(`invalid appearance settings patch`));let n=t.read(),i={...Pm(n),...e.patch};return t.write({...n,theme:i.theme,syntaxHighlighting:i.syntaxHighlighting,reducedMotion:i.reducedMotion}),null}case`remote-control-enable`:{if(t.invocationSource!==`user`)return{success:!1,message:"Cannot apply 'remote-control-enable': only the operator at this terminal can pair a device. Run `/remote-control` on the host terminal."};let i=r.remoteControl?.enable;return i?(n.push(await i.call(r.remoteControl)),null):Y(e.type,`a remote-control adapter with enable()`)}case`remote-control-stop`:{let t=r.remoteControl?.stop;return t?(n.push(await t.call(r.remoteControl)),null):Y(e.type,`a remote-control adapter with stop()`)}}}catch(t){return Ym(e.type,t)}}function Qm(e,t,n){return t===void 0?e===`model`?n??void 0:e===`user`?We:void 0:t}function $m(e,t,n){for(let r of e)n({intent:r,...t===void 0?{}:{requesterDriverId:t}})}function eh(e,t){let n=bd(e,t);return Object.freeze({kind:`host`,scope:e,displayName:t,source:n,read:()=>{if(!M(t))return{};let e=It(t,`utf8`);try{return JSON.parse(e)}catch(e){throw new yd(t,e instanceof Error?e.message:String(e))}},write:e=>{Et(ze(t)),Ot(t),Ht(t,`${JSON.stringify(e,null,2)}\n`,{encoding:`utf8`,mode:384})}})}function th(e,t){let n=Dc(t,e),r=ac(e),i=n.target,a=n.relativePath,o=Object.freeze({kind:`project`,scope:i,displayName:a,relativePath:a,reader:r});return Object.freeze({kind:`project`,scope:i,displayName:a,source:o,read:()=>{let e=r.readText(a,`read project settings for update`);if(e===void 0)return{};try{return JSON.parse(e)}catch(e){throw new yd(a,e instanceof Error?e.message:String(e))}},write:e=>{n.writeText(`${JSON.stringify(e,null,2)}\n`)}})}function nh(e,t){if(process.platform!==`linux`||e?.status!==`trusted`)return;let n=t?.find(e=>e.scope===`project-local`);if(n!==void 0)return t=>{let r=Tc(e.authority,{status:`approved`,target:`project-local`,relativePath:n.relativePath,purpose:`persist user-approved project permission`}),i=th(e.authority,r),a=i.read(),o=typeof a.permissions==`object`&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{},s=Array.isArray(o.allow)?o.allow:[];s.includes(t)||i.write({...a,permissions:{...o,allow:[...s,t]}})}}function rh(e){return e.commandSemanticRoles?e.commandSemanticRoles:(e.commandModules?.flatMap(e=>e.systemCommands??[])??[]).reduce((e,t)=>t.semanticRole?{...e,[t.semanticRole]:t.name}:e,{})}function ih(e,t){let{mergedConfig:n,cwd:r,context:i,projectInfo:a,sessionId:o,contextCapacityHint:s,contributionSources:c,skillRoots:l}=t,u=nh(e.projectAccess,e.projectSettingsPaths);return{config:n,cwd:r,context:i,contributionSources:c,skillRoots:l,...e.pluginSkills===void 0?{}:{pluginSkills:e.pluginSkills},projectInfo:a,permissionMode:e.permissionMode,baselinePermissionAllow:e.baselinePermissionAllow,maxTurns:e.maxTurns,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},terminal:ir,sessionLogger:e.sessionLogSink===void 0?new pt:new it(e.sessionLogSink),...e.transcriptPath===void 0?{}:{transcriptPath:e.transcriptPath},permissionHandler:e.permissionHandler,...u===void 0?{}:{persistProjectPermission:u},...e.askHandler?{ask:e.askHandler}:{},provider:e.provider,onTextDelta:e.onTextDelta,...e.onThinkingDelta===void 0?{}:{onThinkingDelta:e.onThinkingDelta},onContextUpdate:e.onContextUpdate,onCompactEvent:e.onCompactEvent,...e.onUsageRecorded===void 0?{}:{onUsageRecorded:e.onUsageRecorded},onToolExecution:e.onToolExecution,checkpointHistory:e.checkpointHistory,sessionId:o,allowedTools:e.allowedTools,deniedTools:e.deniedTools,disableBuiltInHookExecutors:e.disableBuiltInHookExecutors,commandHookShell:e.commandHookShell,model:e.model,...e.effort===void 0?{}:{effort:e.effort},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},appendSystemPrompt:e.appendSystemPrompt,...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},...e.persona===void 0?{}:{persona:e.persona},...e.systemPrompt?{systemPromptBuilder:()=>e.systemPrompt}:{},...e.guardrails===void 0?{}:{guardrails:e.guardrails},...e.retrievalAdapter===void 0?{}:{retrievalAdapter:e.retrievalAdapter},backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.resumeSessionStore===void 0?{}:{resumeSessionStore:e.resumeSessionStore},...e.agentDefinitions?{agentDefinitions:e.agentDefinitions}:{},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.commandModules?.some(e=>e.sessionRequirements?.includes(`runtime`))?{enableAgentRuntime:!0}:{},...e.enableParallelSubagents===void 0?{}:{enableParallelSubagents:e.enableParallelSubagents},...e.selfVerification===void 0?{}:{selfVerification:e.selfVerification},...e.commandModules||e.commandDescriptors?{commandDescriptors:[...e.commandDescriptors??[],...e.commandModules?.flatMap(e=>e.commandDescriptors??[])??[]]}:{},commandSemanticRoles:rh(e),modelCommandExecutor:e.modelCommandExecutor,modelCommandToolPrefix:e.modelCommandToolPrefix,subagentHookEnvironmentNames:e.subagentHookEnvironmentNames,observerFailureWarningCode:e.observerFailureWarningCode,isModelCommandInvocable:e.isModelCommandInvocable,editCheckpointRecorder:e.editCheckpointRecorder,reversibleExecution:e.reversibleExecution,sandboxClient:e.sandboxClient,...e.disableAutoMode===!0?{disableAutoMode:!0}:{},sandboxType:e.sandboxType,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.defaultTools?{defaultTools:e.defaultTools}:{},includeGoalTool:!0,includeSessionLoopDecisionTool:!0,...e.peerReply?{peerReply:e.peerReply}:{},...e.peerSendFile?{peerSendFile:e.peerSendFile}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},...s===void 0?{}:{contextCapacityHint:s}}}function ah(e,t){return{...e.sandboxClient?{sandboxClient:e.sandboxClient}:{},...e.sandboxType?{sandboxType:e.sandboxType}:{},...e.workspaceManifest?{workspaceManifest:e.workspaceManifest}:{},...e.sandboxWorkspaceRoot?{sandboxWorkspaceRoot:e.sandboxWorkspaceRoot}:{},...t?{sandboxSnapshotId:t}:{}}}async function oh(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await $e(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function sh(e){if(!e.sandboxSnapshotId)return!1;if(!e.sandboxClient?.restore)throw Error(`sandboxSnapshotId requires sandboxClient with restore().`);return await e.sandboxClient.restore(e.sandboxSnapshotId),!0}function ch(e){return{...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt}}}const lh=Object.freeze({defaultTrustLevel:`most-restrictive`,disabledHooks:`accumulate`,provider:`object-merge`,"permissions.allow":`union`,"permissions.deny":`union`,"permissions.ask":`union`,env:`object-merge`,providers:`object-merge`,enabledPlugins:`object-merge`,extraKnownMarketplaces:`replace`,autoCompactThreshold:`replace`,hooks:`per-event`,taskContext:`object-merge`,sandbox:`object-merge`});function uh(e){let t=dh(e);return{settings:t.settings,hookSources:t.hookSources}}function dh(e){let t=new Set,n={},r=[];for(let{settings:i,source:a}of e){let e=xh(i.hooks,t);a!==void 0&&fh(e,a,r);for(let e of i.disabledHooks??[])t.add(e);n=ph(n,{...i,hooks:e},t)}return{settings:n,hookSources:r}}function fh(e,t,n){for(let[r,i]of Object.entries(e??{}))for(let e of i??[])for(let i of e.hooks)n.push({event:r,type:i.type,source:t})}function ph(e,t,n){return{...e,...t,defaultTrustLevel:wh(e.defaultTrustLevel,t.defaultTrustLevel),disabledHooks:mh(n),provider:Th(e.provider,t.provider),permissions:hh(e.permissions,t.permissions),env:{...e.env??{},...t.env??{}},providers:_h(e.providers,t.providers),enabledPlugins:gh(e.enabledPlugins,t.enabledPlugins),extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold,hooks:vh(e.hooks,t.hooks),taskContext:gh(e.taskContext,t.taskContext),sandbox:gh(e.sandbox,t.sandbox)}}function mh(e){return e.size===0?void 0:[...e]}function hh(e,t){if(e!==void 0||t!==void 0)return{allow:bh(e?.allow,t?.allow),deny:bh(e?.deny,t?.deny),ask:bh(e?.ask,t?.ask)}}function gh(e,t){if(e!==void 0||t!==void 0)return{...e,...t}}function _h(e,t){if(e!==void 0||t!==void 0)return Sh(e,t)}function vh(e,t){if(e!==void 0||t!==void 0)return yh(e,t)}function yh(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{})){if(r===void 0)continue;let t=e,i=n[t];n[t]=i===void 0?[...r]:[...i,...r]}return n}function bh(e,t){return e===void 0?t===void 0?void 0:[...t]:t===void 0?[...e]:[...new Set([...e,...t])]}function xh(e,t){if(e===void 0||t.size===0)return e;let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=r;n[e]=i.filter(e=>e.id===void 0||!t.has(e.id))}return n}function Sh(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]=Th(n[e],r);return n}const Ch={safe:0,moderate:1,full:2};function wh(e,t){return e===void 0?t:t===void 0||Ch[e]<=Ch[t]?e:t}function Th(e,t){if(e===void 0&&t===void 0)return;if(t?.apiKeyRef!==void 0&&(t.apiKey!==void 0||t.apiKeyEnv!==void 0))throw Error(`Provider settings have conflicting credential origins`);let n={...e,...t};return t?.apiKeyRef===void 0?(t?.apiKey!==void 0||t?.apiKeyEnv!==void 0)&&delete n.apiKeyRef:(delete n.apiKey,delete n.apiKeyEnv),t?.baseURL!==void 0&&t.baseURL!==e?.baseURL&&(t?.apiKeyRef===void 0?t?.apiKey===void 0?t?.apiKeyEnv===void 0?(delete n.apiKey,delete n.apiKeyEnv,delete n.apiKeyRef,e?.apiKeyRef!==void 0&&(n.apiKey=``)):delete n.apiKey:delete n.apiKeyEnv:(delete n.apiKey,delete n.apiKeyEnv)),n}const Eh=k.lazy(()=>k.union([k.string(),k.number(),k.boolean(),k.null(),k.undefined(),k.date(),k.array(Eh),k.record(k.string(),Eh)])),Dh=k.object({service:k.string().min(1),account:k.string().min(1)}).strict(),Oh=k.object({name:k.string().optional(),model:k.string().optional(),apiKey:k.string().optional(),apiKeyRef:Dh.optional(),baseURL:k.string().optional(),timeout:k.number().optional(),options:k.record(k.string(),Eh).optional()}),kh=k.object({type:k.string().optional(),model:k.string().optional(),apiKey:k.string().optional(),apiKeyRef:Dh.optional(),baseURL:k.string().optional(),timeout:k.number().optional(),options:k.record(k.string(),Eh).optional()}),Ah=k.object({allow:k.array(k.string()).optional(),deny:k.array(k.string()).optional(),ask:k.array(k.string()).optional()}),jh=k.record(k.string(),k.string()).optional(),Mh=k.object({type:k.literal(`command`),command:k.string(),timeout:k.number().optional()}),Nh=k.object({type:k.literal(`http`),url:k.string(),headers:k.record(k.string(),k.string()).optional(),timeout:k.number().optional()}),Ph=k.object({type:k.literal(`prompt`),prompt:k.string(),model:k.string().optional()}),Fh=k.object({type:k.literal(`agent`),agent:k.string(),maxTurns:k.number().optional(),timeout:k.number().optional()}),Ih=k.object({type:k.literal(`guardrail`),guardrails:k.array(k.string()).optional()}),Lh=k.discriminatedUnion(`type`,[Mh,Nh,Ph,Fh,Ih]),X=k.object({id:k.string().optional(),matcher:k.string(),hooks:k.array(Lh)}),Rh=k.object({PreToolUse:k.array(X).optional(),PostToolUse:k.array(X).optional(),SessionStart:k.array(X).optional(),SessionEnd:k.array(X).optional(),Stop:k.array(X).optional(),StopFailure:k.array(X).optional(),PreCompact:k.array(X).optional(),PostCompact:k.array(X).optional(),UserPromptSubmit:k.array(X).optional(),SubagentStart:k.array(X).optional(),SubagentStop:k.array(X).optional(),WorktreeCreate:k.array(X).optional(),WorktreeRemove:k.array(X).optional(),PreModelCall:k.array(X).optional(),PostModelCall:k.array(X).optional(),PermissionDecision:k.array(X).optional()}).optional(),zh=k.record(k.string(),k.boolean()).optional(),Bh=k.object({source:k.object({type:k.enum([`github`,`git`,`local`,`url`]),repo:k.string().optional(),url:k.string().optional(),path:k.string().optional(),ref:k.string().optional()})}),Vh=k.record(k.string(),Bh).optional().catch(void 0),Hh=k.union([k.number().gt(0).lte(1),k.literal(!1)]).optional(),Uh=k.object({enabled:k.boolean().optional(),options:k.record(k.string(),Eh).optional()}),Wh=k.object({enabled:k.boolean().optional(),autoAllowBashIfSandboxed:k.boolean().optional(),excludedCommands:k.array(k.string()).optional(),failIfUnavailable:k.boolean().optional(),filesystem:k.object({allowWrite:k.array(k.string()).optional(),denyRead:k.array(k.string()).optional()}).optional(),network:k.object({enabled:k.boolean().optional()}).optional()}),Gh=k.object({defaultTrustLevel:k.enum([`safe`,`moderate`,`full`]).optional(),language:k.string().optional(),preset:k.string().optional(),currentProvider:k.string().optional(),providers:k.record(k.string(),kh).optional(),provider:Oh.optional(),permissions:Ah.optional(),env:jh,commandEnvAllow:k.array(k.string()).optional(),hooks:Rh,disabledHooks:k.array(k.string()).optional(),enabledPlugins:zh,extraKnownMarketplaces:Vh,autoCompactThreshold:Hh,transports:k.record(k.string(),Uh).optional(),sandbox:Wh.optional(),taskContext:k.object({enabled:k.boolean().optional(),dir:k.string().min(1).optional()}).optional()}),Kh=/position (\d+)/;function qh(e){let t=Kh.exec(e.message);return t===null?void 0:Number(t[1])}function Jh(e){let t=e.code;return typeof t==`string`?t:void 0}function Yh(e){let t;try{t=Cd(e,`load configuration settings`)}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`unreadable`,cause:{state:`unreadable`,errno:Jh(n)},error:n}}if(t===void 0)return{source:e,state:`absent`};let n=t.trim();if(n.length===0)return{source:e,state:`empty`,cause:{state:`empty`}};try{return{source:e,state:`ok`,raw:JSON.parse(n)}}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`invalid-json`,cause:{state:`invalid-json`,offset:qh(n)},error:n}}}function Xh(e){if(e.state!==`ok`)return e;let t=Gh.safeParse(e.raw);return t.success?{...e,settings:t.data}:{...e,state:`schema-invalid`,cause:{state:`schema-invalid`,issues:t.error.issues.map(e=>({path:e.path.map(String).join(`.`),code:e.code}))},schemaMessage:t.error.message}}function Zh(e){return e.map(Yh).map(Xh)}function Qh(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0){if(n===`permissions`&&typeof r==`object`&&r){for(let e of[`allow`,`deny`,`ask`])r[e]!==void 0&&t.push(`permissions.${e}`);continue}t.push(n)}return t}function $h(e){let t=new Map;for(let n of e)if(n.settings!==void 0)for(let e of Qh(n.settings)){let r=t.get(e)??[];r.push(n.displayName),t.set(e,r)}return[...t.entries()].map(([e,t])=>({key:e,rule:lh[e]??`replace`,contributors:t}))}function eg(e){let t=Zh(e).map(e=>({source:e.source,displayName:e.source.displayName,kind:e.source.kind,scope:e.source.scope,state:e.state,...e.cause===void 0?{}:{cause:e.cause},...e.settings===void 0?{}:{settings:e.settings}})),n=t.some(e=>e.state!==`ok`&&e.state!==`absent`),r=uh(t.flatMap(e=>e.settings===void 0?[]:[{settings:e.settings,source:e.displayName}]));return{layers:t,merged:r.settings,partial:n,provenance:$h(t),hookSources:r.hookSources}}const tg={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[],ask:[]},env:{}};function ng(e){if(e.state===`empty`)throw new yd(e.source.displayName,`the settings file is empty`);if(e.state===`invalid-json`)throw new yd(e.source.displayName,e.error?.message??`invalid JSON`);if(e.state===`unreadable`)throw e.error}function rg(e,t){return e.startsWith(`$ENV:`)?t[e.slice(5)]??e:e}function ig(e,t){let n=e.provider?.apiKey===void 0?e.provider:ag(e.provider,t);if(e.providers!==void 0){let r=Object.fromEntries(Object.entries(e.providers).map(([e,n])=>[e,ag(n,t)]));return{...e,provider:n,providers:r}}return{...e,provider:n}}function ag(e,t){if(e.apiKey===void 0)return e;let n=e.apiKey.startsWith(`$ENV:`);return{...e,apiKey:rg(e.apiKey,t),...n&&{apiKeyEnv:e.apiKey.slice(5)}}}function og(e){if(e.currentProvider!==void 0)return sg(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...tg.provider}}function sg(e){let t=e.currentProvider;if(t===void 0)throw Error(`currentProvider is required`);let n=e.providers?.[t];if(n===void 0)throw Error(`currentProvider "${t}" was not found in providers`);if(n.type===void 0)throw Error(`Provider profile "${t}" is missing type`);return{name:n.type,model:n.model??tg.provider.model,apiKey:n.apiKeyRef===void 0?n.apiKey??tg.provider.apiKey:void 0,...n.apiKeyRef!==void 0&&{apiKeyRef:n.apiKeyRef},...n.apiKeyEnv!==void 0&&{apiKeyEnv:n.apiKeyEnv},...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function cg(e){return{defaultTrustLevel:e.defaultTrustLevel??tg.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:og(e),permissions:{allow:e.permissions?.allow??tg.permissions.allow,deny:e.permissions?.deny??tg.permissions.deny,ask:e.permissions?.ask??tg.permissions.ask},env:e.env??tg.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold,taskContext:e.taskContext??void 0,...e.sandbox===void 0?{}:{sandbox:e.sandbox}}}async function lg(e,t={}){let n=Zh(e);for(let e of n)ng(e);let r=[];for(let e of n)if(e.state!==`absent`){if(e.state===`schema-invalid`||e.settings===void 0)throw Error(`Invalid settings in ${e.source.displayName}: ${e.schemaMessage}`);r.push({settings:ig(e.settings,t),source:e.source.displayName})}let i=uh(r);return{config:cg(i.settings),hookSources:i.hookSources}}const ug={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function dg(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function fg(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||T(t,`.md`)}function pg(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function mg(e,t){let n=e.split(/\r?\n/),r=RegExp(`^(#{2,6})\\s+${t}\\b`,`i`),i=n.findIndex(e=>r.test(e));if(i<0)return;let a=[];for(let e of n.slice(i+1)){if(/^##\s+/.test(e))break;a.push(e)}let o=a.join(`
|
|
105
105
|
`).trim();return o.length>0?o:void 0}function hg(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(\S.*)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function gg(e,t){return t&&e.branch===t?0:ug[e.status]}function _g(e){let t=[`### ${e.title}`,`- **Path:** \`${e.relativePath}\``];return t.push(`- **Status:** ${e.status}`),e.branch&&t.push(`- **Branch:** ${e.branch}`),e.scope&&t.push(`- **Scope:** ${e.scope}`),e.objective&&t.push(`- **Objective:** ${e.objective}`),e.openItems.length>0&&(t.push(`- **Open items:**`),t.push(...e.openItems.map(e=>` - ${e}`))),t.join(`
|
|
106
106
|
`)}function vg(e,t){let n=O(e),r=!1;for(;!r;){let e=D(n,`.git`);if(t.existsSync(e)){if(t.statSync(e).isDirectory())return e;let r=t.readFileSync(e,`utf8`).trim().match(/^gitdir:\s*(\S.*)$/)?.[1];if(r)return E(r)?r:O(n,r)}let i=ze(n);r=i===n,n=i}}function yg(e,t=new Go){let n=vg(e,t);if(!n)return;let r=D(n,`HEAD`);if(t.existsSync(r))return(t.readFileSync(r,`utf8`).trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1])?.trim()}function bg(e,t){return W(e).listDirectory(t,`discover project task context`).filter(e=>e.kind===`file`).map(e=>e.name).filter(e=>e!==`README.md`&&e.endsWith(`.md`)).sort((e,t)=>e.localeCompare(t)).map(e=>D(t,e))}function xg(e,t){let n=W(t).readText(e,`load project task context`);if(n===void 0)throw Error(`Task context file is missing: ${e}`);return{path:e,relativePath:e,title:fg(n,e),status:dg(pg(n,`Status`)),branch:pg(n,`Branch`),scope:pg(n,`Scope`),objective:mg(n,`Objective`),openItems:hg(n)}}function Sg(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>gg(e,t.currentBranch)-gg(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function Cg(e){return e.map(_g).join(`
|
|
107
107
|
|
|
@@ -128,4 +128,4 @@ Do not use emojis.`}function ma(){return`You are a worker subagent executing a s
|
|
|
128
128
|
`),n=this.projectNotesFileEntries.map(e=>e.content).join(`
|
|
129
129
|
|
|
130
130
|
`),r=this.rebuildSystemMessage(t,n,e);this.getSessionOrThrow().updateSystemMessage(r)}applyPersona(e){this.rebuildLivePrompt({persona:e})}getActiveOutputStyleId(){return this.activeOutputStyleId}applyOutputStyle(e){this.activeOutputStyleId=e.id,this.rebuildLivePrompt({outputStyle:e})}applySelfVerification(e){this.rebuildLivePrompt({selfVerification:e})}applyResponseLanguage(e){this.rebuildLivePrompt({language:e})}applyPresetSystemPrompt(e){this.rebuildLivePrompt({presetSystemPrompt:e})}applyCommandModuleSelection(e,t){return this.skillRouter.reapplyCommandModuleSelection(e,t)}getAgentJobCapability(){return this}getUserInteraction(){if((this.listeners.get(`ask_request`)?.size??0)!==0)return lx(this.askHandler,()=>this.getCommandInvocationSource())}resolvePermission(e,t,n){this.promptRegistry.resolvePermission(e,t,n??We)}resolveAsk(e,t,n){this.promptRegistry.resolveAsk(e,t,n??We)}canHandoffTerminal(){return this.terminalHandoffGate.canHandoffTerminal()}runWithTerminal(e){return this.terminalHandoffGate.runWithTerminal(e)}async forkSession(e={}){await this.ensureInitialized(),this.getSessionOrThrow().assertInputAllowed();let t=this.getSessionOrThrow();if(!this.sessionStore)throw Error(`Cannot fork: this session has no session store to write the copy to.`);return $p({source:t,fullHistory:()=>this.getFullHistory(),sessionStore:this.sessionStore,requestedName:e.name,sourceName:this.sessionName,sourceId:t.getSessionId(),cwd:this.getCwd()})}async moveWorkspace(e){await this.ensureInitialized();let t=this.getCommandHostAdapters().workspace;if(!t)throw Error(`Moving to another directory is not available in this environment.`);if(this.workspaceMovePending)throw Error(`A move to another directory is already under way.`);if(!this.sessionStore)throw Error(`This session does not save its conversation, so it cannot move it.`);let n=this.getSessionOrThrow();n.assertInputAllowed();let r=(this.getBackgroundTaskManager()?.list()??[]).filter(e=>![`completed`,`failed`,`cancelled`].includes(e.status)),i=im({requestedPath:e,workspace:this.workspace,executing:this.execCtrl.executing,liveBackgroundTasks:r.length,permissionMode:n.getPermissionMode(),rules:n.getPermissionRules(),source:{getHistory:()=>n.getHistory(),getSystemMessage:()=>n.getSystemMessage(),getToolSchemas:()=>n.getToolSchemas(),getFullHistory:()=>this.getFullHistory()},sessionName:this.sessionName??``}),a=i.record.name?i:{...i,record:{...i.record,name:T(i.targetCwd)}};this.persistCurrentSession(),this.workspaceMovePending=!0;try{await t.move(a)}catch(e){throw this.workspaceMovePending=!1,e}return`Moving to ${i.targetCwd}${i.restricted?` (restricted)`:``}...`}setAutoCompactThreshold(e,t=`session`){this.getSessionOrThrow().setAutoCompactThreshold(e),this.autoCompactThresholdSource=t,this.emit(`context_update`,this.getContextState()),this.persistCurrentSession()}clearConversationHistory(){this.getSessionOrThrow().clearHistory(),this.histTracker.clearHistory(),this.execCtrl.appViews.clear(),this.persistCurrentSession(),this.emit(`context_update`,this.getContextState()),this.emit(`history_cleared`)}getName(){return this.sessionName}getStatusSnapshot(){let e=this.getSessionOrThrow(),t;try{let e=this.getCwd();t={name:T(e),path:e}}catch{t=void 0}return{sessionId:e.getSessionId(),...this.sessionName===void 0?{}:{sessionName:this.sessionName},model:e.getModelId(),permissionMode:e.getPermissionMode(),effort:e.getModelEffort(),context:e.getContextState(),goal:this.getGoalState(),...this.setupRequired?{setupRequired:!0}:{},...t===void 0?{}:{workspace:t}}}listModels(){let e=M_(this.userSettingsSources),t=this.getSessionOrThrow();return V_(e.providers,e.currentProvider,t.getModelId(),this.providerDefinitions,this.orgPolicy?.allowedProviders)}isSetupRequired(){return this.setupRequired}attachTransport(e){e.attach(this)}setName(e){if(this.sessionStore&&this.session){let t;try{t=this.getSessionOrThrow().getSessionId()}catch{this.sessionName=e;return}W_(this.sessionStore,t,e)}this.sessionName=e}getBackgroundTaskManager(){if(this.session)return yi(this.session)??mo(this.session)?.backgroundTaskManager}reportBackgroundError(e,t=`background`){let n=Vn(e,this.providerErrorGuidance);this.histTracker.append(C(S(`Error: ${n}`,{metadata:{kind:`error`,source:t}}))),this.emit(`error`,e)}async captureSandboxSnapshot(){if(this.sandboxClient?.snapshot)try{this.sandboxSnapshotId=await this.sandboxClient.snapshot()}catch(e){let t=e instanceof Error?e:Error(String(e));this.histTracker.append(C(S(`Sandbox snapshot error: ${t.message}`))),this.emit(`error`,t)}}persistCurrentSession(e=!1,t,n){if(!this.sessionStore||!this.session){if(e)throw Error(`A session store is required for a resumable loop.`);return}let r=this.bgTracker.getState(),i=this.histTracker.getState();T_(this.sessionStore,this.session,this.sessionName,this.workspace.cwd,i.history,{tasks:r.tasks.filter(n=>{let r=n.metadata?.sessionLoopId;return typeof r!=`string`||!this.pendingLoopCreations.has(r)||e&&r===t}).map(e=>this.pendingLoopStops.has(e.id)?{...e,status:`cancelled`}:e),events:r.taskEvents,groups:r.groups,groupEvents:r.groupEvents},{events:i.memoryEvents,usedReferences:i.usedMemoryReferences},{events:i.skillActivationEvents},{references:i.contextReferences},{snapshotId:this.sandboxSnapshotId},this.goalController.getState()??void 0,this.planController.getState()??void 0,this.histTracker.getActiveBranchPointer(),e,n??this.selfPacedLoops.snapshotForOrdinarySave())}async setGoal(e,t={}){await this.ensureInitialized();let{goal:n,prompt:r}=this.goalController.start(e,t);return this.emit(`goal_event`,{type:`goal_started`,goal:n}),this.persistCurrentSession(),this.scheduleGoalTurn(r,n),n}getGoalState(){return this.goalController.getState()}cancelGoal(){let e=this.goalController.cancel();return e&&(this.emit(`goal_event`,{type:`goal_stopped`,goal:e}),this.persistCurrentSession()),e}async setPlan(e,t=[]){await this.ensureInitialized();let n=this.getSessionOrThrow(),r=this.planController.start(e,t);return n.setPermissionMode(`plan`),this.emit(`plan_event`,{type:`plan_created`,plan:r}),this.persistCurrentSession(),r}getPlanState(){return this.planController.getState()}approvePlan(){let e=this.getSessionOrThrow();this.planController.getState()?.phase===`planning`&&this.planController.requestApproval();let t=this.planController.approve();return e.setPermissionMode(t.nextMode),this.emit(`plan_event`,{type:`plan_approved`,plan:t.plan}),this.persistCurrentSession(),t.plan}revertPlan(){let e=this.getSessionOrThrow(),t=this.planController.revert();return e.setPermissionMode(t.nextMode),this.emit(`plan_event`,{type:`plan_reverted`,plan:t.plan}),this.persistCurrentSession(),t.plan}scheduleGoalTurn(e,t){if(this.execCtrl.shuttingDown)return;let n=`goal:${t.id}:${t.iterations}`,r=`Goal: ${t.objective} (iteration ${t.iterations+1} of ${t.maxIterations})`;setTimeout(()=>this.requestWakeup(e,n,r),0)}handleGoalTurnComplete(e){if(!this.goalController.isActive()||this.currentTurnSource!==`agent-wakeup`)return;let t=this.goalController.onTurnComplete(e);t&&(this.persistCurrentSession(),t.action===`continue`?(this.emit(`goal_event`,{type:`goal_progress`,goal:t.goal}),this.scheduleGoalTurn(t.prompt,t.goal)):this.emit(`goal_event`,{type:`goal_stopped`,goal:t.goal}))}resumeGoalIfActive(){let e=this.goalController.getState();!e||e.status!==`active`||this.ensureInitialized().then(()=>{!this.goalController.isActive()||this.execCtrl.shuttingDown||this.scheduleGoalTurn(gs(e),e)}).catch(e=>this.reportBackgroundError(e instanceof Error?e:Error(String(e)),`goal-resume`))}async switchProvider(e){let t=this.getSessionOrThrow(),{settings:n,provider:r}=await I_(e,this.providerDefinitions,this.userSettingsSources,this.providerEnvironment,this.resolveProviderCredential);if(this.setupRequired=!1,this.modelFallback===void 0){t.swapProvider(r,n.model);return}let{entries:i,options:a}=this.modelFallback,o=Wd({provider:r,entries:i,settings:M_(this.userSettingsSources),primary:{profile:e,config:n},providerDefinitions:this.providerDefinitions,...this.resolveProviderCredential!==void 0&&{resolveCredential:this.resolveProviderCredential},...this.providerEnvironment!==void 0&&{environment:this.providerEnvironment},...this.orgPolicy?.allowedProviders!==void 0&&{allowedProviders:this.orgPolicy.allowedProviders},providerOptions:a});for(let e of o.notices)this.histTracker.append(C(S(e)));t.swapProvider(o.provider,n.model)}async executeCommand(e,t,n=`user`,r,i,a){if(this.orgPolicy?.blockedCommands?.includes(e))return{message:zm(`Command /${e} is blocked by your organization policy.`,this.orgPolicy.adminContact),success:!1};if(e===`goal`&&Cs(t)&&this.execCtrl.executing&&this.goalController.isActive()){let e=this.cancelGoal();return this.abort(),this.statusPush.push(),e?{message:`Goal cancelled: ${e.objective}`,success:!0}:{message:`No active goal to cancel.`,success:!1}}let o=e===`loop`&&ix(t)&&this.execCtrl.executing?await this.skillRouter.executeCommand(e,t,n,r,i,a):await super.executeCommand(e,t,n,r,i,a);if(o===null)return null;if(o.data?.pluginRegistryReloaded===!0&&n!==`model`){this.pluginSkills=this.loadPluginSkills(),this.skillRouter.replacePluginSkills(this.pluginSkills);let e=this.skillRouter.commandExecutor.getSemanticRoles().skillActivation;this.rebuildLivePrompt({skills:e&&this.skillRouter.commandExecutor.isModelInvocable(e)?this.skillRouter.listSkills().filter(e=>e.modelInvocable).map(e=>({name:e.name,description:e.description})):[]})}let s=await Xm(o,{getAdapters:()=>this.getCommandHostAdapters(),invocationSource:n,orgPolicy:this.orgPolicy,switchProvider:e=>this.switchProvider(e),moveWorkspace:e=>this.moveWorkspace(e),applyOutputStyle:e=>this.applyOutputStyle(e),renameSession:e=>{this.setName(e),this.emit(`session_renamed`,{name:e})}});return $m(s.uiIntents,Qm(n,r,this.execCtrl.activeDriverId),e=>this.emit(`ui_intent`,e)),this.statusPush.push(),s.result}},dS=class extends Error{code;name=`SessionChangeRefusal`;constructor(e,t){super(t),this.code=e}},fS=class extends Error{code;name=`SessionDeleteRefusal`;constructor(e,t){super(t),this.code=e}};async function pS(e,t,n=5e3){let r;await Promise.race([e.shutdown({reason:`other`,message:t}).catch(()=>void 0),new Promise(e=>{r=setTimeout(e,n)})]),r!==void 0&&clearTimeout(r)}var mS=class{currentSession;listeners=new Map;shutdownTimeoutMs;constructor(e,t={}){this.currentSession=e,this.shutdownTimeoutMs=t.shutdownTimeoutMs??5e3}get current(){return this.currentSession}moveTo(e){let t=this.swap(e);t!==void 0&&this.emitSwitched(t.sessionId)}async replace(e,t=`session switched`){let n=this.swap(e);n!==void 0&&(await pS(n.previous,t,this.shutdownTimeoutMs),this.emitSwitched(n.sessionId))}swap(e){let t=this.currentSession;if(e===t)return;let n=e.getSession().getSessionId();for(let[n,r]of this.listeners)for(let i of r)t.off(n,i),e.on(n,i);return this.currentSession=e,{previous:t,sessionId:n}}emitSwitched(e){for(let t of[...this.listeners.get(`session_switched`)??[]])t({sessionId:e})}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t),this.currentSession.on(e,t)}off(e,t){this.listeners.get(e)?.delete(t),this.currentSession.off(e,t)}get isInitialized(){return this.currentSession.isInitialized}shutdown=(...e)=>this.currentSession.shutdown(...e);submit=(...e)=>this.currentSession.submit(...e);abort=(...e)=>this.currentSession.abort(...e);cancelQueue=(...e)=>this.currentSession.cancelQueue(...e);setGoal=(...e)=>this.currentSession.setGoal(...e);getGoalState=(...e)=>this.currentSession.getGoalState(...e);cancelGoal=(...e)=>this.currentSession.cancelGoal(...e);isExecuting=(...e)=>this.currentSession.isExecuting(...e);getPendingPrompt=(...e)=>this.currentSession.getPendingPrompt(...e);getPendingCount=(...e)=>this.currentSession.getPendingCount(...e);getActiveDriverId=(...e)=>this.currentSession.getActiveDriverId(...e);getMessages=(...e)=>this.currentSession.getMessages(...e);getFullHistory=(...e)=>this.currentSession.getFullHistory(...e);getMessagesDisplay=(...e)=>this.currentSession.getMessagesDisplay(...e);getContextState=(...e)=>this.currentSession.getContextState(...e);getSession=(...e)=>this.currentSession.getSession(...e);getCwd=(...e)=>this.currentSession.getCwd(...e);executeCommand=(...e)=>this.currentSession.executeCommand(...e);listCommands=(...e)=>this.currentSession.listCommands(...e);listSkills=(...e)=>this.currentSession.listSkills(...e);getStatusSnapshot=(...e)=>this.currentSession.getStatusSnapshot(...e);listModels=(...e)=>this.currentSession.listModels(...e);listRuntimeTools=(...e)=>this.currentSession.listRuntimeTools(...e);invokeRuntimeTool=(...e)=>this.currentSession.invokeRuntimeTool(...e);readToolAppView=(...e)=>this.currentSession.readToolAppView(...e);resolvePermission=(...e)=>this.currentSession.resolvePermission(...e);resolveAsk=(...e)=>this.currentSession.resolveAsk(...e);listBackgroundTasks=(...e)=>this.currentSession.listBackgroundTasks(...e);getBackgroundTask=(...e)=>this.currentSession.getBackgroundTask(...e);cancelBackgroundTask=(...e)=>this.currentSession.cancelBackgroundTask(...e);closeBackgroundTask=(...e)=>this.currentSession.closeBackgroundTask(...e);sendBackgroundTask=(...e)=>this.currentSession.sendBackgroundTask(...e);readBackgroundTaskLog=(...e)=>this.currentSession.readBackgroundTaskLog(...e);listBackgroundJobGroups=(...e)=>this.currentSession.listBackgroundJobGroups(...e);getBackgroundJobGroup=(...e)=>this.currentSession.getBackgroundJobGroup(...e);createBackgroundJobGroup=(...e)=>this.currentSession.createBackgroundJobGroup(...e);waitBackgroundJobGroup=(...e)=>this.currentSession.waitBackgroundJobGroup(...e);getExecutionWorkspaceSnapshot=(...e)=>this.currentSession.getExecutionWorkspaceSnapshot(...e);readExecutionWorkspaceDetail=(...e)=>this.currentSession.readExecutionWorkspaceDetail(...e);stopWaitingSelfPacedLoop=(...e)=>this.currentSession.stopWaitingSelfPacedLoop(...e);listAgentDefinitions=(...e)=>this.currentSession.listAgentDefinitions(...e);getDefaultAgentType=(...e)=>this.currentSession.getDefaultAgentType(...e);setDefaultAgentType=(...e)=>this.currentSession.setDefaultAgentType(...e);listAgentJobs=(...e)=>this.currentSession.listAgentJobs(...e);spawnAgentJob=(...e)=>this.currentSession.spawnAgentJob(...e);sendAgentJob=(...e)=>this.currentSession.sendAgentJob(...e);cancelAgentJob=(...e)=>this.currentSession.cancelAgentJob(...e);closeAgentJob=(...e)=>this.currentSession.closeAgentJob(...e)};const hS=4,gS=3e5;function _S(e,t=Date.now()){return e.isExecuting()||e.getLocalActivityStatus?.()===`needs-input`||e.getPendingPrompt()!==null||e.getPendingCount()>0||e.listBackgroundTasks().some(e=>!Ye(e.status))?!0:(e.listSelfPacedLoops?.()??[]).some(e=>e.phase!==`stopped`&&e.phase!==`expired`&&Date.parse(e.expiresAt)>t)}const vS=`This runtime is stopping.`;var yS=class{options;entries=new Set;primaryEntry;building=new Map;closing=new Map;leases=new WeakMap;maxLive;idleGraceMs;isBusy;shutdownSession;clock=0;freshBuilds=0;drained;constructor(e){this.options=e,this.maxLive=e.maxLive??4,this.idleGraceMs=e.idleGraceMs??3e5,this.isBusy=e.isBusy??(e=>_S(e)),this.shutdownSession=e.shutdown??((e,t)=>pS(e,t)),this.primaryEntry=this.register(e.primary,void 0,0,!0)}bind(e){let t=this.primaryEntry,n=!1,r=new mS(t.session);return this.join(t,e),{role:e,slot:r,moveTo:i=>{let a=this.leases.get(i);if(a===void 0||a.state!==`held`)throw Error(`SessionPool: the lease was already used or cancelled.`);if(n)throw i.cancel(),Error(`SessionPool: the binding was released.`);if(this.drained!==void 0)throw i.cancel(),new dS(`stopping`,vS);if(a.state=`moved`,--a.entry.holds,a.entry===t){this.touch(t);return}let o=t;t=a.entry,this.join(t,e),this.leave(o,e),r.moveTo(t.session)},isLastDriver:()=>!n&&e===`drive`&&t.drivers===1,release:()=>{n||(n=!0,this.leave(t,e))}}}async acquire(e){if(this.assertOpen(),e!==void 0){await this.namePrimary();for(let t=this.closing.get(e);t!==void 0;)await t,t=this.closing.get(e);this.assertOpen();let t=this.findLive(e);if(t!==void 0)return t.holds+=1,this.touch(t),this.lease(t);let n=this.building.get(e);if(n!==void 0)return n.waiters+=1,this.lease(await n.ready)}return this.makeRoom(),this.lease(await this.startBuild(e).ready)}listLive(){let e=[];for(let t of this.entries){let n=this.entryId(t);n!==void 0&&e.push({sessionId:n,session:t.session,clients:t.clients,drivers:t.drivers})}return e}shutdownAll(e=`runtime host stopped`){if(this.drained!==void 0)return this.drained;let t=[...this.closing.values()];for(let n of this.entries)this.clearGrace(n),t.push(this.shutdownQuietly(n.session,e));this.entries.clear();for(let n of this.building.values())n.abandoned=!0,t.push(this.shutdownQuietly(n.session,e));return this.building.clear(),this.drained=Promise.all(t).then(()=>void 0),this.drained}assertOpen(){if(this.drained!==void 0)throw new dS(`stopping`,vS)}register(e,t,n,r=!1){let i={id:t,session:e,primary:r,clients:0,drivers:0,holds:n,lastActive:this.clock+=1,grace:void 0};return this.entries.add(i),i}entryId(e){if(e.id!==void 0)return e.id;try{e.id=e.session.getSession().getSessionId()}catch{return}return e.id}async namePrimary(){this.entryId(this.primaryEntry)===void 0&&await bS(this.primaryEntry.session).catch(()=>void 0)}findLive(e){for(let t of this.entries)if(this.entryId(t)===e)return t}lease(e){let t={entry:e,state:`held`},n={session:e.session,cancel:()=>{t.state===`held`&&(t.state=`cancelled`,--e.holds,this.touch(e),this.settle(e))}};return this.leases.set(n,t),n}join(e,t){e.clients+=1,t===`drive`&&(e.drivers+=1),this.touch(e)}leave(e,t){--e.clients,t===`drive`&&--e.drivers,this.touch(e),this.settle(e)}touch(e){e.lastActive=this.clock+=1,this.clearGrace(e)}settle(e){if(e.primary||e.clients>0||e.holds>0||this.drained!==void 0||!this.entries.has(e))return;this.clearGrace(e);let t=setTimeout(()=>{if(e.grace=void 0,!(!this.entries.has(e)||e.clients>0||e.holds>0)){if(this.busy(e)){this.settle(e);return}this.close(e,`session idle with no client`)}},this.idleGraceMs);t.unref?.(),e.grace=t}clearGrace(e){e.grace!==void 0&&(clearTimeout(e.grace),e.grace=void 0)}busy(e){try{return this.isBusy(e.session)}catch{return!0}}makeRoom(){if(this.entries.size+this.building.size<this.maxLive)return;let e;for(let t of this.entries)t.primary||t.clients>0||t.holds>0||this.busy(t)||(e===void 0||t.lastActive<e.lastActive)&&(e=t);if(e===void 0)throw new dS(`limit`,`${this.maxLive} sessions are live, the most this runtime keeps, and none of them can be closed now: each has a client on it or work in progress.`);this.close(e,`session closed to make room for another`)}close(e,t){this.clearGrace(e),this.entries.delete(e),this.trackClosing(this.entryId(e),this.shutdownQuietly(e.session,t))}trackClosing(e,t){let n=e??`\0closing#${this.clock+=1}`,r=t.then(()=>{this.closing.get(n)===r&&this.closing.delete(n)});this.closing.set(n,r)}shutdownQuietly(e,t){return this.shutdownSession(e,t).catch(()=>void 0)}startBuild(e){let t;try{t=this.options.build(e)}catch(e){throw xS(e)}let n=e??`\0new#${this.freshBuilds+=1}`,r={key:n,session:t,waiters:1,abandoned:!1},i=Object.assign(r,{ready:this.finishBuild(r,e)});return this.building.set(n,i),i}async finishBuild(e,t){try{await bS(e.session)}catch(n){if(this.building.delete(e.key),e.abandoned)throw new dS(`stopping`,vS);let r=this.shutdownQuietly(e.session,`session failed to start`);throw this.trackClosing(t,r),await r,xS(n)}if(this.building.delete(e.key),e.abandoned)throw new dS(`stopping`,vS);return this.register(e.session,t,e.waiters)}};async function bS(e){let t=e.whenInitialized;typeof t==`function`&&await t.call(e)}function xS(e){return new dS(`start_failed`,`The session could not be started: ${e instanceof Error?e.message:String(e)}`)}function SS(e){if(`session`in e){if(!e.session)throw Error(`buildRuntimeSession: injected session is required`)}else{if(!e.provider)throw Error(`buildRuntimeSession: provider is required`);if(!e.cwd)throw Error(`buildRuntimeSession: cwd is required`)}return new uS(e)}async function CS(e){let t=e.session;if(e.pool!==void 0&&`session`in t)throw Error(`startRuntimeHost: a session pool builds sessions from a recipe, not an injected session`);let n=SS(t),r=new mS(n),i=e.pool===void 0?void 0:new yS({primary:n,build:e=>SS({...t,resumeSessionId:e,forkSession:void 0,sessionName:void 0}),...e.pool});e.transportRegistry&&(e.bindTransports?.(r),await e.transportRegistry.startAll());let a=!1;return{session:r,...i===void 0?{}:{pool:i},async waitForCompletion(){return await e.transportRegistry?.waitForCompletion()??[]},async waitForFailure(){return e.transportRegistry?.waitForFailure()},async shutdown(t=`runtime host stopped`){a||(a=!0,e.transportRegistry&&await e.transportRegistry.stopAll().catch(()=>void 0),i===void 0?await pS(r,t):await i.shutdownAll(t))}}}function wS(e){return/^\/\S/.test(e)}function TS(e){let t=e.slice(1).trim().split(/\s+/);return{name:t[0]??``,args:t.slice(1).filter(e=>e.length>0)}}function ES(e){if(!wS(e))return{type:`user-message`,text:e};let{name:t,args:n}=TS(e);return{type:`slash-command`,name:t,args:n}}function DS(e){return e.map(e=>({name:e.name,description:e.description}))}function OS(e,t){let n=e=>{t.write({type:`assistant-chunk`,chunk:e})},r=e=>{t.write({type:`assistant-done`,fullText:e.response}),t.setBusy(!1)},i=e=>{t.write({type:`tool-call`,id:e.executionId??e.toolName,name:e.toolName,args:e.firstArg})},a=e=>{t.write({type:`tool-result`,id:e.executionId??e.toolName,name:e.toolName,result:e.toolResultData??e.result})},o=e=>{t.setBusy(!1),t.write({type:`error`,error:e})},s=()=>{t.setBusy(!1)},c=({id:n,request:r})=>{Promise.resolve(t.askUser(r)).then(t=>e.resolveAsk(n,t)).catch(()=>e.resolveAsk(n,{type:`cancelled`}))};return e.on(`text_delta`,n),e.on(`complete`,r),e.on(`tool_start`,i),e.on(`tool_end`,a),e.on(`error`,o),e.on(`interrupted`,s),e.on(`ask_request`,c),()=>{e.off(`text_delta`,n),e.off(`complete`,r),e.off(`tool_start`,i),e.off(`tool_end`,a),e.off(`error`,o),e.off(`interrupted`,s),e.off(`ask_request`,c)}}function kS(e){let{provider:t,cwd:n,channel:r,commandModules:i,projectAccess:a,userSettingsSources:o,environment:s,sessionStore:c,permissionMode:l}=e,u={provider:t,cwd:n,projectAccess:a,...o===void 0?{}:{userSettingsSources:o},...s===void 0?{}:{environment:s},sessionStore:c,commandModules:i,permissionMode:l};return AS({channel:r,commandModules:i,projectAccess:a,userSettingsSources:o,sessionStore:c,permissionMode:l},()=>SS(u))}function AS(e,t){let{channel:n}=e,r=null,i=null;async function a(e){if(!r)return;let t=ES(e);if(t.type===`user-message`){n.write({type:`user-message`,text:e}),n.setBusy(!0),await r.submit(e);return}let{name:i,args:a}=t,o=await r.executeCommand(i,a.join(` `));o?n.write({type:`command-result`,name:i,output:o.message}):n.write({type:`error`,error:Error(`Unknown command "/${i}". Type /help for help.`)})}return{async start(){r=t(),i=OS(r,n);let e=r.listCommands();n.setAvailableCommands(DS(e)),n.onSubmit(a),await n.start()},async stop(){try{i?.(),await n.stop()}catch{}await r?.shutdown(),r=null}}}function jS(e){let t=new Map;for(let n of e){let e=MS(n);e&&t.set(e.id,e)}return[...t.values()]}function MS(e){switch(e.type){case`background_task_created`:case`background_task_started`:case`background_task_updated`:case`background_task_completed`:case`background_task_failed`:case`background_task_cancelled`:return e.task;default:return}}function NS(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function PS(e,t){let n=xc(e);if(n.namespace!==t)throw Error(`Workspace session persistence requires the ${t} state namespace.`);return n}function FS(e){return e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0}function IS(e){let t=gt(e);return t.status===`valid`?{status:`valid`,record:t.record}:t.status===`corrupt`?{status:`corrupt`,issues:t.issues}:{status:`unsupported`,schemaVersion:t.schemaVersion}}function LS(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=_t(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}}}var RS=class{sessions;logs;constructor(e,t){this.sessions=PS(e,`sessions`),this.logs=PS(t,`session-logs`),Sc(this.sessions,this.logs)}save(e){mt(e.id),this.sessions.writeText(`${e.id}.json`,JSON.stringify({schemaVersion:lt,record:e},null,2),`persist project session record`)}load(e){mt(e);let t=this.sessions.readText(`${e}.json`,`load project session record`);return t===void 0?this.loadFromReplayLog(e):LS(t)}list(){let e=this.sessions.listDirectory(``,`list project session records`).filter(e=>e.kind===`file`&&e.name.endsWith(`.json`)).map(e=>e.name.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})),t=new Set(e.map(e=>e.id)),n=[...e];for(let e of this.listReplayLogIds())t.has(e)||n.push({id:e,outcome:this.outcomeForListedId(e)});return n.sort((e,t)=>FS(t)-FS(e))}outcomeForListedId(e){return vt(e)?this.load(e):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){mt(e),this.sessions.deleteFile(`${e}.json`,`delete project session record`)}loadFromReplayLog(e){try{let t=this.reconstructReplayLog(e);return t===void 0?{status:`missing`}:IS(t)}catch(e){if(!(e instanceof dt))throw e;return e.code===`UNSUPPORTED_VERSION`?{status:`unsupported`,schemaVersion:e.schemaVersion}:{status:`corrupt`,issues:e.issues}}}reconstructReplayLog(e){let t=bt(yt(new ol(this.logs,e)));if(!t.sessionId||t.messages.length===0)return;let n=t.backgroundTaskEvents,r=t.backgroundJobGroupEvents;return{id:t.sessionId,cwd:t.cwd??``,createdAt:t.createdAt??t.updatedAt??new Date(0).toISOString(),updatedAt:t.updatedAt??t.createdAt??new Date(0).toISOString(),messages:t.messages,history:t.history,backgroundTasks:jS(n),backgroundTaskEvents:n,backgroundJobGroups:NS(r),backgroundJobGroupEvents:r,skillActivationEvents:[],memoryEvents:t.memoryEvents}}listReplayLogIds(){return this.logs.listDirectory(``,`list project session logs`).filter(e=>e.kind===`file`&&e.name.endsWith(`.jsonl`)).map(e=>e.name.slice(0,-6))}};function zS(e={}){return new ct(e)}function BS(e){return vt(e)}function VS(e,t){return new RS(e,t)}function HS(e,t){return new st(e,t)}function US(e){return new at(e,{ownedRoot:ze(e)})}function WS(e){return new st(e,ze(e))}function GS(e,t){return(e?.list()??[]).flatMap(e=>e.outcome.status===`valid`?[e.outcome.record]:[]).filter(e=>e.cwd===t).sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime()).map(e=>{let t=$S(e.messages);return{id:e.id,...e.name===void 0?{}:{name:e.name},cwd:e.cwd,updatedAt:e.updatedAt,messageCount:e.messages.length,preview:QS(e.messages),...t===void 0?{}:{title:t}}})}function KS(e){return(e?.list()??[]).filter(e=>e.outcome.status!==`valid`)}function qS(e,t){return KS(e).filter(e=>JS(e.outcome)===t).map(e=>({id:e.id}))}function JS(e){return e.status===`corrupt`||e.status===`unsupported`?e.cwd:void 0}function YS(e,t){return GS(e,t)[0]?.id}function XS(e,t,n={}){return GS(e,t).find(e=>e.messageCount===0&&e.id!==n.excludeSessionId&&(n.otherClientsOf?.(e.id)??0)<=0&&(n.isBusy?.(e.id)??!1)===!1)?.id}function ZS(e,t){return(e?.list()??[]).find(e=>e.id===t||e.outcome.status===`valid`&&e.outcome.record.name===t)?.id}function QS(e){for(let t of[...e].reverse())if(t.role===`assistant`&&typeof t.content==`string`)return t.content.replace(/[\n\r]+/g,` `).trim();return``}function $S(e){for(let t of e){if(t.role!==`user`||typeof t.content!=`string`)continue;let e=eC(t.content);if(e.length>0)return e}}function eC(e){let t=e.replace(/[#*_~`]/g,` `).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\s+/g,` `).trim();return t.length<=60?t:`${t.slice(0,60).trimEnd()}…`}function tC(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`TurnNotRunError`}var nC=class{host;options;constructor(e,t={}){this.host=e,this.options=t}async receive(e){let t={id:e.message.id,sequence:e.message.sequence},n=e=>({outcome:`refused`,ack:{...t,state:`refused`,reason:e}});if(!e.admission.admitted)return n(e.admission.reason??`the peer was not admitted`);if(this.options.requireSameEnvironment===!0&&!on(e.admission))return n(`this session requires a same-environment peer; admission established '${e.admission.trust}'. A token proves possession, which is copyable, and says nothing about where the peer runs.`);let r=e.admission.origin;if(r===void 0)return n(`the admission names no sender, so an answer would have nowhere to go`);if(e.message.origin.sessionId!==r.sessionId)return n(`the message names sender ${JSON.stringify(e.message.origin.sessionId)}, but ${JSON.stringify(r.sessionId)} was admitted`);let{workspaceRelation:i}=e.message.origin,a={sessionId:r.sessionId,...r.driverId===void 0?{}:{driverId:r.driverId},...i===void 0?{}:{workspaceRelation:i}},o;try{o=await new Promise((t,n)=>{this.host.submit(e.message.text,a,t).then(t,n)})}catch(e){return n(e instanceof Error?e.message:`the session refused the submission`)}return{outcome:`accepted`,ack:{...t,state:`pending`},settled:o.completed.then(()=>({...t,state:`acknowledged`}),e=>({...t,state:`refused`,reason:tC(e)?e.reason:`the turn failed`}))}}};export{nx as $,Rr as $a,oc as $i,Cg as $n,Dd as $r,Nv as $t,Zx as A,Pa as Aa,_l as Ai,j_ as An,lm as Ar,Dy as At,Sx as B,ga as Ba,tl as Bi,a_ as Bn,jf as Br,$v as Bt,hS as C,ao as Ca,ml as Ci,tv as Cn,Pm as Cr,Ry as Ct,dS as D,Da,pl as Di,W_ as Dn,Dm as Dr,yy as Dt,mS as E,Va as Ea,dl as Ei,U_ as En,Om as Er,by as Et,Xx as F,Ta as Fa,Sl as Fi,p_ as Fn,zp as Fr,Yv as Ft,fx as G,Wi as Ga,Mc as Gi,zg as Gn,Pd as Gr,ty as Gt,Mx as H,pa as Ha,Lc as Hi,Gg as Hn,vf as Hr,Qv as Ht,Px as I,Ea as Ia,sl as Ii,l_ as In,Pp as Ir,Kv as It,bx as J,zi as Ja,Tc as Ji,Ig as Jn,Id as Jr,ry as Jt,hx as K,qi as Ka,Ac as Ki,Lg as Kn,Wd as Kr,oy as Kt,Vx as L,Ca as La,ol as Li,u_ as Ln,Hp as Lr,Jv as Lt,lS as M,Ma,Cl as Mi,M_ as Mn,dm as Mr,Gv as Mt,Hx as N,ka as Na,gl as Ni,P_ as Nn,pm as Nr,Wv as Nt,fS as O,Oa,hl as Oi,V_ as On,Tm as Or,My as Ot,Wx as P,Na as Pa,bl as Pi,N_ as Pn,em as Pr,Uv as Pt,ix as Q,li as Qa,G as Qi,bg as Qn,jd as Qr,Mv as Qt,Rx as R,Sa as Ra,nl as Ri,d_ as Rn,Cp as Rr,Xv as Rt,gS as S,po as Sa,fl as Si,rv as Sn,Nm as Sr,zy as St,_S as T,Ua as Ta,ul as Ti,Y_ as Tn,Em as Tr,Vy as Tt,Ax as U,Ji as Ua,Fc as Ui,Ug as Un,af as Ur,iy as Ut,Nx as V,ma as Va,el as Vi,Bg as Vn,_f as Vr,ay as Vt,Ox as W,na as Wa,jc as Wi,Kg as Wn,Fd as Wr,Zv as Wt,xx as X,di as Xa,bc as Xi,Tg as Xn,Ud as Xr,Hv as Xt,gx as Y,mi as Ya,xc as Yi,Z as Yn,Ld as Yr,ny as Yt,dx as Z,ui as Za,lc as Zi,Eg as Zn,Rd as Zr,Pv as Zt,wS as _,Do as _a,Du as _i,av as _n,ln as _o,Lm as _r,Py as _t,US as a,_s as aa,bd as ai,hv as an,Fr as ao,Zh as ar,db as at,SS as b,yo as ba,wu as bi,Q_ as bn,Mm as br,Iy as bt,GS as c,xs as ca,qu as ci,gv as cn,dr as co,Um as cr,rb as ct,YS as d,hs as da,Hu as di,pv as dn,Vn as do,qm as dr,Qy as dt,ac as ea,Ed as ei,Av as en,R as eo,wg as er,Fb as et,XS as f,ds as fa,Vu as fi,Z_ as fn,In as fo,Wm as fr,Zy as ft,AS as g,Eo as ga,Cu as gi,iv as gn,pn as go,Bm as gr,qy as gt,kS as h,Ko as ha,Eu as hi,cv as hn,Fn as ho,zm as hr,Ky as ht,VS as i,z as ia,Cd as ii,Sv as in,Mr as io,eg as ir,vb as it,eS as j,Aa as ja,vl as ji,F_ as jn,fm as jr,uy as jt,uS as k,ja as ka,yl as ki,H_ as kn,Cm as kr,wy as kt,KS as l,Cs as la,Bu as li,dv as ln,Zn as lo,Hm as lr,eb as lt,RS as m,Go as ma,Iu as mi,ov as mn,Rn as mo,Km as mr,Jy as mt,HS as n,nc as na,kd as ni,wv as nn,Nr as no,yg as nr,Ib as nt,WS as o,vs as oa,yd as oi,mv as on,pr as oo,th as or,ub as ot,ZS as p,ps as pa,Uu as pi,X_ as pn,Ln as po,Gm as pr,Xy as pt,mx as q,Ki as qa,Ec as qi,Rg as qn,Kd as qr,ey as qt,zS as r,Ls as ra,Sd as ri,Cv as rn,Ir as ro,Sg as rr,pb as rt,BS as s,ws as sa,Ju as si,fv as sn,vr as so,eh as sr,ob as st,nC as t,W as ta,wd as ti,kv as tn,Pr as to,xg as tr,Lb as tt,qS as u,gs as ua,Wu as ui,uv as un,Wn as uo,Vm as ur,$y as ut,ES as v,So as va,Tu as vi,$_ as vn,vn as vo,Im as vr,Ny as vt,yS as w,qa as wa,ll as wi,nv as wn,Am as wr,By as wt,CS as x,mo as xa,cl as xi,sv as xn,Fm as xr,Ly as xt,TS as y,Co as ya,Ou as yi,ev as yn,cn as yo,jm as yr,Fy as yt,Ix as z,wa as za,Zc as zi,c_ as zn,Nf as zr,ly as zt};
|
|
131
|
-
//# sourceMappingURL=interactive-
|
|
131
|
+
//# sourceMappingURL=interactive-DommsJxu.js.map
|