@robota-sdk/agent-framework 3.0.0-beta.66 → 3.0.0-beta.67

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.
@@ -91,12 +91,12 @@ Do not use emojis.`}function nt(){return`You are a worker subagent executing a s
91
91
  `),o=i.map(e=>e.content).join(`
92
92
 
93
93
  `),s=co(o),c=new oo(e).loadStartupMemory().content||void 0,l=Ya(e);return{agentsMd:a,claudeMd:o,memoryMd:c,taskContext:l.trim().length>0?l:void 0,compactInstructions:s,agentsFileEntries:r,claudeFileEntries:i}}var uo=class{settingsPath;fs;constructor(e,t=new M){this.settingsPath=e,this.fs=t}readAll(){if(!this.fs.existsSync(this.settingsPath))return{};try{let e=this.fs.readFileSync(this.settingsPath,`utf-8`),t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}writeAll(e){let t=(0,g.dirname)(this.settingsPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.settingsPath,JSON.stringify(e,null,2),`utf-8`)}getEnabledPlugins(){let e=this.readAll().enabledPlugins;return typeof e==`object`&&e?e:{}}setPluginEnabled(e,t){let n=this.readAll(),r=this.getEnabledPluginsFrom(n);r[e]=t,n.enabledPlugins=r,this.writeAll(n)}removePluginEntry(e){let t=this.readAll(),n=this.getEnabledPluginsFrom(t);delete n[e],t.enabledPlugins=n,this.writeAll(t)}getMarketplaceSources(){let e=this.readAll().extraKnownMarketplaces;return typeof e==`object`&&e?e:{}}setMarketplaceSource(e,t){let n=this.readAll(),r=this.getMarketplaceSourcesFrom(n);r[e]={source:t},n.extraKnownMarketplaces=r,this.writeAll(n)}removeMarketplaceSource(e){let t=this.readAll(),n=this.getMarketplaceSourcesFrom(t);delete n[e],t.extraKnownMarketplaces=n,this.writeAll(t)}getEnabledPluginsFrom(e){let t=e.enabledPlugins;return typeof t==`object`&&t?t:{}}getMarketplaceSourcesFrom(e){let t=e.extraKnownMarketplaces;return typeof t==`object`&&t?t:{}}};function fo(e){let t=e.trimStart();if(!t.startsWith(`---`))return{metadata:{},content:e};let n=t.indexOf(`---`,3);if(n===-1)return{metadata:{},content:e};let r=t.slice(3,n).trim(),i=t.slice(n+3).trimStart(),a={};for(let e of r.split(`
