@robota-sdk/agent-framework 3.0.0-beta.87 → 3.0.0-beta.90

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.
@@ -101,7 +101,7 @@ Do not use emojis.`}function Qn(){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 iu(i.diagnostics).message}}function rd(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=nd(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 id(e,t=[]){return{roots:e.flatMap(e=>t.map(({root:t,kind:n})=>rd(e,t,n)))}}function ad(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function od(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function sd(e,t){return e.some(e=>od(e.name)===t)}function cd(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 ld(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??ud(),o=new td(e.contributionSources??[],e.skillRoots??[]),s=ad(e.commandDescriptors),l=s.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,u=l?hr(s,e.modelCommandToolPrefix):void 0,d=sd(s,e.commandSemanticRoles?.skillActivation??``)?ed(o.getCommands(),e.pluginSkills??[]).filter(e=>e.disableModelInvocation!==!0):[],f,{tools:p,wrapAdded:m}=await Gl(e,i,()=>f===void 0?void 0:Fn(f,e.onUsageRecorded));l&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&p.push(...vr({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:s,toolNamePrefix:e.modelCommandToolPrefix}));let h=Xl(e),g=cd(e.config.hooks,e.guardrails);Ju(g,h,n);let{agentToolDeps:_,agentDefinitions:v,backgroundTaskManager:y}=uu(e,a,i,r,p,h),{backgroundProcessToolDeps:b}=Vu(e,y,a,i,p);Hu(e,y,a,i,p);let{finalSystemMessage:ee,rebuildSystemMessage:x}=Wu(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,sessionId:a,permissionHandler:e.permissionHandler,...e.sandboxClient?.autoApproves===void 0?{}:{commandSandbox:Dr(e.sandboxClient)},...e.disableAutoMode===!0?{}:{permissionClassifier:Xn(r,{cwd:i,model:e.model??e.config.provider.model})},...e.ask?{ask:e.ask}:{},...ne===void 0?{}:{onProjectAllowTool:ne},onTextDelta:e.onTextDelta,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,Gu(T,_,b,y),{session:T,rebuildSystemMessage:x}}function ud(){return`session_${(0,n.randomUUID)()}`}function dd(e){let t=new Date().toISOString();return{id:ud(),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 fd(e,t){return!t.isFork||t.restoredSystemPrompt===void 0||t.explicitSystemPrompt!==void 0?!1:(e.updateSystemMessage(t.restoredSystemPrompt),!0)}function pd(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 md(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 hd(e){let t=md(e.requestedName,e.sourceName,e.sourceId,pd(e.sessionStore)),n=dd({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 gd(e,t){let n=e.name??e.id,r=pd(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 _d(e,t,n){let r=M(n),i=r?.customAgentRegistry?.(e)??(r?.builtInAgents?r.builtInAgents.find(t=>t.name===e):wn(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 vd(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=_d(t.agent??`general-purpose`,t,n),a=Tr({pathProtection:r.pathProtection,agentDefinition:i,parentConfig:Br(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,...Vr(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 yd(e,t){return e===`~`?t:e.startsWith(`~/`)?`${t}/${e.slice(2)}`:e}function bd(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=yd(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:dd({source:e.source,name:e.sessionName,cwd:o}),restricted:e.workspace.projectAccess.status===`restricted`}}function xd(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 Sd(e,t,n,i){if(n.status!==`trusted`)throw new N(`Adding a project context reference requires explicit workspace project authority.`);let a=await hc([t],{reader:B(n.authority),startRelativeDirectory:(0,r.relative)(n.identity.worktreeRoot,i),reason:`manual`});if(cc(a.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[lc(a.diagnostics)]}};let o=a.references[0];if(!o)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let s=Ws(uc([o])[0],`manual`,`active`),c=Gs(e,s);return{references:c.references,result:{reference:s,evicted:c.evicted,diagnostics:[]}}}function Cd(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=Ws(e,n.loadType,n.status,r);i=Gs(i,t).references}return i}function wd(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 Td=`main`;var Ed=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 Dd(e,t){if(t.length===0||(0,r.isAbsolute)(t))throw new Ed(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 Ed(e,t);return n}function Od(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:Td,...r?{parentId:r.id}:{}}})}function kd(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}const Ad={create:`checkpoint_created`,fork:`branch_forked`,switch:`branch_switched`,restore:`checkpoint_restored`,rollback:`checkpoint_rolled_back`,resume_pointer:`non_event`};var jd=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=Ad[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 Md(e){return e.source===`plugin`?`plugin`:`skill`}function Nd(e){return e.context===`fork`?`fork`:`inject`}function Pd(e){return{type:`skill-activation`,skillName:e.skill.name,source:Md(e.skill),invocation:e.invocation,mode:Nd(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function Fd(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 Id=new Set([`memory_candidate_saved`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`]);function Ld(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 Rd={"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 zd=class extends N{reason;name=`EditCheckpointsUnavailableError`;constructor(e){super(Rd[e]),this.reason=e}},Bd=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 jd(()=>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=Cd(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=Cd(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),Id.has(e.type)&&this.history.push({id:(0,n.randomUUID)(),timestamp:new Date(e.at),category:`event`,type:`memory-event`,data:{...e,message:Ld(e)}}),this.emitMemoryEvent(e),this.persistSession()}recordSystemContextFiles(e){this.systemContextReferences=wd(e,this.workspace.cwd)}listContextReferences(){return[...this.systemContextReferences,...this.contextReferences]}listInjectionContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await Sd(this.contextReferences,e,this.workspace.projectAccess,this.workspace.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=Ks(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=qs(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:Fd(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){if(!this.editCheckpointStore)throw new zd(this.noStoreReason());return this.applyPendingActiveBranch(),this.editCheckpointStore}noStoreReason(){return La()?this.workspace.projectAccess.status===`trusted`?`no-checkpoint-store`:`restricted-workspace`:`host-cannot-write-project`}},Vd=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 Hd(e){if(!(0,d.existsSync)(e))return{};let t=(0,d.readFileSync)(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new Bc(e,t instanceof Error?t.message:String(t))}}function Ud(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 Wd(e,t){let n=Hd(e),r=n.currentProvider,i=n.providers;if(typeof r!=`string`||!Gd(i))throw new Vd(e);let a=i;a[r]={...Gd(a[r])?a[r]:{},model:t},n.providers=a,Ud(e,n)}function Gd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Kd(e){return(0,d.existsSync)(e)?((0,d.unlinkSync)(e),!0):!1}const G=Object.freeze({theme:`theme`,syntaxHighlighting:`syntaxHighlighting`,reducedMotion:`reducedMotion`}),qd=Object.freeze({theme:`dark`,syntaxHighlighting:!0,reducedMotion:!1});function Jd(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 Yd(e){let t=e[G.theme],n=e[G.syntaxHighlighting],r=e[G.reducedMotion];return{theme:typeof t==`string`&&t.length>0?t:qd.theme,syntaxHighlighting:typeof n==`boolean`?n:qd.syntaxHighlighting,reducedMotion:typeof r==`boolean`?r:qd.reducedMotion}}function Xd(e,t){let n=Hd(e),r={...Yd(n),...t};return n[G.theme]=r.theme,n[G.syntaxHighlighting]=r.syntaxHighlighting,n[G.reducedMotion]=r.reducedMotion,Ud(e,n),r}var Zd=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 Qd(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 Zd(e,t instanceof Error?t.message:String(t))}let n=$d(t);if(n!==void 0)throw new Zd(e,n);return t}function $d(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 ef(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function tf(e){return e?!e.startsWith(`$ENV:`):!1}const nf={enabled:!0,gitBranch:!0};function rf(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 af(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function of(e){let t=e.statusline;return cf(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:nf.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:nf.gitBranch}:{...nf}}function sf(e,t){let n=Hd(e),r={...of(n),...t};return n.statusline=r,Ud(e,n),r}function cf(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 lf(e,t){return{success:!1,message:`Failed to apply '${e}': ${t instanceof Error?t.message:String(t)}`}}async function uf(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 df(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 df(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:ef(`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(!af(e.patch))return lf(e.type,Error(`invalid statusline settings patch`));let n=t.read(),i={...of(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(!Jd(e.patch))return lf(e.type,Error(`invalid appearance settings patch`));let n=t.read(),i={...Yd(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 lf(e.type,t)}}function ff(e,t,n){return t===void 0?e===`model`?n??void 0:e===`user`?i.OWNER_DRIVER_ID:void 0:t}function pf(e,t,n){for(let r of e)n({intent:r,...t===void 0?{}:{requesterDriverId:t}})}function mf(e,t){let n=Vc(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 Bc(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 hf(e,t){let n=to(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 Bc(a,e instanceof Error?e.message:String(e))}},write:e=>{n.writeText(`${JSON.stringify(e,null,2)}\n`)}})}function gf(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=$a(e.authority,{status:`approved`,target:`project-local`,relativePath:n.relativePath,purpose:`persist user-approved project permission`}),i=hf(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 _f(e){return e.commandSemanticRoles?e.commandSemanticRoles:(e.commandModules?.flatMap(e=>e.systemCommands??[])??[]).reduce((e,t)=>t.semanticRole?{...e,[t.semanticRole]:t.name}:e,{})}function vf(e,t){let{mergedConfig:n,cwd:r,context:i,projectInfo:a,sessionId:o,contextCapacityHint:s,contributionSources:l,skillRoots:u}=t,d=gf(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,onContextUpdate:e.onContextUpdate,onCompactEvent:e.onCompactEvent,...e.onUsageRecorded===void 0?{}:{onUsageRecorded:e.onUsageRecorded},onToolExecution:e.onToolExecution,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:_f(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 yf(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 bf(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 xf(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 Sf(e){return{...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt}}}const Cf=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 wf(e){let t=Tf(e);return{settings:t.settings,hookSources:t.hookSources}}function Tf(e){let t=new Set,n={},r=[];for(let{settings:i,source:a}of e){let e=Ff(i.hooks,t);a!==void 0&&Ef(e,a,r);for(let e of i.disabledHooks??[])t.add(e);n=Df(n,{...i,hooks:e},t)}return{settings:n,hookSources:r}}function Ef(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 Df(e,t,n){return{...e,...t,defaultTrustLevel:Rf(e.defaultTrustLevel,t.defaultTrustLevel),disabledHooks:Of(n),provider:zf(e.provider,t.provider),permissions:kf(e.permissions,t.permissions),env:{...e.env??{},...t.env??{}},providers:jf(e.providers,t.providers),enabledPlugins:Af(e.enabledPlugins,t.enabledPlugins),extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold,hooks:Mf(e.hooks,t.hooks),taskContext:Af(e.taskContext,t.taskContext),sandbox:Af(e.sandbox,t.sandbox)}}function Of(e){return e.size===0?void 0:[...e]}function kf(e,t){if(e!==void 0||t!==void 0)return{allow:Pf(e?.allow,t?.allow),deny:Pf(e?.deny,t?.deny),ask:Pf(e?.ask,t?.ask)}}function Af(e,t){if(e!==void 0||t!==void 0)return{...e,...t}}function jf(e,t){if(e!==void 0||t!==void 0)return If(e,t)}function Mf(e,t){if(e!==void 0||t!==void 0)return Nf(e,t)}function Nf(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 Pf(e,t){return e===void 0?t===void 0?void 0:[...t]:t===void 0?[...e]:[...new Set([...e,...t])]}function Ff(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 If(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]=zf(n[e],r);return n}const Lf={safe:0,moderate:1,full:2};function Rf(e,t){return e===void 0?t:t===void 0||Lf[e]<=Lf[t]?e:t}function zf(e,t){if(e===void 0&&t===void 0)return;let n={...e,...t};return t?.baseURL!==void 0&&t.baseURL!==e?.baseURL&&(t?.apiKey===void 0?t?.apiKeyEnv===void 0?(delete n.apiKey,delete n.apiKeyEnv):delete n.apiKey:delete n.apiKeyEnv),n}const Bf=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(Bf),s.z.record(Bf)])),Vf=s.z.object({name:s.z.string().optional(),model:s.z.string().optional(),apiKey:s.z.string().optional(),baseURL:s.z.string().optional(),timeout:s.z.number().optional(),options:s.z.record(Bf).optional()}),Hf=s.z.object({type:s.z.string().optional(),model:s.z.string().optional(),apiKey:s.z.string().optional(),baseURL:s.z.string().optional(),timeout:s.z.number().optional(),options:s.z.record(Bf).optional()}),Uf=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()}),Wf=s.z.record(s.z.string()).optional(),Gf=s.z.object({type:s.z.literal(`command`),command:s.z.string(),timeout:s.z.number().optional()}),Kf=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()}),qf=s.z.object({type:s.z.literal(`prompt`),prompt:s.z.string(),model:s.z.string().optional()}),Jf=s.z.object({type:s.z.literal(`agent`),agent:s.z.string(),maxTurns:s.z.number().optional(),timeout:s.z.number().optional()}),Yf=s.z.object({type:s.z.literal(`guardrail`),guardrails:s.z.array(s.z.string()).optional()}),Xf=s.z.discriminatedUnion(`type`,[Gf,Kf,qf,Jf,Yf]),q=s.z.object({id:s.z.string().optional(),matcher:s.z.string(),hooks:s.z.array(Xf)}),Zf=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(),Qf=s.z.record(s.z.boolean()).optional(),$f=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()})}),ep=s.z.record($f).optional().catch(void 0),tp=s.z.union([s.z.number().gt(0).lte(1),s.z.literal(!1)]).optional(),np=s.z.object({enabled:s.z.boolean().optional(),options:s.z.record(Bf).optional()}),rp=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()}),ip=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(Hf).optional(),provider:Vf.optional(),permissions:Uf.optional(),env:Wf,hooks:Zf,disabledHooks:s.z.array(s.z.string()).optional(),enabledPlugins:Qf,extraKnownMarketplaces:ep,autoCompactThreshold:tp,transports:s.z.record(np).optional(),sandbox:rp.optional(),taskContext:s.z.object({enabled:s.z.boolean().optional(),dir:s.z.string().min(1).optional()}).optional()}),ap=/position (\d+)/;function op(e){let t=ap.exec(e.message);return t===null?void 0:Number(t[1])}function sp(e){let t=e.code;return typeof t==`string`?t:void 0}function cp(e){let t;try{t=Wc(e,`load configuration settings`)}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`unreadable`,cause:{state:`unreadable`,errno:sp(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:op(n)},error:n}}}function lp(e){if(e.state!==`ok`)return e;let t=ip.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 up(e){return e.map(cp).map(lp)}function dp(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 fp(e){let t=new Map;for(let n of e)if(n.settings!==void 0)for(let e of dp(n.settings)){let r=t.get(e)??[];r.push(n.displayName),t.set(e,r)}return[...t.entries()].map(([e,t])=>({key:e,rule:Cf[e]??`replace`,contributors:t}))}function pp(e){let t=up(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=wf(t.flatMap(e=>e.settings===void 0?[]:[{settings:e.settings,source:e.displayName}]));return{layers:t,merged:r.settings,partial:n,provenance:fp(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 mp(e){if(e.state===`empty`)throw new Bc(e.source.displayName,`the settings file is empty`);if(e.state===`invalid-json`)throw new Bc(e.source.displayName,e.error?.message??`invalid JSON`);if(e.state===`unreadable`)throw e.error}function hp(e,t){return e.startsWith(`$ENV:`)?t[e.slice(5)]??e:e}function gp(e,t){let n=e.provider?.apiKey===void 0?e.provider:_p(e.provider,t);if(e.providers!==void 0){let r=Object.fromEntries(Object.entries(e.providers).map(([e,n])=>[e,_p(n,t)]));return{...e,provider:n,providers:r}}return{...e,provider:n}}function _p(e,t){if(e.apiKey===void 0)return e;let n=e.apiKey.startsWith(`$ENV:`);return{...e,apiKey:hp(e.apiKey,t),...n&&{apiKeyEnv:e.apiKey.slice(5)}}}function vp(e){if(e.currentProvider!==void 0)return yp(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...J.provider}}function yp(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.apiKey??J.provider.apiKey,...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 bp(e){return{defaultTrustLevel:e.defaultTrustLevel??J.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:vp(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 xp(e,t={}){let n=up(e);for(let e of n)mp(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:gp(e.settings,t),source:e.source.displayName})}let i=wf(r);return{config:bp(i.settings),hookSources:i.hookSources}}const Sp={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function Cp(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function wp(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||(0,r.basename)(t,`.md`)}function Tp(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function Ep(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 df(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:ef(`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(!af(e.patch))return lf(e.type,Error(`invalid statusline settings patch`));let n=t.read(),i={...of(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(!Jd(e.patch))return lf(e.type,Error(`invalid appearance settings patch`));let n=t.read(),i={...Yd(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 lf(e.type,t)}}function ff(e,t,n){return t===void 0?e===`model`?n??void 0:e===`user`?i.OWNER_DRIVER_ID:void 0:t}function pf(e,t,n){for(let r of e)n({intent:r,...t===void 0?{}:{requesterDriverId:t}})}function mf(e,t){let n=Vc(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 Bc(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 hf(e,t){let n=to(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 Bc(a,e instanceof Error?e.message:String(e))}},write:e=>{n.writeText(`${JSON.stringify(e,null,2)}\n`)}})}function gf(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=$a(e.authority,{status:`approved`,target:`project-local`,relativePath:n.relativePath,purpose:`persist user-approved project permission`}),i=hf(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 _f(e){return e.commandSemanticRoles?e.commandSemanticRoles:(e.commandModules?.flatMap(e=>e.systemCommands??[])??[]).reduce((e,t)=>t.semanticRole?{...e,[t.semanticRole]:t.name}:e,{})}function vf(e,t){let{mergedConfig:n,cwd:r,context:i,projectInfo:a,sessionId:o,contextCapacityHint:s,contributionSources:l,skillRoots:u}=t,d=gf(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,onContextUpdate:e.onContextUpdate,onCompactEvent:e.onCompactEvent,...e.onUsageRecorded===void 0?{}:{onUsageRecorded:e.onUsageRecorded},onToolExecution:e.onToolExecution,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:_f(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 yf(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 bf(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 xf(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 Sf(e){return{...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt}}}const Cf=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 wf(e){let t=Tf(e);return{settings:t.settings,hookSources:t.hookSources}}function Tf(e){let t=new Set,n={},r=[];for(let{settings:i,source:a}of e){let e=Ff(i.hooks,t);a!==void 0&&Ef(e,a,r);for(let e of i.disabledHooks??[])t.add(e);n=Df(n,{...i,hooks:e},t)}return{settings:n,hookSources:r}}function Ef(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 Df(e,t,n){return{...e,...t,defaultTrustLevel:Rf(e.defaultTrustLevel,t.defaultTrustLevel),disabledHooks:Of(n),provider:zf(e.provider,t.provider),permissions:kf(e.permissions,t.permissions),env:{...e.env??{},...t.env??{}},providers:jf(e.providers,t.providers),enabledPlugins:Af(e.enabledPlugins,t.enabledPlugins),extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold,hooks:Mf(e.hooks,t.hooks),taskContext:Af(e.taskContext,t.taskContext),sandbox:Af(e.sandbox,t.sandbox)}}function Of(e){return e.size===0?void 0:[...e]}function kf(e,t){if(e!==void 0||t!==void 0)return{allow:Pf(e?.allow,t?.allow),deny:Pf(e?.deny,t?.deny),ask:Pf(e?.ask,t?.ask)}}function Af(e,t){if(e!==void 0||t!==void 0)return{...e,...t}}function jf(e,t){if(e!==void 0||t!==void 0)return If(e,t)}function Mf(e,t){if(e!==void 0||t!==void 0)return Nf(e,t)}function Nf(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 Pf(e,t){return e===void 0?t===void 0?void 0:[...t]:t===void 0?[...e]:[...new Set([...e,...t])]}function Ff(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 If(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]=zf(n[e],r);return n}const Lf={safe:0,moderate:1,full:2};function Rf(e,t){return e===void 0?t:t===void 0||Lf[e]<=Lf[t]?e:t}function zf(e,t){if(e===void 0&&t===void 0)return;let n={...e,...t};return t?.baseURL!==void 0&&t.baseURL!==e?.baseURL&&(t?.apiKey===void 0?t?.apiKeyEnv===void 0?(delete n.apiKey,delete n.apiKeyEnv):delete n.apiKey:delete n.apiKeyEnv),n}const Bf=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(Bf),s.z.record(Bf)])),Vf=s.z.object({name:s.z.string().optional(),model:s.z.string().optional(),apiKey:s.z.string().optional(),baseURL:s.z.string().optional(),timeout:s.z.number().optional(),options:s.z.record(Bf).optional()}),Hf=s.z.object({type:s.z.string().optional(),model:s.z.string().optional(),apiKey:s.z.string().optional(),baseURL:s.z.string().optional(),timeout:s.z.number().optional(),options:s.z.record(Bf).optional()}),Uf=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()}),Wf=s.z.record(s.z.string()).optional(),Gf=s.z.object({type:s.z.literal(`command`),command:s.z.string(),timeout:s.z.number().optional()}),Kf=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()}),qf=s.z.object({type:s.z.literal(`prompt`),prompt:s.z.string(),model:s.z.string().optional()}),Jf=s.z.object({type:s.z.literal(`agent`),agent:s.z.string(),maxTurns:s.z.number().optional(),timeout:s.z.number().optional()}),Yf=s.z.object({type:s.z.literal(`guardrail`),guardrails:s.z.array(s.z.string()).optional()}),Xf=s.z.discriminatedUnion(`type`,[Gf,Kf,qf,Jf,Yf]),q=s.z.object({id:s.z.string().optional(),matcher:s.z.string(),hooks:s.z.array(Xf)}),Zf=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(),Qf=s.z.record(s.z.boolean()).optional(),$f=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()})}),ep=s.z.record($f).optional().catch(void 0),tp=s.z.union([s.z.number().gt(0).lte(1),s.z.literal(!1)]).optional(),np=s.z.object({enabled:s.z.boolean().optional(),options:s.z.record(Bf).optional()}),rp=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()}),ip=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(Hf).optional(),provider:Vf.optional(),permissions:Uf.optional(),env:Wf,commandEnvAllow:s.z.array(s.z.string()).optional(),hooks:Zf,disabledHooks:s.z.array(s.z.string()).optional(),enabledPlugins:Qf,extraKnownMarketplaces:ep,autoCompactThreshold:tp,transports:s.z.record(np).optional(),sandbox:rp.optional(),taskContext:s.z.object({enabled:s.z.boolean().optional(),dir:s.z.string().min(1).optional()}).optional()}),ap=/position (\d+)/;function op(e){let t=ap.exec(e.message);return t===null?void 0:Number(t[1])}function sp(e){let t=e.code;return typeof t==`string`?t:void 0}function cp(e){let t;try{t=Wc(e,`load configuration settings`)}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`unreadable`,cause:{state:`unreadable`,errno:sp(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:op(n)},error:n}}}function lp(e){if(e.state!==`ok`)return e;let t=ip.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 up(e){return e.map(cp).map(lp)}function dp(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 fp(e){let t=new Map;for(let n of e)if(n.settings!==void 0)for(let e of dp(n.settings)){let r=t.get(e)??[];r.push(n.displayName),t.set(e,r)}return[...t.entries()].map(([e,t])=>({key:e,rule:Cf[e]??`replace`,contributors:t}))}function pp(e){let t=up(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=wf(t.flatMap(e=>e.settings===void 0?[]:[{settings:e.settings,source:e.displayName}]));return{layers:t,merged:r.settings,partial:n,provenance:fp(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 mp(e){if(e.state===`empty`)throw new Bc(e.source.displayName,`the settings file is empty`);if(e.state===`invalid-json`)throw new Bc(e.source.displayName,e.error?.message??`invalid JSON`);if(e.state===`unreadable`)throw e.error}function hp(e,t){return e.startsWith(`$ENV:`)?t[e.slice(5)]??e:e}function gp(e,t){let n=e.provider?.apiKey===void 0?e.provider:_p(e.provider,t);if(e.providers!==void 0){let r=Object.fromEntries(Object.entries(e.providers).map(([e,n])=>[e,_p(n,t)]));return{...e,provider:n,providers:r}}return{...e,provider:n}}function _p(e,t){if(e.apiKey===void 0)return e;let n=e.apiKey.startsWith(`$ENV:`);return{...e,apiKey:hp(e.apiKey,t),...n&&{apiKeyEnv:e.apiKey.slice(5)}}}function vp(e){if(e.currentProvider!==void 0)return yp(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...J.provider}}function yp(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.apiKey??J.provider.apiKey,...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 bp(e){return{defaultTrustLevel:e.defaultTrustLevel??J.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:vp(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 xp(e,t={}){let n=up(e);for(let e of n)mp(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:gp(e.settings,t),source:e.source.displayName})}let i=wf(r);return{config:bp(i.settings),hookSources:i.hookSources}}const Sp={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function Cp(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function wp(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||(0,r.basename)(t,`.md`)}function Tp(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function Ep(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 Dp(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(\S.*)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function Op(e,t){return t&&e.branch===t?0:Sp[e.status]}function kp(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 Ap(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 jp(e,t=new Ci){let n=Ap(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 Mp(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 Np(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:wp(n,e),status:Cp(Tp(n,`Status`)),branch:Tp(n,`Branch`),scope:Tp(n,`Scope`),objective:Ep(n,`Objective`),openItems:Dp(n)}}function Pp(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>Op(e,t.currentBranch)-Op(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function Fp(e){return e.map(kp).join(`
107
107
 
@@ -111,7 +111,7 @@ Do not use emojis.`}function Qn(){return`You are a worker subagent executing a s
111
111
 
112
112
  `),o=i.map(e=>e.content).join(`
113
113
 
114
- `),s=Bp(o),c=(await t?.loadStartupMemory())?.content||void 0,l=n.taskContext?.enabled!==!1&&n.taskContext?.dir&&e!==void 0?Ip(e.reader,{...n.taskContext?.dir?{dir:n.taskContext.dir}:{},...e.currentBranch?{currentBranch:e.currentBranch}:{}}):``;return{agentsMd:a,projectNotesMd:o,memoryMd:c,taskContext:l.trim().length>0?l:void 0,compactInstructions:s,agentsFileEntries:r,projectNotesFileEntries:i}}const Y={packageJson:`package.json`,tsconfig:`tsconfig.json`,pnpmWorkspace:`pnpm-workspace.yaml`,pnpmLock:`pnpm-lock.yaml`,yarnLock:`yarn.lock`,bunLock:`bun.lockb`,npmLock:`package-lock.json`,pyproject:`pyproject.toml`,setup:`setup.py`,cargo:`Cargo.toml`,goMod:`go.mod`};function Hp(e,t){let n=e.readText(t,`detect project package metadata`);if(n!==void 0)try{return JSON.parse(n)}catch{return}}function X(e,t){return e.inspectKind(t,`detect project type`)===`file`}function Up(e){if(X(e,Y.pnpmWorkspace)||X(e,Y.pnpmLock))return`pnpm`;if(X(e,Y.yarnLock))return`yarn`;if(X(e,Y.bunLock))return`bun`;if(X(e,Y.npmLock))return`npm`}async function Wp(e){let t=R(e);if(X(t,Y.packageJson)){let e=Hp(t,Y.packageJson),n=X(t,Y.tsconfig)?`typescript`:`javascript`,r=Up(t);return{type:`node`,name:e?.name,packageManager:r,language:n}}return X(t,Y.pyproject)||X(t,Y.setup)?{type:`python`,language:`python`}:X(t,Y.cargo)?{type:`rust`,language:`rust`}:X(t,Y.goMod)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}async function Gp(e,t,n=[],r=[],i={}){if(e!==void 0)return{config:e,hookSources:[]};let a=t?.status===`trusted`?B(t.authority):void 0;return xp([...r,...a===void 0?[]:Uc(a,n)],i)}async function Kp(e,t){return e.config===void 0?Gp(void 0,t,e.projectSettingsPaths,e.userSettingsSources,e.environment):{config:e.config,hookSources:e.hookSources??[]}}async function qp(e){let t=e.projectAccess??V(`identity-unavailable`,e.cwd),n=t.status===`trusted`?B(t.authority):void 0,i=t.status!==`trusted`||n===void 0?void 0:{reader:n,startRelativeDirectory:(0,r.relative)(t.identity.worktreeRoot,(0,r.resolve)(e.cwd))},{config:a,hookSources:o}=await Kp(e,t),s={...e.taskContext,...a.taskContext},[c,l]=await Promise.all([e.bare?Promise.resolve({agentsMd:``,projectNotesMd:``,agentsFileEntries:[],projectNotesFileEntries:[]}):Vp(i,e.memoryStore,s.dir!==void 0||s.enabled!==void 0?{taskContext:s}:{}),e.bare||n===void 0?Promise.resolve({type:`unknown`,language:`unknown`}):Wp(n)]);return{projectAccess:t,config:a,context:c,projectInfo:l,contributionSources:e.contributionSources??[],hookSources:o}}function Jp(e){if(e)return`Run /${e} and retry.`}function Yp(e,t,n,i=new Ci){let a=(0,r.join)(n,e,`subagents`);return i.mkdirSync(a,{recursive:!0}),new c.FileSessionLogger(new c.NodeSessionLogSink(a))}function Xp(e,t){return(0,r.join)(t,e,`subagents`)}var Zp=class{settingsPath;fs;constructor(e,t=new Ci){this.settingsPath=e,this.fs=t}readAll(){if(!this.fs.existsSync(this.settingsPath))return{};let e=this.fs.readFileSync(this.settingsPath,`utf-8`),t;try{t=JSON.parse(e)}catch(e){throw Error(`Plugin settings cannot be read: ${this.settingsPath} is not valid JSON. Fix the file; until then no plugin is loaded and plugin settings are not changed.`,{cause:e})}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Plugin settings cannot be read: ${this.settingsPath} does not hold a JSON object.`);return t}writeAll(e){let t=(0,r.dirname)(this.settingsPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.settingsPath,JSON.stringify(e,null,2),`utf-8`)}getEnabledPlugins(){let e=this.readAll().enabledPlugins;return typeof e==`object`&&e?e:{}}setPluginEnabled(e,t){let n=this.readAll(),r=this.getEnabledPluginsFrom(n);r[e]=t,n.enabledPlugins=r,this.writeAll(n)}removePluginEntry(e){let t=this.readAll(),n=this.getEnabledPluginsFrom(t);delete n[e],t.enabledPlugins=n,this.writeAll(t)}getMarketplaceSources(){let e=this.readAll().extraKnownMarketplaces;return typeof e==`object`&&e?e:{}}setMarketplaceSource(e,t){let n=this.readAll(),r=this.getMarketplaceSourcesFrom(n);r[e]={source:t},n.extraKnownMarketplaces=r,this.writeAll(n)}removeMarketplaceSource(e){let t=this.readAll(),n=this.getMarketplaceSourcesFrom(t);delete n[e],t.extraKnownMarketplaces=n,this.writeAll(t)}getEnabledPluginsFrom(e){let t=e.enabledPlugins;return typeof t==`object`&&t?t:{}}getMarketplaceSourcesFrom(e){let t=e.extraKnownMarketplaces;return typeof t==`object`&&t?t:{}}},Qp=class extends Error{name=`PluginPathContainmentError`};const $p=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function em(e){return typeof e==`string`&&e.length>0&&e.length<=128&&$p.test(e)}function tm(e,t){if(!em(e))throw Error(`Invalid plugin ${t}: ${JSON.stringify(e)}. It is used as a filesystem path component, so it must be 1-128 characters of letters, digits, dot, underscore or hyphen, starting with a letter or digit.`)}function nm(e,t){let n=(0,r.resolve)(e),i=[];for(;;){if(t.existsSync(n))return(0,r.resolve)(t.realpathSync(n),...i.reverse());let a=(0,r.resolve)(n,`..`);if(a===n)return(0,r.resolve)(e);i.push(n.slice(a.length+1)),n=a}}function rm(e,t,n,i){let a=nm(e,i),o=nm(t,i);if(!(o===a||o.startsWith(a.endsWith(r.sep)?a:a+r.sep)))throw new Qp(`Refusing to ${n} outside the plugin root: ${JSON.stringify(t)} resolves to ${JSON.stringify(o)}, which is not inside ${JSON.stringify(a)}.`)}function im(e,t,n,i){if((0,r.isAbsolute)(t))throw new Qp(`Refusing to ${n} from an absolute path: ${JSON.stringify(t)}. This field takes a path relative to the plugin root.`);let a=(0,r.resolve)(e,t);return rm(e,a,n,i),a}var am=class extends Error{code;name=`McpContributionError`;constructor(e){super(e),this.code=e}};function om(e,t=!0){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Date)throw new am(`invalid-object`);let n=t&&Object.hasOwn(e,`mcpServers`)?e.mcpServers:e;if(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date)throw new am(`invalid-object`);return n}function sm(e,t,n,i){let a=(0,r.join)(e,`.mcp.json`),o=t=>(rm(e,t,`read MCP contribution`,n),JSON.parse(n.readFileSync(t,`utf-8`))),s=n.existsSync(a)?o(a):void 0;if(t===void 0)return s;if(s!==void 0&&i)for(let e of Object.keys(om(s)))i(e,a);let c=Array.isArray(t)?t:[t],l=s===void 0?{}:{...om(s)};for(let t of c){let n=t,a=(0,r.join)(e,`.claude-plugin`,`plugin.json`);if(typeof t==`string`){if(!t.startsWith(`./`)||!t.endsWith(`.json`)||t.includes(`\\`))throw new am(`unsupported-path`);a=(0,r.join)(e,t),n=o(a)}let s=om(n,typeof t==`string`);for(let e of Object.keys(s))i?.(e,a);l={...l,...s}}return{mcpServers:l}}const cm={"manifest-unreadable":`plugin manifest could not be read — skipping this plugin`,"manifest-invalid":`plugin manifest is not a valid plugin.json — skipping this plugin`,disabled:`plugin is disabled`,"load-failed":`plugin failed to load — skipping this plugin`,"revision-unselected":`plugin has no valid selected installed revision — skipping this plugin`},lm=/position (\d+)/;function um(e){if(e===void 0)return`Error`;if(e instanceof am)return`${e.name} [${e.code}]`;if(e instanceof iu)return e.diagnostics.map(e=>`${e.line===void 0?e.source:`${e.source}:${e.line}${e.column===void 0?``:`:${e.column}`}`} [${e.code}]${e.field===void 0?``:` ${e.field}`}`).join(`; `);let t=lm.exec(e.message);return t===null?e.name:`${e.name} at position ${t[1]}`}function dm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function fm(e,t,n,r){let i=dm(r)?r:{},a=typeof i.command==`string`?i.command:void 0,o=typeof i.url==`string`?i.url:void 0;return{pluginId:e,mcpPath:t,name:n,transport:a===void 0?o===void 0?`unknown`:`http`:`stdio`,...a===void 0?{}:{command:a},...o===void 0?{}:{url:o},envKeys:dm(i.env)?Object.keys(i.env):[]}}function pm(e,t,n,i){if(Object.keys(n).length===0)return;let a=Zf.safeParse(n);a.success||i.push({pluginId:e,hooksPath:(0,r.join)(t,`hooks`,`hooks.json`),issues:a.error.issues.map(e=>({path:e.path.map(String).join(`.`),code:e.code}))})}function mm(e,t,n,i,a){if(n===void 0)return;let o=(0,r.join)(t,`.mcp.json`);if(!dm(n)){i.mcpFaults.push({pluginId:e,mcpPath:o,reason:`not-an-object`});return}let s=n.mcpServers;if(!dm(s)){i.mcpFaults.push({pluginId:e,mcpPath:o,reason:`no-servers`});return}for(let[t,n]of Object.entries(s)){let r=a&&Object.hasOwn(a,t)?a[t]:o;i.mcpServers.push(fm(e,r,t,n))}}function hm(e){if(typeof e!=`object`||!e)return null;let t=e;if(typeof t.name!=`string`||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t.name)||t.version!==void 0&&typeof t.version!=`string`||t.description!==void 0&&typeof t.description!=`string`)return null;let n=typeof t.features==`object`&&t.features!==null?t.features:{};return{name:t.name,...typeof t.version==`string`?{version:t.version}:{},...typeof t.description==`string`?{description:t.description}:{},...Object.fromEntries([`commands`,`skills`,`hooks`,`agents`].filter(e=>Object.hasOwn(t,e)).map(e=>[e,t[e]])),...t.mcpServers===void 0?{}:{mcpServers:t.mcpServers},features:{commands:n.commands===!0||void 0,agents:n.agents===!0||void 0,skills:n.skills===!0||void 0,hooks:n.hooks===!0||void 0,mcp:n.mcp===!0||void 0}}}function gm(e,t=new Ci){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function _m(e,t){let n=[],i=[],a=(t,n,r,a,o,s=`supported`)=>{i.push({identity:`${e.manifest.name}:${t}:${n}`,kind:t,source:r,requiredCapabilities:a,disposition:s,...o?{reason:o}:{}})};for(let t of e.commands)a(`command`,t.name.startsWith(`${e.manifest.name}:`)?t.name.slice(e.manifest.name.length+1):t.name,t.skillDirectory??(0,r.join)(e.pluginDir,`commands`),[`command-router`]);for(let t of e.skills)a(`skill`,t.name,t.skillDirectory??(0,r.join)(e.pluginDir,`skills`),[`skill-reader`]);let o=typeof e.hooks.hooks==`object`&&e.hooks.hooks!==null?e.hooks.hooks:e.hooks;for(let t of Object.keys(o))a(`hook`,t,(0,r.join)(e.pluginDir,`hooks`,`hooks.json`),[`hook-executor`]);for(let t of e.agents)a(`agent`,t,(0,r.join)(e.pluginDir,`agents`),[`agent-router`],`Agent names are inspected; execution definitions are unavailable from this adapter`,`unavailable`);let s=e.mcpConfig;if(typeof s==`object`&&s&&!Array.isArray(s)&&!(s instanceof Date)){let t=s.mcpServers;if(typeof t==`object`&&t&&!Array.isArray(t)&&!(t instanceof Date))for(let[i,o]of Object.entries(t)){let t=[`mcp-client`],s=!1;if(typeof o==`object`&&o&&!Array.isArray(o)&&!(o instanceof Date)){let e=o.type??(typeof o.command==`string`?`stdio`:typeof o.url==`string`?`http`:void 0);e===`stdio`?(t.push(`stdio-authority`),s=typeof o.command==`string`):e===`http`&&(t.push(`http-transport`),s=typeof o.url==`string`)}a(`mcp`,i,e.mcpSourcePaths?.[i]??(0,r.join)(e.pluginDir,`.mcp.json`),t,s?void 0:`No supported transport declaration`,s?`supported`:`unsupported`),s||n.push({component:`mcp`,code:`unsupported-transport`})}}s!==void 0&&(typeof s!=`object`||!s||Array.isArray(s)||s instanceof Date||typeof s.mcpServers!=`object`||s.mcpServers===null||Array.isArray(s.mcpServers)||s.mcpServers instanceof Date)&&n.push({component:`mcp`,code:`invalid-configuration`});for(let t of[`commands`,`skills`,`hooks`,`agents`])e.manifest[t]!==void 0&&(n.push({component:t,code:`unsupported-component-declaration`}),i.push({identity:`${e.manifest.name}:declaration:${t}`,kind:t===`commands`?`command`:t===`skills`?`skill`:t===`hooks`?`hook`:`agent`,source:(0,r.join)(e.pluginDir,`.claude-plugin`,`plugin.json`),requiredCapabilities:[],disposition:`unsupported`,reason:`Declared component paths are not consumed by this adapter`}));let c=(0,r.basename)(e.pluginDir);return{schemaVersion:1,identity:t,installedRevision:c,generation:JSON.stringify([t,c,e.pluginDir]),source:{kind:`bundle`,location:e.pluginDir},requiredCapabilities:[...new Set(i.flatMap(e=>e.requiredCapabilities))],contributions:i,lifecycle:{activation:`unadmitted`,activeCalls:`host-owned`},diagnostics:n}}const vm=(0,t.createLogger)(`BundlePluginLoader`);function ym(e,t){let n=be({source:e,content:t,profile:`bundle-skill`});if(!n.ok)throw new iu(n.diagnostics);return n}var bm=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new Ci){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){let e=this.inspectPluginsSync();for(let t of e.skipped)t.reason!==`disabled`&&vm.warn(cm[t.reason],{plugin:t.pluginId,manifestPath:t.manifestPath,...t.detail===void 0?{}:{error:t.detail}});return[...e.loaded]}async loadAll(){return this.loadPluginsSync()}inspectPluginsSync(){let e=(0,r.join)(this.pluginsDir,`cache`),t=this.snapshotInstalledSelection(),n=new Set,i={loaded:[],skipped:[],hookIssues:[],mcpServers:[],mcpFaults:[]},a=this.fs.existsSync(e);if(a)for(let a of gm(e,this.fs)){let o=(0,r.join)(e,a);for(let e of gm(o,this.fs))n.add(`${e}@${a}`),this.inspectPluginDir(a,e,(0,r.join)(o,e),i,t)}for(let e of Object.keys(t.records??{}))n.has(e)||i.skipped.push({pluginId:e,manifestPath:(0,r.join)(this.pluginsDir,`installed_plugins.json`),reason:`revision-unselected`,detail:`Selected plugin source is missing from cache`});return t.error&&n.size===0&&i.skipped.push({pluginId:`installed_plugins.json`,manifestPath:(0,r.join)(this.pluginsDir,`installed_plugins.json`),reason:`revision-unselected`,detail:um(t.error)}),{pluginsDir:this.pluginsDir,cacheDirPresent:a,...i}}inspectPluginDir(e,t,n,i,a){let o=gm(n,this.fs),s=`${t}@${e}`,c;try{c=this.selectRevision(n,e,t,o,a)}catch(e){i.skipped.push({pluginId:s,manifestPath:(0,r.join)(n,`.claude-plugin`,`plugin.json`),reason:`revision-unselected`,detail:um(e instanceof Error?e:void 0)});return}let l=(0,r.join)(c,`.claude-plugin`,`plugin.json`),u;try{u=this.readManifest(l)}catch(e){let t=um(e instanceof Error?e:void 0);i.skipped.push({pluginId:s,manifestPath:l,reason:`manifest-unreadable`,detail:t});return}if(!u){i.skipped.push({pluginId:s,manifestPath:l,reason:`manifest-invalid`});return}let d=`${u.name}@${e}`;if(this.isDisabled(s,t)||this.isDisabled(d,u.name)){i.skipped.push({pluginId:d,manifestPath:l,reason:`disabled`});return}try{let e=this.loadPlugin(c,u);e.descriptor=_m(e,s),i.loaded.push(e),pm(d,c,e.hooks,i.hookIssues),mm(d,c,e.mcpConfig,i,e.mcpSourcePaths)}catch(e){let t=um(e instanceof Error?e:void 0);i.skipped.push({pluginId:d,manifestPath:l,reason:`load-failed`,detail:t})}}snapshotInstalledSelection(){let e=(0,r.join)(this.pluginsDir,`installed_plugins.json`);if(!this.fs.existsSync(e))return{};try{let t=JSON.parse(this.fs.readFileSync(e,`utf-8`));if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Invalid installed registry`);return{records:t}}catch(e){return{error:e instanceof Error?e:Error(`Invalid installed registry`)}}}selectRevision(e,t,n,i,a){if(a.error)throw a.error;let o;if(a.records){let i=Object.hasOwn(a.records,`${n}@${t}`)?a.records[`${n}@${t}`]:void 0;if(typeof i!=`object`||!i||Array.isArray(i))throw Error(`No selected installation`);let s=i;if(tm(s.version,`installed revision`),o=s.version,s.pluginName!==n||s.marketplace!==t||typeof s.installPath!=`string`||(0,r.resolve)(s.installPath)!==(0,r.resolve)(e,o))throw Error(`Installed record does not match its cached source`)}else{if(i.length!==1)throw Error(`Select an installed revision before loading multiple cached sources`);o=i[0]}tm(o,`source revision`);let s=(0,r.join)(e,o);if(!i.includes(o))throw Error(`Selected revision is not installed`);return rm((0,r.join)(this.pluginsDir,`cache`),s,`load installed source`,this.fs),rm(e,s,`load selected plugin revision`,this.fs),rm(s,(0,r.join)(s,`.claude-plugin`,`plugin.json`),`read plugin manifest`,this.fs),s}readManifest(e){let t=this.fs.readFileSync(e,`utf-8`);return hm(JSON.parse(t))}isDisabled(e,t){return e in this.enabledPlugins?this.enabledPlugins[e]===!1:t in this.enabledPlugins&&this.enabledPlugins[t]===!1}loadPlugin(e,t){let n={},r=sm(e,t.mcpServers,this.fs,(e,t)=>{n={...n,[e]:t}});return{manifest:t,skills:this.loadSkills(e,t.name),commands:this.loadCommands(e,t.name),hooks:this.loadHooks(e),mcpConfig:r,mcpSourcePaths:n,agents:this.loadAgents(e),pluginDir:e}}loadSkills(e,t){let n=(0,r.join)(e,`skills`);if(!this.fs.existsSync(n))return[];let i=this.fs.readdirSync(n,{withFileTypes:!0}),a=[];for(let e of i){if(!e.isDirectory())continue;let t=(0,r.join)(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let i=this.fs.readFileSync(t,`utf-8`),{metadata:o,body:s}=ym(t,i),c=typeof o.description==`string`?o.description:``,l={name:e.name,description:c,skillContent:s===i?s:s.trimStart(),...o,skillDirectory:(0,r.join)(n,e.name)};a.push(l)}return a}loadCommands(e,t){let n=(0,r.join)(e,`commands`);if(!this.fs.existsSync(n))return[];let i=this.fs.readdirSync(n,{withFileTypes:!0}),a=[];for(let e of i){if(!e.isFile()||!e.name.endsWith(`.md`))continue;let i=(0,r.join)(n,e.name),o=this.fs.readFileSync(i,`utf-8`),{metadata:s,body:c}=ym(i,o),l=typeof s.name==`string`?s.name:e.name.replace(/\.md$/,``),u=typeof s.description==`string`?s.description:``;a.push({...s,name:`${t}:${l}`,description:u,skillContent:c===o?c:c.trimStart(),skillDirectory:n})}return a}loadHooks(e){let t=(0,r.join)(e,`hooks`,`hooks.json`);if(!this.fs.existsSync(t))return{};let n=this.fs.readFileSync(t,`utf-8`),i=JSON.parse(n);return typeof i==`object`&&i?i:{}}loadAgents(e){let t=(0,r.join)(e,`agents`);return this.fs.existsSync(t)?this.fs.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.name.endsWith(`.md`)).map(e=>e.name.replace(/\.md$/,``)):[]}};function xm(e){if(e.settingsPath===void 0&&e.enabledPlugins===void 0)throw Error(`Plugin enablement requires settingsPath or enabledPlugins`);let t=e.enabledPlugins??new Zp(e.settingsPath,e.fs).getEnabledPlugins();return new bm(e.pluginsDir,t,e.fs)}function Sm(e,t={}){return[...new Set(e)].map(e=>xm({...t,pluginsDir:e}).inspectPluginsSync())}function Cm(e,t={}){let n=new Set,r=[];for(let i of new Set(e))for(let e of xm({...t,pluginsDir:i}).loadPluginsSync())n.has(e.manifest.name)||(n.add(e.manifest.name),r.push(e));return r}function wm(e){return{...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.disableModelInvocation===void 0?{}:{disableModelInvocation:e.disableModelInvocation},...e.userInvocable===void 0?{}:{userInvocable:e.userInvocable},...e.allowedTools===void 0?{}:{allowedTools:e.allowedTools},...e.model===void 0?{}:{model:e.model},...e.effort===void 0?{}:{effort:e.effort},...e.context===void 0?{}:{context:e.context},...e.agent===void 0?{}:{agent:e.agent}}}var Tm=class{name=`plugin`;plugins;constructor(e){this.plugins=e}getCommands(){let e=[];for(let t of this.plugins){for(let n of t.skills){let r=n.name.includes(`@`)?n.name.split(`@`)[0]:n.name;e.push({name:r,description:`(${t.manifest.name}) ${n.description}`,source:`plugin`,skillContent:n.skillContent,...n.skillDirectory===void 0?{}:{skillDirectory:n.skillDirectory},pluginDir:t.pluginDir,...wm(n)})}for(let n of t.commands)e.push({name:n.name,description:n.description,source:`plugin`,skillContent:n.skillContent,...n.skillDirectory===void 0?{}:{skillDirectory:n.skillDirectory},pluginDir:t.pluginDir,...wm(n)})}return e}};function Em(e,t){try{let n=(0,r.relative)((0,d.realpathSync)(Pa(t.authority).worktreeRoot),(0,d.existsSync)(e)?(0,d.realpathSync)(e):(0,r.resolve)(e));return n!==`..`&&!n.startsWith(`..${r.sep}`)&&!(0,r.isAbsolute)(n)}catch{return!1}}function Dm(e){let t=e.projectAccess,n=e.pluginDirectories?.project;return[...t?.status===`trusted`&&n!==void 0&&Em(n,t)?[n]:[],...e.pluginDirectories?.user===void 0?[]:[e.pluginDirectories.user]]}function Om(e){if(e.bare!==!0)return e.userSettingsSources?.find(e=>e.scope===`user`)?.path}function km(e){let t=Om(e);if(t===void 0)return[];try{return new Tm(Cm(Dm(e),{settingsPath:t})).getCommands()}catch{return[]}}function Am(e){let t=(0,r.join)((0,r.dirname)((0,r.dirname)(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function jm(e,t){return Array.isArray(e.hooks)?{...e,hooks:e.hooks.map(e=>typeof e.command==`string`?{...e,command:e.command.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,t)}:e)}:e}function Mm(e){let t={},n=[];for(let i of e){let e=i.hooks;if(!e)continue;let a=Am(i),o=e.hooks??e;for(let[e,s]of Object.entries(o)){if(!Array.isArray(s))continue;t[e]||(t[e]=[]);let o=s.map(e=>{let t=jm(e,i.pluginDir);return t.env=a,t});t[e].push(...o);for(let t of o)if(Array.isArray(t.hooks))for(let a of t.hooks)typeof a?.type==`string`&&n.push({event:e,type:a.type,source:(0,r.join)(i.pluginDir,`hooks`,`hooks.json`)})}}return{hooks:t,hookSources:n}}function Nm(e,t){if(Object.keys(t).length===0)return e;let n={};for(let[e,r]of Object.entries(t))n[e]=[...r];if(e)for(let[t,r]of Object.entries(e))Array.isArray(r)&&(n[t]||(n[t]=[]),n[t].push(...r));return n}const Pm=(0,t.createLogger)(`InteractiveSessionInit`);async function Fm(e){let t=e.cwd,{config:n,context:r,projectInfo:i,contributionSources:a,hookSources:o}=await qp(e),s=e.language?{...n,language:e.language}:n;e.skipConfiguredHooks===!0&&(s={...s,hooks:void 0});let c=e.skipConfiguredHooks===!0?[]:[...o],l=Dm(e),u=Om(e);if(u!==void 0)try{let e=Cm(l,{settingsPath:u});if(e.length>0){let t=Mm(e);s={...s,hooks:Nm(s.hooks,t.hooks)},c.push(...t.hookSources)}}catch(e){Pm.warn(`plugin discovery failed — no bundle plugin hooks are active this session`,{pluginsDirs:l,error:e instanceof Error?e.message:String(e)})}await xf(e)||await bf(e,t);let d=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,f=Jp(e.commandSemanticRoles?.contextReduction),{session:p,rebuildSystemMessage:m}=await ld(vf(e,{mergedConfig:s,cwd:t,context:r,projectInfo:i,sessionId:d,contextCapacityHint:f,contributionSources:a,skillRoots:e.skillRoots}),c);return{session:p,agentsFileEntries:r.agentsFileEntries??[],projectNotesFileEntries:r.projectNotesFileEntries??[],rebuildSystemMessage:m}}async function Im(e,t){let{config:n,hookSources:r}=await Gp(e.config,e.projectAccess,e.projectSettingsPaths,e.userSettingsSources,e.environment),i=n.autoCompactThreshold===void 0?`default`:`settings`,a=e.editCheckpointStore;a!==void 0&&t.setEditCheckpointStore(a);let o=await Fm({cwd:e.cwd,provider:e.provider,...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess},...e.projectSettingsPaths===void 0?{}:{projectSettingsPaths:e.projectSettingsPaths},...e.taskContext===void 0?{}:{taskContext:e.taskContext},...e.userSettingsSources===void 0?{}:{userSettingsSources:e.userSettingsSources},...e.environment===void 0?{}:{environment:e.environment},config:n,hookSources:r,contributionSources:e.contributionSources,skillRoots:e.skillRoots,pluginSkills:t.pluginSkills,permissionMode:e.permissionMode,baselinePermissionAllow:e.baselinePermissionAllow,maxTurns:e.maxTurns,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},permissionHandler:t.permissionHandler,...t.askHandler?{askHandler:t.askHandler}:{},resumeSessionId:t.resumeSessionId,forkSession:e.forkSession,...e.sessionStore===void 0?{}:{resumeSessionStore:e.sessionStore},...e.sessionLogSink===void 0?{}:{sessionLogSink:e.sessionLogSink},...e.transcriptPath===void 0?{}:{transcriptPath:e.transcriptPath},onTextDelta:t.onTextDelta,onContextUpdate:t.onContextUpdate,onCompactEvent:t.onCompactEvent,onUsageRecorded:t.onUsageRecorded,onToolExecution:t.onToolExecution,bare:e.bare,...e.orgPolicy?.disableAutoMode===!0?{disableAutoMode:!0}:{},...e.skipConfiguredHooks===!0?{skipConfiguredHooks:!0}:{},disableBuiltInHookExecutors:e.disableBuiltInHookExecutors,commandHookShell:e.commandHookShell,allowedTools:e.allowedTools,deniedTools:e.deniedTools,model:e.model,...e.effort===void 0?{}:{effort:e.effort},appendSystemPrompt:e.appendSystemPrompt,...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},...e.persona===void 0?{}:{persona:e.persona},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},language:e.language,backgroundTaskRunners:e.backgroundTaskRunners,subagentHookEnvironmentNames:e.subagentHookEnvironmentNames,observerFailureWarningCode:e.observerFailureWarningCode,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions?{agentDefinitions:e.agentDefinitions}:{},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.commandModules?{commandModules:e.commandModules}:{},...a===void 0?{}:{editCheckpointRecorder:a},...e.reversibleExecution?{reversibleExecution:e.reversibleExecution}:{},...yf(e,t.sandboxSnapshotId),...Sf(e),...e.memoryStore?{memoryStore:e.memoryStore}:{},...e.agentName?{agentName:e.agentName}:{},...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.enableParallelSubagents===void 0?{}:{enableParallelSubagents:e.enableParallelSubagents},...e.selfVerification===void 0?{}:{selfVerification:e.selfVerification},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.defaultTools?{defaultTools:e.defaultTools}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.guardrails?{guardrails:e.guardrails}:{},...e.retrievalAdapter?{retrievalAdapter:e.retrievalAdapter}:{},...t.peerReply===void 0?{}:{peerReply:t.peerReply},...t.peerSendFile===void 0?{}:{peerSendFile:t.peerSendFile},commandDescriptors:t.commandDescriptors,...t.commandSemanticRoles?{commandSemanticRoles:t.commandSemanticRoles}:{},...t.commandDescriptors.length>0?{modelCommandExecutor:t.executeModelCommand,modelCommandToolPrefix:e.modelCommandToolPrefix,isModelCommandInvocable:t.isModelCommandInvocable}:{}});if(fd(o.session,{isFork:e.forkSession===!0||e.workspaceMovedFrom!==void 0,restoredSystemPrompt:t.restoredSystemPrompt,explicitSystemPrompt:e.systemPrompt}),t.pendingRestoreMessages){for(let e of t.pendingRestoreMessages)Or(o.session,e);o.session.syncContextFromHistory()}return{session:o.session,agentsFileEntries:o.agentsFileEntries,projectNotesFileEntries:o.projectNotesFileEntries,rebuildSystemMessage:o.rebuildSystemMessage,autoCompactThresholdSource:i}}function Lm(e,t,n,r,i,a,o,s,c,l,u,d,f,p=!1,m){try{let h=t.getSessionId(),g=e.load(h);if(g.status!==`valid`&&g.status!==`missing`){if(p)throw Error(`Session record cannot be updated: ${g.status}`);return}let _=g.status===`valid`?g.record:void 0,v=l?.snapshotId??_?.sandboxSnapshotId;e.save(Rm({session:t,sessionId:h,sessionName:n??_?.name,cwd:r,history:i,createdAt:_?.createdAt,backgroundState:a,memoryState:o,skillActivationState:s,contextReferenceState:c,...v===void 0?{}:{sandboxSnapshotId:v},...u===void 0?{}:{goalState:u},...d===void 0?{}:{planState:d},...f===void 0?{}:{activeBranchState:f},...m!==void 0||_?.sessionLoops!==void 0?{sessionLoops:m??_?.sessionLoops}:{}}))}catch(e){if(p)throw e}}function Rm(e){return{id:e.sessionId,...e.goalState===void 0?{}:{goal:e.goalState},...e.planState===void 0?{}:{plan:e.planState},...e.activeBranchState===void 0?{}:{activeBranch:e.activeBranchState},...e.sessionLoops===void 0?{}:{sessionLoops:[...e.sessionLoops]},...e.sessionName===void 0?{}:{name:e.sessionName},cwd:e.cwd,createdAt:e.createdAt??new Date().toISOString(),updatedAt:new Date().toISOString(),messages:e.session.getHistory(),history:e.history,systemPrompt:e.session.getSystemMessage(),toolSchemas:e.session.getToolSchemas(),...e.sandboxSnapshotId===void 0?{}:{sandboxSnapshotId:e.sandboxSnapshotId},...zm(e.backgroundState),...Bm(e.memoryState),...Vm(e.skillActivationState),...Hm(e.contextReferenceState)}}function zm(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function Bm(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function Vm(e){return e?{skillActivationEvents:[...e.events]}:{}}function Hm(e){return e?{contextReferences:[...e.references]}:{}}var Um=class extends Error{constructor(e){super(e),this.name=`ProviderConfigError`}};function Wm(e){return Gc(e)}function Gm(e,n=process.env){for(let r of e){let e=r.defaults;if(e?.apiKey===void 0||e.model===void 0||!(0,t.isEnvReference)(e.apiKey))continue;let i=e.apiKey.slice(t.ENV_REFERENCE_PREFIX.length).trim();if(i.length===0)continue;let a=n[i];if(a!==void 0&&a.length!==0)return{name:r.type,model:e.model,apiKey:a,...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},...e.options!==void 0&&{options:e.options},source:`env-default`,sourceEnvVar:i,apiKeyEnv:i}}}function Km(e,t={}){let n=Xc(Wm(e),t.providerOverride,t.providerDefinitions??[],t.env);if(n!==void 0)return n;let r=Gm(t.providerDefinitions??[],t.env);if(r!==void 0)return r;throw new Um(`No provider configuration found. Configure a provider before starting a session.`)}function qm(e,n,r={}){let i=r.providerDefinitions??[],a=Km(e,{...r,providerDefinitions:i}),o=n??a.model;return(0,t.createProviderFromConfig)({...a,model:o},i)}function Jm(e,t,n,r){let i={providerOverride:e,providerDefinitions:t,...r!==void 0&&{env:r}},a=Km(n,i),o=qm(n,void 0,i);return An(o,On(a,t)),{settings:a,provider:o}}function Ym(e,t){return e?.displayName??t.type??`Unknown provider`}function Xm(e,t){let n=t?.modelCatalog,r=(n!==void 0&&n.status!==`unavailable`?n.entries??[]:[]).map(e=>({id:e.id,label:e.displayName}));return typeof e.model==`string`&&e.model.length>0&&(r.some(t=>t.id===e.model)||r.push({id:e.model,label:e.model})),r}function Zm(e,t){let n=Object.keys(e);return t===void 0||!n.includes(t)?n:[t,...n.filter(e=>e!==t)]}function Qm(e,n,r,i,a){let o=e??{},s=[];for(let e of Zm(o,n)){if(a!==void 0&&!a.includes(e))continue;let n=o[e];if(n===void 0||!n.type||!n.model)continue;let r=(0,t.findProviderDefinition)(i,n.type);s.push({profileName:e,providerLabel:Ym(r,n),models:Xm(n,r)})}return{groups:s,...n===void 0?{}:{currentProfile:n},currentModel:r}}function $m(e,t){for(let n of e.groups){let e=n.models.find(e=>e.id===t);if(e!==void 0)return{profileName:n.profileName,model:e}}}var eh=class extends Error{sessionId;outcome;constructor(e,t){super(`session ${e} could not be renamed on disk: the stored record is ${t}`),this.name=`SessionRenameUnavailableError`,this.sessionId=e,this.outcome=t}};function th(e,t,n){let r=e.load(t);if(r.status===`missing`)return;if(r.status!==`valid`)throw new eh(t,r.status);let i={...r.record,name:n,updatedAt:new Date().toISOString()};e.save(i)}var nh=class{deps;inFlight;constructor(e){this.deps=e}async listRuntimeTools(){return this.assertOpen(),await this.deps.ensureInitialized(),this.assertOpen(),this.deps.session().listRuntimeTools()}async invokeRuntimeTool(e,t,n){this.assertOpen(),n?.signal?.throwIfAborted();let r=this.deps.controller();if(r.pendingCount()>0)throw Error(`A submission is already queued.`);let i=r.executionClaim.acquire(`runtime-tool`),a=(async()=>(await this.deps.ensureInitialized(),this.assertOpen(),n?.signal?.throwIfAborted(),this.deps.session().invokeRuntimeTool(e,t,n)))();this.inFlight=a;try{return await a}finally{this.inFlight=void 0,r.executionClaim.complete(i,()=>{})}}async drain(){await this.inFlight?.then(()=>{},()=>{})}assertOpen(){if(this.deps.controller().shuttingDown)throw Error(`Interactive session is shutting down.`)}};function rh(e){return{name:e.name,...e.displayName===void 0?{}:{displayName:e.displayName},description:e.description,...e.example===void 0?{}:{example:e.example},modelInvocable:e.modelInvocable===!0,runner:e.runner??`runtime`,...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.subcommands!==void 0&&e.subcommands.length>0?{subcommands:e.subcommands.map(ih)}:{}}}function ih(e){return{name:e.name,description:e.description,...e.displayName===void 0?{}:{displayName:e.displayName},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint}}}function ah(e){return{name:e.name,description:e.description,source:e.source,modelInvocable:e.disableModelInvocation!==!0,userInvocable:e.userInvocable!==!1,...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.context===void 0?{}:{context:e.context},...e.agent===void 0?{}:{agent:e.agent}}}var oh=class extends Error{role;existingCommandName;duplicateCommandName;code=`DUPLICATE_SYSTEM_COMMAND_SEMANTIC_ROLE`;constructor(e,t,n){super(`System command semantic role "${e}" is claimed by both "${t}" and "${n}".`),this.role=e,this.existingCommandName=t,this.duplicateCommandName=n,this.name=`DuplicateSystemCommandSemanticRoleError`}};const sh=c.AUTO_COMPACT_THRESHOLD,ch=`autoCompactThreshold`;function lh(e){return e.getContextState()}function uh(e){return e.getAutoCompactThreshold()}function dh(e){return e.getAutoCompactThresholdSource()}function fh(e,t,n){e.setAutoCompactThreshold(t,n)}function ph(e,t){let n=bh(e);return n?(n.write({...n.read(),[ch]:t}),!0):!1}function mh(e){let t=bh(e);if(!t)return!1;let n={...t.read()};return delete n[ch],t.write(n),!0}async function hh(e,t){let n=lh(e),r=e.getSession().getMessageCount();return await e.compactContext(t),{before:n,after:lh(e),beforeMessageCount:r,afterMessageCount:e.getSession().getMessageCount()}}function gh(e){return e.listContextReferences()}async function _h(e,t){return e.addContextReference(t)}function vh(e,t){return e.removeContextReference(t)}function yh(e){return e.clearContextReferences()}function bh(e){return e.getCommandHostAdapters?.().settings}function xh(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function Sh(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function Ch(e,t,n={}){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);let r={...e.providers};if(delete r[t],n.replacementCurrentProvider!==void 0&&r[n.replacementCurrentProvider]===void 0)throw Error(`Provider profile "${n.replacementCurrentProvider}" was not found`);let i={...e,providers:r};if(e.currentProvider!==t)return i;if(n.replacementCurrentProvider!==void 0)return{...i,currentProvider:n.replacementCurrentProvider};let a={...i};return delete a.currentProvider,a}function wh(e,n,r={}){if(!n.type)throw Error(`Provider profile "${e}" is missing type`);let i=r.providerDefinitions??[],a=(0,t.findProviderDefinition)(i,n.type);if(a===void 0&&i.length>0)throw Error(`Unknown provider "${n.type}". Supported providers: ${(0,t.formatSupportedProviderTypes)(i)}`);if(!n.model)throw Error(`Provider profile "${e}" is missing model`);let o=(0,t.getProviderCredentialRequirement)(a);if(o!==void 0&&!kh(n,a?.defaults,o,r.env))throw Error(`Provider profile "${e}" is missing ${jh(o)}`)}function Th(e,t={}){let n=Eh(e,t);return wh(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function Eh(e,n={}){let r=Oh(e.type,n.providerDefinitions??[]);if(e.apiKey!==void 0&&e.apiKeyEnv===void 0&&console.warn(`API key stored as plain text in settings. Use --api-key-env for better security.`),e.apiKeyEnv!==void 0){let t=(n.env??process.env)[e.apiKeyEnv];if(t===void 0||t.length===0)throw Error(`Environment variable ${e.apiKeyEnv} is not set — set it before configuring (the profile will reference $ENV:${e.apiKeyEnv})`)}let i=e.apiKeyEnv===void 0?e.apiKey??r.apiKey:(0,t.formatEnvReference)(e.apiKeyEnv),a=e.baseURL??r.baseURL;return{type:e.type,model:e.model??r.model,...Mh(i)&&{apiKey:i},...a!==void 0&&{baseURL:a},...e.timeout!==void 0&&{timeout:e.timeout}}}function Dh(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=xh(e,n,r);return t.currentProvider?Sh(i,t.currentProvider):i}function Oh(e,n){return(0,t.findProviderDefinition)(n,e)?.defaults??{}}function kh(e,n,r,i){return r.anyOf.some(r=>(0,t.hasUsableSecretReference)(Ah(r,e,n),i===void 0?void 0:e=>i[e]))}function Ah(e,t,n){return t[e]??n?.[e]}function jh(e){return e.anyOf.join(` or `)}function Mh(e){return e!==void 0&&e.length>0}async function Nh(e,n,r,i){let a=r??e;if(!a)return{message:`No provider profile selected.`,success:!1};let o=n?.[a];if(!o)return{message:`Provider profile "${a}" was not found.`,success:!1};try{wh(a,o,{providerDefinitions:i.providerDefinitions})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let s=await((o.type?(0,t.findProviderDefinition)(i.providerDefinitions,o.type):void 0)?.probeProfile??Ph)(o);return{message:s.ok?`Provider "${a}" test passed: ${s.message}`:`Provider "${a}" test failed: ${s.message}; manual configuration can continue.`,success:!0,data:{providerTest:{profile:a}}}}async function Ph(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function Fh(e,t=[]){return Ih(e,t)?`valid`:`incomplete`}function Ih(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return Lh(n?.type,n,t)}return!!(e.provider&&Lh(e.provider.name,e.provider,t))}function Lh(e,n,r){if(!n)return!1;if(!e)return(0,t.hasUsableSecretReference)(n.apiKey);let i=(0,t.findProviderDefinition)(r,e);if(i===void 0)return!1;let a=(0,t.getProviderCredentialRequirement)(i);return a===void 0||Rh(n,i,a)}function Rh(e,n,r){return r.anyOf.some(r=>(0,t.hasUsableSecretReference)(zh(r,e,n)))}function zh(e,t,n){return t[e]??n.defaults?.[e]}function Bh(e,t=[]){if(!(0,d.existsSync)(e))return`missing`;try{let n=(0,d.readFileSync)(e,`utf8`).trim();return n.length===0?`incomplete`:Fh(JSON.parse(n),t)}catch{return`corrupt`}}function Vh(e){let t=Jh(e)??e[0];if(t===void 0)throw Error(`No settings store available for provider update`);return t}function Hh(e){return e.read()}function Uh(e,t,n={}){let r=Dh(Hh(e),Th(t,n));return e.write(r),r}function Wh(e,t,n={}){let r=Hh(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:Sh(r,t);return e.write(o),o}function Gh(e,t,n,r={}){let i=Gc(e),a=r.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Kh(t,a,n)}function Kh(e,t,n){let r=qh(e,t)??e[0];if(r===void 0)throw Error(`No settings store available for model update`);let i=Hh(r),a=i.providers??{},o=a[t]??{},s={...i,providers:{...a,[t]:{...o,model:n}}};return r.write(s),{settingsPath:r.displayName,settings:s,profileName:t}}function qh(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&Hh(r).providers?.[t]!==void 0)return r}}function Jh(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&Hh(n).currentProvider!==void 0)return n}}function Yh(e,t){return e?.displayName??t.type??`Unknown provider`}function Xh(e,t){let n=t?.modelCatalog;return(n!==void 0&&n.status!==`unavailable`?n.entries??[]:[]).find(t=>t.id===e)?.displayName??e}function Zh(e,t,n){let r=e[n]??t?.defaults?.[n];return typeof r==`string`?r:void 0}function Qh(e,n){let r=(0,t.getProviderCredentialRequirement)(n);if(r!==void 0)return r.anyOf.some(r=>(0,t.hasUsableSecretReference)(Zh(e,n,r)))?void 0:`Key missing`}function $h(e,n,r,i){let a=e??{},o=[];for(let e of Object.keys(a)){if(i!==void 0&&!i.includes(e))continue;let s=a[e];if(s===void 0)continue;let c=typeof s.type==`string`?(0,t.findProviderDefinition)(r,s.type):void 0,l=Qh(s,c);o.push({name:e,providerLabel:Yh(c,s),...typeof s.model==`string`&&s.model.length>0?{model:{id:s.model,label:Xh(s.model,c)}}:{},current:e===n,...l===void 0?{}:{connectionState:l}})}return{profiles:o}}const eg=`this session (CLI flags, preset, commands)`,tg=[`deny`,`ask`,`allow`],ng=[`plan`,`default`,`acceptEdits`,`bypassPermissions`,`auto`],rg={plan:`Plan only`,default:`Ask first`,acceptEdits:`Accept edits`,bypassPermissions:`Skip all checks`,auto:`Auto`};function ig(e=`mode`){return[{name:`plan`,displayName:rg.plan,description:`Plan only, no execution`,source:e},{name:`default`,displayName:rg.default,description:`Ask before risky actions`,source:e},{name:`acceptEdits`,displayName:rg.acceptEdits,description:`Auto-approve file edits`,source:e},{name:`bypassPermissions`,displayName:rg.bypassPermissions,description:`Skip all permission checks`,source:e},{name:`auto`,displayName:rg.auto,description:`A model classifier approves or blocks risky actions`,source:e}]}function ag(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function og(e){return ng.includes(e)}function sg(){return`Invalid mode. Valid: ${ng.join(` | `)}`}function cg(e){let t=e.getCommandHostAdapters?.().permissionMode;if(t!==void 0)return t;let n=e.getSession();return{getPermissionMode:()=>n.getPermissionMode(),setPermissionMode:e=>n.setPermissionMode(e),listSessionAllowedTools:()=>n.getSessionAllowedTools(),getPermissionRules:()=>n.getPermissionRules(),listRecentDenials:()=>n.getRecentPermissionDenials(),retryDenial:e=>n.retryPermissionDenial(e)}}function lg(e){return cg(e).getPermissionMode()}function ug(e,t){cg(e).setPermissionMode(t)}function dg(e,t){if(!(!Number.isInteger(t)||t<1))return cg(e).retryDenial(t-1)}function fg(e){return cg(e).listSessionAllowedTools()}function pg(e,t){let n=new Set,r=[];for(let i of t){let t=t=>i[t].filter(n=>e[t].includes(n)),a={source:i.source,scope:i.scope,deny:t(`deny`),ask:t(`ask`),allow:t(`allow`)};for(let e of tg)for(let t of a[e])n.add(`${e}\0${t}`);tg.some(e=>a[e].length>0)&&r.push(a)}let i=t=>[...new Set(e[t])].filter(e=>!n.has(`${t}\0${e}`)),a={source:eg,deny:i(`deny`),ask:i(`ask`),allow:i(`allow`)};return tg.some(e=>a[e].length>0)&&r.push(a),r}function mg(e){let t=cg(e),n=e.getCommandHostAdapters?.().permissionRules?.readLayers()??[];return{mode:t.getPermissionMode(),sessionAllowed:t.listSessionAllowedTools(),rules:pg(t.getPermissionRules(),n),recentDenials:t.listRecentDenials()}}const hg={policy:`denied by a rule or the mode`,user:`declined when asked`,"no-approver":`needed approval, none available`,classifier:`blocked by the auto-mode classifier`};function gg(e){let t=new Date(e);return[t.getHours(),t.getMinutes(),t.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`)}function _g(e){let t=[`Permission mode: ${e.mode}`,``];if(e.rules.length===0)t.push(`Rules: none configured.`);else{t.push(`Rules (checked deny, then ask, then allow):`);for(let n of e.rules){t.push(` ${n.source}${n.scope===void 0?``:` [${n.scope}]`}`);for(let e of tg)n[e].length>0&&t.push(` ${e}: ${n[e].join(`, `)}`)}}return t.push(``),e.sessionAllowed.length>0?t.push(`Approved this session ("allow always"): ${e.sessionAllowed.join(`, `)}`):t.push(`No session-approved tools.`),t.push(``),e.recentDenials.length===0?t.push(`Recent denials: none.`):(t.push(`Recent denials (most recent first):`),e.recentDenials.forEach((e,n)=>{let r=e.argument===void 0?e.toolName:`${e.toolName}(${e.argument})`,i=hg[e.reason],a=e.detail===void 0?``:`: ${e.detail}`;t.push(` ${n+1}. ${gg(e.at)} ${r} — ${i}${a}`)}),e.recentDenials.some(e=>e.reason===`classifier`)&&t.push(` To let a blocked call run once when the model retries it: /permissions retry <n>`)),t.join(`
114
+ `),s=Bp(o),c=(await t?.loadStartupMemory())?.content||void 0,l=n.taskContext?.enabled!==!1&&n.taskContext?.dir&&e!==void 0?Ip(e.reader,{...n.taskContext?.dir?{dir:n.taskContext.dir}:{},...e.currentBranch?{currentBranch:e.currentBranch}:{}}):``;return{agentsMd:a,projectNotesMd:o,memoryMd:c,taskContext:l.trim().length>0?l:void 0,compactInstructions:s,agentsFileEntries:r,projectNotesFileEntries:i}}const Y={packageJson:`package.json`,tsconfig:`tsconfig.json`,pnpmWorkspace:`pnpm-workspace.yaml`,pnpmLock:`pnpm-lock.yaml`,yarnLock:`yarn.lock`,bunLock:`bun.lockb`,npmLock:`package-lock.json`,pyproject:`pyproject.toml`,setup:`setup.py`,cargo:`Cargo.toml`,goMod:`go.mod`};function Hp(e,t){let n=e.readText(t,`detect project package metadata`);if(n!==void 0)try{return JSON.parse(n)}catch{return}}function X(e,t){return e.inspectKind(t,`detect project type`)===`file`}function Up(e){if(X(e,Y.pnpmWorkspace)||X(e,Y.pnpmLock))return`pnpm`;if(X(e,Y.yarnLock))return`yarn`;if(X(e,Y.bunLock))return`bun`;if(X(e,Y.npmLock))return`npm`}async function Wp(e){let t=R(e);if(X(t,Y.packageJson)){let e=Hp(t,Y.packageJson),n=X(t,Y.tsconfig)?`typescript`:`javascript`,r=Up(t);return{type:`node`,name:e?.name,packageManager:r,language:n}}return X(t,Y.pyproject)||X(t,Y.setup)?{type:`python`,language:`python`}:X(t,Y.cargo)?{type:`rust`,language:`rust`}:X(t,Y.goMod)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}async function Gp(e,t,n=[],r=[],i={}){if(e!==void 0)return{config:e,hookSources:[]};let a=t?.status===`trusted`?B(t.authority):void 0;return xp([...r,...a===void 0?[]:Uc(a,n)],i)}async function Kp(e,t){return e.config===void 0?Gp(void 0,t,e.projectSettingsPaths,e.userSettingsSources,e.environment):{config:e.config,hookSources:e.hookSources??[]}}async function qp(e){let t=e.projectAccess??V(`identity-unavailable`,e.cwd),n=t.status===`trusted`?B(t.authority):void 0,i=t.status!==`trusted`||n===void 0?void 0:{reader:n,startRelativeDirectory:(0,r.relative)(t.identity.worktreeRoot,(0,r.resolve)(e.cwd))},{config:a,hookSources:o}=await Kp(e,t),s={...e.taskContext,...a.taskContext},[c,l]=await Promise.all([e.bare?Promise.resolve({agentsMd:``,projectNotesMd:``,agentsFileEntries:[],projectNotesFileEntries:[]}):Vp(i,e.memoryStore,s.dir!==void 0||s.enabled!==void 0?{taskContext:s}:{}),e.bare||n===void 0?Promise.resolve({type:`unknown`,language:`unknown`}):Wp(n)]);return{projectAccess:t,config:a,context:c,projectInfo:l,contributionSources:e.contributionSources??[],hookSources:o}}function Jp(e){if(e)return`Run /${e} and retry.`}function Yp(e,t,n,i=new Ci){let a=(0,r.join)(n,e,`subagents`);return i.mkdirSync(a,{recursive:!0}),new c.FileSessionLogger(new c.NodeSessionLogSink(a))}function Xp(e,t){return(0,r.join)(t,e,`subagents`)}var Zp=class{settingsPath;fs;constructor(e,t=new Ci){this.settingsPath=e,this.fs=t}readAll(){if(!this.fs.existsSync(this.settingsPath))return{};let e=this.fs.readFileSync(this.settingsPath,`utf-8`),t;try{t=JSON.parse(e)}catch(e){throw Error(`Plugin settings cannot be read: ${this.settingsPath} is not valid JSON. Fix the file; until then no plugin is loaded and plugin settings are not changed.`,{cause:e})}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Plugin settings cannot be read: ${this.settingsPath} does not hold a JSON object.`);return t}writeAll(e){let t=(0,r.dirname)(this.settingsPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.settingsPath,JSON.stringify(e,null,2),`utf-8`)}getEnabledPlugins(){let e=this.readAll().enabledPlugins;return typeof e==`object`&&e?e:{}}setPluginEnabled(e,t){let n=this.readAll(),r=this.getEnabledPluginsFrom(n);r[e]=t,n.enabledPlugins=r,this.writeAll(n)}removePluginEntry(e){let t=this.readAll(),n=this.getEnabledPluginsFrom(t);delete n[e],t.enabledPlugins=n,this.writeAll(t)}getMarketplaceSources(){let e=this.readAll().extraKnownMarketplaces;return typeof e==`object`&&e?e:{}}setMarketplaceSource(e,t){let n=this.readAll(),r=this.getMarketplaceSourcesFrom(n);r[e]={source:t},n.extraKnownMarketplaces=r,this.writeAll(n)}removeMarketplaceSource(e){let t=this.readAll(),n=this.getMarketplaceSourcesFrom(t);delete n[e],t.extraKnownMarketplaces=n,this.writeAll(t)}getEnabledPluginsFrom(e){let t=e.enabledPlugins;return typeof t==`object`&&t?t:{}}getMarketplaceSourcesFrom(e){let t=e.extraKnownMarketplaces;return typeof t==`object`&&t?t:{}}},Qp=class extends Error{name=`PluginPathContainmentError`};const $p=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function em(e){return typeof e==`string`&&e.length>0&&e.length<=128&&$p.test(e)}function tm(e,t){if(!em(e))throw Error(`Invalid plugin ${t}: ${JSON.stringify(e)}. It is used as a filesystem path component, so it must be 1-128 characters of letters, digits, dot, underscore or hyphen, starting with a letter or digit.`)}function nm(e,t){let n=(0,r.resolve)(e),i=[];for(;;){if(t.existsSync(n))return(0,r.resolve)(t.realpathSync(n),...i.reverse());let a=(0,r.resolve)(n,`..`);if(a===n)return(0,r.resolve)(e);i.push(n.slice(a.length+1)),n=a}}function rm(e,t,n,i){let a=nm(e,i),o=nm(t,i);if(!(o===a||o.startsWith(a.endsWith(r.sep)?a:a+r.sep)))throw new Qp(`Refusing to ${n} outside the plugin root: ${JSON.stringify(t)} resolves to ${JSON.stringify(o)}, which is not inside ${JSON.stringify(a)}.`)}function im(e,t,n,i){if((0,r.isAbsolute)(t))throw new Qp(`Refusing to ${n} from an absolute path: ${JSON.stringify(t)}. This field takes a path relative to the plugin root.`);let a=(0,r.resolve)(e,t);return rm(e,a,n,i),a}var am=class extends Error{code;name=`McpContributionError`;constructor(e){super(e),this.code=e}};function om(e,t=!0){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Date)throw new am(`invalid-object`);let n=t&&Object.hasOwn(e,`mcpServers`)?e.mcpServers:e;if(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date)throw new am(`invalid-object`);return n}function sm(e,t,n,i){let a=(0,r.join)(e,`.mcp.json`),o=t=>(rm(e,t,`read MCP contribution`,n),JSON.parse(n.readFileSync(t,`utf-8`))),s=n.existsSync(a)?o(a):void 0;if(t===void 0)return s;if(s!==void 0&&i)for(let e of Object.keys(om(s)))i(e,a);let c=Array.isArray(t)?t:[t],l=s===void 0?{}:{...om(s)};for(let t of c){let n=t,a=(0,r.join)(e,`.claude-plugin`,`plugin.json`);if(typeof t==`string`){if(!t.startsWith(`./`)||!t.endsWith(`.json`)||t.includes(`\\`))throw new am(`unsupported-path`);a=(0,r.join)(e,t),n=o(a)}let s=om(n,typeof t==`string`);for(let e of Object.keys(s))i?.(e,a);l={...l,...s}}return{mcpServers:l}}const cm={"manifest-unreadable":`plugin manifest could not be read — skipping this plugin`,"manifest-invalid":`plugin manifest is not a valid plugin.json — skipping this plugin`,disabled:`plugin is disabled`,"load-failed":`plugin failed to load — skipping this plugin`,"revision-unselected":`plugin has no valid selected installed revision — skipping this plugin`},lm=/position (\d+)/;function um(e){if(e===void 0)return`Error`;if(e instanceof am)return`${e.name} [${e.code}]`;if(e instanceof iu)return e.diagnostics.map(e=>`${e.line===void 0?e.source:`${e.source}:${e.line}${e.column===void 0?``:`:${e.column}`}`} [${e.code}]${e.field===void 0?``:` ${e.field}`}`).join(`; `);let t=lm.exec(e.message);return t===null?e.name:`${e.name} at position ${t[1]}`}function dm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function fm(e,t,n,r){let i=dm(r)?r:{},a=typeof i.command==`string`?i.command:void 0,o=typeof i.url==`string`?i.url:void 0;return{pluginId:e,mcpPath:t,name:n,transport:a===void 0?o===void 0?`unknown`:`http`:`stdio`,...a===void 0?{}:{command:a},...o===void 0?{}:{url:o},envKeys:dm(i.env)?Object.keys(i.env):[]}}function pm(e,t,n,i){if(Object.keys(n).length===0)return;let a=Zf.safeParse(n);a.success||i.push({pluginId:e,hooksPath:(0,r.join)(t,`hooks`,`hooks.json`),issues:a.error.issues.map(e=>({path:e.path.map(String).join(`.`),code:e.code}))})}function mm(e,t,n,i,a){if(n===void 0)return;let o=(0,r.join)(t,`.mcp.json`);if(!dm(n)){i.mcpFaults.push({pluginId:e,mcpPath:o,reason:`not-an-object`});return}let s=n.mcpServers;if(!dm(s)){i.mcpFaults.push({pluginId:e,mcpPath:o,reason:`no-servers`});return}for(let[t,n]of Object.entries(s)){let r=a&&Object.hasOwn(a,t)?a[t]:o;i.mcpServers.push(fm(e,r,t,n))}}function hm(e){if(typeof e!=`object`||!e)return null;let t=e;if(typeof t.name!=`string`||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t.name)||t.version!==void 0&&typeof t.version!=`string`||t.description!==void 0&&typeof t.description!=`string`)return null;let n=typeof t.features==`object`&&t.features!==null?t.features:{};return{name:t.name,...typeof t.version==`string`?{version:t.version}:{},...typeof t.description==`string`?{description:t.description}:{},...Object.fromEntries([`commands`,`skills`,`hooks`,`agents`].filter(e=>Object.hasOwn(t,e)).map(e=>[e,t[e]])),...t.mcpServers===void 0?{}:{mcpServers:t.mcpServers},features:{commands:n.commands===!0||void 0,agents:n.agents===!0||void 0,skills:n.skills===!0||void 0,hooks:n.hooks===!0||void 0,mcp:n.mcp===!0||void 0}}}function gm(e,t=new Ci){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function _m(e,t){let n=[],i=[],a=(t,n,r,a,o,s=`supported`)=>{i.push({identity:`${e.manifest.name}:${t}:${n}`,kind:t,source:r,requiredCapabilities:a,disposition:s,...o?{reason:o}:{}})};for(let t of e.commands)a(`command`,t.name.startsWith(`${e.manifest.name}:`)?t.name.slice(e.manifest.name.length+1):t.name,t.skillDirectory??(0,r.join)(e.pluginDir,`commands`),[`command-router`]);for(let t of e.skills)a(`skill`,t.name,t.skillDirectory??(0,r.join)(e.pluginDir,`skills`),[`skill-reader`]);let o=typeof e.hooks.hooks==`object`&&e.hooks.hooks!==null?e.hooks.hooks:e.hooks;for(let t of Object.keys(o))a(`hook`,t,(0,r.join)(e.pluginDir,`hooks`,`hooks.json`),[`hook-executor`]);for(let t of e.agents)a(`agent`,t,(0,r.join)(e.pluginDir,`agents`),[`agent-router`],`Agent names are inspected; execution definitions are unavailable from this adapter`,`unavailable`);let s=e.mcpConfig;if(typeof s==`object`&&s&&!Array.isArray(s)&&!(s instanceof Date)){let t=s.mcpServers;if(typeof t==`object`&&t&&!Array.isArray(t)&&!(t instanceof Date))for(let[i,o]of Object.entries(t)){let t=[`mcp-client`],s=!1;if(typeof o==`object`&&o&&!Array.isArray(o)&&!(o instanceof Date)){let e=o.type??(typeof o.command==`string`?`stdio`:typeof o.url==`string`?`http`:void 0);e===`stdio`?(t.push(`stdio-authority`),s=typeof o.command==`string`):e===`http`&&(t.push(`http-transport`),s=typeof o.url==`string`)}a(`mcp`,i,e.mcpSourcePaths?.[i]??(0,r.join)(e.pluginDir,`.mcp.json`),t,s?void 0:`No supported transport declaration`,s?`supported`:`unsupported`),s||n.push({component:`mcp`,code:`unsupported-transport`})}}s!==void 0&&(typeof s!=`object`||!s||Array.isArray(s)||s instanceof Date||typeof s.mcpServers!=`object`||s.mcpServers===null||Array.isArray(s.mcpServers)||s.mcpServers instanceof Date)&&n.push({component:`mcp`,code:`invalid-configuration`});for(let t of[`commands`,`skills`,`hooks`,`agents`])e.manifest[t]!==void 0&&(n.push({component:t,code:`unsupported-component-declaration`}),i.push({identity:`${e.manifest.name}:declaration:${t}`,kind:t===`commands`?`command`:t===`skills`?`skill`:t===`hooks`?`hook`:`agent`,source:(0,r.join)(e.pluginDir,`.claude-plugin`,`plugin.json`),requiredCapabilities:[],disposition:`unsupported`,reason:`Declared component paths are not consumed by this adapter`}));let c=(0,r.basename)(e.pluginDir);return{schemaVersion:1,identity:t,installedRevision:c,generation:JSON.stringify([t,c,e.pluginDir]),source:{kind:`bundle`,location:e.pluginDir},requiredCapabilities:[...new Set(i.flatMap(e=>e.requiredCapabilities))],contributions:i,lifecycle:{activation:`unadmitted`,activeCalls:`host-owned`},diagnostics:n}}const vm=(0,t.createLogger)(`BundlePluginLoader`);function ym(e,t){let n=be({source:e,content:t,profile:`bundle-skill`});if(!n.ok)throw new iu(n.diagnostics);return n}var bm=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new Ci){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){let e=this.inspectPluginsSync();for(let t of e.skipped)t.reason!==`disabled`&&vm.warn(cm[t.reason],{plugin:t.pluginId,manifestPath:t.manifestPath,...t.detail===void 0?{}:{error:t.detail}});return[...e.loaded]}async loadAll(){return this.loadPluginsSync()}inspectPluginsSync(){let e=(0,r.join)(this.pluginsDir,`cache`),t=this.snapshotInstalledSelection(),n=new Set,i={loaded:[],skipped:[],hookIssues:[],mcpServers:[],mcpFaults:[]},a=this.fs.existsSync(e);if(a)for(let a of gm(e,this.fs)){let o=(0,r.join)(e,a);for(let e of gm(o,this.fs))n.add(`${e}@${a}`),this.inspectPluginDir(a,e,(0,r.join)(o,e),i,t)}for(let e of Object.keys(t.records??{}))n.has(e)||i.skipped.push({pluginId:e,manifestPath:(0,r.join)(this.pluginsDir,`installed_plugins.json`),reason:`revision-unselected`,detail:`Selected plugin source is missing from cache`});return t.error&&n.size===0&&i.skipped.push({pluginId:`installed_plugins.json`,manifestPath:(0,r.join)(this.pluginsDir,`installed_plugins.json`),reason:`revision-unselected`,detail:um(t.error)}),{pluginsDir:this.pluginsDir,cacheDirPresent:a,...i}}inspectPluginDir(e,t,n,i,a){let o=gm(n,this.fs),s=`${t}@${e}`,c;try{c=this.selectRevision(n,e,t,o,a)}catch(e){i.skipped.push({pluginId:s,manifestPath:(0,r.join)(n,`.claude-plugin`,`plugin.json`),reason:`revision-unselected`,detail:um(e instanceof Error?e:void 0)});return}let l=(0,r.join)(c,`.claude-plugin`,`plugin.json`),u;try{u=this.readManifest(l)}catch(e){let t=um(e instanceof Error?e:void 0);i.skipped.push({pluginId:s,manifestPath:l,reason:`manifest-unreadable`,detail:t});return}if(!u){i.skipped.push({pluginId:s,manifestPath:l,reason:`manifest-invalid`});return}let d=`${u.name}@${e}`;if(this.isDisabled(s,t)||this.isDisabled(d,u.name)){i.skipped.push({pluginId:d,manifestPath:l,reason:`disabled`});return}try{let e=this.loadPlugin(c,u);e.descriptor=_m(e,s),i.loaded.push(e),pm(d,c,e.hooks,i.hookIssues),mm(d,c,e.mcpConfig,i,e.mcpSourcePaths)}catch(e){let t=um(e instanceof Error?e:void 0);i.skipped.push({pluginId:d,manifestPath:l,reason:`load-failed`,detail:t})}}snapshotInstalledSelection(){let e=(0,r.join)(this.pluginsDir,`installed_plugins.json`);if(!this.fs.existsSync(e))return{};try{let t=JSON.parse(this.fs.readFileSync(e,`utf-8`));if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Invalid installed registry`);return{records:t}}catch(e){return{error:e instanceof Error?e:Error(`Invalid installed registry`)}}}selectRevision(e,t,n,i,a){if(a.error)throw a.error;let o;if(a.records){let i=Object.hasOwn(a.records,`${n}@${t}`)?a.records[`${n}@${t}`]:void 0;if(typeof i!=`object`||!i||Array.isArray(i))throw Error(`No selected installation`);let s=i;if(tm(s.version,`installed revision`),o=s.version,s.pluginName!==n||s.marketplace!==t||typeof s.installPath!=`string`||(0,r.resolve)(s.installPath)!==(0,r.resolve)(e,o))throw Error(`Installed record does not match its cached source`)}else{if(i.length!==1)throw Error(`Select an installed revision before loading multiple cached sources`);o=i[0]}tm(o,`source revision`);let s=(0,r.join)(e,o);if(!i.includes(o))throw Error(`Selected revision is not installed`);return rm((0,r.join)(this.pluginsDir,`cache`),s,`load installed source`,this.fs),rm(e,s,`load selected plugin revision`,this.fs),rm(s,(0,r.join)(s,`.claude-plugin`,`plugin.json`),`read plugin manifest`,this.fs),s}readManifest(e){let t=this.fs.readFileSync(e,`utf-8`);return hm(JSON.parse(t))}isDisabled(e,t){return e in this.enabledPlugins?this.enabledPlugins[e]===!1:t in this.enabledPlugins&&this.enabledPlugins[t]===!1}loadPlugin(e,t){let n={},r=sm(e,t.mcpServers,this.fs,(e,t)=>{n={...n,[e]:t}});return{manifest:t,skills:this.loadSkills(e,t.name),commands:this.loadCommands(e,t.name),hooks:this.loadHooks(e),mcpConfig:r,mcpSourcePaths:n,agents:this.loadAgents(e),pluginDir:e}}loadSkills(e,t){let n=(0,r.join)(e,`skills`);if(!this.fs.existsSync(n))return[];let i=this.fs.readdirSync(n,{withFileTypes:!0}),a=[];for(let e of i){if(!e.isDirectory())continue;let t=(0,r.join)(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let i=this.fs.readFileSync(t,`utf-8`),{metadata:o,body:s}=ym(t,i),c=typeof o.description==`string`?o.description:``,l={name:e.name,description:c,skillContent:s===i?s:s.trimStart(),...o,skillDirectory:(0,r.join)(n,e.name)};a.push(l)}return a}loadCommands(e,t){let n=(0,r.join)(e,`commands`);if(!this.fs.existsSync(n))return[];let i=this.fs.readdirSync(n,{withFileTypes:!0}),a=[];for(let e of i){if(!e.isFile()||!e.name.endsWith(`.md`))continue;let i=(0,r.join)(n,e.name),o=this.fs.readFileSync(i,`utf-8`),{metadata:s,body:c}=ym(i,o),l=typeof s.name==`string`?s.name:e.name.replace(/\.md$/,``),u=typeof s.description==`string`?s.description:``;a.push({...s,name:`${t}:${l}`,description:u,skillContent:c===o?c:c.trimStart(),skillDirectory:n})}return a}loadHooks(e){let t=(0,r.join)(e,`hooks`,`hooks.json`);if(!this.fs.existsSync(t))return{};let n=this.fs.readFileSync(t,`utf-8`),i=JSON.parse(n);return typeof i==`object`&&i?i:{}}loadAgents(e){let t=(0,r.join)(e,`agents`);return this.fs.existsSync(t)?this.fs.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.name.endsWith(`.md`)).map(e=>e.name.replace(/\.md$/,``)):[]}};function xm(e){if(e.settingsPath===void 0&&e.enabledPlugins===void 0)throw Error(`Plugin enablement requires settingsPath or enabledPlugins`);let t=e.enabledPlugins??new Zp(e.settingsPath,e.fs).getEnabledPlugins();return new bm(e.pluginsDir,t,e.fs)}function Sm(e,t={}){return[...new Set(e)].map(e=>xm({...t,pluginsDir:e}).inspectPluginsSync())}function Cm(e,t={}){let n=new Set,r=[];for(let i of new Set(e))for(let e of xm({...t,pluginsDir:i}).loadPluginsSync())n.has(e.manifest.name)||(n.add(e.manifest.name),r.push(e));return r}function wm(e){return{...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.disableModelInvocation===void 0?{}:{disableModelInvocation:e.disableModelInvocation},...e.userInvocable===void 0?{}:{userInvocable:e.userInvocable},...e.allowedTools===void 0?{}:{allowedTools:e.allowedTools},...e.model===void 0?{}:{model:e.model},...e.effort===void 0?{}:{effort:e.effort},...e.context===void 0?{}:{context:e.context},...e.agent===void 0?{}:{agent:e.agent}}}var Tm=class{name=`plugin`;plugins;constructor(e){this.plugins=e}getCommands(){let e=[];for(let t of this.plugins){for(let n of t.skills){let r=n.name.includes(`@`)?n.name.split(`@`)[0]:n.name;e.push({name:r,description:`(${t.manifest.name}) ${n.description}`,source:`plugin`,skillContent:n.skillContent,...n.skillDirectory===void 0?{}:{skillDirectory:n.skillDirectory},pluginDir:t.pluginDir,...wm(n)})}for(let n of t.commands)e.push({name:n.name,description:n.description,source:`plugin`,skillContent:n.skillContent,...n.skillDirectory===void 0?{}:{skillDirectory:n.skillDirectory},pluginDir:t.pluginDir,...wm(n)})}return e}};function Em(e,t){try{let n=(0,r.relative)((0,d.realpathSync)(Pa(t.authority).worktreeRoot),(0,d.existsSync)(e)?(0,d.realpathSync)(e):(0,r.resolve)(e));return n!==`..`&&!n.startsWith(`..${r.sep}`)&&!(0,r.isAbsolute)(n)}catch{return!1}}function Dm(e){let t=e.projectAccess,n=e.pluginDirectories?.project;return[...t?.status===`trusted`&&n!==void 0&&Em(n,t)?[n]:[],...e.pluginDirectories?.user===void 0?[]:[e.pluginDirectories.user]]}function Om(e){if(e.bare!==!0)return e.userSettingsSources?.find(e=>e.scope===`user`)?.path}function km(e){let t=Om(e);if(t===void 0)return[];try{return new Tm(Cm(Dm(e),{settingsPath:t})).getCommands()}catch{return[]}}function Am(e){let t=(0,r.join)((0,r.dirname)((0,r.dirname)(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function jm(e,t){return Array.isArray(e.hooks)?{...e,hooks:e.hooks.map(e=>typeof e.command==`string`?{...e,command:e.command.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,t)}:e)}:e}function Mm(e){let t={},n=[];for(let i of e){let e=i.hooks;if(!e)continue;let a=Am(i),o=e.hooks??e;for(let[e,s]of Object.entries(o)){if(!Array.isArray(s))continue;t[e]||(t[e]=[]);let o=s.map(e=>{let t=jm(e,i.pluginDir);return t.env=a,t});t[e].push(...o);for(let t of o)if(Array.isArray(t.hooks))for(let a of t.hooks)typeof a?.type==`string`&&n.push({event:e,type:a.type,source:(0,r.join)(i.pluginDir,`hooks`,`hooks.json`)})}}return{hooks:t,hookSources:n}}function Nm(e,t){if(Object.keys(t).length===0)return e;let n={};for(let[e,r]of Object.entries(t))n[e]=[...r];if(e)for(let[t,r]of Object.entries(e))Array.isArray(r)&&(n[t]||(n[t]=[]),n[t].push(...r));return n}const Pm=(0,t.createLogger)(`InteractiveSessionInit`);async function Fm(e){let t=e.cwd,{config:n,context:r,projectInfo:i,contributionSources:a,hookSources:o}=await qp(e),s=e.language?{...n,language:e.language}:n;e.skipConfiguredHooks===!0&&(s={...s,hooks:void 0});let c=e.skipConfiguredHooks===!0?[]:[...o],l=Dm(e),u=Om(e);if(u!==void 0)try{let e=Cm(l,{settingsPath:u});if(e.length>0){let t=Mm(e);s={...s,hooks:Nm(s.hooks,t.hooks)},c.push(...t.hookSources)}}catch(e){Pm.warn(`plugin discovery failed — no bundle plugin hooks are active this session`,{pluginsDirs:l,error:e instanceof Error?e.message:String(e)})}await xf(e)||await bf(e,t);let d=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,f=Jp(e.commandSemanticRoles?.contextReduction),{session:p,rebuildSystemMessage:m}=await ld(vf(e,{mergedConfig:s,cwd:t,context:r,projectInfo:i,sessionId:d,contextCapacityHint:f,contributionSources:a,skillRoots:e.skillRoots}),c);return{session:p,agentsFileEntries:r.agentsFileEntries??[],projectNotesFileEntries:r.projectNotesFileEntries??[],rebuildSystemMessage:m}}async function Im(e,t){let{config:n,hookSources:r}=await Gp(e.config,e.projectAccess,e.projectSettingsPaths,e.userSettingsSources,e.environment),i=n.autoCompactThreshold===void 0?`default`:`settings`,a=e.editCheckpointStore;a!==void 0&&t.setEditCheckpointStore(a);let o=await Fm({cwd:e.cwd,provider:e.provider,...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess},...e.projectSettingsPaths===void 0?{}:{projectSettingsPaths:e.projectSettingsPaths},...e.taskContext===void 0?{}:{taskContext:e.taskContext},...e.userSettingsSources===void 0?{}:{userSettingsSources:e.userSettingsSources},...e.environment===void 0?{}:{environment:e.environment},config:n,hookSources:r,contributionSources:e.contributionSources,skillRoots:e.skillRoots,pluginSkills:t.pluginSkills,permissionMode:e.permissionMode,baselinePermissionAllow:e.baselinePermissionAllow,maxTurns:e.maxTurns,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},permissionHandler:t.permissionHandler,...t.askHandler?{askHandler:t.askHandler}:{},resumeSessionId:t.resumeSessionId,forkSession:e.forkSession,...e.sessionStore===void 0?{}:{resumeSessionStore:e.sessionStore},...e.sessionLogSink===void 0?{}:{sessionLogSink:e.sessionLogSink},...e.transcriptPath===void 0?{}:{transcriptPath:e.transcriptPath},onTextDelta:t.onTextDelta,onContextUpdate:t.onContextUpdate,onCompactEvent:t.onCompactEvent,onUsageRecorded:t.onUsageRecorded,onToolExecution:t.onToolExecution,bare:e.bare,...e.orgPolicy?.disableAutoMode===!0?{disableAutoMode:!0}:{},...e.skipConfiguredHooks===!0?{skipConfiguredHooks:!0}:{},disableBuiltInHookExecutors:e.disableBuiltInHookExecutors,commandHookShell:e.commandHookShell,allowedTools:e.allowedTools,deniedTools:e.deniedTools,model:e.model,...e.effort===void 0?{}:{effort:e.effort},appendSystemPrompt:e.appendSystemPrompt,...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},...e.persona===void 0?{}:{persona:e.persona},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},language:e.language,backgroundTaskRunners:e.backgroundTaskRunners,subagentHookEnvironmentNames:e.subagentHookEnvironmentNames,observerFailureWarningCode:e.observerFailureWarningCode,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions?{agentDefinitions:e.agentDefinitions}:{},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.commandModules?{commandModules:e.commandModules}:{},...a===void 0?{}:{editCheckpointRecorder:a},...e.reversibleExecution?{reversibleExecution:e.reversibleExecution}:{},...yf(e,t.sandboxSnapshotId),...Sf(e),...e.memoryStore?{memoryStore:e.memoryStore}:{},...e.agentName?{agentName:e.agentName}:{},...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.enableParallelSubagents===void 0?{}:{enableParallelSubagents:e.enableParallelSubagents},...e.selfVerification===void 0?{}:{selfVerification:e.selfVerification},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.defaultTools?{defaultTools:e.defaultTools}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.guardrails?{guardrails:e.guardrails}:{},...e.retrievalAdapter?{retrievalAdapter:e.retrievalAdapter}:{},...t.peerReply===void 0?{}:{peerReply:t.peerReply},...t.peerSendFile===void 0?{}:{peerSendFile:t.peerSendFile},commandDescriptors:t.commandDescriptors,...t.commandSemanticRoles?{commandSemanticRoles:t.commandSemanticRoles}:{},...t.commandDescriptors.length>0?{modelCommandExecutor:t.executeModelCommand,modelCommandToolPrefix:e.modelCommandToolPrefix,isModelCommandInvocable:t.isModelCommandInvocable}:{}});if(fd(o.session,{isFork:e.forkSession===!0||e.workspaceMovedFrom!==void 0,restoredSystemPrompt:t.restoredSystemPrompt,explicitSystemPrompt:e.systemPrompt}),t.pendingRestoreMessages){for(let e of t.pendingRestoreMessages)Or(o.session,e);o.session.syncContextFromHistory()}return{session:o.session,agentsFileEntries:o.agentsFileEntries,projectNotesFileEntries:o.projectNotesFileEntries,rebuildSystemMessage:o.rebuildSystemMessage,autoCompactThresholdSource:i}}function Lm(e,t,n,r,i,a,o,s,c,l,u,d,f,p=!1,m){try{let h=t.getSessionId(),g=e.load(h);if(g.status!==`valid`&&g.status!==`missing`){if(p)throw Error(`Session record cannot be updated: ${g.status}`);return}let _=g.status===`valid`?g.record:void 0,v=l?.snapshotId??_?.sandboxSnapshotId;e.save(Rm({session:t,sessionId:h,sessionName:n??_?.name,cwd:r,history:i,createdAt:_?.createdAt,backgroundState:a,memoryState:o,skillActivationState:s,contextReferenceState:c,...v===void 0?{}:{sandboxSnapshotId:v},...u===void 0?{}:{goalState:u},...d===void 0?{}:{planState:d},...f===void 0?{}:{activeBranchState:f},...m!==void 0||_?.sessionLoops!==void 0?{sessionLoops:m??_?.sessionLoops}:{}}))}catch(e){if(p)throw e}}function Rm(e){return{id:e.sessionId,...e.goalState===void 0?{}:{goal:e.goalState},...e.planState===void 0?{}:{plan:e.planState},...e.activeBranchState===void 0?{}:{activeBranch:e.activeBranchState},...e.sessionLoops===void 0?{}:{sessionLoops:[...e.sessionLoops]},...e.sessionName===void 0?{}:{name:e.sessionName},cwd:e.cwd,createdAt:e.createdAt??new Date().toISOString(),updatedAt:new Date().toISOString(),messages:e.session.getHistory(),history:e.history,systemPrompt:e.session.getSystemMessage(),toolSchemas:e.session.getToolSchemas(),...e.sandboxSnapshotId===void 0?{}:{sandboxSnapshotId:e.sandboxSnapshotId},...zm(e.backgroundState),...Bm(e.memoryState),...Vm(e.skillActivationState),...Hm(e.contextReferenceState)}}function zm(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function Bm(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function Vm(e){return e?{skillActivationEvents:[...e.events]}:{}}function Hm(e){return e?{contextReferences:[...e.references]}:{}}var Um=class extends Error{constructor(e){super(e),this.name=`ProviderConfigError`}};function Wm(e){return Gc(e)}function Gm(e,n=process.env){for(let r of e){let e=r.defaults;if(e?.apiKey===void 0||e.model===void 0||!(0,t.isEnvReference)(e.apiKey))continue;let i=e.apiKey.slice(t.ENV_REFERENCE_PREFIX.length).trim();if(i.length===0)continue;let a=n[i];if(a!==void 0&&a.length!==0)return{name:r.type,model:e.model,apiKey:a,...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},...e.options!==void 0&&{options:e.options},source:`env-default`,sourceEnvVar:i,apiKeyEnv:i}}}function Km(e,t={}){let n=Xc(Wm(e),t.providerOverride,t.providerDefinitions??[],t.env);if(n!==void 0)return n;let r=Gm(t.providerDefinitions??[],t.env);if(r!==void 0)return r;throw new Um(`No provider configuration found. Configure a provider before starting a session.`)}function qm(e,n,r={}){let i=r.providerDefinitions??[],a=Km(e,{...r,providerDefinitions:i}),o=n??a.model;return(0,t.createProviderFromConfig)({...a,model:o},i)}function Jm(e,t,n,r){let i={providerOverride:e,providerDefinitions:t,...r!==void 0&&{env:r}},a=Km(n,i),o=qm(n,void 0,i);return An(o,On(a,t)),{settings:a,provider:o}}function Ym(e,t){return e?.displayName??t.type??`Unknown provider`}function Xm(e,t){let n=t?.modelCatalog,r=(n!==void 0&&n.status!==`unavailable`?n.entries??[]:[]).map(e=>({id:e.id,label:e.displayName}));return typeof e.model==`string`&&e.model.length>0&&(r.some(t=>t.id===e.model)||r.push({id:e.model,label:e.model})),r}function Zm(e,t){let n=Object.keys(e);return t===void 0||!n.includes(t)?n:[t,...n.filter(e=>e!==t)]}function Qm(e,n,r,i,a){let o=e??{},s=[];for(let e of Zm(o,n)){if(a!==void 0&&!a.includes(e))continue;let n=o[e];if(n===void 0||!n.type||!n.model)continue;let r=(0,t.findProviderDefinition)(i,n.type);s.push({profileName:e,providerLabel:Ym(r,n),models:Xm(n,r)})}return{groups:s,...n===void 0?{}:{currentProfile:n},currentModel:r}}function $m(e,t){for(let n of e.groups){let e=n.models.find(e=>e.id===t);if(e!==void 0)return{profileName:n.profileName,model:e}}}var eh=class extends Error{sessionId;outcome;constructor(e,t){super(`session ${e} could not be renamed on disk: the stored record is ${t}`),this.name=`SessionRenameUnavailableError`,this.sessionId=e,this.outcome=t}};function th(e,t,n){let r=e.load(t);if(r.status===`missing`)return;if(r.status!==`valid`)throw new eh(t,r.status);let i={...r.record,name:n,updatedAt:new Date().toISOString()};e.save(i)}var nh=class{deps;inFlight;constructor(e){this.deps=e}async listRuntimeTools(){return this.assertOpen(),await this.deps.ensureInitialized(),this.assertOpen(),this.deps.session().listRuntimeTools()}async invokeRuntimeTool(e,t,n){this.assertOpen(),n?.signal?.throwIfAborted();let r=this.deps.controller();if(r.pendingCount()>0)throw Error(`A submission is already queued.`);let i=r.executionClaim.acquire(`runtime-tool`),a=(async()=>(await this.deps.ensureInitialized(),this.assertOpen(),n?.signal?.throwIfAborted(),this.deps.session().invokeRuntimeTool(e,t,n)))();this.inFlight=a;try{return await a}finally{this.inFlight=void 0,r.executionClaim.complete(i,()=>{})}}async drain(){await this.inFlight?.then(()=>{},()=>{})}assertOpen(){if(this.deps.controller().shuttingDown)throw Error(`Interactive session is shutting down.`)}};function rh(e){return{name:e.name,...e.displayName===void 0?{}:{displayName:e.displayName},description:e.description,...e.example===void 0?{}:{example:e.example},modelInvocable:e.modelInvocable===!0,runner:e.runner??`runtime`,...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.subcommands!==void 0&&e.subcommands.length>0?{subcommands:e.subcommands.map(ih)}:{}}}function ih(e){return{name:e.name,description:e.description,...e.displayName===void 0?{}:{displayName:e.displayName},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint}}}function ah(e){return{name:e.name,description:e.description,source:e.source,modelInvocable:e.disableModelInvocation!==!0,userInvocable:e.userInvocable!==!1,...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.context===void 0?{}:{context:e.context},...e.agent===void 0?{}:{agent:e.agent}}}var oh=class extends Error{role;existingCommandName;duplicateCommandName;code=`DUPLICATE_SYSTEM_COMMAND_SEMANTIC_ROLE`;constructor(e,t,n){super(`System command semantic role "${e}" is claimed by both "${t}" and "${n}".`),this.role=e,this.existingCommandName=t,this.duplicateCommandName=n,this.name=`DuplicateSystemCommandSemanticRoleError`}};const sh=c.AUTO_COMPACT_THRESHOLD,ch=`autoCompactThreshold`;function lh(e){return e.getContextState()}function uh(e){return e.getAutoCompactThreshold()}function dh(e){return e.getAutoCompactThresholdSource()}function fh(e,t,n){e.setAutoCompactThreshold(t,n)}function ph(e,t){let n=bh(e);return n?(n.write({...n.read(),[ch]:t}),!0):!1}function mh(e){let t=bh(e);if(!t)return!1;let n={...t.read()};return delete n[ch],t.write(n),!0}async function hh(e,t){let n=lh(e),r=e.getSession().getMessageCount();return await e.compactContext(t),{before:n,after:lh(e),beforeMessageCount:r,afterMessageCount:e.getSession().getMessageCount()}}function gh(e){return e.listContextReferences()}async function _h(e,t){return e.addContextReference(t)}function vh(e,t){return e.removeContextReference(t)}function yh(e){return e.clearContextReferences()}function bh(e){return e.getCommandHostAdapters?.().settings}function xh(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function Sh(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function Ch(e,t,n={}){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);let r={...e.providers};if(delete r[t],n.replacementCurrentProvider!==void 0&&r[n.replacementCurrentProvider]===void 0)throw Error(`Provider profile "${n.replacementCurrentProvider}" was not found`);let i={...e,providers:r};if(e.currentProvider!==t)return i;if(n.replacementCurrentProvider!==void 0)return{...i,currentProvider:n.replacementCurrentProvider};let a={...i};return delete a.currentProvider,a}function wh(e,n,r={}){if(!n.type)throw Error(`Provider profile "${e}" is missing type`);let i=r.providerDefinitions??[],a=(0,t.findProviderDefinition)(i,n.type);if(a===void 0&&i.length>0)throw Error(`Unknown provider "${n.type}". Supported providers: ${(0,t.formatSupportedProviderTypes)(i)}`);if(!n.model)throw Error(`Provider profile "${e}" is missing model`);let o=(0,t.getProviderCredentialRequirement)(a);if(o!==void 0&&!kh(n,a?.defaults,o,r.env))throw Error(`Provider profile "${e}" is missing ${jh(o)}`)}function Th(e,t={}){let n=Eh(e,t);return wh(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function Eh(e,n={}){let r=Oh(e.type,n.providerDefinitions??[]);if(e.apiKey!==void 0&&e.apiKeyEnv===void 0&&console.warn(`API key stored as plain text in settings. Use --api-key-env for better security.`),e.apiKeyEnv!==void 0){let t=(n.env??process.env)[e.apiKeyEnv];if(t===void 0||t.length===0)throw Error(`Environment variable ${e.apiKeyEnv} is not set — set it before configuring (the profile will reference $ENV:${e.apiKeyEnv})`)}let i=e.apiKeyEnv===void 0?e.apiKey??r.apiKey:(0,t.formatEnvReference)(e.apiKeyEnv),a=e.baseURL??r.baseURL;return{type:e.type,model:e.model??r.model,...Mh(i)&&{apiKey:i},...a!==void 0&&{baseURL:a},...e.timeout!==void 0&&{timeout:e.timeout}}}function Dh(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=xh(e,n,r);return t.currentProvider?Sh(i,t.currentProvider):i}function Oh(e,n){return(0,t.findProviderDefinition)(n,e)?.defaults??{}}function kh(e,n,r,i){return r.anyOf.some(r=>(0,t.hasUsableSecretReference)(Ah(r,e,n),i===void 0?void 0:e=>i[e]))}function Ah(e,t,n){return t[e]??n?.[e]}function jh(e){return e.anyOf.join(` or `)}function Mh(e){return e!==void 0&&e.length>0}async function Nh(e,n,r,i){let a=r??e;if(!a)return{message:`No provider profile selected.`,success:!1};let o=n?.[a];if(!o)return{message:`Provider profile "${a}" was not found.`,success:!1};try{wh(a,o,{providerDefinitions:i.providerDefinitions,...i.env===void 0?{}:{env:i.env}})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let s=await((o.type?(0,t.findProviderDefinition)(i.providerDefinitions,o.type):void 0)?.probeProfile??Ph)(o);return{message:s.ok?`Provider "${a}" test passed: ${s.message}`:`Provider "${a}" test failed: ${s.message}; manual configuration can continue.`,success:!0,data:{providerTest:{profile:a}}}}async function Ph(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function Fh(e,t=[],n){return Ih(e,t,n===void 0?void 0:e=>n[e])?`valid`:`incomplete`}function Ih(e,t,n){if(typeof e.currentProvider==`string`){let r=e.providers?.[e.currentProvider];return Lh(r?.type,r,t,n)}return!!(e.provider&&Lh(e.provider.name,e.provider,t,n))}function Lh(e,n,r,i){if(!n)return!1;if(!e)return(0,t.hasUsableSecretReference)(n.apiKey,i);let a=(0,t.findProviderDefinition)(r,e);if(a===void 0)return!1;let o=(0,t.getProviderCredentialRequirement)(a);return o===void 0||Rh(n,a,o,i)}function Rh(e,n,r,i){return r.anyOf.some(r=>(0,t.hasUsableSecretReference)(zh(r,e,n),i))}function zh(e,t,n){return t[e]??n.defaults?.[e]}function Bh(e,t=[]){if(!(0,d.existsSync)(e))return`missing`;try{let n=(0,d.readFileSync)(e,`utf8`).trim();return n.length===0?`incomplete`:Fh(JSON.parse(n),t)}catch{return`corrupt`}}function Vh(e){let t=Jh(e)??e[0];if(t===void 0)throw Error(`No settings store available for provider update`);return t}function Hh(e){return e.read()}function Uh(e,t,n={}){let r=Dh(Hh(e),Th(t,n));return e.write(r),r}function Wh(e,t,n={}){let r=Hh(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:Sh(r,t);return e.write(o),o}function Gh(e,t,n,r={}){let i=Gc(e),a=r.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Kh(t,a,n)}function Kh(e,t,n){let r=qh(e,t)??e[0];if(r===void 0)throw Error(`No settings store available for model update`);let i=Hh(r),a=i.providers??{},o=a[t]??{},s={...i,providers:{...a,[t]:{...o,model:n}}};return r.write(s),{settingsPath:r.displayName,settings:s,profileName:t}}function qh(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&Hh(r).providers?.[t]!==void 0)return r}}function Jh(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&Hh(n).currentProvider!==void 0)return n}}function Yh(e,t){return e?.displayName??t.type??`Unknown provider`}function Xh(e,t){let n=t?.modelCatalog;return(n!==void 0&&n.status!==`unavailable`?n.entries??[]:[]).find(t=>t.id===e)?.displayName??e}function Zh(e,t,n){let r=e[n]??t?.defaults?.[n];return typeof r==`string`?r:void 0}function Qh(e,n,r){let i=(0,t.getProviderCredentialRequirement)(n);if(i===void 0)return;let a=r===void 0?void 0:e=>r[e];return i.anyOf.some(r=>(0,t.hasUsableSecretReference)(Zh(e,n,r),a))?void 0:`Key missing`}function $h(e,n,r,i,a){let o=e??{},s=[];for(let e of Object.keys(o)){if(i!==void 0&&!i.includes(e))continue;let c=o[e];if(c===void 0)continue;let l=typeof c.type==`string`?(0,t.findProviderDefinition)(r,c.type):void 0,u=Qh(c,l,a);s.push({name:e,providerLabel:Yh(l,c),...typeof c.model==`string`&&c.model.length>0?{model:{id:c.model,label:Xh(c.model,l)}}:{},current:e===n,...u===void 0?{}:{connectionState:u}})}return{profiles:s}}const eg=`this session (CLI flags, preset, commands)`,tg=[`deny`,`ask`,`allow`],ng=[`plan`,`default`,`acceptEdits`,`bypassPermissions`,`auto`],rg={plan:`Plan only`,default:`Ask first`,acceptEdits:`Accept edits`,bypassPermissions:`Skip all checks`,auto:`Auto`};function ig(e=`mode`){return[{name:`plan`,displayName:rg.plan,description:`Plan only, no execution`,source:e},{name:`default`,displayName:rg.default,description:`Ask before risky actions`,source:e},{name:`acceptEdits`,displayName:rg.acceptEdits,description:`Auto-approve file edits`,source:e},{name:`bypassPermissions`,displayName:rg.bypassPermissions,description:`Skip all permission checks`,source:e},{name:`auto`,displayName:rg.auto,description:`A model classifier approves or blocks risky actions`,source:e}]}function ag(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function og(e){return ng.includes(e)}function sg(){return`Invalid mode. Valid: ${ng.join(` | `)}`}function cg(e){let t=e.getCommandHostAdapters?.().permissionMode;if(t!==void 0)return t;let n=e.getSession();return{getPermissionMode:()=>n.getPermissionMode(),setPermissionMode:e=>n.setPermissionMode(e),listSessionAllowedTools:()=>n.getSessionAllowedTools(),getPermissionRules:()=>n.getPermissionRules(),listRecentDenials:()=>n.getRecentPermissionDenials(),retryDenial:e=>n.retryPermissionDenial(e)}}function lg(e){return cg(e).getPermissionMode()}function ug(e,t){cg(e).setPermissionMode(t)}function dg(e,t){if(!(!Number.isInteger(t)||t<1))return cg(e).retryDenial(t-1)}function fg(e){return cg(e).listSessionAllowedTools()}function pg(e,t){let n=new Set,r=[];for(let i of t){let t=t=>i[t].filter(n=>e[t].includes(n)),a={source:i.source,scope:i.scope,deny:t(`deny`),ask:t(`ask`),allow:t(`allow`)};for(let e of tg)for(let t of a[e])n.add(`${e}\0${t}`);tg.some(e=>a[e].length>0)&&r.push(a)}let i=t=>[...new Set(e[t])].filter(e=>!n.has(`${t}\0${e}`)),a={source:eg,deny:i(`deny`),ask:i(`ask`),allow:i(`allow`)};return tg.some(e=>a[e].length>0)&&r.push(a),r}function mg(e){let t=cg(e),n=e.getCommandHostAdapters?.().permissionRules?.readLayers()??[];return{mode:t.getPermissionMode(),sessionAllowed:t.listSessionAllowedTools(),rules:pg(t.getPermissionRules(),n),recentDenials:t.listRecentDenials()}}const hg={policy:`denied by a rule or the mode`,user:`declined when asked`,"no-approver":`needed approval, none available`,classifier:`blocked by the auto-mode classifier`};function gg(e){let t=new Date(e);return[t.getHours(),t.getMinutes(),t.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`)}function _g(e){let t=[`Permission mode: ${e.mode}`,``];if(e.rules.length===0)t.push(`Rules: none configured.`);else{t.push(`Rules (checked deny, then ask, then allow):`);for(let n of e.rules){t.push(` ${n.source}${n.scope===void 0?``:` [${n.scope}]`}`);for(let e of tg)n[e].length>0&&t.push(` ${e}: ${n[e].join(`, `)}`)}}return t.push(``),e.sessionAllowed.length>0?t.push(`Approved this session ("allow always"): ${e.sessionAllowed.join(`, `)}`):t.push(`No session-approved tools.`),t.push(``),e.recentDenials.length===0?t.push(`Recent denials: none.`):(t.push(`Recent denials (most recent first):`),e.recentDenials.forEach((e,n)=>{let r=e.argument===void 0?e.toolName:`${e.toolName}(${e.argument})`,i=hg[e.reason],a=e.detail===void 0?``:`: ${e.detail}`;t.push(` ${n+1}. ${gg(e.at)} ${r} — ${i}${a}`)}),e.recentDenials.some(e=>e.reason===`classifier`)&&t.push(` To let a blocked call run once when the model retries it: /permissions retry <n>`)),t.join(`
115
115
  `)}async function vg(e,n,r){let i=[],a=[],o=(0,t.findInvalidPermissionPatterns)((0,t.toolNamesToPatterns)(r.allowedTools),`allow`);if(o.length>0){let e=o.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Preset "${n}" has invalid allowedTools: ${e}.`)}e.getSession().setActivePresetId(n),r.permissionMode===void 0?a.push(`permissionMode`):(ug(e,r.permissionMode),i.push(`permissionMode`)),r.allowedTools!==void 0||r.deniedTools!==void 0?(e.getSession().applyPresetToolLists({...r.allowedTools!==void 0&&{allowedTools:r.allowedTools},...r.deniedTools!==void 0&&{deniedTools:r.deniedTools}}),i.push(`toolLists`)):a.push(`toolLists`);let s={...r.model!==void 0&&{model:r.model},...r.effort!==void 0&&{effort:r.effort},...r.temperature!==void 0&&{temperature:r.temperature},...r.maxOutputTokens!==void 0&&{maxOutputTokens:r.maxOutputTokens}};for(let e of[`model`,`effort`,`temperature`,`maxOutputTokens`])r[e]===void 0?a.push(e):i.push(e);Object.keys(s).length>0&&await e.getSession().applyModelOptions(s),r.persona===void 0?a.push(`persona`):(e.applyPersona(r.persona),i.push(`persona`)),r.language===void 0?a.push(`language`):(e.applyResponseLanguage(r.language),i.push(`language`)),r.systemPrompt===void 0?a.push(`systemPrompt`):(e.applyPresetSystemPrompt(r.systemPrompt),i.push(`systemPrompt`)),r.agentName===void 0?a.push(`agentName`):(await e.getSession().applyAgentName(r.agentName),i.push(`agentName`));let c=r.enabledCommandModules!==void 0||r.disabledCommandModules!==void 0,l=c?e.applyCommandModuleSelection(r.enabledCommandModules,r.disabledCommandModules):[];return c?i.push(`commandModules`):a.push(`commandModules`),r.enableParallelSubagents===void 0?a.push(`enableParallelSubagents`):(e.getSession().setParallelSubagentsEnabled(r.enableParallelSubagents),i.push(`enableParallelSubagents`)),r.selfVerification===void 0?a.push(`selfVerification`):(e.applySelfVerification(r.selfVerification),i.push(`selfVerification`)),{applied:i,skipped:a,unknownCommandModules:l}}const yg=[/(?<![a-z])(api[_-]?key|secret|token|password|private key)(?![a-z])/i,/\b\d{3}-\d{2}-\d{4}\b/,/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/,/주민등록|비밀번호|시크릿|토큰/u,/\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{22,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35}|xox[abprs]-[A-Za-z0-9-]{10,}|glpat-[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{36}|[rs]k_live_[A-Za-z0-9]{16,})/,/-----BEGIN [A-Z ]*PRIVATE KEY-----/,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/],bg=/[A-Za-z0-9+_=]+/g;function xg(e){for(let[t]of e.matchAll(bg))if(t.length>=24&&/[a-z]/.test(t)&&/[A-Z]/.test(t)&&(t.match(/[0-9]/g)?.length??0)>=3)return!0;return!1}function Sg(e){return yg.some(t=>t.test(e))||xg(e)}var Cg=class{evaluate(e,t){return t.policy===`disabled`?{action:`skip`,reason:`memory-policy-disabled`}:Sg(e.text)?{action:`skip`,reason:`sensitive-content`}:t.policy===`approval_required`?{action:`queue`,reason:`approval-required`}:e.confidence>=.85?{action:`save`,reason:`high-confidence-auto-save`}:{action:`queue`,reason:`low-confidence-auto-save-review`}}};const wg=`lifecycle.json`;var Tg=class{storage;constructor(e){this.storage=e}list(){let e=this.storage.readText(wg,`read memory lifecycle`);if(e===void 0)return[];let t=JSON.parse(e);if(!t||typeof t!=`object`||!(`version`in t)||t.version!==1||!(`topics`in t)||!Array.isArray(t.topics))throw Error(`Invalid memory lifecycle; refusing to restore superseded memory.`);let n=[],r=new Set;for(let e of t.topics){if(!e||typeof e!=`object`||typeof e.topic!=`string`||!/^[a-z0-9가-힣_-]{1,80}$/.test(e.topic)||r.has(e.topic)||e.entry!==void 0&&typeof e.entry!=`string`)throw Error(`Invalid memory lifecycle; refusing to restore superseded memory.`);r.add(e.topic),n.push({topic:e.topic,...e.entry===void 0?{}:{entry:e.entry}})}return n}get(e){return this.list().find(t=>t.topic===e)}set(e,t){let n=this.list().filter(t=>t.topic!==e);n.push({topic:e,...t===void 0?{}:{entry:t}}),this.storage.writeText(wg,JSON.stringify({version:1,topics:n},null,2),`persist user memory lifecycle`)}applyIndex(e){let t=this.list(),n=new Set(t.map(e=>e.topic)),r=e.split(/\r?\n/).filter(e=>{let t=/^- \[[^\]]+\] \((?:user|feedback|project|reference)\/([^)]*)\) /.exec(e);return!t||!n.has(t[1])}),i=t.flatMap(e=>e.entry===void 0?[]:[`- ${e.entry}`]);return[...r,...i].join(`
116
116
  `).trimEnd()}};const Eg=25600,Dg=`MEMORY.md`,Z=`topics`,Og=[`user`,`feedback`,`project`,`reference`];function kg(e){return Og.includes(e)}function Ag(e,t){let n=Buffer.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function jg(e,t){let n=e.split(/\r?\n/);return{content:n.slice(0,t).join(`
117
117
  `).trimEnd(),truncated:n.length>t}}function Mg(e){return lr(e.trim().toLowerCase().replace(/[^a-z0-9가-힣_-]+/g,`-`),`-`).slice(0,80)||`general`}var Ng=class extends Error{constructor(){super(`This topic is controlled by the user. Use /memory correct <type> <topic> <text> to replace or restore it.`),this.name=`MemoryTopicCuratedError`}};function Pg(e){if(!/[a-z0-9가-힣]/i.test(e))throw Error(`A nonempty memory topic is required.`);return Mg(e)}function Fg(e,t,n){let r=e.toISOString().slice(0,10),i=t.text.trim().replace(/\s+/g,` `);return`[${r}] (${t.type}/${n}) ${i}`}function Ig(e){return e.trim().replace(/\s+/g,` `)}var Lg=class{storage;now;lifecycle;constructor(e,t=()=>new Date){if(this.storage=Ya(e),e.namespace!==`memory`)throw Error(`ProjectMemoryStore requires the memory state namespace.`);this.now=t,this.lifecycle=new Tg(e)}getIndexPath(){return this.storage.projectRelativePath(Dg)}getTopicsPath(){return this.storage.projectRelativePath(Z)}loadStartupMemory(){let e=this.getIndexPath(),t=this.lifecycle.applyIndex(this.storage.readText(Dg,`load startup memory`)??``),n=Ag(t,Eg),r=Buffer.byteLength(t,`utf8`)>Eg,i=jg(n,200);return{content:i.content,path:e,lineCount:i.content.length===0?0:i.content.split(/\r?\n/).length,truncated:r||i.truncated}}list(){let e=this.getTopicsPath(),t=this.lifecycle.list(),n=new Set(t.map(e=>e.topic)),i=this.storage.listDirectory(Z,`list memory topics`).filter(e=>e.kind===`file`&&e.name.endsWith(`.md`)).map(e=>({name:(0,r.basename)(e.name,`.md`),path:this.storage.projectRelativePath((0,r.join)(Z,e.name))})).filter(e=>!n.has(e.name));for(let e of t)e.entry!==void 0&&i.push({name:e.topic,path:this.storage.projectRelativePath((0,r.join)(Z,`${e.topic}.md`))});return i.sort((e,t)=>e.name.localeCompare(t.name)),{indexPath:this.getIndexPath(),topicsPath:e,topics:i}}readTopic(e){let t=Mg(e),n=this.lifecycle.get(t);return n?n.entry===void 0?``:`# ${t}\n\n- ${n.entry}`:(this.storage.readText((0,r.join)(Z,`${t}.md`),`read memory topic`)??``).trimEnd()}append(e){let t=Mg(e.topic);if(this.isTopicCurated(t))throw new Ng;let n=this.getIndexPath(),i=(0,r.join)(Z,`${t}.md`),a=this.storage.projectRelativePath(i),o=Fg(this.now(),e,t),s=this.storage.readText(i,`deduplicate memory topic`),c=s===void 0?`# ${t}\n\n`:``,l=Ig(e.text);return s?.includes(`) ${l}`)===!0?{indexPath:n,topicPath:a,topic:t,deduplicated:!0}:(this.storage.readText(Dg,`inspect memory index`)===void 0&&this.storage.writeText(Dg,`# Project Memory