@robota-sdk/agent-framework 3.0.0-beta.88 → 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.
- package/CHANGELOG.md +69 -0
- package/dist/node/{createInteractiveRuntime-CHR5gjdl.d.cts → createInteractiveRuntime-CFJnp3Or.d.cts} +23 -4
- package/dist/node/createInteractiveRuntime-CFJnp3Or.d.cts.map +1 -0
- package/dist/node/{createInteractiveRuntime-BMLlR29T.d.ts → createInteractiveRuntime-TZ4FdldF.d.ts} +23 -4
- package/dist/node/createInteractiveRuntime-TZ4FdldF.d.ts.map +1 -0
- package/dist/node/index.cjs +1 -1
- package/dist/node/index.d.cts +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.js +1 -1
- package/dist/node/{interactive-CT4ca0_q.cjs → interactive-CTqHYwZF.cjs} +2 -2
- package/dist/node/{interactive-DZfVMwYx.js → interactive-CoGijXC0.js} +3 -3
- package/dist/node/{interactive-DZfVMwYx.js.map → interactive-CoGijXC0.js.map} +1 -1
- package/dist/node/testing/index.cjs +1 -1
- package/dist/node/testing/index.d.cts +1 -1
- package/dist/node/testing/index.d.ts +1 -1
- package/dist/node/testing/index.js +1 -1
- package/package.json +18 -18
- package/dist/node/createInteractiveRuntime-BMLlR29T.d.ts.map +0 -1
- package/dist/node/createInteractiveRuntime-CHR5gjdl.d.cts.map +0 -1
|
@@ -101,7 +101,7 @@ Do not use emojis.`}function fa(){return`You are a worker subagent executing a s
|
|
|
101
101
|
`)[0]?.trim()===`---`?void 0:{path:t,reason:`frontmatter-missing`}:{path:t,reason:r.diagnostics[0].code===`unterminated`?`frontmatter-unterminated`:`frontmatter-invalid`,detail:new Pf(r.diagnostics).message}}function Np(e,t,n){let r={sourceDisplayName:e.displayName,root:t};if(e.inspectKind(t,`inspect skill directory`)!==`directory`)return{...r,present:!1,discovered:[],skipped:[]};let i=[],a=[];for(let r of e.listDirectory(t,`inspect skills`)){let o;if(n===`skills`){if(r.kind!==`directory`)continue;if(o=E(t,r.name,`SKILL.md`),e.inspectKind(o,`inspect skill definition`)!==`file`){a.push({path:E(t,r.name),reason:`missing-skill-file`});continue}}else{if(r.kind!==`file`||!r.name.endsWith(`.md`))continue;o=E(t,r.name)}let s=e.readText(o,`inspect skill definition`);if(s===void 0){a.push({path:o,reason:`unreadable`});continue}let c=Mp(e,o,s);c!==void 0&&a.push(c),(c===void 0||c.reason===`frontmatter-missing`)&&i.push(n===`skills`?w(E(o,`..`)):w(r.name,`.md`))}return{...r,present:!0,discovered:i,skipped:a}}function Pp(e,t=[]){return{roots:e.flatMap(e=>t.map(({root:t,kind:n})=>Np(e,t,n)))}}function Fp(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function Ip(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Lp(e,t){return e.some(e=>Ip(e.name)===t)}function Rp(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 zp(e,t=[]){if(!e.provider)throw Error(`provider is required. SDK is provider-neutral — consumer must create and pass a provider instance.`);let n=e.provider,r=e.cwd??process.cwd(),i=e.sessionId??Bp(),a=new jp(e.contributionSources??[],e.skillRoots??[]),o=Fp(e.commandDescriptors),s=o.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,c=s?ka(o,e.modelCommandToolPrefix):void 0,l=Lp(o,e.commandSemanticRoles?.skillActivation??``)?Ap(a.getCommands(),e.pluginSkills??[]).filter(e=>e.disableModelInvocation!==!0):[],u,{tools:d,wrapAdded:f}=await xf(e,r,()=>u===void 0?void 0:Yi(u,e.onUsageRecorded));s&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&d.push(...Ma({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:o,toolNamePrefix:e.modelCommandToolPrefix}));let p=Ef(e),m=Rp(e.config.hooks,e.guardrails);wp(m,p,t);let{agentToolDeps:h,agentDefinitions:g,backgroundTaskManager:_}=Bf(e,i,r,n,d,p),{backgroundProcessToolDeps:v}=_p(e,_,i,r,d);vp(e,_,i,r,d);let{finalSystemMessage:ee,rebuildSystemMessage:te}=bp(e,r,o,c,v,l,g,d),y=c?c.commandTools.filter(e=>!e.requiresPermission).map(e=>e.toolName):[],b={allow:[...e.baselinePermissionAllow??[],...y,...e.config.permissions.allow??[]],deny:e.config.permissions.deny??[]},ne={...re(b,e),ask:[...e.config.permissions.ask??[]]},ie=e.persistProjectPermission,ae=ie?e=>{ie(e.includes(`(`)?e:`${e}(*)`)}:void 0,oe=new lt({pathProtection:e.pathProtection,tools:d,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},wrapAddedTools:f,provider:n,systemMessage:ee,terminal:e.terminal,cwd:r,permissions:ne,presetFreePermissions:b,hooks:m,permissionMode:e.permissionMode,defaultTrustLevel:e.config.defaultTrustLevel,model:e.model??e.config.provider.model,providerTimeout:e.config.provider.timeout??12e4,maxTurns:e.maxTurns,sessionStore:e.sessionStore,sessionId:i,permissionHandler:e.permissionHandler,...e.sandboxClient?.autoApproves===void 0?{}:{commandSandbox:Va(e.sandboxClient)},...e.disableAutoMode===!0?{}:{permissionClassifier:ua(n,{cwd:r,model:e.model??e.config.provider.model})},...e.ask?{ask:e.ask}:{},...ae===void 0?{}:{onProjectAllowTool:ae},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:p,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens}});return u=oe,xp(oe,h,v,_),{session:oe,rebuildSystemMessage:te}}function Bp(){return`session_${C()}`}function Vp(e){let t=new Date().toISOString();return{id:Bp(),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 Hp(e,t){return!t.isFork||t.restoredSystemPrompt===void 0||t.explicitSystemPrompt!==void 0?!1:(e.updateSystemMessage(t.restoredSystemPrompt),!0)}function Up(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 Wp(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 Gp(e){let t=Wp(e.requestedName,e.sourceName,e.sourceId,Up(e.sessionStore)),n=Vp({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 Kp(e,t){let n=e.name??e.id,r=Up(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 qp(e,t,n){let r=uo(n),i=r?.customAgentRegistry?.(e)??(r?.builtInAgents?r.builtInAgents.find(t=>t.name===e):Ri(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 Jp(e,t,n){t.signal?.throwIfAborted();let r=uo(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);let i=qp(t.agent??`general-purpose`,t,n),a=za({pathProtection:r.pathProtection,agentDefinition:i,parentConfig:eo(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,...to(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 Yp(e,t){return e===`~`?t:e.startsWith(`~/`)?`${t}/${e.slice(2)}`:e}function Xp(e){if(e.executing)throw Error(`Finish or cancel the current turn before moving to another directory.`);if(e.liveBackgroundTasks>0)throw Error(`${e.liveBackgroundTasks} background task(s) are still running in this directory and would not survive the move. Wait for them or cancel them first.`);let t=e.requestedPath.trim();if(t===``)throw Error(`Usage: /cd <directory>`);let n=Yp(t,e.homeDirectory??nn()),r=T(n)?n:D(e.workspace.cwd,n),i;try{i=M(r)}catch{throw Error(`No such directory: ${r}`)}if(!zt(i).isDirectory())throw Error(`Not a directory: ${i}`);if(i===M(e.workspace.cwd))throw Error(`Already in ${i}.`);if(pe(`Cd`,{path:i},e.permissionMode,e.rules)===`deny`)throw Error(`Moving to ${i} is denied by a permission rule.`);return{fromCwd:e.workspace.cwd,targetCwd:i,record:Vp({source:e.source,name:e.sessionName,cwd:i}),restricted:e.workspace.projectAccess.status===`restricted`}}function Zp(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 Qp(e,t,n,r){if(n.status!==`trusted`)throw new R(`Adding a project context reference requires explicit workspace project authority.`);let i=await Uu([t],{reader:tc(n.authority),startRelativeDirectory:ze(n.identity.worktreeRoot,r),reason:`manual`});if(Iu(i.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[Lu(i.diagnostics)]}};let a=i.references[0];if(!a)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let o=vu(Ru([a])[0],`manual`,`active`),s=yu(e,o);return{references:s.references,result:{reference:o,evicted:s.evicted,diagnostics:[]}}}function $p(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=vu(e,n.loadType,n.status,r);i=yu(i,t).references}return i}function em(e,t){let n=new Date().toISOString();return e.map(e=>{let r=T(e.filePath)?ze(t,e.filePath):e.filePath;return{id:`system:${r}`,sourcePath:e.filePath,relativePath:r,originalReference:r,loadType:`system`,status:`active`,byteLength:Buffer.byteLength(e.content,`utf-8`),loadedAt:n,lastUsedAt:n}})}const tm=`main`;var nm=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 rm(e,t){if(t.length===0||T(t))throw new nm(e,t);let n=E(e,t),r=ze(e,n);if(r.length===0||r===`..`||r.startsWith(`../`)||r.startsWith(`..\\`)||T(r))throw new nm(e,t);return n}function im(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:tm,...r?{parentId:r.id}:{}}})}function am(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}const om={create:`checkpoint_created`,fork:`branch_forked`,switch:`branch_switched`,restore:`checkpoint_restored`,rollback:`checkpoint_rolled_back`,resume_pointer:`non_event`};var sm=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=om[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 cm(e){return e.source===`plugin`?`plugin`:`skill`}function lm(e){return e.context===`fork`?`fork`:`inject`}function um(e){return{type:`skill-activation`,skillName:e.skill.name,source:cm(e.skill),invocation:e.invocation,mode:lm(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function dm(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 fm=new Set([`memory_candidate_saved`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`]);function pm(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 mm={"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 hm=class extends R{reason;name=`EditCheckpointsUnavailableError`;constructor(e){super(mm[e]),this.reason=e}},gm=class{workspace;getSessionId;getExecuting;persistSession;emitSkillActivation;emitMemoryEvent;history=[];editCheckpointStore=null;branchEvents;pendingActiveBranch=void 0;memoryEvents=[];usedMemoryReferences=[];contextReferences=[];systemContextReferences=[];skillActivationEvents=[];constructor(e,t,n,r,i,a,o=null,s=()=>void 0){this.workspace=e,this.getSessionId=t,this.getExecuting=n,this.persistSession=r,this.emitSkillActivation=i,this.emitMemoryEvent=a,this.editCheckpointStore=o,this.branchEvents=new sm(()=>this.getCheckpointStore(),t,r,s,e=>this.history.push(S(x(`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=$p(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=$p(this.contextReferences,e,{loadType:`prompt-reference`,status:`observed`}),this.persistSession()}listEditCheckpoints(){let e=this.getSessionId();return this.getCheckpointStore().list(e)}inspectEditCheckpoint(e){let t=this.getSessionId();return this.getCheckpointStore().inspect(t,e)}async restoreEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot restore edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push(S(x(`Restored edit checkpoint: ${e}`))),this.persistSession(),this.branchEvents.emit(`restore`,e),t}async rollbackEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot rollback edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().rollbackThroughCheckpoint(this.getSessionId(),e);return this.history.push(S(x(`Rolled back edit checkpoint: ${e}`))),this.persistSession(),this.branchEvents.emit(`rollback`,e),t}listCheckpointBranches(){return this.getCheckpointStore().listCheckpointBranches(this.getSessionId())}async forkCheckpointBranch(e){if(this.getExecuting())throw Error(`Cannot fork edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push(S(x(`Forked new branch from checkpoint: ${e}`))),this.persistSession(),this.branchEvents.emit(`fork`,e),t}switchCheckpointBranch(e){if(this.getExecuting())throw Error(`Cannot switch edit checkpoint branch while a prompt is running.`);this.getCheckpointStore().switchToCheckpoint(this.getSessionId(),e),this.history.push(S(x(`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),fm.has(e.type)&&this.history.push({id:C(),timestamp:new Date(e.at),category:`event`,type:`memory-event`,data:{...e,message:pm(e)}}),this.emitMemoryEvent(e),this.persistSession()}recordSystemContextFiles(e){this.systemContextReferences=em(e,this.workspace.cwd)}listContextReferences(){return[...this.systemContextReferences,...this.contextReferences]}listInjectionContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await Qp(this.contextReferences,e,this.workspace.projectAccess,this.workspace.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=bu(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=xu(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,t){this.skillActivationEvents.push(e),t&&this.history.push({id:C(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:dm(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){if(!this.editCheckpointStore)throw new hm(this.noStoreReason());return this.applyPendingActiveBranch(),this.editCheckpointStore}noStoreReason(){return ac()?this.workspace.projectAccess.status===`trusted`?`no-checkpoint-store`:`restricted-workspace`:`host-cannot-write-project`}},_m=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 vm(e){if(!j(e))return{};let t=Ft(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new md(e,t instanceof Error?t.message:String(t))}}function ym(e,t){Tt(Re(e)),Dt(e),Vt(e,JSON.stringify(t,null,2)+`
|
|
103
103
|
`,{encoding:`utf8`,mode:384})}function bm(e,t){let n=vm(e),r=n.currentProvider,i=n.providers;if(typeof r!=`string`||!xm(i))throw new _m(e);let a=i;a[r]={...xm(a[r])?a[r]:{},model:t},n.providers=a,ym(e,n)}function xm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Sm(e){return j(e)?(Bt(e),!0):!1}const Cm=Object.freeze({theme:`theme`,syntaxHighlighting:`syntaxHighlighting`,reducedMotion:`reducedMotion`}),wm=Object.freeze({theme:`dark`,syntaxHighlighting:!0,reducedMotion:!1});function Tm(e){let t=new Set(Object.values(Cm));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 Em(e){let t=e[Cm.theme],n=e[Cm.syntaxHighlighting],r=e[Cm.reducedMotion];return{theme:typeof t==`string`&&t.length>0?t:wm.theme,syntaxHighlighting:typeof n==`boolean`?n:wm.syntaxHighlighting,reducedMotion:typeof r==`boolean`?r:wm.reducedMotion}}function Dm(e,t){let n=vm(e),r={...Em(n),...t};return n[Cm.theme]=r.theme,n[Cm.syntaxHighlighting]=r.syntaxHighlighting,n[Cm.reducedMotion]=r.reducedMotion,ym(e,n),r}var Om=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 km(e){if(typeof e!=`string`||e.trim()===``)throw TypeError(`Organization policy path is required`);if(!j(e))return null;let t;try{t=JSON.parse(Ft(e,`utf8`))}catch(t){throw new Om(e,t instanceof Error?t.message:String(t))}let n=Am(t);if(n!==void 0)throw new Om(e,n);return t}function Am(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 jm(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function Mm(e){return e?!e.startsWith(`$ENV:`):!1}const Nm=`Configure TUI status-line visibility and fields such as model, context, tokens, session, and git branch.`,Pm=`on | off | reset | git on | git off`,Fm={enabled:!0,gitBranch:!0};function Im(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 Lm(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function Rm(e){let t=e.statusline;return Bm(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:Fm.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:Fm.gitBranch}:{...Fm}}function zm(e,t){let n=vm(e),r={...Rm(n),...t};return n.statusline=r,ym(e,n),r}function Bm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Y(e,t){return{success:!1,message:`Cannot apply '${e}': ${t} is not available in this environment.`}}function Vm(e,t){return{success:!1,message:`Failed to apply '${e}': ${t instanceof Error?t.message:String(t)}`}}async function Hm(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 Um(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 Um(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:jm(`Provider "${e.profileName}" is not allowed by your organization policy. Allowed: ${n.allowedProviders.join(`, `)}.`,n.adminContact),success:!1}:(await t.switchProvider(e.profileName),null)}case`output-style-change`:{let i=r.outputStyleRegistry;if(!i)return Y(e.type,`an output-style registry adapter`);let a=i.getOutputStyle(e.styleId);if(!a){let t=i.listOutputStyles().map(e=>e.id).join(`, `);return{success:!1,message:`Unknown output style "${e.styleId}". Available: ${t||`(none)`}`}}let o=r.settings;return o?(o.write({...o.read(),outputStyle:e.styleId}),t.applyOutputStyle(a),n.push(`Output style: ${a.name}`),null):Y(e.type,`a settings adapter`)}case`language-change`:{let t=r.settings;return t?r.process?(t.write({...t.read(),language:e.language}),n.push(`Restarting...`),r.process.requestRestart(`other`,`Language change restart`),null):Y(e.type,`a process adapter (restart)`):Y(e.type,`a settings adapter`)}case`settings-reset`:{let t=r.settings;if(!t?.delete)return Y(e.type,`a settings adapter with delete()`);if(!r.process)return Y(e.type,`a process adapter (exit)`);let i=t.delete();return n.push(i?`User settings deleted. Exiting...`:`No user settings found. Exiting...`),r.process.requestExit(`other`),null}case`session-exit`:return r.process?(r.process.requestExit(e.reason??`prompt_input_exit`),null):Y(e.type,`a process adapter`);case`session-restart`:return r.process?(r.process.requestRestart(e.reason,e.message),null):Y(e.type,`a process adapter`);case`session-rename`:return t.renameSession(e.name),null;case`workspace-move`:return r.workspace?(n.push(await t.moveWorkspace(e.path)),null):Y(e.type,`a host that can start a session elsewhere`);case`statusline-settings-patch`:{let t=r.settings;if(!t)return Y(e.type,`a settings adapter`);if(!Lm(e.patch))return Vm(e.type,Error(`invalid statusline settings patch`));let n=t.read(),i={...Rm(n),...e.patch};return t.write({...n,statusline:i}),null}case`appearance-settings-patch`:{let t=r.settings;if(!t)return Y(e.type,`a settings adapter`);if(!Tm(e.patch))return Vm(e.type,Error(`invalid appearance settings patch`));let n=t.read(),i={...Em(n),...e.patch};return t.write({...n,theme:i.theme,syntaxHighlighting:i.syntaxHighlighting,reducedMotion:i.reducedMotion}),null}case`remote-control-enable`:{if(t.invocationSource!==`user`)return{success:!1,message:"Cannot apply 'remote-control-enable': only the operator at this terminal can pair a device. Run `/remote-control` on the host terminal."};let i=r.remoteControl?.enable;return i?(n.push(await i.call(r.remoteControl)),null):Y(e.type,`a remote-control adapter with enable()`)}case`remote-control-stop`:{let t=r.remoteControl?.stop;return t?(n.push(await t.call(r.remoteControl)),null):Y(e.type,`a remote-control adapter with stop()`)}}}catch(t){return Vm(e.type,t)}}function Wm(e,t,n){return t===void 0?e===`model`?n??void 0:e===`user`?Ue:void 0:t}function Gm(e,t,n){for(let r of e)n({intent:r,...t===void 0?{}:{requesterDriverId:t}})}function Km(e,t){let n=hd(e,t);return Object.freeze({kind:`host`,scope:e,displayName:t,source:n,read:()=>{if(!j(t))return{};let e=Ft(t,`utf8`);try{return JSON.parse(e)}catch(e){throw new md(t,e instanceof Error?e.message:String(e))}},write:e=>{Tt(Re(t)),Dt(t),Vt(t,`${JSON.stringify(e,null,2)}\n`,{encoding:`utf8`,mode:384})}})}function qm(e,t){let n=Cc(t,e),r=tc(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 md(a,e instanceof Error?e.message:String(e))}},write:e=>{n.writeText(`${JSON.stringify(e,null,2)}\n`)}})}function Jm(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=xc(e.authority,{status:`approved`,target:`project-local`,relativePath:n.relativePath,purpose:`persist user-approved project permission`}),i=qm(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 Ym(e){return e.commandSemanticRoles?e.commandSemanticRoles:(e.commandModules?.flatMap(e=>e.systemCommands??[])??[]).reduce((e,t)=>t.semanticRole?{...e,[t.semanticRole]:t.name}:e,{})}function Xm(e,t){let{mergedConfig:n,cwd:r,context:i,projectInfo:a,sessionId:o,contextCapacityHint:s,contributionSources:c,skillRoots:l}=t,u=Jm(e.projectAccess,e.projectSettingsPaths);return{config:n,cwd:r,context:i,contributionSources:c,skillRoots:l,...e.pluginSkills===void 0?{}:{pluginSkills:e.pluginSkills},projectInfo:a,permissionMode:e.permissionMode,baselinePermissionAllow:e.baselinePermissionAllow,maxTurns:e.maxTurns,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},terminal:rr,sessionLogger:e.sessionLogSink===void 0?new ft:new rt(e.sessionLogSink),...e.transcriptPath===void 0?{}:{transcriptPath:e.transcriptPath},permissionHandler:e.permissionHandler,...u===void 0?{}:{persistProjectPermission:u},...e.askHandler?{ask:e.askHandler}:{},provider:e.provider,onTextDelta:e.onTextDelta,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:Ym(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 Zm(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 Qm(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await Qe(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function $m(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 eh(e){return{...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt}}}const th=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 nh(e){let t=rh(e);return{settings:t.settings,hookSources:t.hookSources}}function rh(e){let t=new Set,n={},r=[];for(let{settings:i,source:a}of e){let e=ph(i.hooks,t);a!==void 0&&ih(e,a,r);for(let e of i.disabledHooks??[])t.add(e);n=ah(n,{...i,hooks:e},t)}return{settings:n,hookSources:r}}function ih(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 ah(e,t,n){return{...e,...t,defaultTrustLevel:gh(e.defaultTrustLevel,t.defaultTrustLevel),disabledHooks:oh(n),provider:_h(e.provider,t.provider),permissions:sh(e.permissions,t.permissions),env:{...e.env??{},...t.env??{}},providers:lh(e.providers,t.providers),enabledPlugins:ch(e.enabledPlugins,t.enabledPlugins),extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold,hooks:uh(e.hooks,t.hooks),taskContext:ch(e.taskContext,t.taskContext),sandbox:ch(e.sandbox,t.sandbox)}}function oh(e){return e.size===0?void 0:[...e]}function sh(e,t){if(e!==void 0||t!==void 0)return{allow:fh(e?.allow,t?.allow),deny:fh(e?.deny,t?.deny),ask:fh(e?.ask,t?.ask)}}function ch(e,t){if(e!==void 0||t!==void 0)return{...e,...t}}function lh(e,t){if(e!==void 0||t!==void 0)return mh(e,t)}function uh(e,t){if(e!==void 0||t!==void 0)return dh(e,t)}function dh(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 fh(e,t){return e===void 0?t===void 0?void 0:[...t]:t===void 0?[...e]:[...new Set([...e,...t])]}function ph(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 mh(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]=_h(n[e],r);return n}const hh={safe:0,moderate:1,full:2};function gh(e,t){return e===void 0?t:t===void 0||hh[e]<=hh[t]?e:t}function _h(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 vh=O.lazy(()=>O.union([O.string(),O.number(),O.boolean(),O.null(),O.undefined(),O.date(),O.array(vh),O.record(vh)])),yh=O.object({name:O.string().optional(),model:O.string().optional(),apiKey:O.string().optional(),baseURL:O.string().optional(),timeout:O.number().optional(),options:O.record(vh).optional()}),bh=O.object({type:O.string().optional(),model:O.string().optional(),apiKey:O.string().optional(),baseURL:O.string().optional(),timeout:O.number().optional(),options:O.record(vh).optional()}),xh=O.object({allow:O.array(O.string()).optional(),deny:O.array(O.string()).optional(),ask:O.array(O.string()).optional()}),Sh=O.record(O.string()).optional(),Ch=O.object({type:O.literal(`command`),command:O.string(),timeout:O.number().optional()}),wh=O.object({type:O.literal(`http`),url:O.string(),headers:O.record(O.string()).optional(),timeout:O.number().optional()}),Th=O.object({type:O.literal(`prompt`),prompt:O.string(),model:O.string().optional()}),Eh=O.object({type:O.literal(`agent`),agent:O.string(),maxTurns:O.number().optional(),timeout:O.number().optional()}),Dh=O.object({type:O.literal(`guardrail`),guardrails:O.array(O.string()).optional()}),Oh=O.discriminatedUnion(`type`,[Ch,wh,Th,Eh,Dh]),X=O.object({id:O.string().optional(),matcher:O.string(),hooks:O.array(Oh)}),kh=O.object({PreToolUse:O.array(X).optional(),PostToolUse:O.array(X).optional(),SessionStart:O.array(X).optional(),SessionEnd:O.array(X).optional(),Stop:O.array(X).optional(),StopFailure:O.array(X).optional(),PreCompact:O.array(X).optional(),PostCompact:O.array(X).optional(),UserPromptSubmit:O.array(X).optional(),SubagentStart:O.array(X).optional(),SubagentStop:O.array(X).optional(),WorktreeCreate:O.array(X).optional(),WorktreeRemove:O.array(X).optional(),PreModelCall:O.array(X).optional(),PostModelCall:O.array(X).optional(),PermissionDecision:O.array(X).optional()}).optional(),Ah=O.record(O.boolean()).optional(),jh=O.object({source:O.object({type:O.enum([`github`,`git`,`local`,`url`]),repo:O.string().optional(),url:O.string().optional(),path:O.string().optional(),ref:O.string().optional()})}),Mh=O.record(jh).optional().catch(void 0),Nh=O.union([O.number().gt(0).lte(1),O.literal(!1)]).optional(),Ph=O.object({enabled:O.boolean().optional(),options:O.record(vh).optional()}),Fh=O.object({enabled:O.boolean().optional(),autoAllowBashIfSandboxed:O.boolean().optional(),excludedCommands:O.array(O.string()).optional(),failIfUnavailable:O.boolean().optional(),filesystem:O.object({allowWrite:O.array(O.string()).optional(),denyRead:O.array(O.string()).optional()}).optional(),network:O.object({enabled:O.boolean().optional()}).optional()}),Ih=O.object({defaultTrustLevel:O.enum([`safe`,`moderate`,`full`]).optional(),language:O.string().optional(),preset:O.string().optional(),currentProvider:O.string().optional(),providers:O.record(bh).optional(),provider:yh.optional(),permissions:xh.optional(),env:Sh,hooks:kh,disabledHooks:O.array(O.string()).optional(),enabledPlugins:Ah,extraKnownMarketplaces:Mh,autoCompactThreshold:Nh,transports:O.record(Ph).optional(),sandbox:Fh.optional(),taskContext:O.object({enabled:O.boolean().optional(),dir:O.string().min(1).optional()}).optional()}),Lh=/position (\d+)/;function Rh(e){let t=Lh.exec(e.message);return t===null?void 0:Number(t[1])}function zh(e){let t=e.code;return typeof t==`string`?t:void 0}function Bh(e){let t;try{t=vd(e,`load configuration settings`)}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`unreadable`,cause:{state:`unreadable`,errno:zh(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:Rh(n)},error:n}}}function Vh(e){if(e.state!==`ok`)return e;let t=Ih.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 Hh(e){return e.map(Bh).map(Vh)}function Uh(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 Wh(e){let t=new Map;for(let n of e)if(n.settings!==void 0)for(let e of Uh(n.settings)){let r=t.get(e)??[];r.push(n.displayName),t.set(e,r)}return[...t.entries()].map(([e,t])=>({key:e,rule:th[e]??`replace`,contributors:t}))}function Gh(e){let t=Hh(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=nh(t.flatMap(e=>e.settings===void 0?[]:[{settings:e.settings,source:e.displayName}]));return{layers:t,merged:r.settings,partial:n,provenance:Wh(t),hookSources:r.hookSources}}const Kh={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[],ask:[]},env:{}};function qh(e){if(e.state===`empty`)throw new md(e.source.displayName,`the settings file is empty`);if(e.state===`invalid-json`)throw new md(e.source.displayName,e.error?.message??`invalid JSON`);if(e.state===`unreadable`)throw e.error}function Jh(e,t){return e.startsWith(`$ENV:`)?t[e.slice(5)]??e:e}function Yh(e,t){let n=e.provider?.apiKey===void 0?e.provider:Xh(e.provider,t);if(e.providers!==void 0){let r=Object.fromEntries(Object.entries(e.providers).map(([e,n])=>[e,Xh(n,t)]));return{...e,provider:n,providers:r}}return{...e,provider:n}}function Xh(e,t){if(e.apiKey===void 0)return e;let n=e.apiKey.startsWith(`$ENV:`);return{...e,apiKey:Jh(e.apiKey,t),...n&&{apiKeyEnv:e.apiKey.slice(5)}}}function Zh(e){if(e.currentProvider!==void 0)return Qh(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...Kh.provider}}function Qh(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??Kh.provider.model,apiKey:n.apiKey??Kh.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 $h(e){return{defaultTrustLevel:e.defaultTrustLevel??Kh.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:Zh(e),permissions:{allow:e.permissions?.allow??Kh.permissions.allow,deny:e.permissions?.deny??Kh.permissions.deny,ask:e.permissions?.ask??Kh.permissions.ask},env:e.env??Kh.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 eg(e,t={}){let n=Hh(e);for(let e of n)qh(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:Yh(e.settings,t),source:e.source.displayName})}let i=nh(r);return{config:$h(i.settings),hookSources:i.hookSources}}const tg={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function ng(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function rg(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||w(t,`.md`)}function ig(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function ag(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 Um(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:jm(`Provider "${e.profileName}" is not allowed by your organization policy. Allowed: ${n.allowedProviders.join(`, `)}.`,n.adminContact),success:!1}:(await t.switchProvider(e.profileName),null)}case`output-style-change`:{let i=r.outputStyleRegistry;if(!i)return Y(e.type,`an output-style registry adapter`);let a=i.getOutputStyle(e.styleId);if(!a){let t=i.listOutputStyles().map(e=>e.id).join(`, `);return{success:!1,message:`Unknown output style "${e.styleId}". Available: ${t||`(none)`}`}}let o=r.settings;return o?(o.write({...o.read(),outputStyle:e.styleId}),t.applyOutputStyle(a),n.push(`Output style: ${a.name}`),null):Y(e.type,`a settings adapter`)}case`language-change`:{let t=r.settings;return t?r.process?(t.write({...t.read(),language:e.language}),n.push(`Restarting...`),r.process.requestRestart(`other`,`Language change restart`),null):Y(e.type,`a process adapter (restart)`):Y(e.type,`a settings adapter`)}case`settings-reset`:{let t=r.settings;if(!t?.delete)return Y(e.type,`a settings adapter with delete()`);if(!r.process)return Y(e.type,`a process adapter (exit)`);let i=t.delete();return n.push(i?`User settings deleted. Exiting...`:`No user settings found. Exiting...`),r.process.requestExit(`other`),null}case`session-exit`:return r.process?(r.process.requestExit(e.reason??`prompt_input_exit`),null):Y(e.type,`a process adapter`);case`session-restart`:return r.process?(r.process.requestRestart(e.reason,e.message),null):Y(e.type,`a process adapter`);case`session-rename`:return t.renameSession(e.name),null;case`workspace-move`:return r.workspace?(n.push(await t.moveWorkspace(e.path)),null):Y(e.type,`a host that can start a session elsewhere`);case`statusline-settings-patch`:{let t=r.settings;if(!t)return Y(e.type,`a settings adapter`);if(!Lm(e.patch))return Vm(e.type,Error(`invalid statusline settings patch`));let n=t.read(),i={...Rm(n),...e.patch};return t.write({...n,statusline:i}),null}case`appearance-settings-patch`:{let t=r.settings;if(!t)return Y(e.type,`a settings adapter`);if(!Tm(e.patch))return Vm(e.type,Error(`invalid appearance settings patch`));let n=t.read(),i={...Em(n),...e.patch};return t.write({...n,theme:i.theme,syntaxHighlighting:i.syntaxHighlighting,reducedMotion:i.reducedMotion}),null}case`remote-control-enable`:{if(t.invocationSource!==`user`)return{success:!1,message:"Cannot apply 'remote-control-enable': only the operator at this terminal can pair a device. Run `/remote-control` on the host terminal."};let i=r.remoteControl?.enable;return i?(n.push(await i.call(r.remoteControl)),null):Y(e.type,`a remote-control adapter with enable()`)}case`remote-control-stop`:{let t=r.remoteControl?.stop;return t?(n.push(await t.call(r.remoteControl)),null):Y(e.type,`a remote-control adapter with stop()`)}}}catch(t){return Vm(e.type,t)}}function Wm(e,t,n){return t===void 0?e===`model`?n??void 0:e===`user`?Ue:void 0:t}function Gm(e,t,n){for(let r of e)n({intent:r,...t===void 0?{}:{requesterDriverId:t}})}function Km(e,t){let n=hd(e,t);return Object.freeze({kind:`host`,scope:e,displayName:t,source:n,read:()=>{if(!j(t))return{};let e=Ft(t,`utf8`);try{return JSON.parse(e)}catch(e){throw new md(t,e instanceof Error?e.message:String(e))}},write:e=>{Tt(Re(t)),Dt(t),Vt(t,`${JSON.stringify(e,null,2)}\n`,{encoding:`utf8`,mode:384})}})}function qm(e,t){let n=Cc(t,e),r=tc(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 md(a,e instanceof Error?e.message:String(e))}},write:e=>{n.writeText(`${JSON.stringify(e,null,2)}\n`)}})}function Jm(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=xc(e.authority,{status:`approved`,target:`project-local`,relativePath:n.relativePath,purpose:`persist user-approved project permission`}),i=qm(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 Ym(e){return e.commandSemanticRoles?e.commandSemanticRoles:(e.commandModules?.flatMap(e=>e.systemCommands??[])??[]).reduce((e,t)=>t.semanticRole?{...e,[t.semanticRole]:t.name}:e,{})}function Xm(e,t){let{mergedConfig:n,cwd:r,context:i,projectInfo:a,sessionId:o,contextCapacityHint:s,contributionSources:c,skillRoots:l}=t,u=Jm(e.projectAccess,e.projectSettingsPaths);return{config:n,cwd:r,context:i,contributionSources:c,skillRoots:l,...e.pluginSkills===void 0?{}:{pluginSkills:e.pluginSkills},projectInfo:a,permissionMode:e.permissionMode,baselinePermissionAllow:e.baselinePermissionAllow,maxTurns:e.maxTurns,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},terminal:rr,sessionLogger:e.sessionLogSink===void 0?new ft:new rt(e.sessionLogSink),...e.transcriptPath===void 0?{}:{transcriptPath:e.transcriptPath},permissionHandler:e.permissionHandler,...u===void 0?{}:{persistProjectPermission:u},...e.askHandler?{ask:e.askHandler}:{},provider:e.provider,onTextDelta:e.onTextDelta,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:Ym(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 Zm(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 Qm(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await Qe(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function $m(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 eh(e){return{...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt}}}const th=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 nh(e){let t=rh(e);return{settings:t.settings,hookSources:t.hookSources}}function rh(e){let t=new Set,n={},r=[];for(let{settings:i,source:a}of e){let e=ph(i.hooks,t);a!==void 0&&ih(e,a,r);for(let e of i.disabledHooks??[])t.add(e);n=ah(n,{...i,hooks:e},t)}return{settings:n,hookSources:r}}function ih(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 ah(e,t,n){return{...e,...t,defaultTrustLevel:gh(e.defaultTrustLevel,t.defaultTrustLevel),disabledHooks:oh(n),provider:_h(e.provider,t.provider),permissions:sh(e.permissions,t.permissions),env:{...e.env??{},...t.env??{}},providers:lh(e.providers,t.providers),enabledPlugins:ch(e.enabledPlugins,t.enabledPlugins),extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold,hooks:uh(e.hooks,t.hooks),taskContext:ch(e.taskContext,t.taskContext),sandbox:ch(e.sandbox,t.sandbox)}}function oh(e){return e.size===0?void 0:[...e]}function sh(e,t){if(e!==void 0||t!==void 0)return{allow:fh(e?.allow,t?.allow),deny:fh(e?.deny,t?.deny),ask:fh(e?.ask,t?.ask)}}function ch(e,t){if(e!==void 0||t!==void 0)return{...e,...t}}function lh(e,t){if(e!==void 0||t!==void 0)return mh(e,t)}function uh(e,t){if(e!==void 0||t!==void 0)return dh(e,t)}function dh(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 fh(e,t){return e===void 0?t===void 0?void 0:[...t]:t===void 0?[...e]:[...new Set([...e,...t])]}function ph(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 mh(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]=_h(n[e],r);return n}const hh={safe:0,moderate:1,full:2};function gh(e,t){return e===void 0?t:t===void 0||hh[e]<=hh[t]?e:t}function _h(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 vh=O.lazy(()=>O.union([O.string(),O.number(),O.boolean(),O.null(),O.undefined(),O.date(),O.array(vh),O.record(vh)])),yh=O.object({name:O.string().optional(),model:O.string().optional(),apiKey:O.string().optional(),baseURL:O.string().optional(),timeout:O.number().optional(),options:O.record(vh).optional()}),bh=O.object({type:O.string().optional(),model:O.string().optional(),apiKey:O.string().optional(),baseURL:O.string().optional(),timeout:O.number().optional(),options:O.record(vh).optional()}),xh=O.object({allow:O.array(O.string()).optional(),deny:O.array(O.string()).optional(),ask:O.array(O.string()).optional()}),Sh=O.record(O.string()).optional(),Ch=O.object({type:O.literal(`command`),command:O.string(),timeout:O.number().optional()}),wh=O.object({type:O.literal(`http`),url:O.string(),headers:O.record(O.string()).optional(),timeout:O.number().optional()}),Th=O.object({type:O.literal(`prompt`),prompt:O.string(),model:O.string().optional()}),Eh=O.object({type:O.literal(`agent`),agent:O.string(),maxTurns:O.number().optional(),timeout:O.number().optional()}),Dh=O.object({type:O.literal(`guardrail`),guardrails:O.array(O.string()).optional()}),Oh=O.discriminatedUnion(`type`,[Ch,wh,Th,Eh,Dh]),X=O.object({id:O.string().optional(),matcher:O.string(),hooks:O.array(Oh)}),kh=O.object({PreToolUse:O.array(X).optional(),PostToolUse:O.array(X).optional(),SessionStart:O.array(X).optional(),SessionEnd:O.array(X).optional(),Stop:O.array(X).optional(),StopFailure:O.array(X).optional(),PreCompact:O.array(X).optional(),PostCompact:O.array(X).optional(),UserPromptSubmit:O.array(X).optional(),SubagentStart:O.array(X).optional(),SubagentStop:O.array(X).optional(),WorktreeCreate:O.array(X).optional(),WorktreeRemove:O.array(X).optional(),PreModelCall:O.array(X).optional(),PostModelCall:O.array(X).optional(),PermissionDecision:O.array(X).optional()}).optional(),Ah=O.record(O.boolean()).optional(),jh=O.object({source:O.object({type:O.enum([`github`,`git`,`local`,`url`]),repo:O.string().optional(),url:O.string().optional(),path:O.string().optional(),ref:O.string().optional()})}),Mh=O.record(jh).optional().catch(void 0),Nh=O.union([O.number().gt(0).lte(1),O.literal(!1)]).optional(),Ph=O.object({enabled:O.boolean().optional(),options:O.record(vh).optional()}),Fh=O.object({enabled:O.boolean().optional(),autoAllowBashIfSandboxed:O.boolean().optional(),excludedCommands:O.array(O.string()).optional(),failIfUnavailable:O.boolean().optional(),filesystem:O.object({allowWrite:O.array(O.string()).optional(),denyRead:O.array(O.string()).optional()}).optional(),network:O.object({enabled:O.boolean().optional()}).optional()}),Ih=O.object({defaultTrustLevel:O.enum([`safe`,`moderate`,`full`]).optional(),language:O.string().optional(),preset:O.string().optional(),currentProvider:O.string().optional(),providers:O.record(bh).optional(),provider:yh.optional(),permissions:xh.optional(),env:Sh,commandEnvAllow:O.array(O.string()).optional(),hooks:kh,disabledHooks:O.array(O.string()).optional(),enabledPlugins:Ah,extraKnownMarketplaces:Mh,autoCompactThreshold:Nh,transports:O.record(Ph).optional(),sandbox:Fh.optional(),taskContext:O.object({enabled:O.boolean().optional(),dir:O.string().min(1).optional()}).optional()}),Lh=/position (\d+)/;function Rh(e){let t=Lh.exec(e.message);return t===null?void 0:Number(t[1])}function zh(e){let t=e.code;return typeof t==`string`?t:void 0}function Bh(e){let t;try{t=vd(e,`load configuration settings`)}catch(t){let n=t instanceof Error?t:Error(String(t));return{source:e,state:`unreadable`,cause:{state:`unreadable`,errno:zh(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:Rh(n)},error:n}}}function Vh(e){if(e.state!==`ok`)return e;let t=Ih.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 Hh(e){return e.map(Bh).map(Vh)}function Uh(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 Wh(e){let t=new Map;for(let n of e)if(n.settings!==void 0)for(let e of Uh(n.settings)){let r=t.get(e)??[];r.push(n.displayName),t.set(e,r)}return[...t.entries()].map(([e,t])=>({key:e,rule:th[e]??`replace`,contributors:t}))}function Gh(e){let t=Hh(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=nh(t.flatMap(e=>e.settings===void 0?[]:[{settings:e.settings,source:e.displayName}]));return{layers:t,merged:r.settings,partial:n,provenance:Wh(t),hookSources:r.hookSources}}const Kh={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[],ask:[]},env:{}};function qh(e){if(e.state===`empty`)throw new md(e.source.displayName,`the settings file is empty`);if(e.state===`invalid-json`)throw new md(e.source.displayName,e.error?.message??`invalid JSON`);if(e.state===`unreadable`)throw e.error}function Jh(e,t){return e.startsWith(`$ENV:`)?t[e.slice(5)]??e:e}function Yh(e,t){let n=e.provider?.apiKey===void 0?e.provider:Xh(e.provider,t);if(e.providers!==void 0){let r=Object.fromEntries(Object.entries(e.providers).map(([e,n])=>[e,Xh(n,t)]));return{...e,provider:n,providers:r}}return{...e,provider:n}}function Xh(e,t){if(e.apiKey===void 0)return e;let n=e.apiKey.startsWith(`$ENV:`);return{...e,apiKey:Jh(e.apiKey,t),...n&&{apiKeyEnv:e.apiKey.slice(5)}}}function Zh(e){if(e.currentProvider!==void 0)return Qh(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...Kh.provider}}function Qh(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??Kh.provider.model,apiKey:n.apiKey??Kh.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 $h(e){return{defaultTrustLevel:e.defaultTrustLevel??Kh.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:Zh(e),permissions:{allow:e.permissions?.allow??Kh.permissions.allow,deny:e.permissions?.deny??Kh.permissions.deny,ask:e.permissions?.ask??Kh.permissions.ask},env:e.env??Kh.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 eg(e,t={}){let n=Hh(e);for(let e of n)qh(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:Yh(e.settings,t),source:e.source.displayName})}let i=nh(r);return{config:$h(i.settings),hookSources:i.hookSources}}const tg={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function ng(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function rg(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||w(t,`.md`)}function ig(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function ag(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 og(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(\S.*)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function sg(e,t){return t&&e.branch===t?0:tg[e.status]}function cg(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 lg(e,t){let n=D(e),r=!1;for(;!r;){let e=E(n,`.git`);if(t.existsSync(e)){if(t.statSync(e).isDirectory())return e;let r=t.readFileSync(e,`utf8`).trim().match(/^gitdir:\s*(\S.*)$/)?.[1];if(r)return T(r)?r:D(n,r)}let i=Re(n);r=i===n,n=i}}function ug(e,t=new Ho){let n=lg(e,t);if(!n)return;let r=E(n,`HEAD`);if(t.existsSync(r))return(t.readFileSync(r,`utf8`).trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1])?.trim()}function dg(e,t){return U(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=>E(t,e))}function fg(e,t){let n=U(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:rg(n,e),status:ng(ig(n,`Status`)),branch:ig(n,`Branch`),scope:ig(n,`Scope`),objective:ag(n,`Objective`),openItems:og(n)}}function pg(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>sg(e,t.currentBranch)-sg(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function mg(e){return e.map(cg).join(`
|
|
107
107
|
|
|
@@ -111,7 +111,7 @@ Do not use emojis.`}function fa(){return`You are a worker subagent executing a s
|
|
|
111
111
|
|
|
112
112
|
`),o=i.map(e=>e.content).join(`
|
|
113
113
|
|
|
114
|
-
`),s=yg(o),c=(await t?.loadStartupMemory())?.content||void 0,l=n.taskContext?.enabled!==!1&&n.taskContext?.dir&&e!==void 0?hg(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 Z={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 xg(e,t){let n=e.readText(t,`detect project package metadata`);if(n!==void 0)try{return JSON.parse(n)}catch{return}}function Q(e,t){return e.inspectKind(t,`detect project type`)===`file`}function Sg(e){if(Q(e,Z.pnpmWorkspace)||Q(e,Z.pnpmLock))return`pnpm`;if(Q(e,Z.yarnLock))return`yarn`;if(Q(e,Z.bunLock))return`bun`;if(Q(e,Z.npmLock))return`npm`}async function Cg(e){let t=U(e);if(Q(t,Z.packageJson)){let e=xg(t,Z.packageJson),n=Q(t,Z.tsconfig)?`typescript`:`javascript`,r=Sg(t);return{type:`node`,name:e?.name,packageManager:r,language:n}}return Q(t,Z.pyproject)||Q(t,Z.setup)?{type:`python`,language:`python`}:Q(t,Z.cargo)?{type:`rust`,language:`rust`}:Q(t,Z.goMod)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}async function wg(e,t,n=[],r=[],i={}){if(e!==void 0)return{config:e,hookSources:[]};let a=t?.status===`trusted`?tc(t.authority):void 0;return eg([...r,...a===void 0?[]:_d(a,n)],i)}async function Tg(e,t){return e.config===void 0?wg(void 0,t,e.projectSettingsPaths,e.userSettingsSources,e.environment):{config:e.config,hookSources:e.hookSources??[]}}async function Eg(e){let t=e.projectAccess??G(`identity-unavailable`,e.cwd),n=t.status===`trusted`?tc(t.authority):void 0,r=t.status!==`trusted`||n===void 0?void 0:{reader:n,startRelativeDirectory:ze(t.identity.worktreeRoot,D(e.cwd))},{config:i,hookSources:a}=await Tg(e,t),o={...e.taskContext,...i.taskContext},[s,c]=await Promise.all([e.bare?Promise.resolve({agentsMd:``,projectNotesMd:``,agentsFileEntries:[],projectNotesFileEntries:[]}):bg(r,e.memoryStore,o.dir!==void 0||o.enabled!==void 0?{taskContext:o}:{}),e.bare||n===void 0?Promise.resolve({type:`unknown`,language:`unknown`}):Cg(n)]);return{projectAccess:t,config:i,context:s,projectInfo:c,contributionSources:e.contributionSources??[],hookSources:a}}function Dg(e){if(e)return`Run /${e} and retry.`}function Og(e,t,n,r=new Ho){let i=E(n,e,`subagents`);return r.mkdirSync(i,{recursive:!0}),new rt(new at(i))}function kg(e,t){return E(t,e,`subagents`)}var Ag=class{settingsPath;fs;constructor(e,t=new Ho){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=Re(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:{}}},jg=class extends Error{name=`PluginPathContainmentError`};const Mg=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Ng(e){return typeof e==`string`&&e.length>0&&e.length<=128&&Mg.test(e)}function Pg(e,t){if(!Ng(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 Fg(e,t){let n=D(e),r=[];for(;;){if(t.existsSync(n))return D(t.realpathSync(n),...r.reverse());let i=D(n,`..`);if(i===n)return D(e);r.push(n.slice(i.length+1)),n=i}}function Ig(e,t,n,r){let i=Fg(e,r),a=Fg(t,r);if(!(a===i||a.startsWith(i.endsWith(Be)?i:i+Be)))throw new jg(`Refusing to ${n} outside the plugin root: ${JSON.stringify(t)} resolves to ${JSON.stringify(a)}, which is not inside ${JSON.stringify(i)}.`)}function Lg(e,t,n,r){if(T(t))throw new jg(`Refusing to ${n} from an absolute path: ${JSON.stringify(t)}. This field takes a path relative to the plugin root.`);let i=D(e,t);return Ig(e,i,n,r),i}var Rg=class extends Error{code;name=`McpContributionError`;constructor(e){super(e),this.code=e}};function zg(e,t=!0){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Date)throw new Rg(`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 Rg(`invalid-object`);return n}function Bg(e,t,n,r){let i=E(e,`.mcp.json`),a=t=>(Ig(e,t,`read MCP contribution`,n),JSON.parse(n.readFileSync(t,`utf-8`))),o=n.existsSync(i)?a(i):void 0;if(t===void 0)return o;if(o!==void 0&&r)for(let e of Object.keys(zg(o)))r(e,i);let s=Array.isArray(t)?t:[t],c=o===void 0?{}:{...zg(o)};for(let t of s){let n=t,i=E(e,`.claude-plugin`,`plugin.json`);if(typeof t==`string`){if(!t.startsWith(`./`)||!t.endsWith(`.json`)||t.includes(`\\`))throw new Rg(`unsupported-path`);i=E(e,t),n=a(i)}let o=zg(n,typeof t==`string`);for(let e of Object.keys(o))r?.(e,i);c={...c,...o}}return{mcpServers:c}}const Vg={"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`},Hg=/position (\d+)/;function Ug(e){if(e===void 0)return`Error`;if(e instanceof Rg)return`${e.name} [${e.code}]`;if(e instanceof Pf)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=Hg.exec(e.message);return t===null?e.name:`${e.name} at position ${t[1]}`}function Wg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Gg(e,t,n,r){let i=Wg(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:Wg(i.env)?Object.keys(i.env):[]}}function Kg(e,t,n,r){if(Object.keys(n).length===0)return;let i=kh.safeParse(n);i.success||r.push({pluginId:e,hooksPath:E(t,`hooks`,`hooks.json`),issues:i.error.issues.map(e=>({path:e.path.map(String).join(`.`),code:e.code}))})}function qg(e,t,n,r,i){if(n===void 0)return;let a=E(t,`.mcp.json`);if(!Wg(n)){r.mcpFaults.push({pluginId:e,mcpPath:a,reason:`not-an-object`});return}let o=n.mcpServers;if(!Wg(o)){r.mcpFaults.push({pluginId:e,mcpPath:a,reason:`no-servers`});return}for(let[t,n]of Object.entries(o)){let o=i&&Object.hasOwn(i,t)?i[t]:a;r.mcpServers.push(Gg(e,o,t,n))}}function Jg(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 Yg(e,t=new Ho){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function Xg(e,t){let n=[],r=[],i=(t,n,i,a,o,s=`supported`)=>{r.push({identity:`${e.manifest.name}:${t}:${n}`,kind:t,source:i,requiredCapabilities:a,disposition:s,...o?{reason:o}:{}})};for(let t of e.commands)i(`command`,t.name.startsWith(`${e.manifest.name}:`)?t.name.slice(e.manifest.name.length+1):t.name,t.skillDirectory??E(e.pluginDir,`commands`),[`command-router`]);for(let t of e.skills)i(`skill`,t.name,t.skillDirectory??E(e.pluginDir,`skills`),[`skill-reader`]);let a=typeof e.hooks.hooks==`object`&&e.hooks.hooks!==null?e.hooks.hooks:e.hooks;for(let t of Object.keys(a))i(`hook`,t,E(e.pluginDir,`hooks`,`hooks.json`),[`hook-executor`]);for(let t of e.agents)i(`agent`,t,E(e.pluginDir,`agents`),[`agent-router`],`Agent names are inspected; execution definitions are unavailable from this adapter`,`unavailable`);let o=e.mcpConfig;if(typeof o==`object`&&o&&!Array.isArray(o)&&!(o instanceof Date)){let t=o.mcpServers;if(typeof t==`object`&&t&&!Array.isArray(t)&&!(t instanceof Date))for(let[r,a]of Object.entries(t)){let t=[`mcp-client`],o=!1;if(typeof a==`object`&&a&&!Array.isArray(a)&&!(a instanceof Date)){let e=a.type??(typeof a.command==`string`?`stdio`:typeof a.url==`string`?`http`:void 0);e===`stdio`?(t.push(`stdio-authority`),o=typeof a.command==`string`):e===`http`&&(t.push(`http-transport`),o=typeof a.url==`string`)}i(`mcp`,r,e.mcpSourcePaths?.[r]??E(e.pluginDir,`.mcp.json`),t,o?void 0:`No supported transport declaration`,o?`supported`:`unsupported`),o||n.push({component:`mcp`,code:`unsupported-transport`})}}o!==void 0&&(typeof o!=`object`||!o||Array.isArray(o)||o instanceof Date||typeof o.mcpServers!=`object`||o.mcpServers===null||Array.isArray(o.mcpServers)||o.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`}),r.push({identity:`${e.manifest.name}:declaration:${t}`,kind:t===`commands`?`command`:t===`skills`?`skill`:t===`hooks`?`hook`:`agent`,source:E(e.pluginDir,`.claude-plugin`,`plugin.json`),requiredCapabilities:[],disposition:`unsupported`,reason:`Declared component paths are not consumed by this adapter`}));let s=w(e.pluginDir);return{schemaVersion:1,identity:t,installedRevision:s,generation:JSON.stringify([t,s,e.pluginDir]),source:{kind:`bundle`,location:e.pluginDir},requiredCapabilities:[...new Set(r.flatMap(e=>e.requiredCapabilities))],contributions:r,lifecycle:{activation:`unadmitted`,activeCalls:`host-owned`},diagnostics:n}}const Zg=le(`BundlePluginLoader`);function Qg(e,t){let n=Pn({source:e,content:t,profile:`bundle-skill`});if(!n.ok)throw new Pf(n.diagnostics);return n}var $g=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new Ho){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){let e=this.inspectPluginsSync();for(let t of e.skipped)t.reason!==`disabled`&&Zg.warn(Vg[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=E(this.pluginsDir,`cache`),t=this.snapshotInstalledSelection(),n=new Set,r={loaded:[],skipped:[],hookIssues:[],mcpServers:[],mcpFaults:[]},i=this.fs.existsSync(e);if(i)for(let i of Yg(e,this.fs)){let a=E(e,i);for(let e of Yg(a,this.fs))n.add(`${e}@${i}`),this.inspectPluginDir(i,e,E(a,e),r,t)}for(let e of Object.keys(t.records??{}))n.has(e)||r.skipped.push({pluginId:e,manifestPath:E(this.pluginsDir,`installed_plugins.json`),reason:`revision-unselected`,detail:`Selected plugin source is missing from cache`});return t.error&&n.size===0&&r.skipped.push({pluginId:`installed_plugins.json`,manifestPath:E(this.pluginsDir,`installed_plugins.json`),reason:`revision-unselected`,detail:Ug(t.error)}),{pluginsDir:this.pluginsDir,cacheDirPresent:i,...r}}inspectPluginDir(e,t,n,r,i){let a=Yg(n,this.fs),o=`${t}@${e}`,s;try{s=this.selectRevision(n,e,t,a,i)}catch(e){r.skipped.push({pluginId:o,manifestPath:E(n,`.claude-plugin`,`plugin.json`),reason:`revision-unselected`,detail:Ug(e instanceof Error?e:void 0)});return}let c=E(s,`.claude-plugin`,`plugin.json`),l;try{l=this.readManifest(c)}catch(e){let t=Ug(e instanceof Error?e:void 0);r.skipped.push({pluginId:o,manifestPath:c,reason:`manifest-unreadable`,detail:t});return}if(!l){r.skipped.push({pluginId:o,manifestPath:c,reason:`manifest-invalid`});return}let u=`${l.name}@${e}`;if(this.isDisabled(o,t)||this.isDisabled(u,l.name)){r.skipped.push({pluginId:u,manifestPath:c,reason:`disabled`});return}try{let e=this.loadPlugin(s,l);e.descriptor=Xg(e,o),r.loaded.push(e),Kg(u,s,e.hooks,r.hookIssues),qg(u,s,e.mcpConfig,r,e.mcpSourcePaths)}catch(e){let t=Ug(e instanceof Error?e:void 0);r.skipped.push({pluginId:u,manifestPath:c,reason:`load-failed`,detail:t})}}snapshotInstalledSelection(){let e=E(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,r,i){if(i.error)throw i.error;let a;if(i.records){let r=Object.hasOwn(i.records,`${n}@${t}`)?i.records[`${n}@${t}`]:void 0;if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`No selected installation`);let o=r;if(Pg(o.version,`installed revision`),a=o.version,o.pluginName!==n||o.marketplace!==t||typeof o.installPath!=`string`||D(o.installPath)!==D(e,a))throw Error(`Installed record does not match its cached source`)}else{if(r.length!==1)throw Error(`Select an installed revision before loading multiple cached sources`);a=r[0]}Pg(a,`source revision`);let o=E(e,a);if(!r.includes(a))throw Error(`Selected revision is not installed`);return Ig(E(this.pluginsDir,`cache`),o,`load installed source`,this.fs),Ig(e,o,`load selected plugin revision`,this.fs),Ig(o,E(o,`.claude-plugin`,`plugin.json`),`read plugin manifest`,this.fs),o}readManifest(e){let t=this.fs.readFileSync(e,`utf-8`);return Jg(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=Bg(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=E(e,`skills`);if(!this.fs.existsSync(n))return[];let r=this.fs.readdirSync(n,{withFileTypes:!0}),i=[];for(let e of r){if(!e.isDirectory())continue;let t=E(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let r=this.fs.readFileSync(t,`utf-8`),{metadata:a,body:o}=Qg(t,r),s=typeof a.description==`string`?a.description:``,c={name:e.name,description:s,skillContent:o===r?o:o.trimStart(),...a,skillDirectory:E(n,e.name)};i.push(c)}return i}loadCommands(e,t){let n=E(e,`commands`);if(!this.fs.existsSync(n))return[];let r=this.fs.readdirSync(n,{withFileTypes:!0}),i=[];for(let e of r){if(!e.isFile()||!e.name.endsWith(`.md`))continue;let r=E(n,e.name),a=this.fs.readFileSync(r,`utf-8`),{metadata:o,body:s}=Qg(r,a),c=typeof o.name==`string`?o.name:e.name.replace(/\.md$/,``),l=typeof o.description==`string`?o.description:``;i.push({...o,name:`${t}:${c}`,description:l,skillContent:s===a?s:s.trimStart(),skillDirectory:n})}return i}loadHooks(e){let t=E(e,`hooks`,`hooks.json`);if(!this.fs.existsSync(t))return{};let n=this.fs.readFileSync(t,`utf-8`),r=JSON.parse(n);return typeof r==`object`&&r?r:{}}loadAgents(e){let t=E(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 e_(e){if(e.settingsPath===void 0&&e.enabledPlugins===void 0)throw Error(`Plugin enablement requires settingsPath or enabledPlugins`);let t=e.enabledPlugins??new Ag(e.settingsPath,e.fs).getEnabledPlugins();return new $g(e.pluginsDir,t,e.fs)}function t_(e,t={}){return[...new Set(e)].map(e=>e_({...t,pluginsDir:e}).inspectPluginsSync())}function n_(e,t={}){let n=new Set,r=[];for(let i of new Set(e))for(let e of e_({...t,pluginsDir:i}).loadPluginsSync())n.has(e.manifest.name)||(n.add(e.manifest.name),r.push(e));return r}function r_(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 i_=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,...r_(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,...r_(n)})}return e}};function a_(e,t){try{let n=ze(M(nc(t.authority).worktreeRoot),j(e)?M(e):D(e));return n!==`..`&&!n.startsWith(`..${Be}`)&&!T(n)}catch{return!1}}function o_(e){let t=e.projectAccess,n=e.pluginDirectories?.project;return[...t?.status===`trusted`&&n!==void 0&&a_(n,t)?[n]:[],...e.pluginDirectories?.user===void 0?[]:[e.pluginDirectories.user]]}function s_(e){if(e.bare!==!0)return e.userSettingsSources?.find(e=>e.scope===`user`)?.path}function c_(e){let t=s_(e);if(t===void 0)return[];try{return new i_(n_(o_(e),{settingsPath:t})).getCommands()}catch{return[]}}function l_(e){let t=E(Re(Re(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function u_(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 d_(e){let t={},n=[];for(let r of e){let e=r.hooks;if(!e)continue;let i=l_(r),a=e.hooks??e;for(let[e,o]of Object.entries(a)){if(!Array.isArray(o))continue;t[e]||(t[e]=[]);let a=o.map(e=>{let t=u_(e,r.pluginDir);return t.env=i,t});t[e].push(...a);for(let t of a)if(Array.isArray(t.hooks))for(let i of t.hooks)typeof i?.type==`string`&&n.push({event:e,type:i.type,source:E(r.pluginDir,`hooks`,`hooks.json`)})}}return{hooks:t,hookSources:n}}function f_(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 p_=le(`InteractiveSessionInit`);async function m_(e){let t=e.cwd,{config:n,context:r,projectInfo:i,contributionSources:a,hookSources:o}=await Eg(e),s=e.language?{...n,language:e.language}:n;e.skipConfiguredHooks===!0&&(s={...s,hooks:void 0});let c=e.skipConfiguredHooks===!0?[]:[...o],l=o_(e),u=s_(e);if(u!==void 0)try{let e=n_(l,{settingsPath:u});if(e.length>0){let t=d_(e);s={...s,hooks:f_(s.hooks,t.hooks)},c.push(...t.hookSources)}}catch(e){p_.warn(`plugin discovery failed — no bundle plugin hooks are active this session`,{pluginsDirs:l,error:e instanceof Error?e.message:String(e)})}await $m(e)||await Qm(e,t);let d=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,f=Dg(e.commandSemanticRoles?.contextReduction),{session:p,rebuildSystemMessage:m}=await zp(Xm(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 h_(e,t){let{config:n,hookSources:r}=await wg(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 m_({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}:{},...Zm(e,t.sandboxSnapshotId),...eh(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(Hp(o.session,{isFork:e.forkSession===!0||e.workspaceMovedFrom!==void 0,restoredSystemPrompt:t.restoredSystemPrompt,explicitSystemPrompt:e.systemPrompt}),t.pendingRestoreMessages){for(let e of t.pendingRestoreMessages)Ha(o.session,e);o.session.syncContextFromHistory()}return{session:o.session,agentsFileEntries:o.agentsFileEntries,projectNotesFileEntries:o.projectNotesFileEntries,rebuildSystemMessage:o.rebuildSystemMessage,autoCompactThresholdSource:i}}function g_(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(__({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 __(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},...v_(e.backgroundState),...y_(e.memoryState),...b_(e.skillActivationState),...x_(e.contextReferenceState)}}function v_(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function y_(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function b_(e){return e?{skillActivationEvents:[...e.events]}:{}}function x_(e){return e?{contextReferences:[...e.references]}:{}}var S_=class extends Error{constructor(e){super(e),this.name=`ProviderConfigError`}};function C_(e){return yd(e)}function w_(e,t=process.env){for(let n of e){let e=n.defaults;if(e?.apiKey===void 0||e.model===void 0||!Ce(e.apiKey))continue;let r=e.apiKey.slice(l.length).trim();if(r.length===0)continue;let i=t[r];if(i!==void 0&&i.length!==0)return{name:n.type,model:e.model,apiKey:i,...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:r,apiKeyEnv:r}}}function T_(e,t={}){let n=wd(C_(e),t.providerOverride,t.providerDefinitions??[],t.env);if(n!==void 0)return n;let r=w_(t.providerDefinitions??[],t.env);if(r!==void 0)return r;throw new S_(`No provider configuration found. Configure a provider before starting a session.`)}function E_(e,t,n={}){let r=n.providerDefinitions??[],i=T_(e,{...n,providerDefinitions:r}),a=t??i.model;return ue({...i,model:a},r)}function D_(e,t,n,r){let i={providerOverride:e,providerDefinitions:t,...r!==void 0&&{env:r}},a=T_(n,i),o=E_(n,void 0,i);return Wi(o,Hi(a,t)),{settings:a,provider:o}}function O_(e,t){return e?.displayName??t.type??`Unknown provider`}function k_(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 A_(e,t){let n=Object.keys(e);return t===void 0||!n.includes(t)?n:[t,...n.filter(e=>e!==t)]}function j_(e,t,n,r,i){let a=e??{},o=[];for(let e of A_(a,t)){if(i!==void 0&&!i.includes(e))continue;let t=a[e];if(t===void 0||!t.type||!t.model)continue;let n=ge(r,t.type);o.push({profileName:e,providerLabel:O_(n,t),models:k_(t,n)})}return{groups:o,...t===void 0?{}:{currentProfile:t},currentModel:n}}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 N_=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 P_(e,t,n){let r=e.load(t);if(r.status===`missing`)return;if(r.status!==`valid`)throw new N_(t,r.status);let i={...r.record,name:n,updatedAt:new Date().toISOString()};e.save(i)}var F_=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 I_(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(L_)}:{}}}function L_(e){return{name:e.name,description:e.description,...e.displayName===void 0?{}:{displayName:e.displayName},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint}}}function R_(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 z_=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 B_=nt,V_=`autoCompactThreshold`;function H_(e){return e.getContextState()}function U_(e){return e.getAutoCompactThreshold()}function W_(e){return e.getAutoCompactThresholdSource()}function G_(e,t,n){e.setAutoCompactThreshold(t,n)}function K_(e,t){let n=$_(e);return n?(n.write({...n.read(),[V_]:t}),!0):!1}function q_(e){let t=$_(e);if(!t)return!1;let n={...t.read()};return delete n[V_],t.write(n),!0}async function J_(e,t){let n=H_(e),r=e.getSession().getMessageCount();return await e.compactContext(t),{before:n,after:H_(e),beforeMessageCount:r,afterMessageCount:e.getSession().getMessageCount()}}function Y_(e){return e.listContextReferences()}async function X_(e,t){return e.addContextReference(t)}function Z_(e,t){return e.removeContextReference(t)}function Q_(e){return e.clearContextReferences()}function $_(e){return e.getCommandHostAdapters?.().settings}function ev(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function tv(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function nv(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 rv(e,t,n={}){if(!t.type)throw Error(`Provider profile "${e}" is missing type`);let r=n.providerDefinitions??[],i=ge(r,t.type);if(i===void 0&&r.length>0)throw Error(`Unknown provider "${t.type}". Supported providers: ${ve(r)}`);if(!t.model)throw Error(`Provider profile "${e}" is missing model`);let a=ye(i);if(a!==void 0&&!cv(t,i?.defaults,a,n.env))throw Error(`Provider profile "${e}" is missing ${uv(a)}`)}function iv(e,t={}){let n=av(e,t);return rv(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function av(e,t={}){let n=sv(e.type,t.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 n=(t.env??process.env)[e.apiKeyEnv];if(n===void 0||n.length===0)throw Error(`Environment variable ${e.apiKeyEnv} is not set — set it before configuring (the profile will reference $ENV:${e.apiKeyEnv})`)}let r=e.apiKeyEnv===void 0?e.apiKey??n.apiKey:_e(e.apiKeyEnv),i=e.baseURL??n.baseURL;return{type:e.type,model:e.model??n.model,...dv(r)&&{apiKey:r},...i!==void 0&&{baseURL:i},...e.timeout!==void 0&&{timeout:e.timeout}}}function ov(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=ev(e,n,r);return t.currentProvider?tv(i,t.currentProvider):i}function sv(e,t){return ge(t,e)?.defaults??{}}function cv(e,t,n,r){return n.anyOf.some(n=>be(lv(n,e,t),r===void 0?void 0:e=>r[e]))}function lv(e,t,n){return t[e]??n?.[e]}function uv(e){return e.anyOf.join(` or `)}function dv(e){return e!==void 0&&e.length>0}async function fv(e,t,n,r){let i=n??e;if(!i)return{message:`No provider profile selected.`,success:!1};let a=t?.[i];if(!a)return{message:`Provider profile "${i}" was not found.`,success:!1};try{rv(i,a,{providerDefinitions:r.providerDefinitions})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let o=await((a.type?ge(r.providerDefinitions,a.type):void 0)?.probeProfile??pv)(a);return{message:o.ok?`Provider "${i}" test passed: ${o.message}`:`Provider "${i}" test failed: ${o.message}; manual configuration can continue.`,success:!0,data:{providerTest:{profile:i}}}}async function pv(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function mv(e,t=[]){return hv(e,t)?`valid`:`incomplete`}function hv(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return gv(n?.type,n,t)}return!!(e.provider&&gv(e.provider.name,e.provider,t))}function gv(e,t,n){if(!t)return!1;if(!e)return be(t.apiKey);let r=ge(n,e);if(r===void 0)return!1;let i=ye(r);return i===void 0||_v(t,r,i)}function _v(e,t,n){return n.anyOf.some(n=>be(vv(n,e,t)))}function vv(e,t,n){return t[e]??n.defaults?.[e]}function yv(e,t=[]){if(!j(e))return`missing`;try{let n=Ft(e,`utf8`).trim();return n.length===0?`incomplete`:mv(JSON.parse(n),t)}catch{return`corrupt`}}function bv(e){let t=Dv(e)??e[0];if(t===void 0)throw Error(`No settings store available for provider update`);return t}function xv(e){return e.read()}function Sv(e,t,n={}){let r=ov(xv(e),iv(t,n));return e.write(r),r}function Cv(e,t,n={}){let r=xv(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:tv(r,t);return e.write(o),o}function wv(e,t,n,r={}){let i=yd(e),a=r.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Tv(t,a,n)}function Tv(e,t,n){let r=Ev(e,t)??e[0];if(r===void 0)throw Error(`No settings store available for model update`);let i=xv(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 Ev(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&xv(r).providers?.[t]!==void 0)return r}}function Dv(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&xv(n).currentProvider!==void 0)return n}}function Ov(e,t){return e?.displayName??t.type??`Unknown provider`}function kv(e,t){let n=t?.modelCatalog;return(n!==void 0&&n.status!==`unavailable`?n.entries??[]:[]).find(t=>t.id===e)?.displayName??e}function Av(e,t,n){let r=e[n]??t?.defaults?.[n];return typeof r==`string`?r:void 0}function jv(e,t){let n=ye(t);if(n!==void 0)return n.anyOf.some(n=>be(Av(e,t,n)))?void 0:`Key missing`}function Mv(e,t,n,r){let i=e??{},a=[];for(let e of Object.keys(i)){if(r!==void 0&&!r.includes(e))continue;let o=i[e];if(o===void 0)continue;let s=typeof o.type==`string`?ge(n,o.type):void 0,c=jv(o,s);a.push({name:e,providerLabel:Ov(s,o),...typeof o.model==`string`&&o.model.length>0?{model:{id:o.model,label:kv(o.model,s)}}:{},current:e===t,...c===void 0?{}:{connectionState:c}})}return{profiles:a}}const Nv=`Show/change permission mode`,Pv=`plan | default | acceptEdits | bypassPermissions | auto`,Fv=`Show/change permission mode and permission rules`,Iv=`this session (CLI flags, preset, commands)`,Lv=[`deny`,`ask`,`allow`],Rv=[`plan`,`default`,`acceptEdits`,`bypassPermissions`,`auto`],zv={plan:`Plan only`,default:`Ask first`,acceptEdits:`Accept edits`,bypassPermissions:`Skip all checks`,auto:`Auto`};function Bv(e=`mode`){return[{name:`plan`,displayName:zv.plan,description:`Plan only, no execution`,source:e},{name:`default`,displayName:zv.default,description:`Ask before risky actions`,source:e},{name:`acceptEdits`,displayName:zv.acceptEdits,description:`Auto-approve file edits`,source:e},{name:`bypassPermissions`,displayName:zv.bypassPermissions,description:`Skip all permission checks`,source:e},{name:`auto`,displayName:zv.auto,description:`A model classifier approves or blocks risky actions`,source:e}]}function Vv(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Hv(e){return Rv.includes(e)}function Uv(){return`Invalid mode. Valid: ${Rv.join(` | `)}`}function Wv(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 Gv(e){return Wv(e).getPermissionMode()}function Kv(e,t){Wv(e).setPermissionMode(t)}function qv(e,t){if(!(!Number.isInteger(t)||t<1))return Wv(e).retryDenial(t-1)}function Jv(e){return Wv(e).listSessionAllowedTools()}function Yv(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 Lv)for(let t of a[e])n.add(`${e}\0${t}`);Lv.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:Iv,deny:i(`deny`),ask:i(`ask`),allow:i(`allow`)};return Lv.some(e=>a[e].length>0)&&r.push(a),r}function Xv(e){let t=Wv(e),n=e.getCommandHostAdapters?.().permissionRules?.readLayers()??[];return{mode:t.getPermissionMode(),sessionAllowed:t.listSessionAllowedTools(),rules:Yv(t.getPermissionRules(),n),recentDenials:t.listRecentDenials()}}const Zv={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 Qv(e){let t=new Date(e);return[t.getHours(),t.getMinutes(),t.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`)}function $v(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 Lv)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=Zv[e.reason],a=e.detail===void 0?``:`: ${e.detail}`;t.push(` ${n+1}. ${Qv(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=yg(o),c=(await t?.loadStartupMemory())?.content||void 0,l=n.taskContext?.enabled!==!1&&n.taskContext?.dir&&e!==void 0?hg(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 Z={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 xg(e,t){let n=e.readText(t,`detect project package metadata`);if(n!==void 0)try{return JSON.parse(n)}catch{return}}function Q(e,t){return e.inspectKind(t,`detect project type`)===`file`}function Sg(e){if(Q(e,Z.pnpmWorkspace)||Q(e,Z.pnpmLock))return`pnpm`;if(Q(e,Z.yarnLock))return`yarn`;if(Q(e,Z.bunLock))return`bun`;if(Q(e,Z.npmLock))return`npm`}async function Cg(e){let t=U(e);if(Q(t,Z.packageJson)){let e=xg(t,Z.packageJson),n=Q(t,Z.tsconfig)?`typescript`:`javascript`,r=Sg(t);return{type:`node`,name:e?.name,packageManager:r,language:n}}return Q(t,Z.pyproject)||Q(t,Z.setup)?{type:`python`,language:`python`}:Q(t,Z.cargo)?{type:`rust`,language:`rust`}:Q(t,Z.goMod)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}async function wg(e,t,n=[],r=[],i={}){if(e!==void 0)return{config:e,hookSources:[]};let a=t?.status===`trusted`?tc(t.authority):void 0;return eg([...r,...a===void 0?[]:_d(a,n)],i)}async function Tg(e,t){return e.config===void 0?wg(void 0,t,e.projectSettingsPaths,e.userSettingsSources,e.environment):{config:e.config,hookSources:e.hookSources??[]}}async function Eg(e){let t=e.projectAccess??G(`identity-unavailable`,e.cwd),n=t.status===`trusted`?tc(t.authority):void 0,r=t.status!==`trusted`||n===void 0?void 0:{reader:n,startRelativeDirectory:ze(t.identity.worktreeRoot,D(e.cwd))},{config:i,hookSources:a}=await Tg(e,t),o={...e.taskContext,...i.taskContext},[s,c]=await Promise.all([e.bare?Promise.resolve({agentsMd:``,projectNotesMd:``,agentsFileEntries:[],projectNotesFileEntries:[]}):bg(r,e.memoryStore,o.dir!==void 0||o.enabled!==void 0?{taskContext:o}:{}),e.bare||n===void 0?Promise.resolve({type:`unknown`,language:`unknown`}):Cg(n)]);return{projectAccess:t,config:i,context:s,projectInfo:c,contributionSources:e.contributionSources??[],hookSources:a}}function Dg(e){if(e)return`Run /${e} and retry.`}function Og(e,t,n,r=new Ho){let i=E(n,e,`subagents`);return r.mkdirSync(i,{recursive:!0}),new rt(new at(i))}function kg(e,t){return E(t,e,`subagents`)}var Ag=class{settingsPath;fs;constructor(e,t=new Ho){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=Re(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:{}}},jg=class extends Error{name=`PluginPathContainmentError`};const Mg=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Ng(e){return typeof e==`string`&&e.length>0&&e.length<=128&&Mg.test(e)}function Pg(e,t){if(!Ng(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 Fg(e,t){let n=D(e),r=[];for(;;){if(t.existsSync(n))return D(t.realpathSync(n),...r.reverse());let i=D(n,`..`);if(i===n)return D(e);r.push(n.slice(i.length+1)),n=i}}function Ig(e,t,n,r){let i=Fg(e,r),a=Fg(t,r);if(!(a===i||a.startsWith(i.endsWith(Be)?i:i+Be)))throw new jg(`Refusing to ${n} outside the plugin root: ${JSON.stringify(t)} resolves to ${JSON.stringify(a)}, which is not inside ${JSON.stringify(i)}.`)}function Lg(e,t,n,r){if(T(t))throw new jg(`Refusing to ${n} from an absolute path: ${JSON.stringify(t)}. This field takes a path relative to the plugin root.`);let i=D(e,t);return Ig(e,i,n,r),i}var Rg=class extends Error{code;name=`McpContributionError`;constructor(e){super(e),this.code=e}};function zg(e,t=!0){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Date)throw new Rg(`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 Rg(`invalid-object`);return n}function Bg(e,t,n,r){let i=E(e,`.mcp.json`),a=t=>(Ig(e,t,`read MCP contribution`,n),JSON.parse(n.readFileSync(t,`utf-8`))),o=n.existsSync(i)?a(i):void 0;if(t===void 0)return o;if(o!==void 0&&r)for(let e of Object.keys(zg(o)))r(e,i);let s=Array.isArray(t)?t:[t],c=o===void 0?{}:{...zg(o)};for(let t of s){let n=t,i=E(e,`.claude-plugin`,`plugin.json`);if(typeof t==`string`){if(!t.startsWith(`./`)||!t.endsWith(`.json`)||t.includes(`\\`))throw new Rg(`unsupported-path`);i=E(e,t),n=a(i)}let o=zg(n,typeof t==`string`);for(let e of Object.keys(o))r?.(e,i);c={...c,...o}}return{mcpServers:c}}const Vg={"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`},Hg=/position (\d+)/;function Ug(e){if(e===void 0)return`Error`;if(e instanceof Rg)return`${e.name} [${e.code}]`;if(e instanceof Pf)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=Hg.exec(e.message);return t===null?e.name:`${e.name} at position ${t[1]}`}function Wg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Gg(e,t,n,r){let i=Wg(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:Wg(i.env)?Object.keys(i.env):[]}}function Kg(e,t,n,r){if(Object.keys(n).length===0)return;let i=kh.safeParse(n);i.success||r.push({pluginId:e,hooksPath:E(t,`hooks`,`hooks.json`),issues:i.error.issues.map(e=>({path:e.path.map(String).join(`.`),code:e.code}))})}function qg(e,t,n,r,i){if(n===void 0)return;let a=E(t,`.mcp.json`);if(!Wg(n)){r.mcpFaults.push({pluginId:e,mcpPath:a,reason:`not-an-object`});return}let o=n.mcpServers;if(!Wg(o)){r.mcpFaults.push({pluginId:e,mcpPath:a,reason:`no-servers`});return}for(let[t,n]of Object.entries(o)){let o=i&&Object.hasOwn(i,t)?i[t]:a;r.mcpServers.push(Gg(e,o,t,n))}}function Jg(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 Yg(e,t=new Ho){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function Xg(e,t){let n=[],r=[],i=(t,n,i,a,o,s=`supported`)=>{r.push({identity:`${e.manifest.name}:${t}:${n}`,kind:t,source:i,requiredCapabilities:a,disposition:s,...o?{reason:o}:{}})};for(let t of e.commands)i(`command`,t.name.startsWith(`${e.manifest.name}:`)?t.name.slice(e.manifest.name.length+1):t.name,t.skillDirectory??E(e.pluginDir,`commands`),[`command-router`]);for(let t of e.skills)i(`skill`,t.name,t.skillDirectory??E(e.pluginDir,`skills`),[`skill-reader`]);let a=typeof e.hooks.hooks==`object`&&e.hooks.hooks!==null?e.hooks.hooks:e.hooks;for(let t of Object.keys(a))i(`hook`,t,E(e.pluginDir,`hooks`,`hooks.json`),[`hook-executor`]);for(let t of e.agents)i(`agent`,t,E(e.pluginDir,`agents`),[`agent-router`],`Agent names are inspected; execution definitions are unavailable from this adapter`,`unavailable`);let o=e.mcpConfig;if(typeof o==`object`&&o&&!Array.isArray(o)&&!(o instanceof Date)){let t=o.mcpServers;if(typeof t==`object`&&t&&!Array.isArray(t)&&!(t instanceof Date))for(let[r,a]of Object.entries(t)){let t=[`mcp-client`],o=!1;if(typeof a==`object`&&a&&!Array.isArray(a)&&!(a instanceof Date)){let e=a.type??(typeof a.command==`string`?`stdio`:typeof a.url==`string`?`http`:void 0);e===`stdio`?(t.push(`stdio-authority`),o=typeof a.command==`string`):e===`http`&&(t.push(`http-transport`),o=typeof a.url==`string`)}i(`mcp`,r,e.mcpSourcePaths?.[r]??E(e.pluginDir,`.mcp.json`),t,o?void 0:`No supported transport declaration`,o?`supported`:`unsupported`),o||n.push({component:`mcp`,code:`unsupported-transport`})}}o!==void 0&&(typeof o!=`object`||!o||Array.isArray(o)||o instanceof Date||typeof o.mcpServers!=`object`||o.mcpServers===null||Array.isArray(o.mcpServers)||o.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`}),r.push({identity:`${e.manifest.name}:declaration:${t}`,kind:t===`commands`?`command`:t===`skills`?`skill`:t===`hooks`?`hook`:`agent`,source:E(e.pluginDir,`.claude-plugin`,`plugin.json`),requiredCapabilities:[],disposition:`unsupported`,reason:`Declared component paths are not consumed by this adapter`}));let s=w(e.pluginDir);return{schemaVersion:1,identity:t,installedRevision:s,generation:JSON.stringify([t,s,e.pluginDir]),source:{kind:`bundle`,location:e.pluginDir},requiredCapabilities:[...new Set(r.flatMap(e=>e.requiredCapabilities))],contributions:r,lifecycle:{activation:`unadmitted`,activeCalls:`host-owned`},diagnostics:n}}const Zg=le(`BundlePluginLoader`);function Qg(e,t){let n=Pn({source:e,content:t,profile:`bundle-skill`});if(!n.ok)throw new Pf(n.diagnostics);return n}var $g=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new Ho){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){let e=this.inspectPluginsSync();for(let t of e.skipped)t.reason!==`disabled`&&Zg.warn(Vg[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=E(this.pluginsDir,`cache`),t=this.snapshotInstalledSelection(),n=new Set,r={loaded:[],skipped:[],hookIssues:[],mcpServers:[],mcpFaults:[]},i=this.fs.existsSync(e);if(i)for(let i of Yg(e,this.fs)){let a=E(e,i);for(let e of Yg(a,this.fs))n.add(`${e}@${i}`),this.inspectPluginDir(i,e,E(a,e),r,t)}for(let e of Object.keys(t.records??{}))n.has(e)||r.skipped.push({pluginId:e,manifestPath:E(this.pluginsDir,`installed_plugins.json`),reason:`revision-unselected`,detail:`Selected plugin source is missing from cache`});return t.error&&n.size===0&&r.skipped.push({pluginId:`installed_plugins.json`,manifestPath:E(this.pluginsDir,`installed_plugins.json`),reason:`revision-unselected`,detail:Ug(t.error)}),{pluginsDir:this.pluginsDir,cacheDirPresent:i,...r}}inspectPluginDir(e,t,n,r,i){let a=Yg(n,this.fs),o=`${t}@${e}`,s;try{s=this.selectRevision(n,e,t,a,i)}catch(e){r.skipped.push({pluginId:o,manifestPath:E(n,`.claude-plugin`,`plugin.json`),reason:`revision-unselected`,detail:Ug(e instanceof Error?e:void 0)});return}let c=E(s,`.claude-plugin`,`plugin.json`),l;try{l=this.readManifest(c)}catch(e){let t=Ug(e instanceof Error?e:void 0);r.skipped.push({pluginId:o,manifestPath:c,reason:`manifest-unreadable`,detail:t});return}if(!l){r.skipped.push({pluginId:o,manifestPath:c,reason:`manifest-invalid`});return}let u=`${l.name}@${e}`;if(this.isDisabled(o,t)||this.isDisabled(u,l.name)){r.skipped.push({pluginId:u,manifestPath:c,reason:`disabled`});return}try{let e=this.loadPlugin(s,l);e.descriptor=Xg(e,o),r.loaded.push(e),Kg(u,s,e.hooks,r.hookIssues),qg(u,s,e.mcpConfig,r,e.mcpSourcePaths)}catch(e){let t=Ug(e instanceof Error?e:void 0);r.skipped.push({pluginId:u,manifestPath:c,reason:`load-failed`,detail:t})}}snapshotInstalledSelection(){let e=E(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,r,i){if(i.error)throw i.error;let a;if(i.records){let r=Object.hasOwn(i.records,`${n}@${t}`)?i.records[`${n}@${t}`]:void 0;if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`No selected installation`);let o=r;if(Pg(o.version,`installed revision`),a=o.version,o.pluginName!==n||o.marketplace!==t||typeof o.installPath!=`string`||D(o.installPath)!==D(e,a))throw Error(`Installed record does not match its cached source`)}else{if(r.length!==1)throw Error(`Select an installed revision before loading multiple cached sources`);a=r[0]}Pg(a,`source revision`);let o=E(e,a);if(!r.includes(a))throw Error(`Selected revision is not installed`);return Ig(E(this.pluginsDir,`cache`),o,`load installed source`,this.fs),Ig(e,o,`load selected plugin revision`,this.fs),Ig(o,E(o,`.claude-plugin`,`plugin.json`),`read plugin manifest`,this.fs),o}readManifest(e){let t=this.fs.readFileSync(e,`utf-8`);return Jg(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=Bg(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=E(e,`skills`);if(!this.fs.existsSync(n))return[];let r=this.fs.readdirSync(n,{withFileTypes:!0}),i=[];for(let e of r){if(!e.isDirectory())continue;let t=E(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let r=this.fs.readFileSync(t,`utf-8`),{metadata:a,body:o}=Qg(t,r),s=typeof a.description==`string`?a.description:``,c={name:e.name,description:s,skillContent:o===r?o:o.trimStart(),...a,skillDirectory:E(n,e.name)};i.push(c)}return i}loadCommands(e,t){let n=E(e,`commands`);if(!this.fs.existsSync(n))return[];let r=this.fs.readdirSync(n,{withFileTypes:!0}),i=[];for(let e of r){if(!e.isFile()||!e.name.endsWith(`.md`))continue;let r=E(n,e.name),a=this.fs.readFileSync(r,`utf-8`),{metadata:o,body:s}=Qg(r,a),c=typeof o.name==`string`?o.name:e.name.replace(/\.md$/,``),l=typeof o.description==`string`?o.description:``;i.push({...o,name:`${t}:${c}`,description:l,skillContent:s===a?s:s.trimStart(),skillDirectory:n})}return i}loadHooks(e){let t=E(e,`hooks`,`hooks.json`);if(!this.fs.existsSync(t))return{};let n=this.fs.readFileSync(t,`utf-8`),r=JSON.parse(n);return typeof r==`object`&&r?r:{}}loadAgents(e){let t=E(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 e_(e){if(e.settingsPath===void 0&&e.enabledPlugins===void 0)throw Error(`Plugin enablement requires settingsPath or enabledPlugins`);let t=e.enabledPlugins??new Ag(e.settingsPath,e.fs).getEnabledPlugins();return new $g(e.pluginsDir,t,e.fs)}function t_(e,t={}){return[...new Set(e)].map(e=>e_({...t,pluginsDir:e}).inspectPluginsSync())}function n_(e,t={}){let n=new Set,r=[];for(let i of new Set(e))for(let e of e_({...t,pluginsDir:i}).loadPluginsSync())n.has(e.manifest.name)||(n.add(e.manifest.name),r.push(e));return r}function r_(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 i_=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,...r_(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,...r_(n)})}return e}};function a_(e,t){try{let n=ze(M(nc(t.authority).worktreeRoot),j(e)?M(e):D(e));return n!==`..`&&!n.startsWith(`..${Be}`)&&!T(n)}catch{return!1}}function o_(e){let t=e.projectAccess,n=e.pluginDirectories?.project;return[...t?.status===`trusted`&&n!==void 0&&a_(n,t)?[n]:[],...e.pluginDirectories?.user===void 0?[]:[e.pluginDirectories.user]]}function s_(e){if(e.bare!==!0)return e.userSettingsSources?.find(e=>e.scope===`user`)?.path}function c_(e){let t=s_(e);if(t===void 0)return[];try{return new i_(n_(o_(e),{settingsPath:t})).getCommands()}catch{return[]}}function l_(e){let t=E(Re(Re(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function u_(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 d_(e){let t={},n=[];for(let r of e){let e=r.hooks;if(!e)continue;let i=l_(r),a=e.hooks??e;for(let[e,o]of Object.entries(a)){if(!Array.isArray(o))continue;t[e]||(t[e]=[]);let a=o.map(e=>{let t=u_(e,r.pluginDir);return t.env=i,t});t[e].push(...a);for(let t of a)if(Array.isArray(t.hooks))for(let i of t.hooks)typeof i?.type==`string`&&n.push({event:e,type:i.type,source:E(r.pluginDir,`hooks`,`hooks.json`)})}}return{hooks:t,hookSources:n}}function f_(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 p_=le(`InteractiveSessionInit`);async function m_(e){let t=e.cwd,{config:n,context:r,projectInfo:i,contributionSources:a,hookSources:o}=await Eg(e),s=e.language?{...n,language:e.language}:n;e.skipConfiguredHooks===!0&&(s={...s,hooks:void 0});let c=e.skipConfiguredHooks===!0?[]:[...o],l=o_(e),u=s_(e);if(u!==void 0)try{let e=n_(l,{settingsPath:u});if(e.length>0){let t=d_(e);s={...s,hooks:f_(s.hooks,t.hooks)},c.push(...t.hookSources)}}catch(e){p_.warn(`plugin discovery failed — no bundle plugin hooks are active this session`,{pluginsDirs:l,error:e instanceof Error?e.message:String(e)})}await $m(e)||await Qm(e,t);let d=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,f=Dg(e.commandSemanticRoles?.contextReduction),{session:p,rebuildSystemMessage:m}=await zp(Xm(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 h_(e,t){let{config:n,hookSources:r}=await wg(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 m_({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}:{},...Zm(e,t.sandboxSnapshotId),...eh(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(Hp(o.session,{isFork:e.forkSession===!0||e.workspaceMovedFrom!==void 0,restoredSystemPrompt:t.restoredSystemPrompt,explicitSystemPrompt:e.systemPrompt}),t.pendingRestoreMessages){for(let e of t.pendingRestoreMessages)Ha(o.session,e);o.session.syncContextFromHistory()}return{session:o.session,agentsFileEntries:o.agentsFileEntries,projectNotesFileEntries:o.projectNotesFileEntries,rebuildSystemMessage:o.rebuildSystemMessage,autoCompactThresholdSource:i}}function g_(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(__({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 __(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},...v_(e.backgroundState),...y_(e.memoryState),...b_(e.skillActivationState),...x_(e.contextReferenceState)}}function v_(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function y_(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function b_(e){return e?{skillActivationEvents:[...e.events]}:{}}function x_(e){return e?{contextReferences:[...e.references]}:{}}var S_=class extends Error{constructor(e){super(e),this.name=`ProviderConfigError`}};function C_(e){return yd(e)}function w_(e,t=process.env){for(let n of e){let e=n.defaults;if(e?.apiKey===void 0||e.model===void 0||!Ce(e.apiKey))continue;let r=e.apiKey.slice(l.length).trim();if(r.length===0)continue;let i=t[r];if(i!==void 0&&i.length!==0)return{name:n.type,model:e.model,apiKey:i,...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:r,apiKeyEnv:r}}}function T_(e,t={}){let n=wd(C_(e),t.providerOverride,t.providerDefinitions??[],t.env);if(n!==void 0)return n;let r=w_(t.providerDefinitions??[],t.env);if(r!==void 0)return r;throw new S_(`No provider configuration found. Configure a provider before starting a session.`)}function E_(e,t,n={}){let r=n.providerDefinitions??[],i=T_(e,{...n,providerDefinitions:r}),a=t??i.model;return ue({...i,model:a},r)}function D_(e,t,n,r){let i={providerOverride:e,providerDefinitions:t,...r!==void 0&&{env:r}},a=T_(n,i),o=E_(n,void 0,i);return Wi(o,Hi(a,t)),{settings:a,provider:o}}function O_(e,t){return e?.displayName??t.type??`Unknown provider`}function k_(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 A_(e,t){let n=Object.keys(e);return t===void 0||!n.includes(t)?n:[t,...n.filter(e=>e!==t)]}function j_(e,t,n,r,i){let a=e??{},o=[];for(let e of A_(a,t)){if(i!==void 0&&!i.includes(e))continue;let t=a[e];if(t===void 0||!t.type||!t.model)continue;let n=ge(r,t.type);o.push({profileName:e,providerLabel:O_(n,t),models:k_(t,n)})}return{groups:o,...t===void 0?{}:{currentProfile:t},currentModel:n}}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 N_=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 P_(e,t,n){let r=e.load(t);if(r.status===`missing`)return;if(r.status!==`valid`)throw new N_(t,r.status);let i={...r.record,name:n,updatedAt:new Date().toISOString()};e.save(i)}var F_=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 I_(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(L_)}:{}}}function L_(e){return{name:e.name,description:e.description,...e.displayName===void 0?{}:{displayName:e.displayName},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint}}}function R_(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 z_=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 B_=nt,V_=`autoCompactThreshold`;function H_(e){return e.getContextState()}function U_(e){return e.getAutoCompactThreshold()}function W_(e){return e.getAutoCompactThresholdSource()}function G_(e,t,n){e.setAutoCompactThreshold(t,n)}function K_(e,t){let n=$_(e);return n?(n.write({...n.read(),[V_]:t}),!0):!1}function q_(e){let t=$_(e);if(!t)return!1;let n={...t.read()};return delete n[V_],t.write(n),!0}async function J_(e,t){let n=H_(e),r=e.getSession().getMessageCount();return await e.compactContext(t),{before:n,after:H_(e),beforeMessageCount:r,afterMessageCount:e.getSession().getMessageCount()}}function Y_(e){return e.listContextReferences()}async function X_(e,t){return e.addContextReference(t)}function Z_(e,t){return e.removeContextReference(t)}function Q_(e){return e.clearContextReferences()}function $_(e){return e.getCommandHostAdapters?.().settings}function ev(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function tv(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function nv(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 rv(e,t,n={}){if(!t.type)throw Error(`Provider profile "${e}" is missing type`);let r=n.providerDefinitions??[],i=ge(r,t.type);if(i===void 0&&r.length>0)throw Error(`Unknown provider "${t.type}". Supported providers: ${ve(r)}`);if(!t.model)throw Error(`Provider profile "${e}" is missing model`);let a=ye(i);if(a!==void 0&&!cv(t,i?.defaults,a,n.env))throw Error(`Provider profile "${e}" is missing ${uv(a)}`)}function iv(e,t={}){let n=av(e,t);return rv(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function av(e,t={}){let n=sv(e.type,t.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 n=(t.env??process.env)[e.apiKeyEnv];if(n===void 0||n.length===0)throw Error(`Environment variable ${e.apiKeyEnv} is not set — set it before configuring (the profile will reference $ENV:${e.apiKeyEnv})`)}let r=e.apiKeyEnv===void 0?e.apiKey??n.apiKey:_e(e.apiKeyEnv),i=e.baseURL??n.baseURL;return{type:e.type,model:e.model??n.model,...dv(r)&&{apiKey:r},...i!==void 0&&{baseURL:i},...e.timeout!==void 0&&{timeout:e.timeout}}}function ov(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=ev(e,n,r);return t.currentProvider?tv(i,t.currentProvider):i}function sv(e,t){return ge(t,e)?.defaults??{}}function cv(e,t,n,r){return n.anyOf.some(n=>be(lv(n,e,t),r===void 0?void 0:e=>r[e]))}function lv(e,t,n){return t[e]??n?.[e]}function uv(e){return e.anyOf.join(` or `)}function dv(e){return e!==void 0&&e.length>0}async function fv(e,t,n,r){let i=n??e;if(!i)return{message:`No provider profile selected.`,success:!1};let a=t?.[i];if(!a)return{message:`Provider profile "${i}" was not found.`,success:!1};try{rv(i,a,{providerDefinitions:r.providerDefinitions,...r.env===void 0?{}:{env:r.env}})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let o=await((a.type?ge(r.providerDefinitions,a.type):void 0)?.probeProfile??pv)(a);return{message:o.ok?`Provider "${i}" test passed: ${o.message}`:`Provider "${i}" test failed: ${o.message}; manual configuration can continue.`,success:!0,data:{providerTest:{profile:i}}}}async function pv(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function mv(e,t=[],n){return hv(e,t,n===void 0?void 0:e=>n[e])?`valid`:`incomplete`}function hv(e,t,n){if(typeof e.currentProvider==`string`){let r=e.providers?.[e.currentProvider];return gv(r?.type,r,t,n)}return!!(e.provider&&gv(e.provider.name,e.provider,t,n))}function gv(e,t,n,r){if(!t)return!1;if(!e)return be(t.apiKey,r);let i=ge(n,e);if(i===void 0)return!1;let a=ye(i);return a===void 0||_v(t,i,a,r)}function _v(e,t,n,r){return n.anyOf.some(n=>be(vv(n,e,t),r))}function vv(e,t,n){return t[e]??n.defaults?.[e]}function yv(e,t=[]){if(!j(e))return`missing`;try{let n=Ft(e,`utf8`).trim();return n.length===0?`incomplete`:mv(JSON.parse(n),t)}catch{return`corrupt`}}function bv(e){let t=Dv(e)??e[0];if(t===void 0)throw Error(`No settings store available for provider update`);return t}function xv(e){return e.read()}function Sv(e,t,n={}){let r=ov(xv(e),iv(t,n));return e.write(r),r}function Cv(e,t,n={}){let r=xv(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:tv(r,t);return e.write(o),o}function wv(e,t,n,r={}){let i=yd(e),a=r.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Tv(t,a,n)}function Tv(e,t,n){let r=Ev(e,t)??e[0];if(r===void 0)throw Error(`No settings store available for model update`);let i=xv(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 Ev(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&xv(r).providers?.[t]!==void 0)return r}}function Dv(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&xv(n).currentProvider!==void 0)return n}}function Ov(e,t){return e?.displayName??t.type??`Unknown provider`}function kv(e,t){let n=t?.modelCatalog;return(n!==void 0&&n.status!==`unavailable`?n.entries??[]:[]).find(t=>t.id===e)?.displayName??e}function Av(e,t,n){let r=e[n]??t?.defaults?.[n];return typeof r==`string`?r:void 0}function jv(e,t,n){let r=ye(t);if(r===void 0)return;let i=n===void 0?void 0:e=>n[e];return r.anyOf.some(n=>be(Av(e,t,n),i))?void 0:`Key missing`}function Mv(e,t,n,r,i){let a=e??{},o=[];for(let e of Object.keys(a)){if(r!==void 0&&!r.includes(e))continue;let s=a[e];if(s===void 0)continue;let c=typeof s.type==`string`?ge(n,s.type):void 0,l=jv(s,c,i);o.push({name:e,providerLabel:Ov(c,s),...typeof s.model==`string`&&s.model.length>0?{model:{id:s.model,label:kv(s.model,c)}}:{},current:e===t,...l===void 0?{}:{connectionState:l}})}return{profiles:o}}const Nv=`Show/change permission mode`,Pv=`plan | default | acceptEdits | bypassPermissions | auto`,Fv=`Show/change permission mode and permission rules`,Iv=`this session (CLI flags, preset, commands)`,Lv=[`deny`,`ask`,`allow`],Rv=[`plan`,`default`,`acceptEdits`,`bypassPermissions`,`auto`],zv={plan:`Plan only`,default:`Ask first`,acceptEdits:`Accept edits`,bypassPermissions:`Skip all checks`,auto:`Auto`};function Bv(e=`mode`){return[{name:`plan`,displayName:zv.plan,description:`Plan only, no execution`,source:e},{name:`default`,displayName:zv.default,description:`Ask before risky actions`,source:e},{name:`acceptEdits`,displayName:zv.acceptEdits,description:`Auto-approve file edits`,source:e},{name:`bypassPermissions`,displayName:zv.bypassPermissions,description:`Skip all permission checks`,source:e},{name:`auto`,displayName:zv.auto,description:`A model classifier approves or blocks risky actions`,source:e}]}function Vv(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Hv(e){return Rv.includes(e)}function Uv(){return`Invalid mode. Valid: ${Rv.join(` | `)}`}function Wv(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 Gv(e){return Wv(e).getPermissionMode()}function Kv(e,t){Wv(e).setPermissionMode(t)}function qv(e,t){if(!(!Number.isInteger(t)||t<1))return Wv(e).retryDenial(t-1)}function Jv(e){return Wv(e).listSessionAllowedTools()}function Yv(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 Lv)for(let t of a[e])n.add(`${e}\0${t}`);Lv.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:Iv,deny:i(`deny`),ask:i(`ask`),allow:i(`allow`)};return Lv.some(e=>a[e].length>0)&&r.push(a),r}function Xv(e){let t=Wv(e),n=e.getCommandHostAdapters?.().permissionRules?.readLayers()??[];return{mode:t.getPermissionMode(),sessionAllowed:t.listSessionAllowedTools(),rules:Yv(t.getPermissionRules(),n),recentDenials:t.listRecentDenials()}}const Zv={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 Qv(e){let t=new Date(e);return[t.getHours(),t.getMinutes(),t.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`)}function $v(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 Lv)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=Zv[e.reason],a=e.detail===void 0?``:`: ${e.detail}`;t.push(` ${n+1}. ${Qv(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 ey(e,t,n){let r=[],i=[],a=me(Fe(n.allowedTools),`allow`);if(a.length>0){let e=a.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Preset "${t}" has invalid allowedTools: ${e}.`)}e.getSession().setActivePresetId(t),n.permissionMode===void 0?i.push(`permissionMode`):(Kv(e,n.permissionMode),r.push(`permissionMode`)),n.allowedTools!==void 0||n.deniedTools!==void 0?(e.getSession().applyPresetToolLists({...n.allowedTools!==void 0&&{allowedTools:n.allowedTools},...n.deniedTools!==void 0&&{deniedTools:n.deniedTools}}),r.push(`toolLists`)):i.push(`toolLists`);let o={...n.model!==void 0&&{model:n.model},...n.effort!==void 0&&{effort:n.effort},...n.temperature!==void 0&&{temperature:n.temperature},...n.maxOutputTokens!==void 0&&{maxOutputTokens:n.maxOutputTokens}};for(let e of[`model`,`effort`,`temperature`,`maxOutputTokens`])n[e]===void 0?i.push(e):r.push(e);Object.keys(o).length>0&&await e.getSession().applyModelOptions(o),n.persona===void 0?i.push(`persona`):(e.applyPersona(n.persona),r.push(`persona`)),n.language===void 0?i.push(`language`):(e.applyResponseLanguage(n.language),r.push(`language`)),n.systemPrompt===void 0?i.push(`systemPrompt`):(e.applyPresetSystemPrompt(n.systemPrompt),r.push(`systemPrompt`)),n.agentName===void 0?i.push(`agentName`):(await e.getSession().applyAgentName(n.agentName),r.push(`agentName`));let s=n.enabledCommandModules!==void 0||n.disabledCommandModules!==void 0,c=s?e.applyCommandModuleSelection(n.enabledCommandModules,n.disabledCommandModules):[];return s?r.push(`commandModules`):i.push(`commandModules`),n.enableParallelSubagents===void 0?i.push(`enableParallelSubagents`):(e.getSession().setParallelSubagentsEnabled(n.enableParallelSubagents),r.push(`enableParallelSubagents`)),n.selfVerification===void 0?i.push(`selfVerification`):(e.applySelfVerification(n.selfVerification),r.push(`selfVerification`)),{applied:r,skipped:i,unknownCommandModules:c}}const ty=[/(?<![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,}/],ny=/[A-Za-z0-9+_=]+/g;function ry(e){for(let[t]of e.matchAll(ny))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 iy(e){return ty.some(t=>t.test(e))||ry(e)}var ay=class{evaluate(e,t){return t.policy===`disabled`?{action:`skip`,reason:`memory-policy-disabled`}:iy(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 oy=`lifecycle.json`;var sy=class{storage;constructor(e){this.storage=e}list(){let e=this.storage.readText(oy,`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(oy,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 cy=200,ly=25600,uy=`MEMORY.md`,dy=`topics`,fy=[`user`,`feedback`,`project`,`reference`];function py(e){return fy.includes(e)}function my(e,t){let n=Buffer.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function hy(e,t){let n=e.split(/\r?\n/);return{content:n.slice(0,t).join(`
|
|
117
117
|
`).trimEnd(),truncated:n.length>t}}function gy(e){return Ca(e.trim().toLowerCase().replace(/[^a-z0-9가-힣_-]+/g,`-`),`-`).slice(0,80)||`general`}var _y=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 vy(e){if(!/[a-z0-9가-힣]/i.test(e))throw Error(`A nonempty memory topic is required.`);return gy(e)}function yy(e,t,n){let r=e.toISOString().slice(0,10),i=t.text.trim().replace(/\s+/g,` `);return`[${r}] (${t.type}/${n}) ${i}`}function by(e){return e.trim().replace(/\s+/g,` `)}var xy=class{storage;now;lifecycle;constructor(e,t=()=>new Date){if(this.storage=_c(e),e.namespace!==`memory`)throw Error(`ProjectMemoryStore requires the memory state namespace.`);this.now=t,this.lifecycle=new sy(e)}getIndexPath(){return this.storage.projectRelativePath(uy)}getTopicsPath(){return this.storage.projectRelativePath(dy)}loadStartupMemory(){let e=this.getIndexPath(),t=this.lifecycle.applyIndex(this.storage.readText(uy,`load startup memory`)??``),n=my(t,ly),r=Buffer.byteLength(t,`utf8`)>ly,i=hy(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)),r=this.storage.listDirectory(dy,`list memory topics`).filter(e=>e.kind===`file`&&e.name.endsWith(`.md`)).map(e=>({name:w(e.name,`.md`),path:this.storage.projectRelativePath(E(dy,e.name))})).filter(e=>!n.has(e.name));for(let e of t)e.entry!==void 0&&r.push({name:e.topic,path:this.storage.projectRelativePath(E(dy,`${e.topic}.md`))});return r.sort((e,t)=>e.name.localeCompare(t.name)),{indexPath:this.getIndexPath(),topicsPath:e,topics:r}}readTopic(e){let t=gy(e),n=this.lifecycle.get(t);return n?n.entry===void 0?``:`# ${t}\n\n- ${n.entry}`:(this.storage.readText(E(dy,`${t}.md`),`read memory topic`)??``).trimEnd()}append(e){let t=gy(e.topic);if(this.isTopicCurated(t))throw new _y;let n=this.getIndexPath(),r=E(dy,`${t}.md`),i=this.storage.projectRelativePath(r),a=yy(this.now(),e,t),o=this.storage.readText(r,`deduplicate memory topic`),s=o===void 0?`# ${t}\n\n`:``,c=by(e.text);return o?.includes(`) ${c}`)===!0?{indexPath:n,topicPath:i,topic:t,deduplicated:!0}:(this.storage.readText(uy,`inspect memory index`)===void 0&&this.storage.writeText(uy,`# Project Memory
|
|
@@ -128,4 +128,4 @@ Do not use emojis.`}function fa(){return`You are a worker subagent executing a s
|
|
|
128
128
|
`),n=this.projectNotesFileEntries.map(e=>e.content).join(`
|
|
129
129
|
|
|
130
130
|
`),r=this.rebuildSystemMessage(t,n,e);this.getSessionOrThrow().updateSystemMessage(r)}applyPersona(e){this.rebuildLivePrompt({persona:e})}getActiveOutputStyleId(){return this.activeOutputStyleId}applyOutputStyle(e){this.activeOutputStyleId=e.id,this.rebuildLivePrompt({outputStyle:e})}applySelfVerification(e){this.rebuildLivePrompt({selfVerification:e})}applyResponseLanguage(e){this.rebuildLivePrompt({language:e})}applyPresetSystemPrompt(e){this.rebuildLivePrompt({presetSystemPrompt:e})}applyCommandModuleSelection(e,t){return this.skillRouter.reapplyCommandModuleSelection(e,t)}getAgentJobCapability(){return this}getUserInteraction(){if((this.listeners.get(`ask_request`)?.size??0)!==0)return $b(this.askHandler,()=>this.getCommandInvocationSource())}resolvePermission(e,t,n){this.promptRegistry.resolvePermission(e,t,n??Ue)}resolveAsk(e,t,n){this.promptRegistry.resolveAsk(e,t,n??Ue)}canHandoffTerminal(){return this.terminalHandoffGate.canHandoffTerminal()}runWithTerminal(e){return this.terminalHandoffGate.runWithTerminal(e)}async forkSession(e={}){await this.ensureInitialized();let t=this.getSessionOrThrow();if(!this.sessionStore)throw Error(`Cannot fork: this session has no session store to write the copy to.`);return Gp({source:t,fullHistory:()=>this.getFullHistory(),sessionStore:this.sessionStore,requestedName:e.name,sourceName:this.sessionName,sourceId:t.getSessionId(),cwd:this.getCwd()})}async moveWorkspace(e){await this.ensureInitialized();let t=this.getCommandHostAdapters().workspace;if(!t)throw Error(`Moving to another directory is not available in this environment.`);if(this.workspaceMovePending)throw Error(`A move to another directory is already under way.`);if(!this.sessionStore)throw Error(`This session does not save its conversation, so it cannot move it.`);let n=this.getSessionOrThrow(),r=(this.getBackgroundTaskManager()?.list()??[]).filter(e=>![`completed`,`failed`,`cancelled`].includes(e.status)),i=Xp({requestedPath:e,workspace:this.workspace,executing:this.execCtrl.executing,liveBackgroundTasks:r.length,permissionMode:n.getPermissionMode(),rules:n.getPermissionRules(),source:{getHistory:()=>n.getHistory(),getSystemMessage:()=>n.getSystemMessage(),getToolSchemas:()=>n.getToolSchemas(),getFullHistory:()=>this.getFullHistory()},sessionName:this.sessionName??``}),a=i.record.name?i:{...i,record:{...i.record,name:w(i.targetCwd)}};this.persistCurrentSession(),this.workspaceMovePending=!0;try{await t.move(a)}catch(e){throw this.workspaceMovePending=!1,e}return`Moving to ${i.targetCwd}${i.restricted?` (restricted)`:``}...`}setAutoCompactThreshold(e,t=`session`){this.getSessionOrThrow().setAutoCompactThreshold(e),this.autoCompactThresholdSource=t,this.emit(`context_update`,this.getContextState()),this.persistCurrentSession()}clearConversationHistory(){this.getSessionOrThrow().clearHistory(),this.histTracker.clearHistory(),this.persistCurrentSession(),this.emit(`context_update`,this.getContextState()),this.emit(`history_cleared`)}getName(){return this.sessionName}getStatusSnapshot(){let e=this.getSessionOrThrow(),t;try{let e=this.getCwd();t={name:w(e),path:e}}catch{t=void 0}return{sessionId:e.getSessionId(),...this.sessionName===void 0?{}:{sessionName:this.sessionName},model:e.getModelId(),permissionMode:e.getPermissionMode(),effort:e.getModelEffort(),context:e.getContextState(),goal:this.getGoalState(),...this.setupRequired?{setupRequired:!0}:{},...t===void 0?{}:{workspace:t}}}listModels(){let e=C_(this.userSettingsSources),t=this.getSessionOrThrow();return j_(e.providers,e.currentProvider,t.getModelId(),this.providerDefinitions,this.orgPolicy?.allowedProviders)}isSetupRequired(){return this.setupRequired}attachTransport(e){e.attach(this)}setName(e){if(this.sessionStore&&this.session){let t;try{t=this.getSessionOrThrow().getSessionId()}catch{this.sessionName=e;return}P_(this.sessionStore,t,e)}this.sessionName=e}getBackgroundTaskManager(){if(this.session)return _i(this.session)??uo(this.session)?.backgroundTaskManager}reportBackgroundError(e,t=`background`){let n=Bn(e,this.providerErrorGuidance);this.histTracker.append(S(x(`Error: ${n}`,{metadata:{kind:`error`,source:t}}))),this.emit(`error`,e)}async captureSandboxSnapshot(){if(this.sandboxClient?.snapshot)try{this.sandboxSnapshotId=await this.sandboxClient.snapshot()}catch(e){let t=e instanceof Error?e:Error(String(e));this.histTracker.append(S(x(`Sandbox snapshot error: ${t.message}`))),this.emit(`error`,t)}}persistCurrentSession(e=!1,t,n){if(!this.sessionStore||!this.session){if(e)throw Error(`A session store is required for a resumable loop.`);return}let r=this.bgTracker.getState(),i=this.histTracker.getState();g_(this.sessionStore,this.session,this.sessionName,this.workspace.cwd,i.history,{tasks:r.tasks.filter(n=>{let r=n.metadata?.sessionLoopId;return typeof r!=`string`||!this.pendingLoopCreations.has(r)||e&&r===t}).map(e=>this.pendingLoopStops.has(e.id)?{...e,status:`cancelled`}:e),events:r.taskEvents,groups:r.groups,groupEvents:r.groupEvents},{events:i.memoryEvents,usedReferences:i.usedMemoryReferences},{events:i.skillActivationEvents},{references:i.contextReferences},{snapshotId:this.sandboxSnapshotId},this.goalController.getState()??void 0,this.planController.getState()??void 0,this.histTracker.getActiveBranchPointer(),e,n??this.selfPacedLoops.snapshotForOrdinarySave())}async setGoal(e,t={}){await this.ensureInitialized();let{goal:n,prompt:r}=this.goalController.start(e,t);return this.emit(`goal_event`,{type:`goal_started`,goal:n}),this.persistCurrentSession(),this.scheduleGoalTurn(r,n),n}getGoalState(){return this.goalController.getState()}cancelGoal(){let e=this.goalController.cancel();return e&&(this.emit(`goal_event`,{type:`goal_stopped`,goal:e}),this.persistCurrentSession()),e}async setPlan(e,t=[]){await this.ensureInitialized();let n=this.getSessionOrThrow(),r=this.planController.start(e,t);return n.setPermissionMode(`plan`),this.emit(`plan_event`,{type:`plan_created`,plan:r}),this.persistCurrentSession(),r}getPlanState(){return this.planController.getState()}approvePlan(){let e=this.getSessionOrThrow();this.planController.getState()?.phase===`planning`&&this.planController.requestApproval();let t=this.planController.approve();return e.setPermissionMode(t.nextMode),this.emit(`plan_event`,{type:`plan_approved`,plan:t.plan}),this.persistCurrentSession(),t.plan}revertPlan(){let e=this.getSessionOrThrow(),t=this.planController.revert();return e.setPermissionMode(t.nextMode),this.emit(`plan_event`,{type:`plan_reverted`,plan:t.plan}),this.persistCurrentSession(),t.plan}scheduleGoalTurn(e,t){if(this.execCtrl.shuttingDown)return;let n=`goal:${t.id}:${t.iterations}`,r=`Goal: ${t.objective} (iteration ${t.iterations+1} of ${t.maxIterations})`;setTimeout(()=>this.requestWakeup(e,n,r),0)}handleGoalTurnComplete(e){if(!this.goalController.isActive()||this.currentTurnSource!==`agent-wakeup`)return;let t=this.goalController.onTurnComplete(e);t&&(this.persistCurrentSession(),t.action===`continue`?(this.emit(`goal_event`,{type:`goal_progress`,goal:t.goal}),this.scheduleGoalTurn(t.prompt,t.goal)):this.emit(`goal_event`,{type:`goal_stopped`,goal:t.goal}))}resumeGoalIfActive(){let e=this.goalController.getState();!e||e.status!==`active`||this.ensureInitialized().then(()=>{!this.goalController.isActive()||this.execCtrl.shuttingDown||this.scheduleGoalTurn(fs(e),e)}).catch(e=>this.reportBackgroundError(e instanceof Error?e:Error(String(e)),`goal-resume`))}async switchProvider(e){let t=this.getSessionOrThrow(),{settings:n,provider:r}=D_(e,this.providerDefinitions,this.userSettingsSources,this.providerEnvironment);if(this.setupRequired=!1,this.modelFallback===void 0){t.swapProvider(r,n.model);return}let{entries:i,options:a}=this.modelFallback,o=zd({provider:r,entries:i,settings:C_(this.userSettingsSources),primary:{profile:e,config:n},providerDefinitions:this.providerDefinitions,...this.providerEnvironment!==void 0&&{environment:this.providerEnvironment},...this.orgPolicy?.allowedProviders!==void 0&&{allowedProviders:this.orgPolicy.allowedProviders},providerOptions:a});for(let e of o.notices)this.histTracker.append(S(x(e)));t.swapProvider(o.provider,n.model)}async executeCommand(e,t,n=`user`,r,i){if(this.orgPolicy?.blockedCommands?.includes(e))return{message:jm(`Command /${e} is blocked by your organization policy.`,this.orgPolicy.adminContact),success:!1};if(e===`goal`&&ys(t)&&this.execCtrl.executing&&this.goalController.isActive()){let e=this.cancelGoal();return this.abort(),this.statusPush.push(),e?{message:`Goal cancelled: ${e.objective}`,success:!0}:{message:`No active goal to cancel.`,success:!1}}let a=e===`loop`&&Jb(t)&&this.execCtrl.executing?await this.skillRouter.executeCommand(e,t,n,r,i):await super.executeCommand(e,t,n,r,i);if(a===null)return null;if(a.data?.pluginRegistryReloaded===!0&&n!==`model`){this.pluginSkills=this.loadPluginSkills(),this.skillRouter.replacePluginSkills(this.pluginSkills);let e=this.skillRouter.commandExecutor.getSemanticRoles().skillActivation;this.rebuildLivePrompt({skills:e&&this.skillRouter.commandExecutor.isModelInvocable(e)?this.skillRouter.listSkills().filter(e=>e.modelInvocable).map(e=>({name:e.name,description:e.description})):[]})}let o=await Hm(a,{getAdapters:()=>this.getCommandHostAdapters(),invocationSource:n,orgPolicy:this.orgPolicy,switchProvider:e=>this.switchProvider(e),moveWorkspace:e=>this.moveWorkspace(e),applyOutputStyle:e=>this.applyOutputStyle(e),renameSession:e=>{this.setName(e),this.emit(`session_renamed`,{name:e})}});return Gm(o.uiIntents,Wm(n,r,this.execCtrl.activeDriverId),e=>this.emit(`ui_intent`,e)),this.statusPush.push(),o.result}},tS=class extends Error{code;name=`SessionChangeRefusal`;constructor(e,t){super(t),this.code=e}},nS=class extends Error{code;name=`SessionDeleteRefusal`;constructor(e,t){super(t),this.code=e}};async function rS(e,t,n=5e3){let r;await Promise.race([e.shutdown({reason:`other`,message:t}).catch(()=>void 0),new Promise(e=>{r=setTimeout(e,n)})]),r!==void 0&&clearTimeout(r)}var iS=class{currentSession;listeners=new Map;shutdownTimeoutMs;constructor(e,t={}){this.currentSession=e,this.shutdownTimeoutMs=t.shutdownTimeoutMs??5e3}get current(){return this.currentSession}moveTo(e){let t=this.swap(e);t!==void 0&&this.emitSwitched(t.sessionId)}async replace(e,t=`session switched`){let n=this.swap(e);n!==void 0&&(await rS(n.previous,t,this.shutdownTimeoutMs),this.emitSwitched(n.sessionId))}swap(e){let t=this.currentSession;if(e===t)return;let n=e.getSession().getSessionId();for(let[n,r]of this.listeners)for(let i of r)t.off(n,i),e.on(n,i);return this.currentSession=e,{previous:t,sessionId:n}}emitSwitched(e){for(let t of[...this.listeners.get(`session_switched`)??[]])t({sessionId:e})}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t),this.currentSession.on(e,t)}off(e,t){this.listeners.get(e)?.delete(t),this.currentSession.off(e,t)}get isInitialized(){return this.currentSession.isInitialized}shutdown=(...e)=>this.currentSession.shutdown(...e);submit=(...e)=>this.currentSession.submit(...e);abort=(...e)=>this.currentSession.abort(...e);cancelQueue=(...e)=>this.currentSession.cancelQueue(...e);setGoal=(...e)=>this.currentSession.setGoal(...e);getGoalState=(...e)=>this.currentSession.getGoalState(...e);cancelGoal=(...e)=>this.currentSession.cancelGoal(...e);isExecuting=(...e)=>this.currentSession.isExecuting(...e);getPendingPrompt=(...e)=>this.currentSession.getPendingPrompt(...e);getPendingCount=(...e)=>this.currentSession.getPendingCount(...e);getActiveDriverId=(...e)=>this.currentSession.getActiveDriverId(...e);getMessages=(...e)=>this.currentSession.getMessages(...e);getFullHistory=(...e)=>this.currentSession.getFullHistory(...e);getMessagesDisplay=(...e)=>this.currentSession.getMessagesDisplay(...e);getContextState=(...e)=>this.currentSession.getContextState(...e);getSession=(...e)=>this.currentSession.getSession(...e);getCwd=(...e)=>this.currentSession.getCwd(...e);executeCommand=(...e)=>this.currentSession.executeCommand(...e);listCommands=(...e)=>this.currentSession.listCommands(...e);listSkills=(...e)=>this.currentSession.listSkills(...e);getStatusSnapshot=(...e)=>this.currentSession.getStatusSnapshot(...e);listModels=(...e)=>this.currentSession.listModels(...e);listRuntimeTools=(...e)=>this.currentSession.listRuntimeTools(...e);invokeRuntimeTool=(...e)=>this.currentSession.invokeRuntimeTool(...e);resolvePermission=(...e)=>this.currentSession.resolvePermission(...e);resolveAsk=(...e)=>this.currentSession.resolveAsk(...e);listBackgroundTasks=(...e)=>this.currentSession.listBackgroundTasks(...e);getBackgroundTask=(...e)=>this.currentSession.getBackgroundTask(...e);cancelBackgroundTask=(...e)=>this.currentSession.cancelBackgroundTask(...e);closeBackgroundTask=(...e)=>this.currentSession.closeBackgroundTask(...e);sendBackgroundTask=(...e)=>this.currentSession.sendBackgroundTask(...e);readBackgroundTaskLog=(...e)=>this.currentSession.readBackgroundTaskLog(...e);listBackgroundJobGroups=(...e)=>this.currentSession.listBackgroundJobGroups(...e);getBackgroundJobGroup=(...e)=>this.currentSession.getBackgroundJobGroup(...e);createBackgroundJobGroup=(...e)=>this.currentSession.createBackgroundJobGroup(...e);waitBackgroundJobGroup=(...e)=>this.currentSession.waitBackgroundJobGroup(...e);getExecutionWorkspaceSnapshot=(...e)=>this.currentSession.getExecutionWorkspaceSnapshot(...e);readExecutionWorkspaceDetail=(...e)=>this.currentSession.readExecutionWorkspaceDetail(...e);stopWaitingSelfPacedLoop=(...e)=>this.currentSession.stopWaitingSelfPacedLoop(...e);listAgentDefinitions=(...e)=>this.currentSession.listAgentDefinitions(...e);getDefaultAgentType=(...e)=>this.currentSession.getDefaultAgentType(...e);setDefaultAgentType=(...e)=>this.currentSession.setDefaultAgentType(...e);listAgentJobs=(...e)=>this.currentSession.listAgentJobs(...e);spawnAgentJob=(...e)=>this.currentSession.spawnAgentJob(...e);sendAgentJob=(...e)=>this.currentSession.sendAgentJob(...e);cancelAgentJob=(...e)=>this.currentSession.cancelAgentJob(...e);closeAgentJob=(...e)=>this.currentSession.closeAgentJob(...e)};const aS=4,oS=3e5;function sS(e,t=Date.now()){return e.isExecuting()||e.getLocalActivityStatus?.()===`needs-input`||e.getPendingPrompt()!==null||e.getPendingCount()>0||e.listBackgroundTasks().some(e=>!Je(e.status))?!0:(e.listSelfPacedLoops?.()??[]).some(e=>e.phase!==`stopped`&&e.phase!==`expired`&&Date.parse(e.expiresAt)>t)}const cS=`This runtime is stopping.`;var lS=class{options;entries=new Set;primaryEntry;building=new Map;closing=new Map;leases=new WeakMap;maxLive;idleGraceMs;isBusy;shutdownSession;clock=0;freshBuilds=0;drained;constructor(e){this.options=e,this.maxLive=e.maxLive??4,this.idleGraceMs=e.idleGraceMs??3e5,this.isBusy=e.isBusy??(e=>sS(e)),this.shutdownSession=e.shutdown??((e,t)=>rS(e,t)),this.primaryEntry=this.register(e.primary,void 0,0,!0)}bind(e){let t=this.primaryEntry,n=!1,r=new iS(t.session);return this.join(t,e),{role:e,slot:r,moveTo:i=>{let a=this.leases.get(i);if(a===void 0||a.state!==`held`)throw Error(`SessionPool: the lease was already used or cancelled.`);if(n)throw i.cancel(),Error(`SessionPool: the binding was released.`);if(this.drained!==void 0)throw i.cancel(),new tS(`stopping`,cS);if(a.state=`moved`,--a.entry.holds,a.entry===t){this.touch(t);return}let o=t;t=a.entry,this.join(t,e),this.leave(o,e),r.moveTo(t.session)},isLastDriver:()=>!n&&e===`drive`&&t.drivers===1,release:()=>{n||(n=!0,this.leave(t,e))}}}async acquire(e){if(this.assertOpen(),e!==void 0){await this.namePrimary();for(let t=this.closing.get(e);t!==void 0;)await t,t=this.closing.get(e);this.assertOpen();let t=this.findLive(e);if(t!==void 0)return t.holds+=1,this.touch(t),this.lease(t);let n=this.building.get(e);if(n!==void 0)return n.waiters+=1,this.lease(await n.ready)}return this.makeRoom(),this.lease(await this.startBuild(e).ready)}listLive(){let e=[];for(let t of this.entries){let n=this.entryId(t);n!==void 0&&e.push({sessionId:n,session:t.session,clients:t.clients,drivers:t.drivers})}return e}shutdownAll(e=`runtime host stopped`){if(this.drained!==void 0)return this.drained;let t=[...this.closing.values()];for(let n of this.entries)this.clearGrace(n),t.push(this.shutdownQuietly(n.session,e));this.entries.clear();for(let n of this.building.values())n.abandoned=!0,t.push(this.shutdownQuietly(n.session,e));return this.building.clear(),this.drained=Promise.all(t).then(()=>void 0),this.drained}assertOpen(){if(this.drained!==void 0)throw new tS(`stopping`,cS)}register(e,t,n,r=!1){let i={id:t,session:e,primary:r,clients:0,drivers:0,holds:n,lastActive:this.clock+=1,grace:void 0};return this.entries.add(i),i}entryId(e){if(e.id!==void 0)return e.id;try{e.id=e.session.getSession().getSessionId()}catch{return}return e.id}async namePrimary(){this.entryId(this.primaryEntry)===void 0&&await uS(this.primaryEntry.session).catch(()=>void 0)}findLive(e){for(let t of this.entries)if(this.entryId(t)===e)return t}lease(e){let t={entry:e,state:`held`},n={session:e.session,cancel:()=>{t.state===`held`&&(t.state=`cancelled`,--e.holds,this.touch(e),this.settle(e))}};return this.leases.set(n,t),n}join(e,t){e.clients+=1,t===`drive`&&(e.drivers+=1),this.touch(e)}leave(e,t){--e.clients,t===`drive`&&--e.drivers,this.touch(e),this.settle(e)}touch(e){e.lastActive=this.clock+=1,this.clearGrace(e)}settle(e){if(e.primary||e.clients>0||e.holds>0||this.drained!==void 0||!this.entries.has(e))return;this.clearGrace(e);let t=setTimeout(()=>{if(e.grace=void 0,!(!this.entries.has(e)||e.clients>0||e.holds>0)){if(this.busy(e)){this.settle(e);return}this.close(e,`session idle with no client`)}},this.idleGraceMs);t.unref?.(),e.grace=t}clearGrace(e){e.grace!==void 0&&(clearTimeout(e.grace),e.grace=void 0)}busy(e){try{return this.isBusy(e.session)}catch{return!0}}makeRoom(){if(this.entries.size+this.building.size<this.maxLive)return;let e;for(let t of this.entries)t.primary||t.clients>0||t.holds>0||this.busy(t)||(e===void 0||t.lastActive<e.lastActive)&&(e=t);if(e===void 0)throw new tS(`limit`,`${this.maxLive} sessions are live, the most this runtime keeps, and none of them can be closed now: each has a client on it or work in progress.`);this.close(e,`session closed to make room for another`)}close(e,t){this.clearGrace(e),this.entries.delete(e),this.trackClosing(this.entryId(e),this.shutdownQuietly(e.session,t))}trackClosing(e,t){let n=e??`\0closing#${this.clock+=1}`,r=t.then(()=>{this.closing.get(n)===r&&this.closing.delete(n)});this.closing.set(n,r)}shutdownQuietly(e,t){return this.shutdownSession(e,t).catch(()=>void 0)}startBuild(e){let t;try{t=this.options.build(e)}catch(e){throw dS(e)}let n=e??`\0new#${this.freshBuilds+=1}`,r={key:n,session:t,waiters:1,abandoned:!1},i=Object.assign(r,{ready:this.finishBuild(r,e)});return this.building.set(n,i),i}async finishBuild(e,t){try{await uS(e.session)}catch(n){if(this.building.delete(e.key),e.abandoned)throw new tS(`stopping`,cS);let r=this.shutdownQuietly(e.session,`session failed to start`);throw this.trackClosing(t,r),await r,dS(n)}if(this.building.delete(e.key),e.abandoned)throw new tS(`stopping`,cS);return this.register(e.session,t,e.waiters)}};async function uS(e){let t=e.whenInitialized;typeof t==`function`&&await t.call(e)}function dS(e){return new tS(`start_failed`,`The session could not be started: ${e instanceof Error?e.message:String(e)}`)}function fS(e){if(`session`in e){if(!e.session)throw Error(`buildRuntimeSession: injected session is required`)}else{if(!e.provider)throw Error(`buildRuntimeSession: provider is required`);if(!e.cwd)throw Error(`buildRuntimeSession: cwd is required`)}return new eS(e)}async function pS(e){let t=e.session;if(e.pool!==void 0&&`session`in t)throw Error(`startRuntimeHost: a session pool builds sessions from a recipe, not an injected session`);let n=fS(t),r=new iS(n),i=e.pool===void 0?void 0:new lS({primary:n,build:e=>fS({...t,resumeSessionId:e,forkSession:void 0,sessionName:void 0}),...e.pool});e.transportRegistry&&(e.bindTransports?.(r),await e.transportRegistry.startAll());let a=!1;return{session:r,...i===void 0?{}:{pool:i},async waitForCompletion(){return await e.transportRegistry?.waitForCompletion()??[]},async waitForFailure(){return e.transportRegistry?.waitForFailure()},async shutdown(t=`runtime host stopped`){a||(a=!0,e.transportRegistry&&await e.transportRegistry.stopAll().catch(()=>void 0),i===void 0?await rS(r,t):await i.shutdownAll(t))}}}function mS(e){return/^\/\S/.test(e)}function hS(e){let t=e.slice(1).trim().split(/\s+/);return{name:t[0]??``,args:t.slice(1).filter(e=>e.length>0)}}function gS(e){if(!mS(e))return{type:`user-message`,text:e};let{name:t,args:n}=hS(e);return{type:`slash-command`,name:t,args:n}}function _S(e){return e.map(e=>({name:e.name,description:e.description}))}function vS(e,t){let n=e=>{t.write({type:`assistant-chunk`,chunk:e})},r=e=>{t.write({type:`assistant-done`,fullText:e.response}),t.setBusy(!1)},i=e=>{t.write({type:`tool-call`,id:e.executionId??e.toolName,name:e.toolName,args:e.firstArg})},a=e=>{t.write({type:`tool-result`,id:e.executionId??e.toolName,name:e.toolName,result:e.toolResultData??e.result})},o=e=>{t.setBusy(!1),t.write({type:`error`,error:e})},s=()=>{t.setBusy(!1)},c=({id:n,request:r})=>{Promise.resolve(t.askUser(r)).then(t=>e.resolveAsk(n,t)).catch(()=>e.resolveAsk(n,{type:`cancelled`}))};return e.on(`text_delta`,n),e.on(`complete`,r),e.on(`tool_start`,i),e.on(`tool_end`,a),e.on(`error`,o),e.on(`interrupted`,s),e.on(`ask_request`,c),()=>{e.off(`text_delta`,n),e.off(`complete`,r),e.off(`tool_start`,i),e.off(`tool_end`,a),e.off(`error`,o),e.off(`interrupted`,s),e.off(`ask_request`,c)}}function yS(e){let{provider:t,cwd:n,channel:r,commandModules:i,projectAccess:a,userSettingsSources:o,environment:s,sessionStore:c,permissionMode:l}=e,u={provider:t,cwd:n,projectAccess:a,...o===void 0?{}:{userSettingsSources:o},...s===void 0?{}:{environment:s},sessionStore:c,commandModules:i,permissionMode:l};return bS({channel:r,commandModules:i,projectAccess:a,userSettingsSources:o,sessionStore:c,permissionMode:l},()=>fS(u))}function bS(e,t){let{channel:n}=e,r=null,i=null;async function a(e){if(!r)return;let t=gS(e);if(t.type===`user-message`){n.write({type:`user-message`,text:e}),n.setBusy(!0),await r.submit(e);return}let{name:i,args:a}=t,o=await r.executeCommand(i,a.join(` `));o?n.write({type:`command-result`,name:i,output:o.message}):n.write({type:`error`,error:Error(`Unknown command "/${i}". Type /help for help.`)})}return{async start(){r=t(),i=vS(r,n);let e=r.listCommands();n.setAvailableCommands(_S(e)),n.onSubmit(a),await n.start()},async stop(){try{i?.(),await n.stop()}catch{}await r?.shutdown(),r=null}}}function xS(e){let t=new Map;for(let n of e){let e=SS(n);e&&t.set(e.id,e)}return[...t.values()]}function SS(e){switch(e.type){case`background_task_created`:case`background_task_started`:case`background_task_updated`:case`background_task_completed`:case`background_task_failed`:case`background_task_cancelled`:return e.task;default:return}}function CS(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function wS(e,t){let n=_c(e);if(n.namespace!==t)throw Error(`Workspace session persistence requires the ${t} state namespace.`);return n}function TS(e){return e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0}function ES(e){let t=ht(e);return t.status===`valid`?{status:`valid`,record:t.record}:t.status===`corrupt`?{status:`corrupt`,issues:t.issues}:{status:`unsupported`,schemaVersion:t.schemaVersion}}function DS(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=gt(t);return n.status===`valid`?{status:`valid`,record:n.record}:n.status===`unsupported`?{status:`unsupported`,schemaVersion:n.schemaVersion,...n.cwd===void 0?{}:{cwd:n.cwd}}:{status:`corrupt`,issues:n.issues,...n.cwd===void 0?{}:{cwd:n.cwd}}}var OS=class{sessions;logs;constructor(e,t){this.sessions=wS(e,`sessions`),this.logs=wS(t,`session-logs`),vc(this.sessions,this.logs)}save(e){pt(e.id),this.sessions.writeText(`${e.id}.json`,JSON.stringify({schemaVersion:ct,record:e},null,2),`persist project session record`)}load(e){pt(e);let t=this.sessions.readText(`${e}.json`,`load project session record`);return t===void 0?this.loadFromReplayLog(e):DS(t)}list(){let e=this.sessions.listDirectory(``,`list project session records`).filter(e=>e.kind===`file`&&e.name.endsWith(`.json`)).map(e=>e.name.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})),t=new Set(e.map(e=>e.id)),n=[...e];for(let e of this.listReplayLogIds())t.has(e)||n.push({id:e,outcome:this.outcomeForListedId(e)});return n.sort((e,t)=>TS(t)-TS(e))}outcomeForListedId(e){return _t(e)?this.load(e):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){pt(e),this.sessions.deleteFile(`${e}.json`,`delete project session record`)}loadFromReplayLog(e){try{let t=this.reconstructReplayLog(e);return t===void 0?{status:`missing`}:ES(t)}catch(e){if(!(e instanceof ut))throw e;return e.code===`UNSUPPORTED_VERSION`?{status:`unsupported`,schemaVersion:e.schemaVersion}:{status:`corrupt`,issues:e.issues}}}reconstructReplayLog(e){let t=yt(vt(new tl(this.logs,e)));if(!t.sessionId||t.messages.length===0)return;let n=t.backgroundTaskEvents,r=t.backgroundJobGroupEvents;return{id:t.sessionId,cwd:t.cwd??``,createdAt:t.createdAt??t.updatedAt??new Date(0).toISOString(),updatedAt:t.updatedAt??t.createdAt??new Date(0).toISOString(),messages:t.messages,history:t.history,backgroundTasks:xS(n),backgroundTaskEvents:n,backgroundJobGroups:CS(r),backgroundJobGroupEvents:r,skillActivationEvents:[],memoryEvents:t.memoryEvents}}listReplayLogIds(){return this.logs.listDirectory(``,`list project session logs`).filter(e=>e.kind===`file`&&e.name.endsWith(`.jsonl`)).map(e=>e.name.slice(0,-6))}};function kS(e={}){return new st(e)}function AS(e){return _t(e)}function jS(e,t){return new OS(e,t)}function MS(e,t){return new ot(e,t)}function NS(e){return new it(e,{ownedRoot:Re(e)})}function PS(e){return new ot(e,Re(e))}function FS(e,t){return(e?.list()??[]).flatMap(e=>e.outcome.status===`valid`?[e.outcome.record]:[]).filter(e=>e.cwd===t).sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime()).map(e=>{let t=US(e.messages);return{id:e.id,...e.name===void 0?{}:{name:e.name},cwd:e.cwd,updatedAt:e.updatedAt,messageCount:e.messages.length,preview:HS(e.messages),...t===void 0?{}:{title:t}}})}function IS(e){return(e?.list()??[]).filter(e=>e.outcome.status!==`valid`)}function LS(e,t){return IS(e).filter(e=>RS(e.outcome)===t).map(e=>({id:e.id}))}function RS(e){return e.status===`corrupt`||e.status===`unsupported`?e.cwd:void 0}function zS(e,t){return FS(e,t)[0]?.id}function BS(e,t,n={}){return FS(e,t).find(e=>e.messageCount===0&&e.id!==n.excludeSessionId&&(n.otherClientsOf?.(e.id)??0)<=0&&(n.isBusy?.(e.id)??!1)===!1)?.id}function VS(e,t){return(e?.list()??[]).find(e=>e.id===t||e.outcome.status===`valid`&&e.outcome.record.name===t)?.id}function HS(e){for(let t of[...e].reverse())if(t.role===`assistant`&&typeof t.content==`string`)return t.content.replace(/[\n\r]+/g,` `).trim();return``}function US(e){for(let t of e){if(t.role!==`user`||typeof t.content!=`string`)continue;let e=WS(t.content);if(e.length>0)return e}}function WS(e){let t=e.replace(/[#*_~`]/g,` `).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\s+/g,` `).trim();return t.length<=60?t:`${t.slice(0,60).trimEnd()}…`}function GS(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`TurnNotRunError`}var KS=class{host;options;constructor(e,t={}){this.host=e,this.options=t}async receive(e){let t={id:e.message.id,sequence:e.message.sequence},n=e=>({outcome:`refused`,ack:{...t,state:`refused`,reason:e}});if(!e.admission.admitted)return n(e.admission.reason??`the peer was not admitted`);if(this.options.requireSameEnvironment===!0&&!an(e.admission))return n(`this session requires a same-environment peer; admission established '${e.admission.trust}'. A token proves possession, which is copyable, and says nothing about where the peer runs.`);let r=e.admission.origin;if(r===void 0)return n(`the admission names no sender, so an answer would have nowhere to go`);if(e.message.origin.sessionId!==r.sessionId)return n(`the message names sender ${JSON.stringify(e.message.origin.sessionId)}, but ${JSON.stringify(r.sessionId)} was admitted`);let{workspaceRelation:i}=e.message.origin,a={sessionId:r.sessionId,...r.driverId===void 0?{}:{driverId:r.driverId},...i===void 0?{}:{workspaceRelation:i}},o;try{o=await new Promise((t,n)=>{this.host.submit(e.message.text,a,t).then(t,n)})}catch(e){return n(e instanceof Error?e.message:`the session refused the submission`)}return{outcome:`accepted`,ack:{...t,state:`pending`},settled:o.completed.then(()=>({...t,state:`acknowledged`}),e=>({...t,state:`refused`,reason:GS(e)?e.reason:`the turn failed`}))}}};export{Kb as $,Ir as $a,nc as $i,mg as $n,Sd as $r,Cv as $t,Vx as A,Ma as Aa,fl as Ai,S_ as An,tm as Ar,gy as At,fx as B,ma as Ba,Xc as Bi,Xg as Bn,Cf as Br,Uv as Bt,aS as C,no as Ca,ll as Ci,G_ as Cn,Em as Cr,Dy as Ct,tS as D,Ta as Da,cl as Di,P_ as Dn,ym as Dr,cy as Dt,iS as E,za as Ea,ol as Ei,N_ as En,bm as Er,ly as Et,Bx as F,Ca as Fa,_l as Fi,i_ as Fn,jp as Fr,zv as Ft,nx as G,Hi as Ga,Oc as Gi,Ag as Gn,kd as Gr,Gv as Gt,Sx as H,da as Ha,Mc as Hi,Ig as Hn,uf as Hr,Hv as Ht,wx as I,wa as Ia,nl as Ii,e_ as In,Ep as Ir,Iv as It,ux as J,Li as Ja,xc as Ji,Dg as Jn,jd as Jr,qv as Jt,ax as K,Gi as Ka,Ec as Ki,Og as Kn,zd as Kr,Xv as Kt,jx as L,xa as La,tl as Li,t_ as Ln,Pp as Lr,Rv as Lt,$x as M,Aa as Ma,vl as Mi,C_ as Mn,rm as Mr,Fv as Mt,Mx as N,Da as Na,dl as Ni,T_ as Nn,am as Nr,Pv as Nt,nS as O,Ea as Oa,ul as Oi,j_ as On,_m as Or,xy as Ot,Px as P,ja as Pa,hl as Pi,w_ as Pn,Kp as Pr,Nv as Pt,Jb as Q,si as Qa,W as Qi,dg as Qn,Ed as Qr,Sv as Qt,Ox as R,ba as Ra,Zc as Ri,n_ as Rn,hp as Rr,Bv as Rt,oS as S,lo as Sa,sl as Si,q_ as Sn,Tm as Sr,Oy as St,sS as T,Va as Ta,al as Ti,z_ as Tn,vm as Tr,Ay as Tt,bx as U,Ki as Ua,G as Ui,Pg as Un,Xd as Ur,Jv as Ut,Cx as V,fa as Va,Yc as Vi,jg as Vn,lf as Vr,Yv as Vt,vx as W,ea as Wa,Dc as Wi,Lg as Wn,Ad as Wr,Vv as Wt,dx as X,li as Xa,gc as Xi,gg as Xn,Rd as Xr,Mv as Xt,ox as Y,fi as Ya,_c as Yi,Z as Yn,Md as Yr,Kv as Yt,tx as Z,ci as Za,ac as Zi,_g as Zn,Nd as Zr,wv as Zt,mS as _,wo as _a,Su as _i,Y_ as _n,_n as _o,km as _r,Cy as _t,NS as a,ps as aa,hd as ai,av as an,Nr as ao,Hh as ar,eb as at,fS as b,go as ba,yu as bi,H_ as bn,wm as br,Ty as bt,FS as c,_s as ca,Hu as ci,ov as cn,Xn as co,Fm as cr,Ky as ct,zS as d,ds as da,Lu as di,rv as dn,Fn as do,zm as dr,Vy as dt,tc as ea,xd as ei,bv as en,L as eo,hg as er,Tb as et,BS as f,ss as fa,Iu as fi,V_ as fn,In as fo,Im as fr,By as ft,bS as g,Co as ga,vu as gi,J_ as gn,cn as go,Mm as gr,Iy as gt,yS as h,Uo as ha,xu as hi,Q_ as hn,fn as ho,jm as hr,Fy as ht,jS as i,R as ia,vd as ii,fv as in,Ar as io,Gh as ir,cb as it,Wx as j,Oa as ja,pl as ji,E_ as jn,im as jr,ey as jt,eS as k,ka,ml as ki,M_ as kn,hm as kr,py as kt,IS as l,ys as la,Fu as li,tv as ln,Un as lo,Pm as lr,Uy as lt,OS as m,Ho as ma,ju as mi,X_ as mn,Pn as mo,Rm as mr,Ly as mt,MS as n,Qs as na,wd as ni,mv as nn,jr as no,ug as nr,Eb as nt,PS as o,ms as oa,md as oi,iv as on,dr as oo,qm as or,$y as ot,VS as p,ls as pa,Ru as pi,B_ as pn,Ln as po,Lm as pr,zy as pt,ix as q,Wi as qa,Sc as qi,kg as qn,Vd as qr,Wv as qt,kS as r,Ns as ra,_d as ri,pv as rn,Pr as ro,pg as rr,rb as rt,AS as s,bs as sa,Uu as si,nv as sn,gr as so,Km as sr,Yy as st,KS as t,U as ta,yd as ti,yv as tn,Mr as to,fg as tr,Db as tt,LS as u,fs as ua,zu as ui,ev as un,Bn as uo,Nm as ur,Hy as ut,gS as v,yo as va,bu as vi,U_ as vn,sn as vo,Om as vr,Sy as vt,lS as w,Wa as wa,il as wi,K_ as wn,Sm as wr,ky as wt,pS as x,uo as xa,rl as xi,Z_ as xn,Dm as xr,Ey as xt,hS as y,bo as ya,Cu as yi,W_ as yn,Cm as yr,wy as yt,Ex as z,Sa as za,Kc as zi,$g as zn,Tf as zr,$v as zt};
|
|
131
|
-
//# sourceMappingURL=interactive-
|
|
131
|
+
//# sourceMappingURL=interactive-CoGijXC0.js.map
|