94
- `)){let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();typeof r==`string`&&r.startsWith(`[`)&&r.endsWith(`]`)&&(r=r.slice(1,-1).split(`,`).map(e=>e.trim()).filter(e=>e.length>0)),n&&(a[n]=r)}return{metadata:a,content:i}}function po(e){if(typeof e!=`object`||!e)return null;let t=e;if(typeof t.name!=`string`||typeof t.version!=`string`||typeof t.description!=`string`)return null;let n=typeof t.features==`object`&&t.features!==null?t.features:{};return{name:t.name,version:t.version,description:t.description,features:{commands:n.commands===!0?!0:void 0,agents:n.agents===!0?!0:void 0,skills:n.skills===!0?!0:void 0,hooks:n.hooks===!0?!0:void 0,mcp:n.mcp===!0?!0:void 0}}}function mo(e,t=new M){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}var ho=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new M){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){return this.discoverAndLoad()}async loadAll(){return this.discoverAndLoad()}discoverAndLoad(){let e=(0,g.join)(this.pluginsDir,`cache`);if(!this.fs.existsSync(e))return[];let t=[],n=mo(e,this.fs);for(let r of n){let n=(0,g.join)(e,r),i=mo(n,this.fs);for(let e of i){let i=(0,g.join)(n,e),a=mo(i,this.fs);if(a.length===0)continue;let o=a[a.length-1],s=(0,g.join)(i,o),c=(0,g.join)(s,`.claude-plugin`,`plugin.json`);if(!this.fs.existsSync(c))continue;let l=this.readManifest(c);if(!l)continue;let u=`${l.name}@${r}`;if(this.isDisabled(u,l.name))continue;let d=this.loadPlugin(s,l);t.push(d)}}return t}readManifest(e){let t=this.fs.readFileSync(e,`utf-8`);return po(JSON.parse(t))}isDisabled(e,t){return e in this.enabledPlugins?this.enabledPlugins[e]===!1:t in this.enabledPlugins?this.enabledPlugins[t]===!1:!1}loadPlugin(e,t){return{manifest:t,skills:this.loadSkills(e,t.name),commands:this.loadCommands(e,t.name),hooks:this.loadHooks(e),mcpConfig:this.loadMcpConfig(e),agents:this.loadAgents(e),pluginDir:e}}loadSkills(e,t){let n=(0,g.join)(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=(0,g.join)(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let{metadata:r,content:a}=fo(this.fs.readFileSync(t,`utf-8`)),o=typeof r.description==`string`?r.description:``,s={name:e.name,description:o,skillContent:a,...r};i.push(s)}return i}loadCommands(e,t){let n=(0,g.join)(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{metadata:r,content:a}=fo(this.fs.readFileSync((0,g.join)(n,e.name),`utf-8`)),o=typeof r.name==`string`?r.name:e.name.replace(/\.md$/,``),s=typeof r.description==`string`?r.description:``;i.push({...r,name:`${t}:${o}`,description:s,skillContent:a})}return i}loadHooks(e){let t=(0,g.join)(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:{}}loadMcpConfig(e){let t=(0,g.join)(e,`.mcp.json`);if(!this.fs.existsSync(t))return;let n=this.fs.readFileSync(t,`utf-8`);return JSON.parse(n)}loadAgents(e){let t=(0,g.join)(e,`agents`);return this.fs.existsSync(t)?this.fs.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.name.endsWith(`.md`)).map(e=>e.name.replace(/\.md$/,``)):[]}},go=class{pluginsDir;cacheDir;registryPath;settingsStore;marketplaceClient;exec;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.cacheDir=(0,g.join)(this.pluginsDir,`cache`),this.registryPath=(0,g.join)(this.pluginsDir,`installed_plugins.json`),this.settingsStore=e.settingsStore,this.marketplaceClient=e.marketplaceClient,this.exec=e.exec,this.fs=e.fs??new M}async install(e,t){let n=this.marketplaceClient.fetchManifest(t).plugins.find(t=>t.name===e);if(!n)throw Error(`Plugin "${e}" not found in marketplace "${t}"`);let r=this.resolveVersion(n,t),i=(0,g.join)(this.cacheDir,t,e,r);if(this.fs.existsSync(i))throw Error(`Plugin "${e}" version "${r}" is already installed from "${t}"`);this.resolveAndInstall(n.source,t,e,i);let a=`${e}@${t}`,o=this.readRegistry();o[a]={pluginName:e,marketplace:t,version:r,installPath:i,installedAt:new Date().toISOString()},this.writeRegistry(o)}async uninstall(e){let t=this.readRegistry(),n=t[e];if(!n)throw Error(`Plugin "${e}" is not installed`);this.fs.existsSync(n.installPath)&&this.fs.rmSync(n.installPath,{recursive:!0,force:!0}),delete t[e],this.writeRegistry(t),this.settingsStore.removePluginEntry(e)}async enable(e){this.settingsStore.setPluginEnabled(e,!0)}async disable(e){this.settingsStore.setPluginEnabled(e,!1)}getInstalledPlugins(){return this.readRegistry()}getPluginsByMarketplace(e){let t=this.readRegistry();return Object.values(t).filter(t=>t.marketplace===e)}resolveVersion(e,t){let n=e;return typeof n.version==`string`&&n.version?n.version:this.marketplaceClient.getMarketplaceSha(t)}normalizeSource(e){if(typeof e==`string`)return e;let t=e;return!t.type&&typeof t.source==`string`?{...t,type:t.source}:e}resolveAndInstall(e,t,n,r){this.fs.mkdirSync(r,{recursive:!0});let i=this.normalizeSource(e);try{if(typeof i==`string`){let e=(0,g.join)(this.marketplaceClient.getMarketplaceDir(t),i);if(!this.fs.existsSync(e))throw Error(`Plugin source path "${i}" not found in marketplace "${t}"`);this.fs.cpSync(e,r,{recursive:!0})}else if(i.type===`github`){let e=`https://github.com/${i.repo}.git`;this.cloneToDir(e,r,n)}else if(i.type===`url`&&typeof i.url==`string`&&i.url.endsWith(`.git`))this.cloneToDir(i.url,r,n);else if(i.type===`url`)throw Error(`URL source "${i.url}" is not a git repository (must end with .git)`);else throw Error(`Unknown source type: ${JSON.stringify(i)}`)}catch(e){throw this.fs.existsSync(r)&&this.fs.rmSync(r,{recursive:!0,force:!0}),e}}cloneToDir(e,t,n){this.fs.rmSync(t,{recursive:!0,force:!0});let r=`git clone --depth 1 ${e} ${t}`;try{this.exec(r,{timeout:6e4,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone plugin "${n}": ${t}`)}}readRegistry(){if(!this.fs.existsSync(this.registryPath))return{};try{let e=this.fs.readFileSync(this.registryPath,`utf-8`),t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}writeRegistry(e){let t=(0,g.dirname)(this.registryPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.registryPath,JSON.stringify(e,null,2),`utf-8`)}};function q(e,t=new M){if(!t.existsSync(e))return{};try{let n=t.readFileSync(e,`utf-8`),r=JSON.parse(n);return typeof r==`object`&&r?r:{}}catch{return{}}}function _o(e,t,n=new M){let r=(0,g.dirname)(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(e,JSON.stringify(t,null,2),`utf-8`)}function vo(e,t,n=new M){let r=(0,g.join)(e,`installed_plugins.json`);if(!n.existsSync(r))return;let i;try{let e=n.readFileSync(r,`utf-8`),t=JSON.parse(e);if(typeof t!=`object`||!t)return;i=t}catch{return}let a=!1;for(let[e,r]of Object.entries(i))r.marketplace===t&&(r.installPath&&n.existsSync(r.installPath)&&n.rmSync(r.installPath,{recursive:!0,force:!0}),delete i[e],a=!0);if(a){let e=(0,g.dirname)(r);n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.writeFileSync(r,JSON.stringify(i,null,2),`utf-8`)}}const yo=6e4;var bo=class{pluginsDir;exec;marketplacesDir;registryPath;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.exec=e.exec,this.marketplacesDir=(0,g.join)(this.pluginsDir,`marketplaces`),this.registryPath=(0,g.join)(this.pluginsDir,`known_marketplaces.json`),this.fs=e.fs??new M}addMarketplace(e){let t=`temp-`+Date.now().toString(36),n=(0,g.join)(this.marketplacesDir,t);if(this.fs.mkdirSync(this.marketplacesDir,{recursive:!0}),e.type===`local`){if(!this.fs.existsSync(e.path))throw Error(`Local marketplace path does not exist: ${e.path}`);this.fs.cpSync(e.path,n,{recursive:!0})}else{let t=`git clone --depth 1 ${this.resolveCloneUrl(e)} ${n}`;try{this.exec(t,{timeout:yo,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone marketplace: ${t}`)}}let r=(0,g.join)(n,`.claude-plugin`,`marketplace.json`);if(!this.fs.existsSync(r))throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(e.type===`local`?`Local directory does not contain .claude-plugin/marketplace.json`:`Cloned repository does not contain .claude-plugin/marketplace.json`);let i=this.readManifestFromPath(r).name;if(!i)throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace manifest does not contain a "name" field`);let a=q(this.registryPath,this.fs);if(a[i])throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace "${i}" already exists`);let o=(0,g.join)(this.marketplacesDir,i);return this.fs.renameSync(n,o),a[i]={source:e,installLocation:o,lastUpdated:new Date().toISOString()},_o(this.registryPath,a,this.fs),i}removeMarketplace(e){let t=q(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);vo(this.pluginsDir,e,this.fs),this.fs.existsSync(n.installLocation)&&this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),delete t[e],_o(this.registryPath,t,this.fs)}updateMarketplace(e){let t=q(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);if(!this.fs.existsSync(n.installLocation))throw Error(`Marketplace directory for "${e}" does not exist`);if(n.source.type===`local`){let e=n.source;if(!this.fs.existsSync(e.path))throw Error(`Local marketplace path does not exist: ${e.path}`);this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),this.fs.cpSync(e.path,n.installLocation,{recursive:!0})}else{let t=`git -C ${n.installLocation} pull`;try{this.exec(t,{timeout:yo,stdio:`pipe`})}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Failed to update marketplace "${e}": ${n}`)}}n.lastUpdated=new Date().toISOString(),_o(this.registryPath,t,this.fs)}listMarketplaces(){let e=q(this.registryPath,this.fs);return Object.entries(e).map(([e,t])=>({name:e,source:t.source,lastUpdated:t.lastUpdated}))}fetchManifest(e){let t=q(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);let n=(0,g.join)(t.installLocation,`.claude-plugin`,`marketplace.json`);if(!this.fs.existsSync(n))throw Error(`Marketplace "${e}" does not contain .claude-plugin/marketplace.json`);return this.readManifestFromPath(n)}getMarketplaceDir(e){let t=q(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);return t.installLocation}getMarketplaceSha(e){let t=this.getMarketplaceDir(e);try{return this.exec(`git -C ${t} rev-parse HEAD`,{timeout:yo,stdio:`pipe`}).toString().trim().slice(0,12)}catch{return`unknown`}}listAvailablePlugins(){let e=[],t=this.listMarketplaces();for(let{name:n}of t)try{let t=this.fetchManifest(n);for(let r of t.plugins)e.push({...r,marketplace:n})}catch{}return e}resolveCloneUrl(e){switch(e.type){case`github`:return`https://github.com/${e.repo}.git`;case`git`:return e.url;case`local`:throw Error(`Local source type does not use git cloning`);case`url`:throw Error(`URL marketplace source is not yet supported`)}}readManifestFromPath(e){let t=this.fs.readFileSync(e,`utf-8`),n=JSON.parse(t);if(typeof n!=`object`||!n)throw Error(`Invalid marketplace manifest: not an object`);if(typeof n.name!=`string`)throw Error(`Invalid marketplace manifest: missing "name" field`);return n}};function xo(e){let t=(0,g.join)((0,g.dirname)((0,g.dirname)(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function So(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 Co(e){let t={};for(let n of e){let e=n.hooks;if(!e)continue;let r=xo(n),i=e.hooks??e;for(let[e,a]of Object.entries(i)){if(!Array.isArray(a))continue;t[e]||(t[e]=[]);let i=a.map(e=>{let t=So(e,n.pluginDir);return t.env=r,t});t[e].push(...i)}}return t}function wo(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}async function To(e){let t=e.cwd,[n,r,i]=await Promise.all([e.config?Promise.resolve(e.config):Aa(t),e.bare?Promise.resolve({agentsMd:``,claudeMd:``,agentsFileEntries:[],claudeFileEntries:[]}):lo(t),e.bare?Promise.resolve({type:`unknown`,language:`unknown`}):jr(t)]),a=e.language?{...n,language:e.language}:n,o=new ho((0,g.join)((0,_.homedir)(),`.robota`,`plugins`));if(!e.bare)try{let e=o.loadPluginsSync();if(e.length>0){let t=Co(e);a={...a,hooks:wo(a.hooks,t)}}}catch{}let s=L(t);await Do(e)||await Eo(e,t);let c=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,{session:l,rebuildSystemMessage:u}=$i({config:a,cwd:t,context:r,projectInfo:i,permissionMode:e.permissionMode,maxTurns:e.maxTurns,terminal:Xn,sessionLogger:new f.FileSessionLogger(s.logs),permissionHandler:e.permissionHandler,provider:e.provider,onTextDelta:e.onTextDelta,onContextUpdate:e.onContextUpdate,onCompactEvent:e.onCompactEvent,onToolExecution:e.onToolExecution,sessionId:c,allowedTools:e.allowedTools,appendSystemPrompt:e.appendSystemPrompt,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,...e.commandModules?.some(e=>e.sessionRequirements?.includes(`agent-runtime`))?{enableAgentRuntime:!0}:{},...e.commandModules||e.commandDescriptors?{commandDescriptors:[...e.commandDescriptors??[],...e.commandModules?.flatMap(e=>e.commandDescriptors??[])??[]]}:{},modelCommandExecutor:e.modelCommandExecutor,isModelCommandInvocable:e.isModelCommandInvocable,editCheckpointRecorder:e.editCheckpointRecorder,reversibleExecution:e.reversibleExecution,sandboxClient:e.sandboxClient,agentName:e.agentName});return{session:l,agentsFileEntries:r.agentsFileEntries??[],claudeFileEntries:r.claudeFileEntries??[],rebuildSystemMessage:u}}async function Eo(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await(0,u.applyWorkspaceManifest)(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function Do(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}async function Oo(e,t){let n=e.config??await Aa(e.cwd),r=n.autoCompactThreshold===void 0?`default`:`settings`,i=new R({cwd:e.cwd});t.setEditCheckpointStore(i);let a=await To({cwd:e.cwd,provider:e.provider,config:n,permissionMode:e.permissionMode,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler,resumeSessionId:t.resumeSessionId,forkSession:e.forkSession,onTextDelta:t.onTextDelta,onContextUpdate:t.onContextUpdate,onCompactEvent:t.onCompactEvent,onToolExecution:t.onToolExecution,bare:e.bare,allowedTools:e.allowedTools,appendSystemPrompt:e.appendSystemPrompt,language:e.language,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,...e.commandModules?{commandModules:e.commandModules}:{},editCheckpointRecorder:i,...e.reversibleExecution?{reversibleExecution:e.reversibleExecution}:{},...e.sandboxClient?{sandboxClient:e.sandboxClient}:{},...e.workspaceManifest?{workspaceManifest:e.workspaceManifest}:{},...e.sandboxWorkspaceRoot?{sandboxWorkspaceRoot:e.sandboxWorkspaceRoot}:{},...t.sandboxSnapshotId?{sandboxSnapshotId:t.sandboxSnapshotId}:{},...e.agentName?{agentName:e.agentName}:{},commandDescriptors:t.commandDescriptors,...t.commandDescriptors.length>0?{modelCommandExecutor:t.executeModelCommand,isModelCommandInvocable:t.isModelCommandInvocable}:{}});if(t.pendingRestoreMessages)for(let e of t.pendingRestoreMessages)Mr(a.session,e);return{session:a.session,agentsFileEntries:a.agentsFileEntries,claudeFileEntries:a.claudeFileEntries,rebuildSystemMessage:a.rebuildSystemMessage,autoCompactThresholdSource:r}}function ko(e,t,n,r,i,a,o,s,c,l){try{let u=t.getSessionId(),d=e.load(u),f=l?.snapshotId??d?.sandboxSnapshotId;e.save(Ao({session:t,sessionId:u,sessionName:n??d?.name,cwd:r,history:i,createdAt:d?.createdAt,backgroundState:a,memoryState:o,skillActivationState:s,contextReferenceState:c,...f===void 0?{}:{sandboxSnapshotId:f}}))}catch{}}function Ao(e){return{id:e.sessionId,...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},...jo(e.backgroundState),...Mo(e.memoryState),...No(e.skillActivationState),...Po(e.contextReferenceState)}}function jo(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function Mo(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function No(e){return e?{skillActivationEvents:[...e.events]}:{}}function Po(e){return e?{contextReferences:[...e.references]}:{}}function Fo(e){return e.source===`skill`||e.source===`plugin`&&e.skillContent?`skill`:`builtin-command`}function Io(e){let t=e.source===`skill`||e.source===`plugin`&&!!e.skillContent;return{name:e.name,kind:Fo(e),description:e.description,userInvocable:e.userInvocable!==!1,modelInvocable:e.modelInvocable===!0||t&&e.disableModelInvocation!==!0,...e.argumentHint?{argumentHint:e.argumentHint}:{},...e.safety?{safety:e.safety}:{}}}var Lo=class{sources=[];addSource(e){this.sources.push(e)}replaceSource(e,t){this.sources=this.sources.filter(t=>t.name!==e),t!==void 0&&this.sources.push(t)}addModule(e){for(let t of e.commandSources??[])this.addSource(t)}getCommands(e){let t=[];for(let e of this.sources)t.push(...e.getCommands());if(!e)return t;let n=e.toLowerCase();return t.filter(e=>e.name.toLowerCase().startsWith(n))}resolveQualifiedName(e){let t=this.getCommands().filter(t=>t.source===`plugin`&&t.name.includes(`:`)&&t.name.endsWith(`:${e}`));return t.length===1?t[0].name:null}getSubcommands(e){let t=e.toLowerCase();for(let e of this.sources)for(let n of e.getCommands())if(n.name.toLowerCase()===t&&n.subcommands)return n.subcommands;return[]}getCapabilityDescriptors(){return this.getCommands().map(e=>Io(e))}},Ro=class{commands;constructor(e){this.commands=new Map;for(let t of e??zo())this.commands.set(t.name,t)}register(e){this.commands.set(e.name,e)}async execute(e,t,n){let r=this.getCommand(e);return r?await this.executeCommand(r,t,n):null}getCommand(e){return this.commands.get(e)}resolveRequiresPermission(e){return e.requiresPermission===void 0?e.safety!==`read-only`:e.requiresPermission}async executeCommand(e,t,n){return await e.execute(t,n)}listCommands(){return[...this.commands.values()]}listModelInvocableCommands(){return this.listCommands().filter(e=>e.modelInvocable===!0).map(e=>({name:e.name,kind:`builtin-command`,description:e.description,userInvocable:e.userInvocable!==!1,modelInvocable:!0,...e.argumentHint?{argumentHint:e.argumentHint}:{},...e.safety?{safety:e.safety}:{}}))}isModelInvocable(e){return this.commands.get(e)?.modelInvocable===!0}async executeModelInvocable(e,t,n){return this.isModelInvocable(e)?this.execute(e,t,n):null}hasCommand(e){return this.commands.has(e)}};function zo(){return[]}function Bo(e){return{name:e.name,description:e.description,source:`builtin`,...e.subcommands?{subcommands:[...e.subcommands]}:{},...e.argumentHint?{argumentHint:e.argumentHint}:{},...e.modelInvocable===void 0?{}:{modelInvocable:e.modelInvocable},...e.userInvocable===void 0?{}:{userInvocable:e.userInvocable},...e.safety?{safety:e.safety}:{}}}var Vo=class{name=`builtin`;commands;constructor(e=zo()){this.commands=e.map(Bo)}getCommands(){return this.commands}};function Ho(){let e=zo();return{name:`sdk-builtin`,commandSources:[new Vo(e)],systemCommands:e}}function Uo(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function Wo(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function Go(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 Ko(e,t,n={}){if(!t.type)throw Error(`Provider profile "${e}" is missing type`);if(!t.model)throw Error(`Provider profile "${e}" is missing model`);let r=(0,c.findProviderDefinition)(n.providerDefinitions??[],t.type),i=(0,c.getProviderCredentialRequirement)(r);if(i!==void 0&&!Zo(t,r?.defaults,i))throw Error(`Provider profile "${e}" is missing ${$o(i)}`)}function qo(e,t={}){let n=Jo(e,t);return Ko(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function Jo(e,t={}){let n=Xo(e.type,t.providerDefinitions??[]),r=e.apiKeyEnv===void 0?e.apiKey??n.apiKey:(0,c.formatEnvReference)(e.apiKeyEnv),i=e.baseURL??n.baseURL;return{type:e.type,model:e.model??n.model,...es(r)&&{apiKey:r},...i!==void 0&&{baseURL:i},...e.timeout!==void 0&&{timeout:e.timeout}}}function Yo(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=Uo(e,n,r);return t.currentProvider?Wo(i,t.currentProvider):i}function Xo(e,t){return(0,c.findProviderDefinition)(t,e)?.defaults??{}}function Zo(e,t,n){return n.anyOf.some(n=>(0,c.hasUsableSecretReference)(Qo(n,e,t)))}function Qo(e,t,n){return t[e]??n?.[e]}function $o(e){return e.anyOf.join(` or `)}function es(e){return e!==void 0&&e.length>0}async function ts(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{Ko(i,a,{providerDefinitions:r.providerDefinitions})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let o=await((a.type?(0,c.findProviderDefinition)(r.providerDefinitions,a.type):void 0)?.probeProfile??ns)(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 ns(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function rs(e,t=[]){return is(e,t)?`valid`:`incomplete`}function is(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return as(n?.type,n,t)}return!!(e.provider&&as(e.provider.name,e.provider,t))}function as(e,t,n){if(!t)return!1;if(!e)return(0,c.hasUsableSecretReference)(t.apiKey);let r=(0,c.findProviderDefinition)(n,e);if(r===void 0)return!1;let i=(0,c.getProviderCredentialRequirement)(r);return i===void 0?!0:os(t,r,i)}function os(e,t,n){return n.anyOf.some(n=>(0,c.hasUsableSecretReference)(ss(n,e,t)))}function ss(e,t,n){return t[e]??n.defaults?.[e]}function cs(e,t=[]){if(!(0,m.existsSync)(e))return`missing`;try{let n=(0,m.readFileSync)(e,`utf8`).trim();return n.length===0?`incomplete`:rs(JSON.parse(n),t)}catch{return`corrupt`}}function ls(e,t=new M){return e.reduce((e,n)=>{let r=us(n,t);return r===void 0?e:ds(e,r)},{})}function us(e,t){if(t.existsSync(e))try{let n=t.readFileSync(e,`utf8`);return JSON.parse(n)}catch{return}}function ds(e,t){return{...e,...t,provider:e.provider!==void 0||t.provider!==void 0?{...e.provider,...t.provider}:void 0,providers:e.providers!==void 0||t.providers!==void 0?fs(e.providers,t.providers):void 0}}function fs(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function ps(e,t,n){let r=t??e.currentProvider;if(r!==void 0){let t=e.providers?.[r];if(t===void 0)throw Error(`Provider profile "${r}" was not found in providers`);if(!t.type)throw Error(`Provider profile "${r}" is missing type`);return(0,l.normalizeProviderConfig)({name:t.type,model:t.model,apiKey:t.apiKey,baseURL:t.baseURL,timeout:t.timeout,options:t.options},n)}let i=e.provider;if(i?.name)return(0,l.normalizeProviderConfig)({name:i.name,model:i.model,apiKey:i.apiKey,baseURL:i.baseURL,timeout:i.timeout,options:i.options},n)}function ms(){return process.env.HOME??process.env.USERPROFILE??`/`}function hs(e){let t=ms();return[(0,g.join)(t,`.robota`,`settings.json`),(0,g.join)(t,`.claude`,`settings.json`),(0,g.join)(e,`.robota`,`settings.json`),(0,g.join)(e,`.robota`,`settings.local.json`),(0,g.join)(e,`.claude`,`settings.json`),(0,g.join)(e,`.claude`,`settings.local.json`)]}function gs(){return(0,g.join)(process.env.HOME??process.env.USERPROFILE??`/`,`.robota`,`settings.json`)}function _s(e,t){return t===void 0||t===`user`?gs():(0,g.join)(e,`.robota`,`settings.local.json`)}function J(e){if(!(0,m.existsSync)(e))return{};let t=(0,m.readFileSync)(e,`utf8`);try{return JSON.parse(t)}catch{return process.stderr.write(`Warning: corrupt settings file at ${e}, resetting to defaults\n`),{}}}function Y(e,t){(0,m.mkdirSync)((0,g.dirname)(e),{recursive:!0}),(0,m.writeFileSync)(e,JSON.stringify(t,null,2)+`
94
+ `)){let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();typeof r==`string`&&r.startsWith(`[`)&&r.endsWith(`]`)&&(r=r.slice(1,-1).split(`,`).map(e=>e.trim()).filter(e=>e.length>0)),n&&(a[n]=r)}return{metadata:a,content:i}}function po(e){if(typeof e!=`object`||!e)return null;let t=e;if(typeof t.name!=`string`||typeof t.version!=`string`||typeof t.description!=`string`)return null;let n=typeof t.features==`object`&&t.features!==null?t.features:{};return{name:t.name,version:t.version,description:t.description,features:{commands:n.commands===!0?!0:void 0,agents:n.agents===!0?!0:void 0,skills:n.skills===!0?!0:void 0,hooks:n.hooks===!0?!0:void 0,mcp:n.mcp===!0?!0:void 0}}}function mo(e,t=new M){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}var ho=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new M){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){return this.discoverAndLoad()}async loadAll(){return this.discoverAndLoad()}discoverAndLoad(){let e=(0,g.join)(this.pluginsDir,`cache`);if(!this.fs.existsSync(e))return[];let t=[],n=mo(e,this.fs);for(let r of n){let n=(0,g.join)(e,r),i=mo(n,this.fs);for(let e of i){let i=(0,g.join)(n,e),a=mo(i,this.fs);if(a.length===0)continue;let o=a[a.length-1],s=(0,g.join)(i,o),c=(0,g.join)(s,`.claude-plugin`,`plugin.json`);if(!this.fs.existsSync(c))continue;let l=this.readManifest(c);if(!l)continue;let u=`${l.name}@${r}`;if(this.isDisabled(u,l.name))continue;let d=this.loadPlugin(s,l);t.push(d)}}return t}readManifest(e){let t=this.fs.readFileSync(e,`utf-8`);return po(JSON.parse(t))}isDisabled(e,t){return e in this.enabledPlugins?this.enabledPlugins[e]===!1:t in this.enabledPlugins?this.enabledPlugins[t]===!1:!1}loadPlugin(e,t){return{manifest:t,skills:this.loadSkills(e,t.name),commands:this.loadCommands(e,t.name),hooks:this.loadHooks(e),mcpConfig:this.loadMcpConfig(e),agents:this.loadAgents(e),pluginDir:e}}loadSkills(e,t){let n=(0,g.join)(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=(0,g.join)(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let{metadata:r,content:a}=fo(this.fs.readFileSync(t,`utf-8`)),o=typeof r.description==`string`?r.description:``,s={name:e.name,description:o,skillContent:a,...r};i.push(s)}return i}loadCommands(e,t){let n=(0,g.join)(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{metadata:r,content:a}=fo(this.fs.readFileSync((0,g.join)(n,e.name),`utf-8`)),o=typeof r.name==`string`?r.name:e.name.replace(/\.md$/,``),s=typeof r.description==`string`?r.description:``;i.push({...r,name:`${t}:${o}`,description:s,skillContent:a})}return i}loadHooks(e){let t=(0,g.join)(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:{}}loadMcpConfig(e){let t=(0,g.join)(e,`.mcp.json`);if(!this.fs.existsSync(t))return;let n=this.fs.readFileSync(t,`utf-8`);return JSON.parse(n)}loadAgents(e){let t=(0,g.join)(e,`agents`);return this.fs.existsSync(t)?this.fs.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.name.endsWith(`.md`)).map(e=>e.name.replace(/\.md$/,``)):[]}},go=class{pluginsDir;cacheDir;registryPath;settingsStore;marketplaceClient;exec;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.cacheDir=(0,g.join)(this.pluginsDir,`cache`),this.registryPath=(0,g.join)(this.pluginsDir,`installed_plugins.json`),this.settingsStore=e.settingsStore,this.marketplaceClient=e.marketplaceClient,this.exec=e.exec,this.fs=e.fs??new M}async install(e,t){let n=this.marketplaceClient.fetchManifest(t).plugins.find(t=>t.name===e);if(!n)throw Error(`Plugin "${e}" not found in marketplace "${t}"`);let r=this.resolveVersion(n,t),i=(0,g.join)(this.cacheDir,t,e,r);if(this.fs.existsSync(i))throw Error(`Plugin "${e}" version "${r}" is already installed from "${t}"`);this.resolveAndInstall(n.source,t,e,i);let a=`${e}@${t}`,o=this.readRegistry();o[a]={pluginName:e,marketplace:t,version:r,installPath:i,installedAt:new Date().toISOString()},this.writeRegistry(o)}async uninstall(e){let t=this.readRegistry(),n=t[e];if(!n)throw Error(`Plugin "${e}" is not installed`);this.fs.existsSync(n.installPath)&&this.fs.rmSync(n.installPath,{recursive:!0,force:!0}),delete t[e],this.writeRegistry(t),this.settingsStore.removePluginEntry(e)}async enable(e){this.settingsStore.setPluginEnabled(e,!0)}async disable(e){this.settingsStore.setPluginEnabled(e,!1)}getInstalledPlugins(){return this.readRegistry()}getPluginsByMarketplace(e){let t=this.readRegistry();return Object.values(t).filter(t=>t.marketplace===e)}resolveVersion(e,t){let n=e;return typeof n.version==`string`&&n.version?n.version:this.marketplaceClient.getMarketplaceSha(t)}normalizeSource(e){if(typeof e==`string`)return e;let t=e;return!t.type&&typeof t.source==`string`?{...t,type:t.source}:e}resolveAndInstall(e,t,n,r){this.fs.mkdirSync(r,{recursive:!0});let i=this.normalizeSource(e);try{if(typeof i==`string`){let e=(0,g.join)(this.marketplaceClient.getMarketplaceDir(t),i);if(!this.fs.existsSync(e))throw Error(`Plugin source path "${i}" not found in marketplace "${t}"`);this.fs.cpSync(e,r,{recursive:!0})}else if(i.type===`github`){let e=`https://github.com/${i.repo}.git`;this.cloneToDir(e,r,n)}else if(i.type===`url`&&typeof i.url==`string`&&i.url.endsWith(`.git`))this.cloneToDir(i.url,r,n);else if(i.type===`url`)throw Error(`URL source "${i.url}" is not a git repository (must end with .git)`);else throw Error(`Unknown source type: ${JSON.stringify(i)}`)}catch(e){throw this.fs.existsSync(r)&&this.fs.rmSync(r,{recursive:!0,force:!0}),e}}cloneToDir(e,t,n){this.fs.rmSync(t,{recursive:!0,force:!0});let r=`git clone --depth 1 ${e} ${t}`;try{this.exec(r,{timeout:6e4,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone plugin "${n}": ${t}`)}}readRegistry(){if(!this.fs.existsSync(this.registryPath))return{};try{let e=this.fs.readFileSync(this.registryPath,`utf-8`),t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}writeRegistry(e){let t=(0,g.dirname)(this.registryPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.registryPath,JSON.stringify(e,null,2),`utf-8`)}};function q(e,t=new M){if(!t.existsSync(e))return{};try{let n=t.readFileSync(e,`utf-8`),r=JSON.parse(n);return typeof r==`object`&&r?r:{}}catch{return{}}}function _o(e,t,n=new M){let r=(0,g.dirname)(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(e,JSON.stringify(t,null,2),`utf-8`)}function vo(e,t,n=new M){let r=(0,g.join)(e,`installed_plugins.json`);if(!n.existsSync(r))return;let i;try{let e=n.readFileSync(r,`utf-8`),t=JSON.parse(e);if(typeof t!=`object`||!t)return;i=t}catch{return}let a=!1;for(let[e,r]of Object.entries(i))r.marketplace===t&&(r.installPath&&n.existsSync(r.installPath)&&n.rmSync(r.installPath,{recursive:!0,force:!0}),delete i[e],a=!0);if(a){let e=(0,g.dirname)(r);n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.writeFileSync(r,JSON.stringify(i,null,2),`utf-8`)}}const yo=6e4;var bo=class{pluginsDir;exec;marketplacesDir;registryPath;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.exec=e.exec,this.marketplacesDir=(0,g.join)(this.pluginsDir,`marketplaces`),this.registryPath=(0,g.join)(this.pluginsDir,`known_marketplaces.json`),this.fs=e.fs??new M}addMarketplace(e){let t=`temp-`+Date.now().toString(36),n=(0,g.join)(this.marketplacesDir,t);if(this.fs.mkdirSync(this.marketplacesDir,{recursive:!0}),e.type===`local`){if(!this.fs.existsSync(e.path))throw Error(`Local marketplace path does not exist: ${e.path}`);this.fs.cpSync(e.path,n,{recursive:!0})}else{let t=`git clone --depth 1 ${this.resolveCloneUrl(e)} ${n}`;try{this.exec(t,{timeout:yo,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone marketplace: ${t}`)}}let r=(0,g.join)(n,`.claude-plugin`,`marketplace.json`);if(!this.fs.existsSync(r))throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(e.type===`local`?`Local directory does not contain .claude-plugin/marketplace.json`:`Cloned repository does not contain .claude-plugin/marketplace.json`);let i=this.readManifestFromPath(r).name;if(!i)throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace manifest does not contain a "name" field`);let a=q(this.registryPath,this.fs);if(a[i])throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace "${i}" already exists`);let o=(0,g.join)(this.marketplacesDir,i);return this.fs.renameSync(n,o),a[i]={source:e,installLocation:o,lastUpdated:new Date().toISOString()},_o(this.registryPath,a,this.fs),i}removeMarketplace(e){let t=q(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);vo(this.pluginsDir,e,this.fs),this.fs.existsSync(n.installLocation)&&this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),delete t[e],_o(this.registryPath,t,this.fs)}updateMarketplace(e){let t=q(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);if(!this.fs.existsSync(n.installLocation))throw Error(`Marketplace directory for "${e}" does not exist`);if(n.source.type===`local`){let e=n.source;if(!this.fs.existsSync(e.path))throw Error(`Local marketplace path does not exist: ${e.path}`);this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),this.fs.cpSync(e.path,n.installLocation,{recursive:!0})}else{let t=`git -C ${n.installLocation} pull`;try{this.exec(t,{timeout:yo,stdio:`pipe`})}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Failed to update marketplace "${e}": ${n}`)}}n.lastUpdated=new Date().toISOString(),_o(this.registryPath,t,this.fs)}listMarketplaces(){let e=q(this.registryPath,this.fs);return Object.entries(e).map(([e,t])=>({name:e,source:t.source,lastUpdated:t.lastUpdated}))}fetchManifest(e){let t=q(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);let n=(0,g.join)(t.installLocation,`.claude-plugin`,`marketplace.json`);if(!this.fs.existsSync(n))throw Error(`Marketplace "${e}" does not contain .claude-plugin/marketplace.json`);return this.readManifestFromPath(n)}getMarketplaceDir(e){let t=q(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);return t.installLocation}getMarketplaceSha(e){let t=this.getMarketplaceDir(e);try{return this.exec(`git -C ${t} rev-parse HEAD`,{timeout:yo,stdio:`pipe`}).toString().trim().slice(0,12)}catch{return`unknown`}}listAvailablePlugins(){let e=[],t=this.listMarketplaces();for(let{name:n}of t)try{let t=this.fetchManifest(n);for(let r of t.plugins)e.push({...r,marketplace:n})}catch{}return e}resolveCloneUrl(e){switch(e.type){case`github`:return`https://github.com/${e.repo}.git`;case`git`:return e.url;case`local`:throw Error(`Local source type does not use git cloning`);case`url`:throw Error(`URL marketplace source is not yet supported`)}}readManifestFromPath(e){let t=this.fs.readFileSync(e,`utf-8`),n=JSON.parse(t);if(typeof n!=`object`||!n)throw Error(`Invalid marketplace manifest: not an object`);if(typeof n.name!=`string`)throw Error(`Invalid marketplace manifest: missing "name" field`);return n}};function xo(e){let t=(0,g.join)((0,g.dirname)((0,g.dirname)(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function So(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 Co(e){let t={};for(let n of e){let e=n.hooks;if(!e)continue;let r=xo(n),i=e.hooks??e;for(let[e,a]of Object.entries(i)){if(!Array.isArray(a))continue;t[e]||(t[e]=[]);let i=a.map(e=>{let t=So(e,n.pluginDir);return t.env=r,t});t[e].push(...i)}}return t}function wo(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}async function To(e){let t=e.cwd,[n,r,i]=await Promise.all([e.config?Promise.resolve(e.config):Aa(t),e.bare?Promise.resolve({agentsMd:``,claudeMd:``,agentsFileEntries:[],claudeFileEntries:[]}):lo(t),e.bare?Promise.resolve({type:`unknown`,language:`unknown`}):jr(t)]),a=e.language?{...n,language:e.language}:n,o=new ho((0,g.join)((0,_.homedir)(),`.robota`,`plugins`));if(!e.bare)try{let e=o.loadPluginsSync();if(e.length>0){let t=Co(e);a={...a,hooks:wo(a.hooks,t)}}}catch{}let s=L(t);await Do(e)||await Eo(e,t);let c=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,{session:l,rebuildSystemMessage:u}=$i({config:a,cwd:t,context:r,projectInfo:i,permissionMode:e.permissionMode,maxTurns:e.maxTurns,terminal:Xn,sessionLogger:new f.FileSessionLogger(s.logs),permissionHandler:e.permissionHandler,provider:e.provider,onTextDelta:e.onTextDelta,onContextUpdate:e.onContextUpdate,onCompactEvent:e.onCompactEvent,onToolExecution:e.onToolExecution,sessionId:c,allowedTools:e.allowedTools,appendSystemPrompt:e.appendSystemPrompt,...e.systemPrompt?{systemPromptBuilder:()=>e.systemPrompt}:{},backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,...e.commandModules?.some(e=>e.sessionRequirements?.includes(`agent-runtime`))?{enableAgentRuntime:!0}:{},...e.commandModules||e.commandDescriptors?{commandDescriptors:[...e.commandDescriptors??[],...e.commandModules?.flatMap(e=>e.commandDescriptors??[])??[]]}:{},modelCommandExecutor:e.modelCommandExecutor,isModelCommandInvocable:e.isModelCommandInvocable,editCheckpointRecorder:e.editCheckpointRecorder,reversibleExecution:e.reversibleExecution,sandboxClient:e.sandboxClient,agentName:e.agentName});return{session:l,agentsFileEntries:r.agentsFileEntries??[],claudeFileEntries:r.claudeFileEntries??[],rebuildSystemMessage:u}}async function Eo(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await(0,u.applyWorkspaceManifest)(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function Do(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}async function Oo(e,t){let n=e.config??await Aa(e.cwd),r=n.autoCompactThreshold===void 0?`default`:`settings`,i=new R({cwd:e.cwd});t.setEditCheckpointStore(i);let a=await To({cwd:e.cwd,provider:e.provider,config:n,permissionMode:e.permissionMode,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler,resumeSessionId:t.resumeSessionId,forkSession:e.forkSession,onTextDelta:t.onTextDelta,onContextUpdate:t.onContextUpdate,onCompactEvent:t.onCompactEvent,onToolExecution:t.onToolExecution,bare:e.bare,allowedTools:e.allowedTools,appendSystemPrompt:e.appendSystemPrompt,...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},language:e.language,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,...e.commandModules?{commandModules:e.commandModules}:{},editCheckpointRecorder:i,...e.reversibleExecution?{reversibleExecution:e.reversibleExecution}:{},...e.sandboxClient?{sandboxClient:e.sandboxClient}:{},...e.workspaceManifest?{workspaceManifest:e.workspaceManifest}:{},...e.sandboxWorkspaceRoot?{sandboxWorkspaceRoot:e.sandboxWorkspaceRoot}:{},...t.sandboxSnapshotId?{sandboxSnapshotId:t.sandboxSnapshotId}:{},...e.agentName?{agentName:e.agentName}:{},commandDescriptors:t.commandDescriptors,...t.commandDescriptors.length>0?{modelCommandExecutor:t.executeModelCommand,isModelCommandInvocable:t.isModelCommandInvocable}:{}});if(t.pendingRestoreMessages)for(let e of t.pendingRestoreMessages)Mr(a.session,e);return{session:a.session,agentsFileEntries:a.agentsFileEntries,claudeFileEntries:a.claudeFileEntries,rebuildSystemMessage:a.rebuildSystemMessage,autoCompactThresholdSource:r}}function ko(e,t,n,r,i,a,o,s,c,l){try{let u=t.getSessionId(),d=e.load(u),f=l?.snapshotId??d?.sandboxSnapshotId;e.save(Ao({session:t,sessionId:u,sessionName:n??d?.name,cwd:r,history:i,createdAt:d?.createdAt,backgroundState:a,memoryState:o,skillActivationState:s,contextReferenceState:c,...f===void 0?{}:{sandboxSnapshotId:f}}))}catch{}}function Ao(e){return{id:e.sessionId,...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},...jo(e.backgroundState),...Mo(e.memoryState),...No(e.skillActivationState),...Po(e.contextReferenceState)}}function jo(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function Mo(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function No(e){return e?{skillActivationEvents:[...e.events]}:{}}function Po(e){return e?{contextReferences:[...e.references]}:{}}function Fo(e){return e.source===`skill`||e.source===`plugin`&&e.skillContent?`skill`:`builtin-command`}function Io(e){let t=e.source===`skill`||e.source===`plugin`&&!!e.skillContent;return{name:e.name,kind:Fo(e),description:e.description,userInvocable:e.userInvocable!==!1,modelInvocable:e.modelInvocable===!0||t&&e.disableModelInvocation!==!0,...e.argumentHint?{argumentHint:e.argumentHint}:{},...e.safety?{safety:e.safety}:{}}}var Lo=class{sources=[];addSource(e){this.sources.push(e)}replaceSource(e,t){this.sources=this.sources.filter(t=>t.name!==e),t!==void 0&&this.sources.push(t)}addModule(e){for(let t of e.commandSources??[])this.addSource(t)}getCommands(e){let t=[];for(let e of this.sources)t.push(...e.getCommands());if(!e)return t;let n=e.toLowerCase();return t.filter(e=>e.name.toLowerCase().startsWith(n))}resolveQualifiedName(e){let t=this.getCommands().filter(t=>t.source===`plugin`&&t.name.includes(`:`)&&t.name.endsWith(`:${e}`));return t.length===1?t[0].name:null}getSubcommands(e){let t=e.toLowerCase();for(let e of this.sources)for(let n of e.getCommands())if(n.name.toLowerCase()===t&&n.subcommands)return n.subcommands;return[]}getCapabilityDescriptors(){return this.getCommands().map(e=>Io(e))}},Ro=class{commands;constructor(e){this.commands=new Map;for(let t of e??zo())this.commands.set(t.name,t)}register(e){this.commands.set(e.name,e)}async execute(e,t,n){let r=this.getCommand(e);return r?await this.executeCommand(r,t,n):null}getCommand(e){return this.commands.get(e)}resolveRequiresPermission(e){return e.requiresPermission===void 0?e.safety!==`read-only`:e.requiresPermission}async executeCommand(e,t,n){return await e.execute(t,n)}listCommands(){return[...this.commands.values()]}listModelInvocableCommands(){return this.listCommands().filter(e=>e.modelInvocable===!0).map(e=>({name:e.name,kind:`builtin-command`,description:e.description,userInvocable:e.userInvocable!==!1,modelInvocable:!0,...e.argumentHint?{argumentHint:e.argumentHint}:{},...e.safety?{safety:e.safety}:{}}))}isModelInvocable(e){return this.commands.get(e)?.modelInvocable===!0}async executeModelInvocable(e,t,n){return this.isModelInvocable(e)?this.execute(e,t,n):null}hasCommand(e){return this.commands.has(e)}};function zo(){return[]}function Bo(e){return{name:e.name,description:e.description,source:`builtin`,...e.subcommands?{subcommands:[...e.subcommands]}:{},...e.argumentHint?{argumentHint:e.argumentHint}:{},...e.modelInvocable===void 0?{}:{modelInvocable:e.modelInvocable},...e.userInvocable===void 0?{}:{userInvocable:e.userInvocable},...e.safety?{safety:e.safety}:{}}}var Vo=class{name=`builtin`;commands;constructor(e=zo()){this.commands=e.map(Bo)}getCommands(){return this.commands}};function Ho(){let e=zo();return{name:`sdk-builtin`,commandSources:[new Vo(e)],systemCommands:e}}function Uo(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function Wo(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function Go(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 Ko(e,t,n={}){if(!t.type)throw Error(`Provider profile "${e}" is missing type`);if(!t.model)throw Error(`Provider profile "${e}" is missing model`);let r=(0,c.findProviderDefinition)(n.providerDefinitions??[],t.type),i=(0,c.getProviderCredentialRequirement)(r);if(i!==void 0&&!Zo(t,r?.defaults,i))throw Error(`Provider profile "${e}" is missing ${$o(i)}`)}function qo(e,t={}){let n=Jo(e,t);return Ko(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function Jo(e,t={}){let n=Xo(e.type,t.providerDefinitions??[]),r=e.apiKeyEnv===void 0?e.apiKey??n.apiKey:(0,c.formatEnvReference)(e.apiKeyEnv),i=e.baseURL??n.baseURL;return{type:e.type,model:e.model??n.model,...es(r)&&{apiKey:r},...i!==void 0&&{baseURL:i},...e.timeout!==void 0&&{timeout:e.timeout}}}function Yo(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=Uo(e,n,r);return t.currentProvider?Wo(i,t.currentProvider):i}function Xo(e,t){return(0,c.findProviderDefinition)(t,e)?.defaults??{}}function Zo(e,t,n){return n.anyOf.some(n=>(0,c.hasUsableSecretReference)(Qo(n,e,t)))}function Qo(e,t,n){return t[e]??n?.[e]}function $o(e){return e.anyOf.join(` or `)}function es(e){return e!==void 0&&e.length>0}async function ts(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{Ko(i,a,{providerDefinitions:r.providerDefinitions})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let o=await((a.type?(0,c.findProviderDefinition)(r.providerDefinitions,a.type):void 0)?.probeProfile??ns)(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 ns(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function rs(e,t=[]){return is(e,t)?`valid`:`incomplete`}function is(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return as(n?.type,n,t)}return!!(e.provider&&as(e.provider.name,e.provider,t))}function as(e,t,n){if(!t)return!1;if(!e)return(0,c.hasUsableSecretReference)(t.apiKey);let r=(0,c.findProviderDefinition)(n,e);if(r===void 0)return!1;let i=(0,c.getProviderCredentialRequirement)(r);return i===void 0?!0:os(t,r,i)}function os(e,t,n){return n.anyOf.some(n=>(0,c.hasUsableSecretReference)(ss(n,e,t)))}function ss(e,t,n){return t[e]??n.defaults?.[e]}function cs(e,t=[]){if(!(0,m.existsSync)(e))return`missing`;try{let n=(0,m.readFileSync)(e,`utf8`).trim();return n.length===0?`incomplete`:rs(JSON.parse(n),t)}catch{return`corrupt`}}function ls(e,t=new M){return e.reduce((e,n)=>{let r=us(n,t);return r===void 0?e:ds(e,r)},{})}function us(e,t){if(t.existsSync(e))try{let n=t.readFileSync(e,`utf8`);return JSON.parse(n)}catch{return}}function ds(e,t){return{...e,...t,provider:e.provider!==void 0||t.provider!==void 0?{...e.provider,...t.provider}:void 0,providers:e.providers!==void 0||t.providers!==void 0?fs(e.providers,t.providers):void 0}}function fs(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function ps(e,t,n){let r=t??e.currentProvider;if(r!==void 0){let t=e.providers?.[r];if(t===void 0)throw Error(`Provider profile "${r}" was not found in providers`);if(!t.type)throw Error(`Provider profile "${r}" is missing type`);return(0,l.normalizeProviderConfig)({name:t.type,model:t.model,apiKey:t.apiKey,baseURL:t.baseURL,timeout:t.timeout,options:t.options},n)}let i=e.provider;if(i?.name)return(0,l.normalizeProviderConfig)({name:i.name,model:i.model,apiKey:i.apiKey,baseURL:i.baseURL,timeout:i.timeout,options:i.options},n)}function ms(){return process.env.HOME??process.env.USERPROFILE??`/`}function hs(e){let t=ms();return[(0,g.join)(t,`.robota`,`settings.json`),(0,g.join)(t,`.claude`,`settings.json`),(0,g.join)(e,`.robota`,`settings.json`),(0,g.join)(e,`.robota`,`settings.local.json`),(0,g.join)(e,`.claude`,`settings.json`),(0,g.join)(e,`.claude`,`settings.local.json`)]}function gs(){return(0,g.join)(process.env.HOME??process.env.USERPROFILE??`/`,`.robota`,`settings.json`)}function _s(e,t){return t===void 0||t===`user`?gs():(0,g.join)(e,`.robota`,`settings.local.json`)}function J(e){if(!(0,m.existsSync)(e))return{};let t=(0,m.readFileSync)(e,`utf8`);try{return JSON.parse(t)}catch{return process.stderr.write(`Warning: corrupt settings file at ${e}, resetting to defaults\n`),{}}}function Y(e,t){(0,m.mkdirSync)((0,g.dirname)(e),{recursive:!0}),(0,m.writeFileSync)(e,JSON.stringify(t,null,2)+`
95
95
  `,`utf8`)}function vs(e,t){let n=J(e),r=n.currentProvider,i=n.providers;if(typeof r==`string`&&ys(i)){let e=i;e[r]={...ys(e[r])?e[r]:{},model:t},n.providers=e}else n.provider={...ys(n.provider)?n.provider:{},model:t};Y(e,n)}function ys(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function bs(e){return(0,m.existsSync)(e)?((0,m.unlinkSync)(e),!0):!1}function xs(e,t={}){let n=t.settingsPaths??hs(e),r=Ds(n)??n[0];if(r===void 0)throw Error(`No settings path available for provider update`);return r}function X(e){return J(e)}function Ss(e,t,n={}){let r=Yo(X(e),qo(t,n));return Y(e,r),r}function Cs(e,t,n={}){let r=X(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:Wo(r,t);return Y(e,o),o}function ws(e,t,n={}){let r=n.settingsPaths??hs(e),i=ls(r),a=n.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Ts(r,a,t)}function Ts(e,t,n){let r=Es(e,t)??e[0];if(r===void 0)throw Error(`No settings path available for model update`);let i=X(r),a=i.providers??{},o=a[t]??{},s={...i,providers:{...a,[t]:{...o,model:n}}};return Y(r,s),{settingsPath:r,settings:s,profileName:t}}function Es(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&X(r).providers?.[t]!==void 0)return r}}function Ds(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&X(n).currentProvider!==void 0)return n}}function Os(e){return ls(hs(e))}function ks(e,t={}){let n=ps(Os(e),t.providerOverride,t.providerDefinitions??[]);if(n!==void 0)return n;throw Error("No provider configuration found. Run `robota` to set up.")}function As(e,t,n={}){let r=n.providerDefinitions??[],i=ks(e,{...n,providerDefinitions:r}),a=t??i.model;return(0,l.createProviderFromConfig)({...i,model:a},r)}var js=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,pluginDir:t.pluginDir})}for(let n of t.commands)e.push({name:n.name,description:n.description,source:`plugin`,skillContent:n.skillContent,pluginDir:t.pluginDir})}return e}};const Ms=f.AUTO_COMPACT_THRESHOLD,Ns=`autoCompactThreshold`;function Ps(e){return e.getContextState()}function Fs(e){return e.getAutoCompactThreshold()}function Is(e){return e.getAutoCompactThresholdSource?.()??`session`}function Ls(e,t,n){if(e.setAutoCompactThreshold){e.setAutoCompactThreshold(t,n);return}let r=e.getSession();if(!r.setAutoCompactThreshold)throw Error(`Command host does not support changing auto-compact threshold.`);r.setAutoCompactThreshold(t)}function Rs(e,t){let n=Gs(e);return n?(n.write({...n.read(),[Ns]:t}),!0):!1}function zs(e){let t=Gs(e);if(!t)return!1;let n={...t.read()};return delete n[Ns],t.write(n),!0}async function Bs(e,t){let n=Ps(e);return await e.compactContext(t),{before:n,after:Ps(e)}}function Vs(e){return e.listContextReferences?.()??[]}async function Hs(e,t){return e.addContextReference?e.addContextReference(t):{evicted:[],diagnostics:[`Command host does not support context reference additions.`]}}function Us(e,t){return e.removeContextReference?.(t)??{}}function Ws(e){return e.clearContextReferences?.()??{removed:[]}}function Gs(e){return e.getCommandHostAdapters?.().settings}function Ks(e,t={}){let n=qs(e.type)??`provider`,r=new Set(t.existingProfileNames??[]);if(!r.has(n))return n;let i=2;for(;r.has(`${n}-${i}`);)i+=1;return`${n}-${i}`}function qs(e){let t=e?.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t!==void 0&&t.length>0?t:void 0}function Js(e){return e.listCommands?.()??[]}function Ys(e){return[`Available commands:`,...Js(e).map(e=>{let t=e.displayName??e.name,n=`/${e.name}`;return` ${(e.displayName?`${t} (${n})`:n).padEnd(32)} — ${e.description}`})].join(`
96
96
  `)}function Xs(){return[{name:`list`,description:`List background tasks`,source:`background`},{name:`read`,description:`Read a background task log page`,source:`background`},{name:`cancel`,description:`Cancel a running background task`,source:`background`},{name:`close`,description:`Dismiss a terminal background task`,source:`background`}]}function Zs(e){let t=e.promptPreview??e.commandPreview??``,n=e.unread?` unread`:``,r=e.currentAction?` (${e.currentAction})`:``,i=e.timeoutReason?` timeout=${e.timeoutReason}`:``,a=e.lastActivityAt?` lastActivityAt=${e.lastActivityAt}`:``,o=ec(e),s=t?` — ${t}`:``;return`${e.id} [${e.status}${n}${i}${a}${o}] ${e.kind}:${e.label}${r}${s}`}function Qs(e){return e.length===0?`No background tasks.`:[`Background tasks:`,...e.map(e=>` ${Zs(e)}`)].join(`
97
97
  `)}function $s(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isNaN(t)?void 0:{offset:t}}function ec(e){let t=[];return e.worktreePath&&t.push(`worktree=${e.worktreePath}`),e.branchName&&t.push(`branch=${e.branchName}`),e.worktreeStatus&&t.push(`worktreeStatus="${tc(e.worktreeStatus)}"`),e.worktreeNextAction&&t.push(`next="${tc(e.worktreeNextAction)}"`),t.length===0?``:` ${t.join(` `)}`}function tc(e){let t=e.trim().replace(/\s+/g,` `);return t.length>160?`${t.slice(0,160)}...`:t}function nc(e,t){return e.listBackgroundTasks(t)}function rc(e,t,n){return e.readBackgroundTaskLog(t,n)}function ic(e,t,n){return e.cancelBackgroundTask(t,n)}function ac(e,t){return e.closeBackgroundTask(t)}function oc(e=`model`){let t=typeof e==`string`?{source:e}:e,n=t.source??`model`,r=lc(t.settings,t.providerDefinitions);return r===void 0?t.settings===void 0?dc(n):[]:fc(r,n)}function sc(e={}){let t=mc(e.settings,e.providerDefinitions);return xc(t===void 0?void 0:gc(t))}async function cc(e={}){return xc(await uc(e))}function lc(e,t=[]){return mc(e,t)?.catalog}async function uc(e){let t=mc(e.settings,e.providerDefinitions);if(t!==void 0){if(!(e.refresh===!0||_c(t.catalog,t.definition?.modelCatalogCacheTtlSeconds))||t.definition?.refreshModelCatalog===void 0)return gc(t);try{let e=await t.definition.refreshModelCatalog({profile:vc(t)});return e.status===`unavailable`?{providerType:t.providerType,catalog:t.catalog??e,refreshAttempted:!0,...e.message===void 0?{}:{refreshMessage:e.message}}:{providerType:t.providerType,catalog:e,refreshAttempted:!0}}catch(e){return{providerType:t.providerType,...t.catalog===void 0?{}:{catalog:t.catalog},refreshAttempted:!0,refreshMessage:e instanceof Error?e.message:String(e)}}}}function dc(e){let t=new Set,n=[];for(let r of Object.values(c.CLAUDE_MODELS))t.has(r.name)||(t.add(r.name),n.push({name:r.id,description:`${r.name} (${(0,c.formatTokenCount)(r.contextWindow).toUpperCase()})`,source:e}));return n}function fc(e,t){return(e.entries??[]).filter(e=>e.lifecycle!==`unavailable`).map(e=>({name:e.id,description:pc(e),source:t}))}function pc(e){return e.contextWindow===void 0?e.displayName:`${e.displayName} (${(0,c.formatTokenCount)(e.contextWindow).toUpperCase()})`}function mc(e,t=[]){let n=hc(e),r=n?.type??n?.name;if(r===void 0)return;let i=(0,c.findProviderDefinition)(t,r);return{providerType:r,...n===void 0?{}:{profile:n},...i===void 0?{}:{definition:i},...i?.modelCatalog===void 0?{}:{catalog:i.modelCatalog}}}function hc(e){return e?.currentProvider===void 0?e?.provider:e.providers?.[e.currentProvider]}function gc(e){return{providerType:e.providerType,...e.catalog===void 0?{}:{catalog:e.catalog},refreshAttempted:!1}}function _c(e,t){return e===void 0||t===void 0||e.lastVerifiedAt===void 0?!1:Date.now()-new Date(e.lastVerifiedAt).getTime()>t*1e3}function vc(e){let t=e.profile,n=e.definition?.defaults,r=bc(t?.apiKey??n?.apiKey),i=yc(t?.model,n?.model),a=yc(t?.baseURL,n?.baseURL),o=yc(t?.timeout,n?.timeout),s=yc(t?.options,n?.options),c={type:t?.type??e.providerType};return i!==void 0&&(c.model=i),r!==void 0&&(c.apiKey=r),a!==void 0&&(c.baseURL=a),o!==void 0&&(c.timeout=o),s!==void 0&&(c.options=s),c}function yc(e,t){return e??t}function bc(e){return e===void 0?void 0:(0,c.resolveEnvReference)(e)}function xc(e){let t=e?.providerType!==void 0&&(e.catalog?.entries===void 0||e.catalog.entries.length===0)?`No model catalog available for provider ${e.providerType}. Usage: model <model-id>`:`Usage: model <model-id>`,n=Sc(e);return n===void 0?t:`${t}\n${n}`}function Sc(e){let t=e?.catalog;if(t===void 0)return;let n=[`Catalog: ${t.status}`];t.entries!==void 0&&n.push(`${t.entries.length} model(s)`),t.lastVerifiedAt!==void 0&&n.push(`verified ${t.lastVerifiedAt}`),t.sourceUrl!==void 0&&n.push(`source ${t.sourceUrl}`);let r=e?.refreshMessage;return r===void 0?t.message!==void 0&&n.push(t.message):n.push(`refresh ${r}`),n.join(`; `)}const Cc=[{code:`ko`,description:`Korean`},{code:`en`,description:`English`},{code:`ja`,description:`Japanese`},{code:`zh`,description:`Chinese`}];function wc(e=`language`){return Cc.map(t=>({name:t.code,description:t.description,source:e}))}function Tc(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Ec(e=`language`){return`Usage: ${e} <code> (e.g., ko, en, ja, zh)`}const Dc=[`plan`,`default`,`acceptEdits`,`bypassPermissions`];function Oc(e=`mode`){return[{name:`plan`,description:`Plan only, no execution`,source:e},{name:`default`,description:`Ask before risky actions`,source:e},{name:`acceptEdits`,description:`Auto-approve file edits`,source:e},{name:`bypassPermissions`,description:`Skip all permission checks`,source:e}]}function kc(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Ac(e){return Dc.includes(e)}function jc(){return`Invalid mode. Valid: ${Dc.join(` | `)}`}function Mc(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()}}function Nc(e){return Mc(e).getPermissionMode()}function Pc(e,t){Mc(e).setPermissionMode(t)}function Fc(e){return Mc(e).listSessionAllowedTools()}function Ic(e){return{mode:Nc(e),sessionAllowed:Fc(e)}}function Lc(e){let t=[`Permission mode: ${e.mode}`];return e.sessionAllowed.length>0?t.push(`Session-approved tools: ${e.sessionAllowed.join(`, `)}`):t.push(`No session-approved tools.`),t.join(`
98
98
  `)}const Rc={enabled:!0,gitBranch:!0};function zc(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 Bc(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function Vc(e){let t=e.statusline;return Uc(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:Rc.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:Rc.gitBranch}:{...Rc}}function Hc(e,t){let n=J(e),r={...Vc(n),...t};return n.statusline=r,Y(e,n),r}function Uc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Wc(){return{type:`plugin-tui-requested`}}function Gc(){return{type:`plugin-registry-reload-requested`}}function Kc(e){return e.getCommandHostAdapters?.().plugin}function qc(){return[{name:`manage`,description:`Open plugin manager`,source:`plugin-manager`},{name:`install`,description:`Install a plugin`,source:`plugin-manager`},{name:`uninstall`,description:`Uninstall a plugin`,source:`plugin-manager`},{name:`enable`,description:`Enable a plugin`,source:`plugin-manager`},{name:`disable`,description:`Disable a plugin`,source:`plugin-manager`},{name:`marketplace`,description:`Manage plugin marketplaces`,source:`plugin-manager`,subcommands:[{name:`add`,description:`Add marketplace source`,source:`plugin-manager`},{name:`remove`,description:`Remove marketplace source`,source:`plugin-manager`},{name:`update`,description:`Update marketplace source`,source:`plugin-manager`},{name:`list`,description:`List marketplace sources`,source:`plugin-manager`}]}]}function Jc(e){if(e.clearConversationHistory!==void 0){e.clearConversationHistory();return}e.getSession().clearHistory()}function Yc(e){let t=e.trim();return t.length>0?t:void 0}function Xc(e){return{type:`session-renamed`,name:e}}function Zc(){return{type:`session-picker-requested`}}function Qc(){return{type:`session-exit-requested`}}function $c(e){let t=e.getSession();return{sessionId:t.getSessionId(),messageCount:t.getMessageCount()}}function el(e){let t=e.validateCurrentSessionReplayLog?.();if(t!==void 0)return t;let n=e.getSession().getSessionId(),r=(0,g.join)(L(e.getCwd()).logs,`${n}.jsonl`),i=(0,f.loadSessionLogEntries)(r);return{logFile:r,entryCount:i.length,validation:(0,f.validateSessionReplayLogEntries)(i)}}function tl(e){let t=e.validation.ok?`Session replay log is valid.`:`Session replay log has ${e.validation.issues.length} issue(s).`,n=[`Log: ${e.logFile}`,`Entries: ${e.entryCount}`];if(e.validation.ok)return[t,...n].join(`
99
99
  `);let r=e.validation.issues.map((e,t)=>{let n=nl(e);return`${t+1}. ${e.code}${n}: ${e.message}`});return[t,...n,``,...r].join(`
100
100
  `)}function nl(e){let t=[];return e.executionId!==void 0&&t.push(`execution=${e.executionId}`),e.round!==void 0&&t.push(`round=${e.round}`),e.toolCallId!==void 0&&t.push(`tool=${e.toolCallId}`),t.length>0?` (${t.join(`, `)})`:``}function rl(e=`rewind`){return[{name:`list`,description:`List edit checkpoints`,source:e},{name:`inspect`,description:`Inspect captured files and restore plans`,source:e},{name:`restore`,description:`Restore code to a checkpoint`,source:e},{name:`code`,description:`Restore code to a checkpoint`,source:e},{name:`rollback`,description:`Rollback code through a checkpoint`,source:e}]}function il(e){return e.listEditCheckpoints()}function al(e,t){if(!e.inspectEditCheckpoint)throw Error(`Checkpoint inspection is not available in this command host.`);return e.inspectEditCheckpoint(t)}function ol(e,t){return e.restoreEditCheckpoint(t)}function sl(e,t){return e.rollbackEditCheckpoint(t)}const cl=[/\b(api[_-]?key|secret|token|password|private key)\b/i,/\b\d{3}-\d{2}-\d{4}\b/,/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/,/주민등록|비밀번호|시크릿|토큰/u];function ll(e){return cl.some(t=>t.test(e))}function ul(e){return(0,g.join)(e,`.robota`,`memory`)}function dl(){return{version:1,records:[]}}var fl=class{fs;path;now;constructor(e,t=()=>new Date,n=new M){this.fs=n,this.path=(0,g.join)(ul(e),`pending.json`),this.now=t}getPath(){return this.path}list(e){let t=this.read().records;return e?t.filter(t=>t.status===e):t}get(e){return this.read().records.find(t=>t.id===e)}upsert(e,t,n){let r=this.read(),i=this.now().toISOString(),a=r.records.findIndex(t=>t.id===e.id),o={...e,status:t,updatedAt:i,decisionReason:n};a>=0?r.records[a]={...r.records[a],...o}:r.records.push(o),this.write(r)}mark(e,t,n){let r=this.read(),i=r.records.findIndex(t=>t.id===e);if(i<0)throw Error(`Memory candidate not found: ${e}`);let a={...r.records[i],status:t,updatedAt:this.now().toISOString(),decisionReason:n};return r.records[i]=a,this.write(r),a}read(){if(!this.fs.existsSync(this.path))return dl();try{return{version:1,records:JSON.parse(this.fs.readFileSync(this.path,`utf8`)).records??[]}}catch{return dl()}}write(e){this.fs.mkdirSync((0,g.dirname)(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,JSON.stringify(e,null,2),`utf8`)}};function pl(e=`memory`){return[{name:`list`,description:`List project memory topics`,source:e},{name:`show`,description:`Show project memory index or a topic`,source:e},{name:`add`,description:`Save durable project memory`,source:e},{name:`pending`,description:`List pending memory candidates`,source:e},{name:`approve`,description:`Approve a pending memory candidate`,source:e},{name:`reject`,description:`Reject a pending memory candidate`,source:e},{name:`used`,description:`Show memory references used in the current turn`,source:e}]}function ml(e,t){return new oo(e,t)}function hl(e,t){return new fl(e,t)}function gl(e,t){let n=e.getCwd();return{project:ml(n,t),pending:hl(n,t)}}function _l(e){return $a(e)}function vl(e){return ll(e)}function yl(e){return e.getUsedMemoryReferences()}function bl(e,t,n=()=>new Date){e.recordMemoryEvent({...t,at:n().toISOString()})}function xl(e,t,n){let r=t?t.split(/\s+/):[],i=e;return i=i.replace(/\$ARGUMENTS\[(\d+)]/g,(e,t)=>r[Number(t)]??``),i=i.replace(/\$ARGUMENTS/g,t),i=i.replace(/\$(\d)(?!\d|\w|\[)/g,(e,t)=>r[Number(t)]??``),i=i.replace(/\$\{CLAUDE_SESSION_ID}/g,n?.sessionId??``),i=i.replace(/\$\{CLAUDE_SKILL_DIR}/g,n?.skillDir??``),i}async function Sl(e,t){let n=/!`([^`]+)`/g;if(!n.test(e))return e;n.lastIndex=0;let r=e,i,a=[];for(;(i=n.exec(e))!==null;)a.push({full:i[0],command:i[1]});for(let{full:e,command:n}of a){let i=``;if(t)try{i=t(n)}catch{i=``}r=r.replace(e,i)}return r}async function Cl(e,t,n,r){return e.skillContent?xl(await Sl(e.skillContent,n.shellExec),t,r):null}async function wl(e,t,n,r){let i=await Cl(e,t,n,r);if(i){let n=t||e.description;return`<skill name="${e.name}">\n${i}\n</skill>\n\nExecute the "${e.name}" skill: ${n}`}return`Use the "${e.name}" skill: ${t||e.description}`}async function Tl(e,t,n,r){if(e.context===`fork`){if(!n.runInFork)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);let i=await Cl(e,t,n,r)??`Use the "${e.name}" skill: ${t||e.description}`,a={};return e.agent&&(a.agent=e.agent),e.allowedTools&&(a.allowedTools=e.allowedTools),{mode:`fork`,result:await n.runInFork(i,a)}}return{mode:`inject`,prompt:await wl(e,t,n,r)}}function El(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Dl(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Ol(e,t){let n=t.trim();return n.length>0?`${e} ${n}`:e}function kl(e){if(!e?.startsWith(`/`))return;let t=e.slice(1).trim().split(/\s+/)[0];return t&&t.length>0?t:void 0}var Al=class{getSession;getSessionId;onSubmit;onApplyResult;recordSkillActivation;runSkillInFork;onForkSkill;onBlockingCommand;shellExec;commandExecutor;skillCommandSource;commandHostAdapters;commandInvocationSource=`user`;constructor(e,t,n,r,i,a,o,s,c,l,u,d){this.getSession=r,this.getSessionId=i,this.onSubmit=a,this.onApplyResult=o,this.recordSkillActivation=s,this.runSkillInFork=c,this.onForkSkill=l,this.onBlockingCommand=u,this.shellExec=d,this.commandExecutor=new Ro(e.flatMap(e=>e.systemCommands??[])),this.skillCommandSource=new Mi(t),this.commandHostAdapters=n}getCommandInvocationSource(){return this.commandInvocationSource}getCommandHostAdapters(){return this.commandHostAdapters??{}}listCommands(){return this.commandExecutor.listCommands().map(e=>({name:e.name,...e.displayName===void 0?{}:{displayName:e.displayName},description:e.description}))}listSkills(){return this.skillCommandSource.getCommands().map(e=>({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}}))}listModelInvocableCommands(){return this.commandExecutor.listModelInvocableCommands().map(e=>({name:e.name,description:e.description}))}findSkillCommand(e){let t=El(e);return this.skillCommandSource.getCommands().find(e=>e.name.toLowerCase()===t.toLowerCase())}async executeCommand(e,t){let n=Dl(e),r=this.commandExecutor.getCommand(n),i=t.trim();if(!r){let e=this.findSkillCommand(n),t=this.commandExecutor.getCommand(`skills`);return!e||!t?null:this.executeCommandWithSource(`user`,t,Ol(e.name,i))}return this.executeCommandWithSource(`user`,r,i)}async executeCommandWithSource(e,t,n){let r=this.commandInvocationSource;this.commandInvocationSource=e;try{return t.lifecycle===`blocking`?this.onBlockingCommand(()=>this.executeForegroundCommand(t,n)):await this.commandExecutor.executeCommand(t,this.getSession(),n)}finally{this.commandInvocationSource=r}}async executeModelCommand(e,t){let n=this.commandInvocationSource;this.commandInvocationSource=`model`;try{return await this.commandExecutor.executeModelInvocable(e,this.getSession(),t)}finally{this.commandInvocationSource=n}}async executeSkillCommandByName(e,t,n){let r=this.findSkillCommand(e);if(!r)return null;if(n.invocationSource===`model`){if(r.disableModelInvocation===!0)return{success:!1,message:`Skill is not model-invocable: ${r.name}`};let e=await this.executeSkillWithActivation(r,t,`model-tool`);return{success:!0,message:`Skill activated: ${r.name}`,data:{skill:r.name,mode:e.mode,...e.prompt===void 0?{}:{prompt:e.prompt},...e.result===void 0?{}:{result:e.result}}}}return await this.executeUserResolvedSkillCommand(r,t,n.displayInput,n.rawInput,`user-slash`),{success:!0,message:``,data:{skill:r.name,sessionExecution:!0},effects:[{type:`session-execution-started`}]}}async executeUserResolvedSkillCommand(e,t,n,r,i){if(e.userInvocable===!1)throw Error(`Skill is not user-invocable: ${e.name}`);let a=kl(r);if(e.context===`fork`)return this.onForkSkill(e,t,n,a,i);let o=await this.executeSkillWithActivation(e,t,i,a);return o.mode===`inject`?(o.prompt&&await this.onSubmit(o.prompt,n,r),o):(await this.onApplyResult(o.result??`(empty response)`),o)}async executeSkillWithActivation(e,t,n,r){this.emitSkillActivation(e,n,`started`,r);try{let i=await Tl(e,t,{runInFork:(e,t)=>this.runSkillInFork(e,t),...this.shellExec?{shellExec:this.shellExec}:{}},{sessionId:this.getSessionId()});return this.emitSkillActivation(e,n,`completed`,r,{appendHistory:!1}),i}catch(t){let i=t instanceof Error?t:Error(String(t));throw this.emitSkillActivation(e,n,`failed`,r,{error:i.message}),i}}emitSkillActivation(e,t,n,r,i={}){let a=Er({skill:e,invocation:t,status:n,...r===void 0?{}:{qualifiedName:r},...i.error===void 0?{}:{error:i.error}});this.recordSkillActivation(a,i.appendHistory??n!==`completed`)}async executeForegroundCommand(e,t){try{return await this.commandExecutor.executeCommand(e,this.getSession(),t)}catch(e){return{success:!1,message:`Error: ${e instanceof Error?e.message:String(e)}`}}}},jl=class extends Yt{session=null;listeners=new Map;initialized=!1;initPromise=null;sessionStore;sessionName;cwd;pendingRestoreMessages=null;resumeSessionId;forkSession;autoCompactThresholdSource=`default`;shutdownPromise=null;sandboxClient;sandboxSnapshotId;agentsFileEntries=[];claudeFileEntries=[];rebuildSystemMessage=null;bgTracker;histTracker;skillRouter;execCtrl;constructor(e){super(),this.sessionStore=e.sessionStore,this.sessionName=e.sessionName,this.cwd=(`cwd`in e?e.cwd:void 0)??``,this.resumeSessionId=e.resumeSessionId,this.forkSession=e.forkSession??!1,this.sandboxClient=`sandboxClient`in e?e.sandboxClient:void 0,this.sandboxSnapshotId=`sandboxSnapshotId`in e?e.sandboxSnapshotId:void 0;let t=this.cwd,n=null;`session`in e&&e.session&&t&&(n=new R({cwd:t})),this.bgTracker=new Ft(()=>this.getBackgroundTaskManager(),(e,t)=>this.execCtrl.emitExecutionWorkspaceUpdated(e,t),e=>this.emit(`background_task_event`,e),e=>this.emit(`background_job_group_event`,e),()=>this.persistCurrentSession()),this.histTracker=new Or(t,()=>this.getSessionOrThrow().getSessionId(),()=>this.execCtrl.executing,()=>this.persistCurrentSession(),e=>this.emit(`skill_activation`,e),n);let r=[...`commandModules`in e?e.commandModules??[]:[]],i=`commandHostAdapters`in e?e.commandHostAdapters:void 0,a=`shellExec`in e?e.shellExec:void 0;this.skillRouter=new Al(r,t,i,()=>this,()=>this.session?.getSessionId()??``,(e,t,n)=>this.submit(e,t,n),e=>this.execCtrl.applyForkSkillResult(e),(e,t)=>this.histTracker.recordSkillActivationEvent(e,t),(e,t)=>lr(e,t,this.getSessionOrThrow()),(e,t,n,r,i)=>this.execCtrl.executeForkSkillCommand(e,t,n,r,i,(e,t,n)=>this.submit(e,t,n)),e=>this.execCtrl.executeForegroundCommand(e,(e,t,n)=>this.submit(e,t,n)),a),this.execCtrl=new sr(this.histTracker,this.skillRouter,{getSession:()=>this.session,getSessionOrThrow:()=>this.getSessionOrThrow(),getCwd:()=>this.getCwd(),getContextState:()=>this.getContextState(),getExecutionWorkspaceSnapshot:()=>this.getExecutionWorkspaceSnapshot(),emit:(e,...t)=>this.emit(e,...t),persistSession:()=>this.persistCurrentSession()});let o=this.configureInjectedSession(e);this.restoreSessionRecordIfNeeded(e),this.startAsyncInitializationIfNeeded(e,o),this.initialized&&this.bgTracker.subscribe(this.session),this.initialized&&this.persistCurrentSession()}configureInjectedSession(e){return`session`in e&&e.session?(this.session=e.session,this.autoCompactThresholdSource=`session`,this.initialized=!0,!0):!1}restoreSessionRecordIfNeeded(e){if(!e.resumeSessionId||!this.sessionStore)return;let t=Nr(this.sessionStore,e.resumeSessionId,this.forkSession,this.session);this.histTracker.restoreState({history:t.history,memoryEvents:t.memoryEvents,usedMemoryReferences:t.usedMemoryReferences,contextReferences:t.contextReferences,skillActivationEvents:t.skillActivationEvents}),t.sessionName&&(this.sessionName=t.sessionName),this.bgTracker.restoreState({tasks:t.backgroundTasks,taskEvents:t.backgroundTaskEvents,groups:t.backgroundJobGroups,groupEvents:t.backgroundJobGroupEvents}),this.pendingRestoreMessages=t.pendingRestoreMessages,this.sandboxSnapshotId=this.forkSession?void 0:t.sandboxSnapshotId}startAsyncInitializationIfNeeded(e,t){if(t)return;let n=e;this.initPromise=this.initializeAsync(n)}async initializeAsync(e){let t=await Oo(e,{sandboxSnapshotId:this.sandboxSnapshotId,resumeSessionId:this.resumeSessionId,pendingRestoreMessages:this.pendingRestoreMessages,onTextDelta:e=>this.execCtrl.handleTextDelta(e),onContextUpdate:e=>this.emit(`context_update`,e),onCompactEvent:e=>this.execCtrl.handleCompactEvent(e),onToolExecution:e=>this.execCtrl.handleToolExecution(e),executeModelCommand:(e,t)=>this.executeModelCommand(e,t),isModelCommandInvocable:e=>this.skillRouter.commandExecutor.isModelInvocable(e),commandDescriptors:this.skillRouter.commandExecutor.listModelInvocableCommands(),setEditCheckpointStore:e=>this.histTracker.setEditCheckpointStore(e)});this.session=t.session,this.agentsFileEntries=t.agentsFileEntries,this.claudeFileEntries=t.claudeFileEntries,this.rebuildSystemMessage=t.rebuildSystemMessage,this.autoCompactThresholdSource=t.autoCompactThresholdSource,this.pendingRestoreMessages=null,this.initialized=!0,this.bgTracker.subscribe(this.session),this.persistCurrentSession()}async ensureInitialized(){!this.initialized&&this.initPromise&&await this.initPromise}getSessionOrThrow(){if(!this.session)throw Error(`InteractiveSession not initialized. Call submit() or await initialization.`);return this.session}getCwd(){if(!this.cwd)throw Error(`cwd is not set — provide cwd in session options`);return this.cwd}get sessionId(){return this.session?.getSessionId()??``}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,...t){let n=this.listeners.get(e);if(n)for(let e of n)e(...t)}async submit(e,t,n){if(await this.ensureInitialized(),this.execCtrl.shuttingDown)throw Error(`Interactive session is shutting down.`);if(this.execCtrl.executing){this.execCtrl.pendingPrompt=e,this.execCtrl.pendingDisplayInput=t,this.execCtrl.pendingRawInput=n;return}await this.execCtrl.executePrompt(e,t,n,this.agentsFileEntries,this.claudeFileEntries,this.rebuildSystemMessage,(e,t)=>{this.agentsFileEntries=e,this.claudeFileEntries=t},(e,t,n)=>this.submit(e,t,n))}abort(){this.execCtrl.clearPendingQueue(),this.session?.abort()}shutdown(e={}){return this.shutdownPromise?this.shutdownPromise:(this.execCtrl.shuttingDown=!0,this.shutdownPromise=(async()=>{await this.ensureInitialized(),this.execCtrl.clearPendingQueue();let t=this.session;t?.abort(),await this.getBackgroundTaskManager()?.shutdown(e.message??`Session shutdown`),this.bgTracker.dispose(),await this.captureSandboxSnapshot(),this.persistCurrentSession(),await t?.shutdown({reason:e.reason??`other`})})(),this.shutdownPromise)}get isInitialized(){return this.initialized}getAutoCompactThresholdSource(){return this.autoCompactThresholdSource}getAutoCompactThreshold(){return this.getSessionOrThrow().getAutoCompactThreshold()}getSession(){return this.getSessionOrThrow()}getAgentJobCapability(){return this}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())}getName(){return this.sessionName}attachTransport(e){e.attach(this)}setName(e){if(this.sessionName=e,this.sessionStore&&this.session)try{let t=this.getSessionOrThrow().getSessionId(),n=this.sessionStore.load(t);n&&(n.name=e,n.updatedAt=new Date().toISOString(),this.sessionStore.save(n))}catch{}}getBackgroundTaskManager(){if(this.session)return Le(this.session)??A(this.session)?.backgroundTaskManager}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((0,c.messageToHistoryEntry)((0,c.createSystemMessage)(`Sandbox snapshot error: ${t.message}`))),this.emit(`error`,t)}}persistCurrentSession(){if(!this.sessionStore||!this.session)return;let e=this.bgTracker.getState(),t=this.histTracker.getState();ko(this.sessionStore,this.session,this.sessionName,this.cwd??``,t.history,{tasks:e.tasks,events:e.taskEvents,groups:e.groups,groupEvents:e.groupEvents},{events:t.memoryEvents,usedReferences:t.usedMemoryReferences},{events:t.skillActivationEvents},{references:t.contextReferences},{snapshotId:this.sandboxSnapshotId})}};function Ml(e,t=new M){let n=L(e);return new Il(n.sessions,n.logs,t)}function Nl(e,t){return(e?.list()??[]).filter(e=>e.cwd===t).sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime()).map(e=>({id:e.id,...e.name===void 0?{}:{name:e.name},cwd:e.cwd,updatedAt:e.updatedAt,messageCount:e.messages.length,preview:Ll(e.messages)}))}function Pl(e,t){return Nl(e,t)[0]?.id}function Fl(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var Il=class{store;logsDir;fs;constructor(e,t,n=new M){this.store=new f.SessionStore(e),this.logsDir=t,this.fs=n}save(e){this.store.save(Rl(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):zl(t)}list(){let e=this.store.list().map(zl),t=new Set(e.map(e=>e.id));for(let n of this.listReplayLogRecords())t.has(n.id)||e.push(n);return e.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime())}delete(e){this.store.delete(e)}loadFromReplayLog(e){if(!this.logsDir)return;let t=(0,f.replaySessionLogEntries)((0,f.loadSessionLogEntries)((0,g.join)(this.logsDir,`${e}.jsonl`)));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:Bl(n),backgroundTaskEvents:n,backgroundJobGroups:Hl(r),backgroundJobGroupEvents:r,skillActivationEvents:[],memoryEvents:t.memoryEvents}}listReplayLogRecords(){return!this.logsDir||!this.fs.existsSync(this.logsDir)?[]:this.fs.readdirSync(this.logsDir).filter(e=>e.endsWith(`.jsonl`)).map(e=>this.loadFromReplayLog(e.slice(0,-6))).filter(e=>e!==void 0)}};function Ll(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 Rl(e){return{...e}}function zl(e){return{id:e.id,...e.name===void 0?{}:{name:e.name},cwd:e.cwd,createdAt:e.createdAt,updatedAt:e.updatedAt,messages:e.messages,...e.history===void 0?{}:{history:e.history},...e.systemPrompt===void 0?{}:{systemPrompt:e.systemPrompt},...e.toolSchemas===void 0?{}:{toolSchemas:e.toolSchemas},...e.backgroundTasks===void 0?{}:{backgroundTasks:e.backgroundTasks},...e.backgroundTaskEvents===void 0?{}:{backgroundTaskEvents:e.backgroundTaskEvents},...e.backgroundJobGroups===void 0?{}:{backgroundJobGroups:e.backgroundJobGroups},...e.backgroundJobGroupEvents===void 0?{}:{backgroundJobGroupEvents:e.backgroundJobGroupEvents},...e.skillActivationEvents===void 0?{}:{skillActivationEvents:e.skillActivationEvents},...e.memoryEvents===void 0?{}:{memoryEvents:e.memoryEvents},...e.usedMemoryReferences===void 0?{}:{usedMemoryReferences:e.usedMemoryReferences},...e.contextReferences===void 0?{}:{contextReferences:e.contextReferences},...e.sandboxSnapshotId===void 0?{}:{sandboxSnapshotId:e.sandboxSnapshotId}}}function Bl(e){let t=new Map;for(let n of e){let e=Vl(n);e&&t.set(e.id,e)}return[...t.values()]}function Vl(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 Hl(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function Ul(e){let t=new jl({cwd:e.cwd??process.cwd(),provider:e.provider,permissionMode:e.permissionMode??`bypassPermissions`,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler});return e.onTextDelta&&t.on(`text_delta`,e.onTextDelta),async e=>new Promise((n,r)=>{let i=e=>{s(),n(e.response)},a=e=>{s(),n(e.response)},o=e=>{s(),r(e)},s=()=>{t.off(`complete`,i),t.off(`interrupted`,a),t.off(`error`,o)};t.on(`complete`,i),t.on(`interrupted`,a),t.on(`error`,o),t.submit(e).catch(e=>{s(),r(e instanceof Error?e:Error(String(e)))})})}const Wl=[`preferences`,`view-state`,`memory-projections`,`task-associations`,`workflow-metadata`,`inspection-index`],Gl=[{category:`preferences`,purpose:`User-local UI and display preferences.`,mayExecuteCommands:!1},{category:`view-state`,purpose:`Last selected panels, filters, and navigation state.`,mayExecuteCommands:!1},{category:`memory-projections`,purpose:`Inspectable local memory item projections and user choices.`,mayExecuteCommands:!1},{category:`task-associations`,purpose:`User-local associations between sessions, tasks, and background items.`,mayExecuteCommands:!1},{category:`workflow-metadata`,purpose:`Transparent workflow metadata that is not repo-owned.`,mayExecuteCommands:!1},{category:`inspection-index`,purpose:`Category and item summaries for user inspection and deletion.`,mayExecuteCommands:!1}];function Kl(e){return e.toISOString()}function ql(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!g.default.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function Jl(){return process.env.HOME??(0,_.homedir)()}function Yl(e,t){let n=g.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!g.default.isAbsolute(n)}async function Xl(e,t){let n=e;for(;g.default.dirname(n)!==n;)try{let r=await t.realpath(n),i=g.default.relative(n,e);return g.default.resolve(r,i)}catch{n=g.default.dirname(n)}try{return await t.realpath(n)}catch{return g.default.resolve(e)}}async function Zl(e){let t=e.fsAsync??new N,n=g.default.resolve(e.activeRepositoryRoot);ql(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?g.default.join(e.homeDir??Jl(),`.robota`):e.storageRoot;ql(`userLocalStorageRoot`,r);let i=g.default.resolve(r),a=await Xl(i,t);if(Yl(await Xl(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function Ql(e,t){return g.default.join(e,t)}async function $l(e,t,n){let r=Ql(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=g.default.join(r,i.name),o=await n.stat(a),s=i.name;return{root:e,category:t,key:s,summary:`${t}/${s}`,source:`user-local-storage`,scope:`user`,storageLocation:a,createdAt:Kl(new Date(o.birthtimeMs)),lastUsedAt:Kl(new Date(o.mtimeMs)),enabled:!0,deleteAvailable:!0,disableAvailable:!1}}))).sort((e,t)=>e.key.localeCompare(t.key))}async function eu(e){let t=e.fsAsync??new N,n=await Zl(e),r=g.default.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all(Gl.map(async e=>{let r=Ql(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await $l(n,e.category,t);return{category:e.category,purpose:e.purpose,mayExecuteCommands:e.mayExecuteCommands,storageLocation:r,itemCount:a.length,items:a}})),generatedAt:Kl((e.now??(()=>new Date))())}}const tu=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],nu=`.json`,ru=/^[a-z0-9][a-z0-9._-]*$/u,iu={"view-preference":`May affect UI panel, filter, density, or sorting display/navigation only.`,"last-visible-cwd":`May display or preselect an already visible workspace context only.`,"background-selection":`May restore the selected background entry in local UI only.`,"task-association":`May group visible tasks by a local association only.`,"display-preference":`May affect local text wrapping, compactness, or visibility only.`,"inspection-choice":`May affect inspection display choices only.`};function au(e){return e.toISOString()}function ou(e){return tu.includes(e)}function su(e){if(!ou(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function cu(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!ru.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function lu(e,t,n){let r=t.trim().replace(/\s+/g,` `);if(r.length===0)throw Error(`${e} must not be empty.`);return r.length>n?r.slice(0,n):r}function uu(e){return lu(`value`,e,240)}function du(e,t){return`${e}__${t}${nu}`}async function fu(e){let t=await Zl(e);return{root:t,memoryRoot:g.default.join(t,`memory-projections`)}}function pu(e,t){let n=JSON.parse(e),r=Z(n,`category`);if(n.schemaVersion!==1)throw Error(`Unsupported user-local memory schema at ${t}`);return{schemaVersion:1,category:su(r),key:Z(n,`key`),value:Z(n,`value`),summary:Z(n,`summary`),source:Z(n,`source`),scope:Z(n,`scope`),createdAt:Z(n,`createdAt`),lastUsedAt:Z(n,`lastUsedAt`),enabled:mu(n,`enabled`)}}function Z(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function mu(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function hu(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:uu(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:iu[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function gu(e,t,n){return hu(e,t,pu(await n.readFile(t,`utf8`),t))}async function _u(e){let t=su(e.category),n=cu(`key`,e.key),{root:r,memoryRoot:i}=await fu(e);return{root:r,storageLocation:g.default.join(i,du(t,n))}}async function vu(e){let t=e.fsAsync??new N,n=su(e.category),r=cu(`key`,e.key),i=lu(`summary`,e.summary,240),a=lu(`source`,e.source,80),o=lu(`scope`,e.scope??`user`,120),s=uu(e.value),c=au((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await fu(e),d=g.default.join(u,du(n,r)),f=c;try{f=pu(await t.readFile(d,`utf8`),d).createdAt}catch(e){if(e instanceof Error&&e.message.includes(`ENOENT`))f=c;else throw e}let p={schemaVersion:1,category:n,key:r,value:s,summary:i,source:a,scope:o,createdAt:f,lastUsedAt:c,enabled:!0};return await t.mkdir(u,{recursive:!0}),await t.writeFile(d,`${JSON.stringify(p,null,2)}\n`,`utf8`),hu(l,d,p)}async function yu(e){let t=e.fsAsync??new N,{root:n,memoryRoot:r}=await fu(e),i;try{i=await t.readdir(r,{withFileTypes:!0})}catch{i=[]}let a=await Promise.all(i.filter(e=>e.isFile()&&e.name.endsWith(nu)).map(e=>gu(n,g.default.join(r,e.name),t)));return{root:n,activeRepositoryRoot:g.default.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function bu(e){let t=e.fsAsync??new N,{root:n,storageLocation:r}=await _u(e);return gu(n,r,t)}async function xu(e){let t=e.fsAsync??new N,{root:n,storageLocation:r}=await _u(e),i={...pu(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:au((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),hu(n,r,i)}async function Su(e){let t=e.fsAsync??new N,{storageLocation:n}=await _u(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}async function Cu(e){let t=await bu(e);return t.enabled?t:null}const wu=[`test`,`typecheck`,`build`],Tu={idle:{checkpoint_created:`checkpointed`,cancelled:`cancelled`},checkpointed:{edits_started:`editing`,cancelled:`cancelled`},editing:{edits_applied:`verifying`,verify_failed:`failed`,cancelled:`cancelled`},verifying:{verify_passed:`passed`,verify_failed:`failed`,cancelled:`cancelled`},passed:{},failed:{rollback_completed:`rolled_back`,cancelled:`cancelled`},rolled_back:{},cancelled:{}};function Eu(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))):[]}function Du(e){return e.flatMap(e=>wu.map(t=>({id:`package-${t}:${e}`,phase:`verify`,description:`Run ${t} for ${e} in a child process against the new on-disk tree.`,required:!0,command:`pnpm --filter ${e} ${t}`})))}function Ou(){return[{id:`checkpoint`,phase:`checkpoint`,description:`Create a recoverable turn-level checkpoint before the first mutation.`,required:!0},{id:`atomic-edit`,phase:`edit`,description:`Apply Write/Edit mutations through same-directory temp files and atomic rename.`,required:!0},{id:`handoff`,phase:`handoff`,description:`Keep the current process on already-loaded code and run verification child processes against disk.`,required:!0}]}function ku(e){return{id:`harness-verify`,phase:`verify`,description:`Run Robota harness verification as the local CI-like gate.`,required:!0,command:`pnpm harness:verify -- --base-ref ${e} --skip-record-check`}}function Au(){return{id:`rollback-on-failure`,phase:`recover`,description:`Use the existing edit checkpoint restore path if verification fails.`,required:!0}}function ju(e){if(e.changedFiles.length===0)throw Error(`Self-hosting verification requires at least one changed file.`);let t=e.baseRef??`origin/develop`,n=Eu(e.packageScopes),r=[...Ou(),...Du(n),ku(t),Au()];return{changedFiles:[...e.changedFiles],packageScopes:n,baseRef:t,steps:r}}function Mu(e,t){let n=Tu[e][t];if(!n)throw Error(`Invalid self-hosting loop transition: ${e} -> ${t}`);return n}function Nu(e){return e}function Pu(e){if(!e||e.length===0)return;let[t,...n]=e;if(t!==void 0)return[t,...n]}function Fu(e){let t=Pu(e),n=t===void 0?d.z.string().describe(`Registered model-invocable command name to execute`):d.z.enum(t).describe(`Registered model-invocable command name to execute`);return d.z.object({command:n,args:d.z.string().optional().describe(`Arguments to pass to the command`)})}function Iu(e){if(e.commandNames!==void 0)return e.commandNames;if(e.commandDescriptors!==void 0)return e.commandDescriptors.map(e=>k(e.name))}function Lu(e){return`- ${k(e.name)}${e.argumentHint?` ${e.argumentHint}`:``}: ${e.description}`}function Ru(e){let t=`Executes a registered model-invocable Robota command through the command registry. Accepted command names and argument grammar come from registered command descriptors.`;return e===void 0||e.length===0?t:[t,`Use the registered command descriptors below as the authority for when to call this tool.`,``,`Registered model-invocable commands:`,...e.map(Lu)].join(`
101
- `)}function zu(e){let t=Fu(Iu(e));return(0,u.createZodFunctionTool)(`ExecuteCommand`,Ru(e.commandDescriptors),Nu(t),async n=>{let r=t.parse(n),i=k(r.command);return e.isModelInvocable(i)?ut(i,await e.execute(i,r.args??``)):JSON.stringify({success:!1,command:i,error:`Command is not model-invocable: ${i}`})})}const Bu=[`Allow`,`Deny`];function Vu(e){let t=Object.entries(e);return t.length===0?`(no arguments)`:t.map(([e,t])=>`${e}: ${typeof t==`string`?t:JSON.stringify(t)}`).join(`, `)}async function Hu(e,t,n){return e.writeLine(``),e.writeError(`[Permission Required] Tool: ${t}`),e.writeLine(` ${Vu(n)}`),e.writeLine(``),await e.select(Bu,0)===0}const Uu={usedTokens:0,maxTokens:2e5,usedPercentage:0,remainingPercentage:100},Wu={sessionId:`test-session-id`,updatedAt:new Date().toISOString(),entries:[]},Gu={id:``,parentSessionId:`test-session-id`,waitPolicy:`wait_all`,taskIds:[],status:`completed`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),results:[]};function Ku(e){return{submit:()=>Promise.resolve(),abort:()=>{},cancelQueue:()=>{},shutdown:()=>Promise.resolve(),isExecuting:()=>!1,getPendingPrompt:()=>null,getMessages:()=>[],getContextState:()=>({...Uu}),getSession:()=>({getSessionId:()=>`test-session-id`}),getCwd:()=>`/workspace`,executeCommand:()=>Promise.resolve(null),listCommands:()=>[],on:()=>{},off:()=>{},listBackgroundTasks:()=>[],getBackgroundTask:()=>void 0,cancelBackgroundTask:()=>Promise.resolve(),closeBackgroundTask:()=>Promise.resolve(),sendBackgroundTask:()=>Promise.resolve(),readBackgroundTaskLog:()=>Promise.resolve({taskId:``,lines:[]}),listBackgroundJobGroups:()=>[],getBackgroundJobGroup:()=>void 0,createBackgroundJobGroup:()=>({...Gu}),waitBackgroundJobGroup:()=>Promise.resolve({...Gu}),getExecutionWorkspaceSnapshot:()=>({...Wu}),listAgentDefinitions:()=>[],listAgentJobs:()=>[],spawnAgentJob:()=>Promise.resolve({id:`agent_1`,type:`general-purpose`,label:`general-purpose`,parentSessionId:`test-session-id`,status:`running`,mode:`background`,depth:1,cwd:`/workspace`,promptPreview:``,updatedAt:new Date().toISOString()}),sendAgentJob:()=>Promise.resolve(),cancelAgentJob:()=>Promise.resolve(),closeAgentJob:()=>Promise.resolve(),...e}}function qu(){let e=gs();return{deleted:bs(e),path:e}}function Ju(e){try{let t=Yu(e);if(!t)return;let n=(0,m.readFileSync)((0,g.join)(t,`HEAD`),`utf8`).trim();if(!n)return;if(n.startsWith(`ref: `)){let e=n.slice(5).trim();return e.startsWith(`refs/heads/`)?e.slice(11):e}return n.slice(0,7)}catch{return}}function Yu(e){let t=(0,g.resolve)(e),n=(0,g.dirname)(t);for(;n!==t;){let e=Xu((0,g.join)(t,`.git`),t);if(e)return e;t=n,n=(0,g.dirname)(t)}return Xu((0,g.join)(t,`.git`),t)}function Xu(e,t){if(!(0,m.existsSync)(e))return;let n=(0,m.lstatSync)(e);if(n.isDirectory())return e;if(!n.isFile())return;let r=(0,m.readFileSync)(e,`utf8`).trim();if(!r.startsWith(`gitdir:`))return;let i=r.slice(7).trim();return(0,g.isAbsolute)(i)?i:(0,g.resolve)(t,i)}function Zu(e,t){let n=$u(e),r=$u(t);if(n===void 0||r===void 0)return Math.sign(e.localeCompare(t));let i=$(n.major,r.major)||$(n.minor,r.minor)||$(n.patch,r.patch);return i===0?ed(n.prerelease,r.prerelease):i}function Qu(e,t){return Zu(e,t)>0}function $u(e){let[t,n]=(e.trim().replace(/^v/,``).split(`+`)[0]??``).split(`-`,2),[r,i,a]=t.split(`.`),o=Q(r),s=Q(i),c=Q(a);if(!(o===void 0||s===void 0||c===void 0))return{major:o,minor:s,patch:c,prerelease:n?n.split(`.`):[]}}function Q(e){if(!(e===void 0||!/^\d+$/.test(e)))return Number(e)}function $(e,t){return Math.sign(e-t)}function ed(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return 1;if(t.length===0)return-1;let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r],i=t[r];if(n===void 0)return-1;if(i===void 0)return 1;let a=td(n,i);if(a!==0)return a}return 0}function td(e,t){let n=Q(e),r=Q(t);return n!==void 0&&r!==void 0?$(n,r):n===void 0?r===void 0?Math.sign(e.localeCompare(t)):1:-1}function nd(e){let t=gs();return{cwd:e.cwd,provider:e.provider,commandModules:e.commandModules??[],commandHostAdapters:e.commandHostAdapters??{settings:{read:()=>J(t),write:e=>Y(t,e)}},backgroundTaskRunners:e.backgroundTaskRunners??(0,l.createDefaultBackgroundTaskRunners)(),subagentRunnerFactory:e.subagentRunnerFactory,sessionStore:`sessionStore`in e?e.sessionStore:Ml(e.cwd),transportRegistry:e.transportRegistry,reloadPluginCommandSource:e.reloadPluginCommandSource??(()=>{})}}function rd(e){let t=(0,g.dirname)((0,ee.fileURLToPath)(e)),n=[(0,g.join)(t,`..`,`..`,`package.json`),(0,g.join)(t,`..`,`package.json`)];for(let e of n)try{let t=(0,m.readFileSync)(e,`utf-8`),n=JSON.parse(t);if(n.version!==void 0&&n.name!==void 0)return n.version}catch{continue}return`0.0.0`}function id(e=process.env.HOME??process.env.USERPROFILE??`/`){return(0,g.join)(e,`.robota`,`update-check.json`)}function ad(e){if((0,m.existsSync)(e))try{return bd(JSON.parse((0,m.readFileSync)(e,`utf8`)))}catch{return}}function od(e,t){(0,m.mkdirSync)((0,g.dirname)(e),{recursive:!0}),(0,m.writeFileSync)(e,JSON.stringify(t,null,2)+`
101
+ `)}function zu(e){let t=Fu(Iu(e));return(0,u.createZodFunctionTool)(`ExecuteCommand`,Ru(e.commandDescriptors),Nu(t),async n=>{let r=t.parse(n),i=k(r.command);return e.isModelInvocable(i)?ut(i,await e.execute(i,r.args??``)):JSON.stringify({success:!1,command:i,error:`Command is not model-invocable: ${i}`})})}const Bu=[`Allow`,`Deny`];function Vu(e){let t=Object.entries(e);return t.length===0?`(no arguments)`:t.map(([e,t])=>`${e}: ${typeof t==`string`?t:JSON.stringify(t)}`).join(`, `)}async function Hu(e,t,n){return e.writeLine(``),e.writeError(`[Permission Required] Tool: ${t}`),e.writeLine(` ${Vu(n)}`),e.writeLine(``),await e.select(Bu,0)===0}const Uu={usedTokens:0,maxTokens:2e5,usedPercentage:0,remainingPercentage:100},Wu={sessionId:`test-session-id`,updatedAt:new Date().toISOString(),entries:[]},Gu={id:``,parentSessionId:`test-session-id`,waitPolicy:`wait_all`,taskIds:[],status:`completed`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),results:[]};function Ku(e){return{submit:()=>Promise.resolve(),abort:()=>{},cancelQueue:()=>{},shutdown:()=>Promise.resolve(),isExecuting:()=>!1,getPendingPrompt:()=>null,getMessages:()=>[],getContextState:()=>({...Uu}),getSession:()=>({getSessionId:()=>`test-session-id`}),getCwd:()=>`/workspace`,executeCommand:()=>Promise.resolve(null),listCommands:()=>[],on:()=>{},off:()=>{},listBackgroundTasks:()=>[],getBackgroundTask:()=>void 0,cancelBackgroundTask:()=>Promise.resolve(),closeBackgroundTask:()=>Promise.resolve(),sendBackgroundTask:()=>Promise.resolve(),readBackgroundTaskLog:()=>Promise.resolve({taskId:``,lines:[]}),listBackgroundJobGroups:()=>[],getBackgroundJobGroup:()=>void 0,createBackgroundJobGroup:()=>({...Gu}),waitBackgroundJobGroup:()=>Promise.resolve({...Gu}),getExecutionWorkspaceSnapshot:()=>({...Wu}),listAgentDefinitions:()=>[],listAgentJobs:()=>[],spawnAgentJob:()=>Promise.resolve({id:`agent_1`,type:`general-purpose`,label:`general-purpose`,parentSessionId:`test-session-id`,status:`running`,mode:`background`,depth:1,cwd:`/workspace`,promptPreview:``,updatedAt:new Date().toISOString()}),sendAgentJob:()=>Promise.resolve(),cancelAgentJob:()=>Promise.resolve(),closeAgentJob:()=>Promise.resolve(),...e}}function qu(){let e=gs();return{deleted:bs(e),path:e}}function Ju(e){try{let t=Yu(e);if(!t)return;let n=(0,m.readFileSync)((0,g.join)(t,`HEAD`),`utf8`).trim();if(!n)return;if(n.startsWith(`ref: `)){let e=n.slice(5).trim();return e.startsWith(`refs/heads/`)?e.slice(11):e}return n.slice(0,7)}catch{return}}function Yu(e){let t=(0,g.resolve)(e),n=(0,g.dirname)(t);for(;n!==t;){let e=Xu((0,g.join)(t,`.git`),t);if(e)return e;t=n,n=(0,g.dirname)(t)}return Xu((0,g.join)(t,`.git`),t)}function Xu(e,t){if(!(0,m.existsSync)(e))return;let n=(0,m.lstatSync)(e);if(n.isDirectory())return e;if(!n.isFile())return;let r=(0,m.readFileSync)(e,`utf8`).trim();if(!r.startsWith(`gitdir:`))return;let i=r.slice(7).trim();return(0,g.isAbsolute)(i)?i:(0,g.resolve)(t,i)}function Zu(e,t){let n=$u(e),r=$u(t);if(n===void 0||r===void 0)return Math.sign(e.localeCompare(t));let i=$(n.major,r.major)||$(n.minor,r.minor)||$(n.patch,r.patch);return i===0?ed(n.prerelease,r.prerelease):i}function Qu(e,t){return Zu(e,t)>0}function $u(e){let[t,n]=(e.trim().replace(/^v/,``).split(`+`)[0]??``).split(`-`,2),[r,i,a]=t.split(`.`),o=Q(r),s=Q(i),c=Q(a);if(!(o===void 0||s===void 0||c===void 0))return{major:o,minor:s,patch:c,prerelease:n?n.split(`.`):[]}}function Q(e){if(!(e===void 0||!/^\d+$/.test(e)))return Number(e)}function $(e,t){return Math.sign(e-t)}function ed(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return 1;if(t.length===0)return-1;let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r],i=t[r];if(n===void 0)return-1;if(i===void 0)return 1;let a=td(n,i);if(a!==0)return a}return 0}function td(e,t){let n=Q(e),r=Q(t);return n!==void 0&&r!==void 0?$(n,r):n===void 0?r===void 0?Math.sign(e.localeCompare(t)):1:-1}function nd(e){let t=gs(),n={settings:{read:()=>J(t),write:e=>Y(t,e)}},r=e.backgroundTaskRunners??(0,l.createDefaultBackgroundTaskRunners)(),i=e.commandModules??[],a=e.commandHostAdapters??n,o=`sessionStore`in e?e.sessionStore:Ml(e.cwd);return{cwd:e.cwd,provider:e.provider,commandModules:i,commandHostAdapters:a,backgroundTaskRunners:r,subagentRunnerFactory:e.subagentRunnerFactory,sessionStore:o,transportRegistry:e.transportRegistry,reloadPluginCommandSource:e.reloadPluginCommandSource??(()=>{}),createSession(t){return new jl({cwd:e.cwd,provider:e.provider,backgroundTaskRunners:r,subagentRunnerFactory:e.subagentRunnerFactory,commandModules:i,commandHostAdapters:a,permissionMode:t.permissionMode,maxTurns:t.maxTurns,sessionStore:t.sessionStore,sessionName:t.sessionName,bare:t.bare,allowedTools:t.allowedTools,appendSystemPrompt:t.appendSystemPrompt,systemPrompt:t.systemPrompt,shellExec:t.shellExec,agentName:t.agentName})}}}function rd(e){let t=(0,g.dirname)((0,ee.fileURLToPath)(e)),n=[(0,g.join)(t,`..`,`..`,`package.json`),(0,g.join)(t,`..`,`package.json`)];for(let e of n)try{let t=(0,m.readFileSync)(e,`utf-8`),n=JSON.parse(t);if(n.version!==void 0&&n.name!==void 0)return n.version}catch{continue}return`0.0.0`}function id(e=process.env.HOME??process.env.USERPROFILE??`/`){return(0,g.join)(e,`.robota`,`update-check.json`)}function ad(e){if((0,m.existsSync)(e))try{return bd(JSON.parse((0,m.readFileSync)(e,`utf8`)))}catch{return}}function od(e,t){(0,m.mkdirSync)((0,g.dirname)(e),{recursive:!0}),(0,m.writeFileSync)(e,JSON.stringify(t,null,2)+`
102
102
  `,`utf8`)}async function sd(e){if(e.disabled===!0)return{status:`skipped`,reason:`disabled`};let t=e.packageName??`@robota-sdk/agent-cli`,n=e.cachePath??id(),r=e.now??new Date,i=e.ttlMs??864e5;if(e.force!==!0){let a=ad(n);if(a!==void 0&&gd(a,r,i,t))return md(a,e.currentVersion)}let a=await cd(e,t,n,r);return typeof a==`string`?hd(e.currentVersion,a):a}async function cd(e,t,n,r){let i=await _d({fetchImpl:e.fetchImpl??fetch,packageName:t,registryUrl:e.registryUrl??`https://registry.npmjs.org`,timeoutMs:e.timeoutMs??1500});return i.ok?(ld(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,latestVersion:i.version}),i.version):(ld(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,errorMessage:i.errorMessage}),{status:`error`,errorMessage:i.errorMessage})}function ld(e,t){try{od(e,t)}catch{}}async function ud(e){let t=await sd(e);return t.status===`update_available`?t.notice:void 0}function dd(e){return e.printMode===!1&&e.disableUpdateCheck===!1}function fd(e){return[`Robota update available: ${e.currentVersion} -> ${e.latestVersion}.`,`Run ${e.installCommand}`].join(` `)}function pd(e){return e.status===`update_available`?fd(e.notice):e.status===`current`?`Robota is up to date (${e.currentVersion}).`:e.status===`skipped`?`Robota update check skipped.`:`Robota update check failed: ${e.errorMessage}`}function md(e,t){return e.errorMessage===void 0?e.latestVersion===void 0?{status:`error`,errorMessage:`Cached update check has no latest version`}:hd(t,e.latestVersion):{status:`error`,errorMessage:e.errorMessage}}function hd(e,t){return Qu(t,e)?{status:`update_available`,notice:{currentVersion:e,latestVersion:t,installCommand:`npm install -g '@robota-sdk/agent-cli@latest'`}}:{status:`current`,currentVersion:e,latestVersion:t}}function gd(e,t,n,r){if(e.packageName!==r)return!1;let i=Date.parse(e.checkedAt);return Number.isFinite(i)?t.getTime()-i<n:!1}async function _d(e){try{return{ok:!0,version:await vd(e)}}catch(e){return{ok:!1,errorMessage:e instanceof Error?e.message:String(e)}}}async function vd(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=yd(e.registryUrl,e.packageName),r=await e.fetchImpl(n,{headers:{accept:`application/json`},signal:t.signal});if(!r.ok)throw Error(`registry responded with HTTP ${r.status}`);let i=(await r.json())[`dist-tags`]?.latest;if(typeof i!=`string`||i.trim().length===0)throw Error(`registry metadata is missing dist-tags.latest`);return i}finally{clearTimeout(n)}}function yd(e,t){return`${e.replace(/\/+$/,``)}/${encodeURIComponent(t)}`}function bd(e){if(!xd(e))return;let t=e;if(typeof t.packageName==`string`&&typeof t.checkedAt==`string`&&typeof t.currentVersion==`string`&&(t.latestVersion===void 0||typeof t.latestVersion==`string`)&&(t.errorMessage===void 0||typeof t.errorMessage==`string`))return{packageName:t.packageName,checkedAt:t.checkedAt,currentVersion:t.currentVersion,...t.latestVersion!==void 0&&{latestVersion:t.latestVersion},...t.errorMessage!==void 0&&{errorMessage:t.errorMessage}}}function xd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}exports.AUTO_COMPACT_THRESHOLD_SETTINGS_KEY=Ns,exports.AgentExecutor=Pi,exports.BACKGROUND_COMMAND_DESCRIPTION=`List and control background tasks`,exports.BACKGROUND_COMMAND_USAGE=`Usage: background list | background read <task-id> [offset] | background cancel <task-id> | background close <task-id>`,exports.BUILT_IN_AGENTS=$e,exports.BackgroundJobOrchestrator=ne,exports.BuiltinCommandSource=Vo,exports.BundlePluginInstaller=go,exports.BundlePluginLoader=ho,exports.CLEAR_COMMAND_DESCRIPTION=`Clear conversation history`,exports.CLI_UPDATE_CACHE_TTL_MS=864e5,exports.CLI_UPDATE_PACKAGE_NAME=`@robota-sdk/agent-cli`,exports.CLI_UPDATE_REGISTRY_URL=`https://registry.npmjs.org`,exports.CLI_UPDATE_TIMEOUT_MS=1500,exports.COST_COMMAND_DESCRIPTION=`Show session info`,exports.CommandRegistry=Lo,exports.DEFAULT_AUTO_COMPACT_THRESHOLD=Ms,exports.DEFAULT_STATUS_LINE_COMMAND_SETTINGS=Rc,exports.EXECUTION_ORIGIN_METADATA_KEYS=x,exports.EXIT_COMMAND_DESCRIPTION=`Exit CLI`,exports.EditCheckpointStore=R,exports.HELP_COMMAND_DESCRIPTION=`Show available commands`,exports.InteractiveSession=jl,exports.LANGUAGE_COMMAND_ARGUMENT_HINT=`<code>`,exports.LANGUAGE_COMMAND_DESCRIPTION=`Set response language`,exports.MEMORY_COMMAND_ARGUMENT_HINT=`list | show [topic] | add <user|feedback|project|reference> <topic> <text> | pending | approve <id> | reject <id> | used`,exports.MEMORY_COMMAND_DESCRIPTION=`Project memory command. Use it to inspect project memory when stored context may help, save durable preferences, project conventions, feedback, or references worth reusing across sessions, review pending candidates, and report memory provenance. Do not store secrets, credentials, or transient facts.`,exports.MEMORY_COMMAND_USAGE=`Usage: memory list | memory show [topic] | memory add <user|feedback|project|reference> <topic> <text> | memory pending | memory approve <id> | memory reject <id> | memory used`,exports.MEMORY_INDEX_MAX_BYTES=Za,exports.MEMORY_INDEX_MAX_LINES=200,exports.MODEL_COMMAND_ARGUMENT_HINT=`<model-id>`,exports.MODEL_COMMAND_DESCRIPTION=`Change AI model`,exports.MODEL_COMMAND_TOOL_PREFIX=it,exports.MarketplaceClient=bo,exports.PERMISSIONS_COMMAND_DESCRIPTION=`Show/change permission mode and permission rules`,exports.PERMISSION_MODE_ARGUMENT_HINT=`plan | default | acceptEdits | bypassPermissions`,exports.PERMISSION_MODE_COMMAND_DESCRIPTION=`Show/change permission mode`,exports.PLUGIN_COMMAND_ARGUMENT_HINT=`manage | install <name@marketplace> | uninstall <name@marketplace> | enable <name@marketplace> | disable <name@marketplace> | marketplace <action>`,exports.PLUGIN_COMMAND_DESCRIPTION=`Manage plugins`,exports.PROVIDER_SAFE_TOOL_NAME_PATTERN=at,exports.PluginCommandSource=js,exports.PluginSettingsStore=uo,exports.ProjectMemoryStore=oo,exports.PromptExecutor=Ii,exports.RECOMMENDED_RESPONSE_LANGUAGES=Cc,exports.RELOAD_PLUGINS_COMMAND_DESCRIPTION=`Reload all plugin resources`,exports.RENAME_COMMAND_DESCRIPTION=`Rename the current session`,exports.RENAME_COMMAND_USAGE=`Usage: rename <name>`,exports.RESUME_COMMAND_DESCRIPTION=`Resume a previous session`,exports.REWIND_COMMAND_ARGUMENT_HINT=`list | inspect CHECKPOINT_ID | restore CHECKPOINT_ID | code CHECKPOINT_ID | rollback CHECKPOINT_ID`,exports.REWIND_COMMAND_DESCRIPTION=`List, inspect, restore, or rollback edit checkpoints.`,exports.STATUSLINE_COMMAND_ARGUMENT_HINT=`on | off | reset | git on | git off`,exports.STATUSLINE_COMMAND_DESCRIPTION=`Configure TUI status-line visibility and fields such as model, context, tokens, session, and git branch.`,exports.SkillCommandSource=Mi,exports.SystemCommandExecutor=Ro,exports.USER_LOCAL_MEMORY_CATEGORIES=tu,exports.USER_LOCAL_STORAGE_CATEGORIES=Wl,exports.USER_LOCAL_STORAGE_CATEGORY_DEFINITIONS=Gl,exports.VALIDATE_SESSION_COMMAND_DESCRIPTION=`Validate current session replay log`,exports.VALID_PERMISSION_MODES=Dc,exports.addCommandContextReference=Hs,exports.applyActiveModelChange=ws,exports.applyProviderConfiguration=Ss,exports.applyProviderSwitch=Cs,exports.applyStatusLineSettings=Hc,exports.assembleSubagentPrompt=rt,exports.buildBackgroundCommandSubcommands=Xs,exports.buildLanguageCommandSubcommands=wc,exports.buildMemoryCommandSubcommands=pl,exports.buildModelCommandSubcommands=oc,exports.buildPermissionModeSubcommands=Oc,exports.buildPluginCommandSubcommands=qc,exports.buildPromptWithFileReferences=mn,exports.buildProviderProfile=Jo,exports.buildProviderSetupPatch=qo,exports.buildRewindCommandSubcommands=rl,exports.buildStatusLineCommandSubcommands=zc,exports.cancelCommandBackgroundTask=ic,exports.checkForCliUpdate=sd,exports.checkSettingsDocument=rs,exports.checkSettingsFile=cs,exports.clearCommandContextReferences=Ws,exports.clearContextReferences=an,exports.clearConversationHistory=Jc,exports.closeCommandBackgroundTask=ac,exports.compactCommandContext=Bs,exports.compareSemverVersions=Zu,exports.createAgentRuntime=nd,exports.createAgentTool=Pt,exports.createBackgroundGroupExecutionEntryId=w,exports.createBackgroundProcessTool=mi,exports.createBackgroundTaskExecutionEntryId=C,exports.createBuiltinCommandModule=Ho,exports.createCommandExecutionTool=zu,exports.createCommandMemoryStores=gl,exports.createCommandPendingMemoryStore=hl,exports.createCommandProjectMemoryStore=ml,exports.createContextReferenceItem=tn,exports.createDefaultTools=zr,exports.createExecutionOriginMetadata=T,exports.createExecutionWorkspaceSnapshot=fe,exports.createExecutionWorkspaceTaskSpawner=Me,exports.createInProcessSubagentRunner=wt,exports.createLineDetailPage=O,exports.createMainThreadDetailPage=ke,exports.createMainThreadExecutionEntryId=S,exports.createModelCommandToolProjection=ct,exports.createPluginRegistryReloadRequestedEffect=Gc,exports.createPluginTuiRequestedEffect=Wc,exports.createProjectSessionStore=Ml,exports.createProjectedCommandExecutionTools=dt,exports.createPromptFileReferenceHistoryEntry=_n,exports.createProviderFromSettings=As,exports.createProviderSafeModelCommandToolName=st,exports.createQuery=Ul,exports.createSessionExitRequestedEffect=Qc,exports.createSessionPickerRequestedEffect=Zc,exports.createSessionRenamedEffect=Xc,exports.createSubagentLogger=ta,exports.createSubagentSession=vt,exports.createSystemCommands=zo,exports.createTestInteractiveSession=Ku,exports.deleteProviderProfile=Go,exports.deleteSettings=bs,exports.deleteUserLocalMemoryItem=Su,exports.disableUserLocalMemoryItem=xu,exports.discoverTaskFiles=Ga,exports.evaluateReversibleToolSafety=Bi,exports.executeSkill=Tl,exports.formatCliUpdateCheckMessage=pd,exports.formatCliUpdateNotice=fd,exports.formatCommandBackgroundTask=Zs,exports.formatCommandBackgroundTaskList=Qs,exports.formatCommandHelpMessage=Ys,exports.formatCommandPermissionsMessage=Lc,exports.formatCommandSessionReplayValidationReport=tl,Object.defineProperty(exports,`formatEnvReference`,{enumerable:!0,get:function(){return c.formatEnvReference}}),exports.formatInvalidPermissionModeMessage=jc,exports.formatLanguageUsageMessage=Ec,exports.formatModelCommandUsageMessage=sc,exports.formatModelCommandUsageMessageAsync=cc,exports.formatProjectedModelCommandToolPromptDescription=lt,exports.formatPromptFileReferenceDiagnostics=gn,exports.formatTaskContext=Ja,exports.getBuiltInAgent=et,exports.getForkWorkerSuffix=nt,exports.getProviderSettingsPaths=hs,exports.getStartupCliUpdateNotice=ud,exports.getSubagentSuffix=tt,exports.getUserSettingsPath=gs,exports.getUserUpdateCheckCachePath=id,exports.hasBlockingPromptFileReferenceDiagnostics=hn,exports.hasSensitiveCommandMemoryContent=vl,Object.defineProperty(exports,`hasUsableSecretReference`,{enumerable:!0,get:function(){return c.hasUsableSecretReference}}),exports.inspectCommandEditCheckpoint=al,exports.inspectUserLocalMemoryItem=bu,exports.inspectUserLocalStorage=eu,exports.isCommandMemoryType=_l,Object.defineProperty(exports,`isEnvReference`,{enumerable:!0,get:function(){return c.isEnvReference}}),exports.isMemoryType=$a,exports.isNewerSemverVersion=Qu,exports.isPermissionMode=Ac,exports.isStatusLineCommandSettingsPatch=Bc,exports.listActiveContextReferences=on,exports.listCommandBackgroundTasks=nc,exports.listCommandContextReferences=Vs,exports.listCommandEditCheckpoints=il,exports.listCommandSessionAllowedTools=Fc,exports.listCommandUsedMemoryReferences=yl,exports.listResumableSessionSummaries=Nl,exports.listUserLocalMemoryItems=yu,exports.loadTaskContext=Ya,exports.mergeProviderPatch=Yo,exports.mergeProviders=fs,exports.mergeSettings=ds,exports.normalizeModelCommandName=k,exports.parseCommandBackgroundLogCursor=$s,exports.parseExecutionWorkspaceEntryId=de,exports.parseFrontmatter=Oi,exports.parseLanguageArgument=Tc,exports.parsePermissionModeArgument=kc,exports.parsePromptFileReferences=xn,exports.parseSessionNameArgument=Yc,exports.parseTaskFile=Ka,exports.planSelfHostingVerification=ju,exports.preprocessShellCommands=Sl,exports.probeProviderProfile=ns,exports.projectPaths=L,exports.promptForApproval=Hu,exports.readAutoCompactThreshold=Fs,exports.readAutoCompactThresholdSource=Is,exports.readCommandBackgroundTaskLog=rc,exports.readCommandContextState=Ps,exports.readCommandPermissionMode=Nc,exports.readCommandPermissionsState=Ic,exports.readCommandSessionInfo=$c,exports.readCurrentGitBranch=Wa,exports.readEnabledUserLocalMemoryItem=Cu,exports.readMergedProviderSettings=Os,exports.readMergedProviderSettingsFromPaths=ls,exports.readPackageVersion=rd,exports.readProviderSettings=ks,exports.readSettings=J,exports.readStatusLineSettings=Vc,exports.readUpdateCheckCache=ad,exports.recordCommandMemoryEvent=bl,exports.removeCommandContextReference=Us,exports.removeContextReference=rn,exports.resetAutoCompactThresholdSetting=zs,exports.resetUserConfig=qu,exports.resolveActiveProvider=ps,exports.resolveActiveProviderModelCatalog=lc,exports.resolveActiveProviderModelCatalogState=uc,Object.defineProperty(exports,`resolveEnvReference`,{enumerable:!0,get:function(){return c.resolveEnvReference}}),exports.resolveGitBranch=Ju,exports.resolveLatestSessionId=Pl,exports.resolvePermissionModeAdapter=Mc,exports.resolvePluginCommandAdapter=Kc,exports.resolvePromptFileReferencePaths=kn,exports.resolvePromptFileReferences=On,exports.resolveProviderSettingsWriteTargetPath=xs,exports.resolveSessionIdByIdOrName=Fl,exports.resolveSettingsPathForScope=_s,exports.resolveSubagentLogDir=na,exports.resolveUserLocalStorageRoot=Zl,exports.restoreCommandEditCheckpoint=ol,exports.retrieveAgentToolDeps=A,exports.rollbackCommandEditCheckpoint=sl,exports.sanitizeProviderProfileName=qs,exports.selectRelevantTasks=qa,exports.setCommandAutoCompactThreshold=Ls,exports.setCurrentProvider=Wo,exports.setUserLocalMemoryItem=vu,exports.shouldRunStartupCliUpdateCheck=dd,exports.storeAgentToolDeps=kt,exports.substituteVariables=xl,exports.suggestProviderProfileName=Ks,exports.summarizeBackgroundJobGroup=se,exports.testProviderProfileCommand=ts,exports.toContextReferenceRecords=sn,exports.toPromptFileReferenceRecords=P,exports.transitionSelfHostingLoop=Mu,exports.updateModelInSettings=vs,exports.updateTaskFileStatus=Xa,exports.upsertContextReference=nn,exports.upsertProviderProfile=Uo,exports.userPaths=fr,exports.validateCommandSessionReplayLog=el,exports.validateProviderProfile=Ko,exports.wrapEditCheckpointTools=xi,exports.wrapReversibleExecutionTools=Vi,exports.writeAutoCompactThresholdSetting=Rs,exports.writeCommandPermissionMode=Pc,exports.writeSettings=Y,exports.writeUpdateCheckCache=od;
@@ -2395,6 +2395,8 @@ interface IInteractiveSessionStandardOptions {
2395
2395
  allowedTools?: string[];
2396
2396
  /** Text to append to the system prompt. */
2397
2397
  appendSystemPrompt?: string;
2398
+ /** Replace the entire system prompt with this string. Takes precedence over the default builder. */
2399
+ systemPrompt?: string;
2398
2400
  /** Override config language (e.g., "ko", "en"). Injected into system prompt. */
2399
2401
  language?: string;
2400
2402
  /** Runtime-composed background task runners. */
@@ -3034,6 +3036,20 @@ interface IAgentRuntimeConfig {
3034
3036
  transportRegistry?: ITransportRegistryView<IInteractiveSession>;
3035
3037
  reloadPluginCommandSource?: (registry: CommandRegistry) => void;
3036
3038
  }
3039
+ /** Session-specific options for IAgentRuntime.createSession(). Runtime fields (cwd, provider, etc.) are inherited automatically. */
3040
+ interface IHeadlessSessionOptions {
3041
+ permissionMode?: TPermissionMode;
3042
+ maxTurns?: number;
3043
+ sessionStore?: IInteractiveSessionStore;
3044
+ sessionName?: string;
3045
+ bare?: boolean;
3046
+ allowedTools?: string[];
3047
+ appendSystemPrompt?: string;
3048
+ /** Replace the entire system prompt. Takes precedence over the default builder. */
3049
+ systemPrompt?: string;
3050
+ shellExec?: TShellExecFn;
3051
+ agentName?: string;
3052
+ }
3037
3053
  interface IAgentRuntime {
3038
3054
  readonly cwd: string;
3039
3055
  readonly provider: IAIProvider;
@@ -3044,6 +3060,7 @@ interface IAgentRuntime {
3044
3060
  readonly sessionStore: IInteractiveSessionStore | undefined;
3045
3061
  readonly transportRegistry: ITransportRegistryView<IInteractiveSession> | undefined;
3046
3062
  readonly reloadPluginCommandSource: (registry: CommandRegistry) => void;
3063
+ createSession(opts: IHeadlessSessionOptions): InteractiveSession;
3047
3064
  }
3048
3065
  declare function createAgentRuntime(config: IAgentRuntimeConfig): IAgentRuntime;
3049
3066
  //#endregion
@@ -3106,5 +3123,5 @@ declare function shouldRunStartupCliUpdateCheck(input: IStartupCliUpdatePolicyIn
3106
3123
  declare function formatCliUpdateNotice(notice: ICliUpdateNotice): string;
3107
3124
  declare function formatCliUpdateCheckMessage(result: TCliUpdateCheckResult): string;
3108
3125
  //#endregion
3109
- export { AUTO_COMPACT_THRESHOLD_SETTINGS_KEY, AgentExecutor, BACKGROUND_COMMAND_DESCRIPTION, BACKGROUND_COMMAND_USAGE, BUILT_IN_AGENTS, BackgroundJobOrchestrator, BuiltinCommandSource, BundlePluginInstaller, BundlePluginLoader, CLEAR_COMMAND_DESCRIPTION, CLI_UPDATE_CACHE_TTL_MS, CLI_UPDATE_PACKAGE_NAME, CLI_UPDATE_REGISTRY_URL, CLI_UPDATE_TIMEOUT_MS, COST_COMMAND_DESCRIPTION, CommandRegistry, DEFAULT_AUTO_COMPACT_THRESHOLD, DEFAULT_STATUS_LINE_COMMAND_SETTINGS, EXECUTION_ORIGIN_METADATA_KEYS, EXIT_COMMAND_DESCRIPTION, EditCheckpointStore, HELP_COMMAND_DESCRIPTION, type IActiveModelChangeOptions, type IActiveModelChangeResult, type IActiveProviderModelCatalogState, type IAgentBackgroundTaskRequest, type IAgentDefinition, type IAgentExecutorOptions, type IAgentJobHostContext, type IAgentRuntime, type IAgentRuntimeConfig, type IAgentSession, type IAgentToolDeps, type IAppendMemoryInput, type IAppendMemoryResult, type IBackgroundJobGroupCreateRequest, type IBackgroundJobGroupState, type IBackgroundJobGroupSummary, type IBackgroundJobOrchestratorOptions, type IBackgroundJobResultEnvelope, type IBackgroundProcessToolDeps, type IBackgroundTaskError, type IBackgroundTaskHandle, type IBackgroundTaskInput, type IBackgroundTaskListFilter, type IBackgroundTaskLogCursor, type IBackgroundTaskLogPage, type IBackgroundTaskManager, type IBackgroundTaskManagerOptions, type IBackgroundTaskResult, type IBackgroundTaskRunner, type IBackgroundTaskSpawnerGroupRequest, type IBackgroundTaskStart, type IBackgroundTaskState, type IBaseBackgroundTaskRequest, type IBuildModelCommandSubcommandsOptions, type IBundlePluginFeatures, type IBundlePluginInstallerOptions, type IBundlePluginManifest, type IBundleSkill, type ICapabilityDescriptor, type ICheckForCliUpdateOptions, type ICliUpdateNotice, type ICommand, type ICommandAvailablePlugin, type ICommandChoicePromptOption, type ICommandExecutionToolDeps, type ICommandHostAdapters, type ICommandHostContext, type ICommandInstalledPlugin, type ICommandInteraction, type ICommandListEntry, type ICommandMarketplaceSource, type ICommandMemoryStores, type ICommandModule, type ICommandPendingMemoryStore, type ICommandPermissionModeAdapter, type ICommandPickerAdapter, type ICommandPluginAdapter, type ICommandPluginReloadResult, type ICommandProcessAdapter, type ICommandProjectMemoryStore, type ICommandResult, type ICommandSessionInfo, type ICommandSessionReplayValidationReport, type ICommandSessionRuntime, type ICommandSettingsAdapter, type ICommandSettingsDocument, type ICommandSkillListEntry, type ICommandSource, type ICompactContextResult, type IConfigurableTransport, type IContextFileRefreshedEvent, type IContextReferenceAddResult, type IContextReferenceClearResult, type IContextReferenceInventoryLimits, type IContextReferenceItem, type IContextReferenceRemoveResult, type IContextReferenceUpsertResult, type ICreateExecutionWorkspaceSnapshotInput, type ICreateExecutionWorkspaceTaskSpawnerOptions, type ICreateLimitedOutputCaptureOptions, type ICreateLineDetailPageInput, type ICreateMainThreadDetailPageInput, type ICreateMainThreadEntryInput, type ICreateQueryOptions, type IDiffLine, type IEditCheckpointFileInspection, type IEditCheckpointFileRecord, type IEditCheckpointInspection, type IEditCheckpointInspectionPlan, type IEditCheckpointManifest, type IEditCheckpointRecorder, type IEditCheckpointRestoreResult, type IEditCheckpointSummary, type IEditCheckpointTurnInput, type IExecutionDetailCursor, type IExecutionDetailPage, type IExecutionDetailRecord, type IExecutionOrigin, type IExecutionResult, type IExecutionWorkspaceEntry, type IExecutionWorkspaceEntryRef, type IExecutionWorkspaceEvent, type IExecutionWorkspaceFilter, type IExecutionWorkspaceSnapshot, type IExecutionWorkspaceSnapshotOptions, type IExecutionWorkspaceTaskSpawner, type IForkExecutionOptions, type IInProcessSubagentRunnerDeps, type IInspectUserLocalStorageOptions, type IInstalledPluginRecord, type IInteractiveSession, type IInteractiveSessionEvents, type IInteractiveSessionRecord, type IInteractiveSessionShutdownOptions, type IInteractiveSessionStore, type IKnownMarketplaceEntry, type ILegacyProviderSettings, type ILimitedOutputCapture, type ILoadedBundlePlugin, type IMarketplaceClientOptions, type IMarketplaceManifest, type IMarketplacePluginEntry, type IMemoryCandidate, type IMemoryEvent, type IMemoryPendingRecord, type IMemoryReference, type IModelCommandModuleOptions, type IModelCommandSettingsAdapter, type IModelCommandToolProjection, type IPermissionsCommandState, type IPluginSettings, type IPreparedSubagentWorktree, type IProcessBackgroundTaskRequest, type IProjectMemorySummary, type IProjectedCommandExecutionToolsDeps, type IProjectedModelCommandTool, type IPromptExecutorOptions, type IPromptFileReferenceDiagnostic, type IPromptFileReferenceHistoryData, type IPromptFileReferenceLimits, type IPromptFileReferenceRecord, type IPromptFileReferenceResolveOptions, type IPromptFileReferenceToken, type IPromptProvider, type IProviderCommandModuleOptions, type IProviderCommandSettingsAdapter, type IProviderProfileNameSuggestionInput, type IProviderProfileNameSuggestionOptions, type IProviderProfileSettings, type IProviderSettingsBuildOptions, type IProviderSettingsWriteTargetOptions, type IProviderSetupInput, type IProviderSetupPatch, type IProviderSwitchOptions, type IReadProviderSettingsOptions, type IResetUserConfigResult, type IResolveActiveProviderModelCatalogStateOptions, type IResolveUserLocalStorageRootOptions, type IResolvedPromptFileReference, type IResolvedPromptFileReferences, type IResumableSessionSummary, type IReversibleExecutionOptions, type IReversibleToolSafetyContext, type IReversibleToolSafetyInput, type IReversibleToolSafetyReport, type ISelfHostingVerificationPlan, type ISelfHostingVerificationPlanInput, type ISelfHostingVerificationStep, type ISerializableProviderProfile, type ISkillActivationEvent, type ISkillActivationHistoryData, type ISkillExecutionCallbacks, type ISkillExecutionResult, type ISpawnAgentTaskRequest, type ISpawnProcessTaskRequest, type IStartupCliUpdatePolicyInput, type IStartupMemory, type IStatusLineCommandSettings, type ISubagentJobHandle, type ISubagentJobResult, type ISubagentJobStart, type ISubagentJobState, type ISubagentManager, type ISubagentManagerOptions, type ISubagentOptions, type ISubagentPromptOptions, type ISubagentRunner, type ISubagentSpawnRequest, type ISubagentWorktreeAdapter, type ISubagentWorktreePrepareRequest, type ISystemCommand, type ITaskContextFile, type ITaskSelectionOptions, type IToolState, type IToolSummary, type ITransportAdapter, type ITransportConfig, type IUpdateCheckCache, type IUpdateTaskFileStatusOptions, type IUsageSnapshot, type IUserLocalMemoryDeleteResult, type IUserLocalMemoryItemOptions, type IUserLocalMemoryItemProjection, type IUserLocalMemoryListOptions, type IUserLocalMemoryListProjection, type IUserLocalMemorySetOptions, type IUserLocalStorageCategoryDefinition, type IUserLocalStorageCategoryProjection, type IUserLocalStorageInspection, type IUserLocalStorageItemSummary, type IWorktreeSubagentRunnerOptions, InteractiveSession, LANGUAGE_COMMAND_ARGUMENT_HINT, LANGUAGE_COMMAND_DESCRIPTION, MEMORY_COMMAND_ARGUMENT_HINT, MEMORY_COMMAND_DESCRIPTION, MEMORY_COMMAND_USAGE, MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, MODEL_COMMAND_ARGUMENT_HINT, MODEL_COMMAND_DESCRIPTION, MODEL_COMMAND_TOOL_PREFIX, MarketplaceClient, PERMISSIONS_COMMAND_DESCRIPTION, PERMISSION_MODE_ARGUMENT_HINT, PERMISSION_MODE_COMMAND_DESCRIPTION, PLUGIN_COMMAND_ARGUMENT_HINT, PLUGIN_COMMAND_DESCRIPTION, PROVIDER_SAFE_TOOL_NAME_PATTERN, PluginCommandSource, PluginSettingsStore, ProjectMemoryStore, PromptExecutor, RECOMMENDED_RESPONSE_LANGUAGES, RELOAD_PLUGINS_COMMAND_DESCRIPTION, RENAME_COMMAND_DESCRIPTION, RENAME_COMMAND_USAGE, RESUME_COMMAND_DESCRIPTION, REWIND_COMMAND_ARGUMENT_HINT, REWIND_COMMAND_DESCRIPTION, STATUSLINE_COMMAND_ARGUMENT_HINT, STATUSLINE_COMMAND_DESCRIPTION, SkillCommandSource, type SkillPromptContext, SystemCommandExecutor, type TAutoCompactThreshold, type TAutoCompactThresholdSource, type TBackgroundJobGroupEvent, type TBackgroundJobGroupEventListener, type TBackgroundJobGroupIdFactory, type TBackgroundJobGroupStatus, type TBackgroundJobWaitPolicy, type TBackgroundPermissionPolicy, type TBackgroundPrimitive, type TBackgroundTaskErrorCategory, type TBackgroundTaskEvent, type TBackgroundTaskEventListener, type TBackgroundTaskIdFactory, type TBackgroundTaskIsolation, type TBackgroundTaskKind, type TBackgroundTaskMode, type TBackgroundTaskRequest, type TBackgroundTaskRunnerEvent, type TBackgroundTaskStatus, type TBackgroundTaskTimeoutReason, type TBackgroundTaskTransitionEvent, type TCapabilityKind, type TCapabilitySafety, type TCliUpdateCheckResult, type TCommandEffect, type TCommandInteractionPrompt, type TCommandModuleSessionRequirement, type TCommandResultDataValue, type TContextReferenceLoadType, type TContextReferenceStatus, type TEditCheckpointFileRestoreAction, type TEnabledPlugins, type TExecutionAttention, type TExecutionControl, type TExecutionDetailRecordKind, type TExecutionEntryKind, type TExecutionOriginKind, type TExecutionWorkspaceStatus, type TExecutionWorkspaceUpdateCause, type TExecutionWorkspaceVisibility, type TInstalledPluginsRegistry, type TInteractiveEventName, type TInteractivePermissionHandler, type TInteractiveSessionOptions, type TKnownMarketplacesRegistry, type TMarketplaceSource, type TMemoryCandidateStatus, type TMemoryType, type TPermissionResultValue, type TPluginInstallScope, type TPromptFileReferenceDiagnosticCode, type TPromptFileReferenceReason, type TProviderFactory, type TProviderSettingsDocument, type TRecommendedResponseLanguage, type TReversibleExecutionIsolation, type TReversibleRollbackLayer, type TReversibleSafetyStatus, type TReversibleSideEffect, type TSelfHostingLoopEvent, type TSelfHostingLoopState, type TSelfHostingVerificationPhase, type TSessionFactory, type TSettingsCheck, type TSettingsData, type TSettingsScope, type TShellExecFn, type TSkillActivationInvocation, type TSkillActivationMode, type TSkillActivationSource, type TSkillActivationStatus, type TStatusLineCommandSettingsPatch, type TSubagentJobMode, type TSubagentJobStatus, type TSubagentRunnerFactory, type TSystemCommandLifecycle, type TTaskFileStatus, type TUserLocalMemoryCategory, type TUserLocalMemoryCommandExecutionEffect, type TUserLocalStorageCategory, USER_LOCAL_MEMORY_CATEGORIES, USER_LOCAL_STORAGE_CATEGORIES, USER_LOCAL_STORAGE_CATEGORY_DEFINITIONS, VALIDATE_SESSION_COMMAND_DESCRIPTION, VALID_PERMISSION_MODES, addCommandContextReference, applyActiveModelChange, applyProviderConfiguration, applyProviderSwitch, applyStatusLineSettings, assembleSubagentPrompt, buildBackgroundCommandSubcommands, buildLanguageCommandSubcommands, buildMemoryCommandSubcommands, buildModelCommandSubcommands, buildPermissionModeSubcommands, buildPluginCommandSubcommands, buildPromptWithFileReferences, buildProviderProfile, buildProviderSetupPatch, buildRewindCommandSubcommands, buildStatusLineCommandSubcommands, cancelCommandBackgroundTask, checkForCliUpdate, checkSettingsDocument, checkSettingsFile, clearCommandContextReferences, clearContextReferences, clearConversationHistory, closeCommandBackgroundTask, compactCommandContext, compareSemverVersions, createAgentRuntime, createAgentTool, createBackgroundGroupExecutionEntryId, createBackgroundProcessTool, createBackgroundTaskExecutionEntryId, createBuiltinCommandModule, createCommandExecutionTool, createCommandMemoryStores, createCommandPendingMemoryStore, createCommandProjectMemoryStore, createContextReferenceItem, createDefaultTools, createExecutionOriginMetadata, createExecutionWorkspaceSnapshot, createExecutionWorkspaceTaskSpawner, createInProcessSubagentRunner, createLineDetailPage, createMainThreadDetailPage, createMainThreadExecutionEntryId, createModelCommandToolProjection, createPluginRegistryReloadRequestedEffect, createPluginTuiRequestedEffect, createProjectSessionStore, createProjectedCommandExecutionTools, createPromptFileReferenceHistoryEntry, createProviderFromSettings, createProviderSafeModelCommandToolName, createQuery, createSessionExitRequestedEffect, createSessionPickerRequestedEffect, createSessionRenamedEffect, createSubagentLogger, createSubagentSession, createSystemCommands, createTestInteractiveSession, deleteProviderProfile, deleteSettings, deleteUserLocalMemoryItem, disableUserLocalMemoryItem, discoverTaskFiles, evaluateReversibleToolSafety, executeSkill, formatCliUpdateCheckMessage, formatCliUpdateNotice, formatCommandBackgroundTask, formatCommandBackgroundTaskList, formatCommandHelpMessage, formatCommandPermissionsMessage, formatCommandSessionReplayValidationReport, formatEnvReference, formatInvalidPermissionModeMessage, formatLanguageUsageMessage, formatModelCommandUsageMessage, formatModelCommandUsageMessageAsync, formatProjectedModelCommandToolPromptDescription, formatPromptFileReferenceDiagnostics, formatTaskContext, getBuiltInAgent, getForkWorkerSuffix, getProviderSettingsPaths, getStartupCliUpdateNotice, getSubagentSuffix, getUserSettingsPath, getUserUpdateCheckCachePath, hasBlockingPromptFileReferenceDiagnostics, hasSensitiveCommandMemoryContent, hasUsableSecretReference, inspectCommandEditCheckpoint, inspectUserLocalMemoryItem, inspectUserLocalStorage, isCommandMemoryType, isEnvReference, isMemoryType, isNewerSemverVersion, isPermissionMode, isStatusLineCommandSettingsPatch, listActiveContextReferences, listCommandBackgroundTasks, listCommandContextReferences, listCommandEditCheckpoints, listCommandSessionAllowedTools, listCommandUsedMemoryReferences, listResumableSessionSummaries, listUserLocalMemoryItems, loadTaskContext, mergeProviderPatch, mergeProviders, mergeSettings, normalizeModelCommandName, parseCommandBackgroundLogCursor, parseExecutionWorkspaceEntryId, parseFrontmatter, parseLanguageArgument, parsePermissionModeArgument, parsePromptFileReferences, parseSessionNameArgument, parseTaskFile, planSelfHostingVerification, preprocessShellCommands, probeProviderProfile, projectPaths, promptForApproval, readAutoCompactThreshold, readAutoCompactThresholdSource, readCommandBackgroundTaskLog, readCommandContextState, readCommandPermissionMode, readCommandPermissionsState, readCommandSessionInfo, readCurrentGitBranch, readEnabledUserLocalMemoryItem, readMergedProviderSettings, readMergedProviderSettingsFromPaths, readPackageVersion, readProviderSettings, readSettings, readStatusLineSettings, readUpdateCheckCache, recordCommandMemoryEvent, removeCommandContextReference, removeContextReference, resetAutoCompactThresholdSetting, resetUserConfig, resolveActiveProvider, resolveActiveProviderModelCatalog, resolveActiveProviderModelCatalogState, resolveEnvReference, resolveGitBranch, resolveLatestSessionId, resolvePermissionModeAdapter, resolvePluginCommandAdapter, resolvePromptFileReferencePaths, resolvePromptFileReferences, resolveProviderSettingsWriteTargetPath, resolveSessionIdByIdOrName, resolveSettingsPathForScope, resolveSubagentLogDir, resolveUserLocalStorageRoot, restoreCommandEditCheckpoint, retrieveAgentToolDeps, rollbackCommandEditCheckpoint, sanitizeProviderProfileName, selectRelevantTasks, setCommandAutoCompactThreshold, setCurrentProvider, setUserLocalMemoryItem, shouldRunStartupCliUpdateCheck, storeAgentToolDeps, substituteVariables, suggestProviderProfileName, summarizeBackgroundJobGroup, testProviderProfileCommand, toContextReferenceRecords, toPromptFileReferenceRecords, transitionSelfHostingLoop, updateModelInSettings, updateTaskFileStatus, upsertContextReference, upsertProviderProfile, userPaths, validateCommandSessionReplayLog, validateProviderProfile, wrapEditCheckpointTools, wrapReversibleExecutionTools, writeAutoCompactThresholdSetting, writeCommandPermissionMode, writeSettings, writeUpdateCheckCache };
3126
+ export { AUTO_COMPACT_THRESHOLD_SETTINGS_KEY, AgentExecutor, BACKGROUND_COMMAND_DESCRIPTION, BACKGROUND_COMMAND_USAGE, BUILT_IN_AGENTS, BackgroundJobOrchestrator, BuiltinCommandSource, BundlePluginInstaller, BundlePluginLoader, CLEAR_COMMAND_DESCRIPTION, CLI_UPDATE_CACHE_TTL_MS, CLI_UPDATE_PACKAGE_NAME, CLI_UPDATE_REGISTRY_URL, CLI_UPDATE_TIMEOUT_MS, COST_COMMAND_DESCRIPTION, CommandRegistry, DEFAULT_AUTO_COMPACT_THRESHOLD, DEFAULT_STATUS_LINE_COMMAND_SETTINGS, EXECUTION_ORIGIN_METADATA_KEYS, EXIT_COMMAND_DESCRIPTION, EditCheckpointStore, HELP_COMMAND_DESCRIPTION, type IActiveModelChangeOptions, type IActiveModelChangeResult, type IActiveProviderModelCatalogState, type IAgentBackgroundTaskRequest, type IAgentDefinition, type IAgentExecutorOptions, type IAgentJobHostContext, type IAgentRuntime, type IAgentRuntimeConfig, type IAgentSession, type IAgentToolDeps, type IAppendMemoryInput, type IAppendMemoryResult, type IBackgroundJobGroupCreateRequest, type IBackgroundJobGroupState, type IBackgroundJobGroupSummary, type IBackgroundJobOrchestratorOptions, type IBackgroundJobResultEnvelope, type IBackgroundProcessToolDeps, type IBackgroundTaskError, type IBackgroundTaskHandle, type IBackgroundTaskInput, type IBackgroundTaskListFilter, type IBackgroundTaskLogCursor, type IBackgroundTaskLogPage, type IBackgroundTaskManager, type IBackgroundTaskManagerOptions, type IBackgroundTaskResult, type IBackgroundTaskRunner, type IBackgroundTaskSpawnerGroupRequest, type IBackgroundTaskStart, type IBackgroundTaskState, type IBaseBackgroundTaskRequest, type IBuildModelCommandSubcommandsOptions, type IBundlePluginFeatures, type IBundlePluginInstallerOptions, type IBundlePluginManifest, type IBundleSkill, type ICapabilityDescriptor, type ICheckForCliUpdateOptions, type ICliUpdateNotice, type ICommand, type ICommandAvailablePlugin, type ICommandChoicePromptOption, type ICommandExecutionToolDeps, type ICommandHostAdapters, type ICommandHostContext, type ICommandInstalledPlugin, type ICommandInteraction, type ICommandListEntry, type ICommandMarketplaceSource, type ICommandMemoryStores, type ICommandModule, type ICommandPendingMemoryStore, type ICommandPermissionModeAdapter, type ICommandPickerAdapter, type ICommandPluginAdapter, type ICommandPluginReloadResult, type ICommandProcessAdapter, type ICommandProjectMemoryStore, type ICommandResult, type ICommandSessionInfo, type ICommandSessionReplayValidationReport, type ICommandSessionRuntime, type ICommandSettingsAdapter, type ICommandSettingsDocument, type ICommandSkillListEntry, type ICommandSource, type ICompactContextResult, type IConfigurableTransport, type IContextFileRefreshedEvent, type IContextReferenceAddResult, type IContextReferenceClearResult, type IContextReferenceInventoryLimits, type IContextReferenceItem, type IContextReferenceRemoveResult, type IContextReferenceUpsertResult, type ICreateExecutionWorkspaceSnapshotInput, type ICreateExecutionWorkspaceTaskSpawnerOptions, type ICreateLimitedOutputCaptureOptions, type ICreateLineDetailPageInput, type ICreateMainThreadDetailPageInput, type ICreateMainThreadEntryInput, type ICreateQueryOptions, type IDiffLine, type IEditCheckpointFileInspection, type IEditCheckpointFileRecord, type IEditCheckpointInspection, type IEditCheckpointInspectionPlan, type IEditCheckpointManifest, type IEditCheckpointRecorder, type IEditCheckpointRestoreResult, type IEditCheckpointSummary, type IEditCheckpointTurnInput, type IExecutionDetailCursor, type IExecutionDetailPage, type IExecutionDetailRecord, type IExecutionOrigin, type IExecutionResult, type IExecutionWorkspaceEntry, type IExecutionWorkspaceEntryRef, type IExecutionWorkspaceEvent, type IExecutionWorkspaceFilter, type IExecutionWorkspaceSnapshot, type IExecutionWorkspaceSnapshotOptions, type IExecutionWorkspaceTaskSpawner, type IForkExecutionOptions, type IHeadlessSessionOptions, type IInProcessSubagentRunnerDeps, type IInspectUserLocalStorageOptions, type IInstalledPluginRecord, type IInteractiveSession, type IInteractiveSessionEvents, type IInteractiveSessionRecord, type IInteractiveSessionShutdownOptions, type IInteractiveSessionStore, type IKnownMarketplaceEntry, type ILegacyProviderSettings, type ILimitedOutputCapture, type ILoadedBundlePlugin, type IMarketplaceClientOptions, type IMarketplaceManifest, type IMarketplacePluginEntry, type IMemoryCandidate, type IMemoryEvent, type IMemoryPendingRecord, type IMemoryReference, type IModelCommandModuleOptions, type IModelCommandSettingsAdapter, type IModelCommandToolProjection, type IPermissionsCommandState, type IPluginSettings, type IPreparedSubagentWorktree, type IProcessBackgroundTaskRequest, type IProjectMemorySummary, type IProjectedCommandExecutionToolsDeps, type IProjectedModelCommandTool, type IPromptExecutorOptions, type IPromptFileReferenceDiagnostic, type IPromptFileReferenceHistoryData, type IPromptFileReferenceLimits, type IPromptFileReferenceRecord, type IPromptFileReferenceResolveOptions, type IPromptFileReferenceToken, type IPromptProvider, type IProviderCommandModuleOptions, type IProviderCommandSettingsAdapter, type IProviderProfileNameSuggestionInput, type IProviderProfileNameSuggestionOptions, type IProviderProfileSettings, type IProviderSettingsBuildOptions, type IProviderSettingsWriteTargetOptions, type IProviderSetupInput, type IProviderSetupPatch, type IProviderSwitchOptions, type IReadProviderSettingsOptions, type IResetUserConfigResult, type IResolveActiveProviderModelCatalogStateOptions, type IResolveUserLocalStorageRootOptions, type IResolvedPromptFileReference, type IResolvedPromptFileReferences, type IResumableSessionSummary, type IReversibleExecutionOptions, type IReversibleToolSafetyContext, type IReversibleToolSafetyInput, type IReversibleToolSafetyReport, type ISelfHostingVerificationPlan, type ISelfHostingVerificationPlanInput, type ISelfHostingVerificationStep, type ISerializableProviderProfile, type ISkillActivationEvent, type ISkillActivationHistoryData, type ISkillExecutionCallbacks, type ISkillExecutionResult, type ISpawnAgentTaskRequest, type ISpawnProcessTaskRequest, type IStartupCliUpdatePolicyInput, type IStartupMemory, type IStatusLineCommandSettings, type ISubagentJobHandle, type ISubagentJobResult, type ISubagentJobStart, type ISubagentJobState, type ISubagentManager, type ISubagentManagerOptions, type ISubagentOptions, type ISubagentPromptOptions, type ISubagentRunner, type ISubagentSpawnRequest, type ISubagentWorktreeAdapter, type ISubagentWorktreePrepareRequest, type ISystemCommand, type ITaskContextFile, type ITaskSelectionOptions, type IToolState, type IToolSummary, type ITransportAdapter, type ITransportConfig, type IUpdateCheckCache, type IUpdateTaskFileStatusOptions, type IUsageSnapshot, type IUserLocalMemoryDeleteResult, type IUserLocalMemoryItemOptions, type IUserLocalMemoryItemProjection, type IUserLocalMemoryListOptions, type IUserLocalMemoryListProjection, type IUserLocalMemorySetOptions, type IUserLocalStorageCategoryDefinition, type IUserLocalStorageCategoryProjection, type IUserLocalStorageInspection, type IUserLocalStorageItemSummary, type IWorktreeSubagentRunnerOptions, InteractiveSession, LANGUAGE_COMMAND_ARGUMENT_HINT, LANGUAGE_COMMAND_DESCRIPTION, MEMORY_COMMAND_ARGUMENT_HINT, MEMORY_COMMAND_DESCRIPTION, MEMORY_COMMAND_USAGE, MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, MODEL_COMMAND_ARGUMENT_HINT, MODEL_COMMAND_DESCRIPTION, MODEL_COMMAND_TOOL_PREFIX, MarketplaceClient, PERMISSIONS_COMMAND_DESCRIPTION, PERMISSION_MODE_ARGUMENT_HINT, PERMISSION_MODE_COMMAND_DESCRIPTION, PLUGIN_COMMAND_ARGUMENT_HINT, PLUGIN_COMMAND_DESCRIPTION, PROVIDER_SAFE_TOOL_NAME_PATTERN, PluginCommandSource, PluginSettingsStore, ProjectMemoryStore, PromptExecutor, RECOMMENDED_RESPONSE_LANGUAGES, RELOAD_PLUGINS_COMMAND_DESCRIPTION, RENAME_COMMAND_DESCRIPTION, RENAME_COMMAND_USAGE, RESUME_COMMAND_DESCRIPTION, REWIND_COMMAND_ARGUMENT_HINT, REWIND_COMMAND_DESCRIPTION, STATUSLINE_COMMAND_ARGUMENT_HINT, STATUSLINE_COMMAND_DESCRIPTION, SkillCommandSource, type SkillPromptContext, SystemCommandExecutor, type TAutoCompactThreshold, type TAutoCompactThresholdSource, type TBackgroundJobGroupEvent, type TBackgroundJobGroupEventListener, type TBackgroundJobGroupIdFactory, type TBackgroundJobGroupStatus, type TBackgroundJobWaitPolicy, type TBackgroundPermissionPolicy, type TBackgroundPrimitive, type TBackgroundTaskErrorCategory, type TBackgroundTaskEvent, type TBackgroundTaskEventListener, type TBackgroundTaskIdFactory, type TBackgroundTaskIsolation, type TBackgroundTaskKind, type TBackgroundTaskMode, type TBackgroundTaskRequest, type TBackgroundTaskRunnerEvent, type TBackgroundTaskStatus, type TBackgroundTaskTimeoutReason, type TBackgroundTaskTransitionEvent, type TCapabilityKind, type TCapabilitySafety, type TCliUpdateCheckResult, type TCommandEffect, type TCommandInteractionPrompt, type TCommandModuleSessionRequirement, type TCommandResultDataValue, type TContextReferenceLoadType, type TContextReferenceStatus, type TEditCheckpointFileRestoreAction, type TEnabledPlugins, type TExecutionAttention, type TExecutionControl, type TExecutionDetailRecordKind, type TExecutionEntryKind, type TExecutionOriginKind, type TExecutionWorkspaceStatus, type TExecutionWorkspaceUpdateCause, type TExecutionWorkspaceVisibility, type TInstalledPluginsRegistry, type TInteractiveEventName, type TInteractivePermissionHandler, type TInteractiveSessionOptions, type TKnownMarketplacesRegistry, type TMarketplaceSource, type TMemoryCandidateStatus, type TMemoryType, type TPermissionResultValue, type TPluginInstallScope, type TPromptFileReferenceDiagnosticCode, type TPromptFileReferenceReason, type TProviderFactory, type TProviderSettingsDocument, type TRecommendedResponseLanguage, type TReversibleExecutionIsolation, type TReversibleRollbackLayer, type TReversibleSafetyStatus, type TReversibleSideEffect, type TSelfHostingLoopEvent, type TSelfHostingLoopState, type TSelfHostingVerificationPhase, type TSessionFactory, type TSettingsCheck, type TSettingsData, type TSettingsScope, type TShellExecFn, type TSkillActivationInvocation, type TSkillActivationMode, type TSkillActivationSource, type TSkillActivationStatus, type TStatusLineCommandSettingsPatch, type TSubagentJobMode, type TSubagentJobStatus, type TSubagentRunnerFactory, type TSystemCommandLifecycle, type TTaskFileStatus, type TUserLocalMemoryCategory, type TUserLocalMemoryCommandExecutionEffect, type TUserLocalStorageCategory, USER_LOCAL_MEMORY_CATEGORIES, USER_LOCAL_STORAGE_CATEGORIES, USER_LOCAL_STORAGE_CATEGORY_DEFINITIONS, VALIDATE_SESSION_COMMAND_DESCRIPTION, VALID_PERMISSION_MODES, addCommandContextReference, applyActiveModelChange, applyProviderConfiguration, applyProviderSwitch, applyStatusLineSettings, assembleSubagentPrompt, buildBackgroundCommandSubcommands, buildLanguageCommandSubcommands, buildMemoryCommandSubcommands, buildModelCommandSubcommands, buildPermissionModeSubcommands, buildPluginCommandSubcommands, buildPromptWithFileReferences, buildProviderProfile, buildProviderSetupPatch, buildRewindCommandSubcommands, buildStatusLineCommandSubcommands, cancelCommandBackgroundTask, checkForCliUpdate, checkSettingsDocument, checkSettingsFile, clearCommandContextReferences, clearContextReferences, clearConversationHistory, closeCommandBackgroundTask, compactCommandContext, compareSemverVersions, createAgentRuntime, createAgentTool, createBackgroundGroupExecutionEntryId, createBackgroundProcessTool, createBackgroundTaskExecutionEntryId, createBuiltinCommandModule, createCommandExecutionTool, createCommandMemoryStores, createCommandPendingMemoryStore, createCommandProjectMemoryStore, createContextReferenceItem, createDefaultTools, createExecutionOriginMetadata, createExecutionWorkspaceSnapshot, createExecutionWorkspaceTaskSpawner, createInProcessSubagentRunner, createLineDetailPage, createMainThreadDetailPage, createMainThreadExecutionEntryId, createModelCommandToolProjection, createPluginRegistryReloadRequestedEffect, createPluginTuiRequestedEffect, createProjectSessionStore, createProjectedCommandExecutionTools, createPromptFileReferenceHistoryEntry, createProviderFromSettings, createProviderSafeModelCommandToolName, createQuery, createSessionExitRequestedEffect, createSessionPickerRequestedEffect, createSessionRenamedEffect, createSubagentLogger, createSubagentSession, createSystemCommands, createTestInteractiveSession, deleteProviderProfile, deleteSettings, deleteUserLocalMemoryItem, disableUserLocalMemoryItem, discoverTaskFiles, evaluateReversibleToolSafety, executeSkill, formatCliUpdateCheckMessage, formatCliUpdateNotice, formatCommandBackgroundTask, formatCommandBackgroundTaskList, formatCommandHelpMessage, formatCommandPermissionsMessage, formatCommandSessionReplayValidationReport, formatEnvReference, formatInvalidPermissionModeMessage, formatLanguageUsageMessage, formatModelCommandUsageMessage, formatModelCommandUsageMessageAsync, formatProjectedModelCommandToolPromptDescription, formatPromptFileReferenceDiagnostics, formatTaskContext, getBuiltInAgent, getForkWorkerSuffix, getProviderSettingsPaths, getStartupCliUpdateNotice, getSubagentSuffix, getUserSettingsPath, getUserUpdateCheckCachePath, hasBlockingPromptFileReferenceDiagnostics, hasSensitiveCommandMemoryContent, hasUsableSecretReference, inspectCommandEditCheckpoint, inspectUserLocalMemoryItem, inspectUserLocalStorage, isCommandMemoryType, isEnvReference, isMemoryType, isNewerSemverVersion, isPermissionMode, isStatusLineCommandSettingsPatch, listActiveContextReferences, listCommandBackgroundTasks, listCommandContextReferences, listCommandEditCheckpoints, listCommandSessionAllowedTools, listCommandUsedMemoryReferences, listResumableSessionSummaries, listUserLocalMemoryItems, loadTaskContext, mergeProviderPatch, mergeProviders, mergeSettings, normalizeModelCommandName, parseCommandBackgroundLogCursor, parseExecutionWorkspaceEntryId, parseFrontmatter, parseLanguageArgument, parsePermissionModeArgument, parsePromptFileReferences, parseSessionNameArgument, parseTaskFile, planSelfHostingVerification, preprocessShellCommands, probeProviderProfile, projectPaths, promptForApproval, readAutoCompactThreshold, readAutoCompactThresholdSource, readCommandBackgroundTaskLog, readCommandContextState, readCommandPermissionMode, readCommandPermissionsState, readCommandSessionInfo, readCurrentGitBranch, readEnabledUserLocalMemoryItem, readMergedProviderSettings, readMergedProviderSettingsFromPaths, readPackageVersion, readProviderSettings, readSettings, readStatusLineSettings, readUpdateCheckCache, recordCommandMemoryEvent, removeCommandContextReference, removeContextReference, resetAutoCompactThresholdSetting, resetUserConfig, resolveActiveProvider, resolveActiveProviderModelCatalog, resolveActiveProviderModelCatalogState, resolveEnvReference, resolveGitBranch, resolveLatestSessionId, resolvePermissionModeAdapter, resolvePluginCommandAdapter, resolvePromptFileReferencePaths, resolvePromptFileReferences, resolveProviderSettingsWriteTargetPath, resolveSessionIdByIdOrName, resolveSettingsPathForScope, resolveSubagentLogDir, resolveUserLocalStorageRoot, restoreCommandEditCheckpoint, retrieveAgentToolDeps, rollbackCommandEditCheckpoint, sanitizeProviderProfileName, selectRelevantTasks, setCommandAutoCompactThreshold, setCurrentProvider, setUserLocalMemoryItem, shouldRunStartupCliUpdateCheck, storeAgentToolDeps, substituteVariables, suggestProviderProfileName, summarizeBackgroundJobGroup, testProviderProfileCommand, toContextReferenceRecords, toPromptFileReferenceRecords, transitionSelfHostingLoop, updateModelInSettings, updateTaskFileStatus, upsertContextReference, upsertProviderProfile, userPaths, validateCommandSessionReplayLog, validateProviderProfile, wrapEditCheckpointTools, wrapReversibleExecutionTools, writeAutoCompactThresholdSetting, writeCommandPermissionMode, writeSettings, writeUpdateCheckCache };
3110
3127
  //# sourceMappingURL=index.d.ts.map