@robota-sdk/agent-framework 3.0.0-beta.71 → 3.0.0-beta.73

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.
@@ -97,7 +97,7 @@ Do not use emojis.`}function sn(){return`You are a worker subagent executing a s
97
97
  `)}function hl(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isNaN(t)?void 0:{offset:t}}function gl(e){let t=[];return e.worktreePath&&t.push(`worktree=${e.worktreePath}`),e.branchName&&t.push(`branch=${e.branchName}`),e.worktreeStatus&&t.push(`worktreeStatus="${_l(e.worktreeStatus)}"`),e.worktreeNextAction&&t.push(`next="${_l(e.worktreeNextAction)}"`),t.length===0?``:` ${t.join(` `)}`}function _l(e){let t=e.trim().replace(/\s+/g,` `);return t.length>160?`${t.slice(0,160)}...`:t}function vl(e,t){return e.listBackgroundTasks(t)}function yl(e,t,n){return e.readBackgroundTaskLog(t,n)}function bl(e,t,n){return e.cancelBackgroundTask(t,n)}function xl(e,t){return e.closeBackgroundTask(t)}const Sl=`Set response language`,Cl=`<code>`,wl=[{code:`ko`,description:`Korean`},{code:`en`,description:`English`},{code:`ja`,description:`Japanese`},{code:`zh`,description:`Chinese`}];function Tl(e=`language`){return wl.map(t=>({name:t.code,description:t.description,source:e}))}function El(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Dl(e=`language`){return`Usage: ${e} <code> (e.g., ko, en, ja, zh)`}const Ol=`Show/change permission mode`,kl=`plan | default | acceptEdits | bypassPermissions`,Al=`Show/change permission mode and permission rules`,jl=[`plan`,`default`,`acceptEdits`,`bypassPermissions`];function Ml(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 Nl(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Pl(e){return jl.includes(e)}function Fl(){return`Invalid mode. Valid: ${jl.join(` | `)}`}function Il(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 Ll(e){return Il(e).getPermissionMode()}function Rl(e,t){Il(e).setPermissionMode(t)}function zl(e){return Il(e).listSessionAllowedTools()}function Bl(e){return{mode:Ll(e),sessionAllowed:zl(e)}}function Vl(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 Hl=`Configure TUI status-line visibility and fields such as model, context, tokens, session, and git branch.`,Ul=`on | off | reset | git on | git off`,Wl={enabled:!0,gitBranch:!0};function Gl(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 Kl(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function ql(e){let t=e.statusline;return Yl(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:Wl.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:Wl.gitBranch}:{...Wl}}function Jl(e,t){let n=q(e),r={...ql(n),...t};return n.statusline=r,J(e,n),r}function Yl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}const Xl=`Manage plugins`,Zl=`manage | install <name@marketplace> | uninstall <name@marketplace> | enable <name@marketplace> | disable <name@marketplace> | marketplace <action>`,Ql=`Reload all plugin resources`;function $l(){return{type:`plugin-tui-requested`}}function eu(){return{type:`plugin-registry-reload-requested`}}function tu(e){return e.getCommandHostAdapters?.().plugin}function nu(){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`}]}]}const ru=`Clear conversation history`,iu=`Rename the current session`,au=`Usage: rename <name>`,ou=`Resume a previous session`,su=`Show session token usage and estimated cost. /cost budget <amount> sets a monthly budget.`,cu=`Validate current session replay log`,lu=`Exit CLI`;function uu(e){if(e.clearConversationHistory!==void 0){e.clearConversationHistory();return}e.getSession().clearHistory()}function du(e){let t=e.trim();return t.length>0?t:void 0}function fu(e){return{type:`session-renamed`,name:e}}function pu(){return{type:`session-picker-requested`}}function mu(){return{type:`session-exit-requested`}}function hu(e){let t=e.getSession();return{sessionId:t.getSessionId(),messageCount:t.getMessageCount()}}function gu(e){let t=e.validateCurrentSessionReplayLog?.();if(t!==void 0)return t;let n=e.getSession().getSessionId(),r=S(U(e.getCwd()).logs,`${n}.jsonl`),i=Se(r);return{logFile:r,entryCount:i.length,validation:we(i)}}function _u(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=vu(e);return`${t+1}. ${e.code}${n}: ${e.message}`});return[t,...n,``,...r].join(`
100
- `)}function vu(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(`, `)})`:``}const yu=`List, inspect, restore, or rollback edit checkpoints.`,bu=`list | inspect CHECKPOINT_ID | restore CHECKPOINT_ID | code CHECKPOINT_ID | rollback CHECKPOINT_ID`;function xu(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 Su(e){return e.listEditCheckpoints()}function Cu(e,t){if(!e.inspectEditCheckpoint)throw Error(`Checkpoint inspection is not available in this command host.`);return e.inspectEditCheckpoint(t)}function wu(e,t){return e.restoreEditCheckpoint(t)}function Tu(e,t){return e.rollbackEditCheckpoint(t)}const Eu=[/\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 Du(e){return Eu.some(t=>t.test(e))}function Ou(e){return S(e,`.robota`,`memory`)}function ku(){return{version:1,records:[]}}var Au=class{fs;path;now;constructor(e,t=()=>new Date,n=new z){this.fs=n,this.path=S(Ou(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 ku();try{return{version:1,records:JSON.parse(this.fs.readFileSync(this.path,`utf8`)).records??[]}}catch{return ku()}}write(e){this.fs.mkdirSync(x(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,JSON.stringify(e,null,2),`utf8`)}};const ju=`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.`,Mu=`list | show [topic] | add <user|feedback|project|reference> <topic> <text> | pending | approve <id> | reject <id> | used`,Nu=`Usage: memory list | memory show [topic] | memory add <user|feedback|project|reference> <topic> <text> | memory pending | memory approve <id> | memory reject <id> | memory used`;function Pu(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 Fu(e,t){return new ws(e,t)}function Iu(e,t){return new Au(e,t)}function Lu(e,t){let n=e.getCwd();return{project:Fu(n,t),pending:Iu(n,t)}}function Ru(e){return _s(e)}function zu(e){return Du(e)}function Bu(e){return e.getUsedMemoryReferences()}function Vu(e,t,n=()=>new Date){e.recordMemoryEvent({...t,at:n().toISOString()})}function Hu(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 Uu(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 Wu(e,t,n,r){return e.skillContent?Hu(await Uu(e.skillContent,n.shellExec),t,r):null}async function Gu(e,t,n,r){let i=await Wu(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 Ku(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 Wu(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 Gu(e,t,n,r)}}function qu(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Ju(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Yu(e,t){let n=t.trim();return n.length>0?`${e} ${n}`:e}function Xu(e){if(!e?.startsWith(`/`))return;let t=e.slice(1).trim().split(/\s+/)[0];return t&&t.length>0?t:void 0}var Zu=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 tc(e.flatMap(e=>e.systemCommands??[])),this.skillCommandSource=new Ua(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,...e.example===void 0?{}:{example:e.example}}))}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=qu(e);return this.skillCommandSource.getCommands().find(e=>e.name.toLowerCase()===t.toLowerCase())}async executeCommand(e,t){let n=Ju(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,Yu(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=Xu(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 Ku(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=Fi({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)}`}}}};function Qu(){let e=S(T(),`.robota`,`org-policy.json`);if(!v(e))return null;try{let t=y(e,`utf8`);return JSON.parse(t)}catch{return null}}function $u(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function ed(e){return e?!e.startsWith(`$ENV:`):!1}var td=class extends er{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;providerDefinitions=[];orgPolicy=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 Di({cwd:t})),this.bgTracker=new Bn(()=>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 Li(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 Zu(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)=>gi(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 mi(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()}),`providerDefinitions`in e&&(this.providerDefinitions=e.providerDefinitions??[]),`orgPolicy`in e&&(this.orgPolicy=e.orgPolicy??null);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=Hi(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,this.session&&t.pendingRestoreMessages===null&&this.session.syncContextFromHistory()}startAsyncInitializationIfNeeded(e,t){if(t)return;let n=e;this.initPromise=this.initializeAsync(n)}async initializeAsync(e){let t=await Gs(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.histTracker.recordSystemContextFiles([...t.agentsFileEntries,...t.claudeFileEntries]),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,this.histTracker.recordSystemContextFiles([...e,...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.listeners.clear()})(),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 Vt(this.session)??L(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(h(o(`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();Ks(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})}async switchProvider(e){let t=this.getSessionOrThrow(),n=this.getCwd(),r=Hc(n,{providerOverride:e,providerDefinitions:this.providerDefinitions}),i=Uc(n,void 0,{providerOverride:e,providerDefinitions:this.providerDefinitions});t.swapProvider(i,r.model)}async executeCommand(e,t){if(this.orgPolicy?.blockedCommands?.includes(e))return{message:$u(`Command /${e} is blocked by your organization policy.`,this.orgPolicy.adminContact),success:!1};let n=await super.executeCommand(e,t);if(n===null)return null;let r=n.effects?.find(e=>e.type===`provider-hot-swap-requested`);if(r){let{orgPolicy:e}=this;return e?.allowedProviders&&!e.allowedProviders.includes(r.profileName)?{message:$u(`Provider "${r.profileName}" is not allowed by your organization policy. Allowed: ${e.allowedProviders.join(`, `)}.`,e.adminContact),success:!1}:(await this.switchProvider(r.profileName),{...n,effects:n.effects?.filter(e=>e.type!==`provider-hot-swap-requested`)})}return n}};function nd(e,t=new z){let n=U(e);return new od(n.sessions,n.logs,t)}function rd(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:sd(e.messages)}))}function id(e,t){return rd(e,t)[0]?.id}function ad(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var od=class{store;logsDir;fs;constructor(e,t,n=new z){this.store=new xe(e),this.logsDir=t,this.fs=n}save(e){this.store.save(cd(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):ld(t)}list(){let e=this.store.list().map(ld),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=Ce(Se(S(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:ud(n),backgroundTaskEvents:n,backgroundJobGroups:fd(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 sd(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 cd(e){return{...e}}function ld(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 ud(e){let t=new Map;for(let n of e){let e=dd(n);e&&t.set(e.id,e)}return[...t.values()]}function dd(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 fd(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function pd(e){let t=new td({cwd:e.cwd??process.cwd(),provider:e.provider,permissionMode:e.permissionMode??`bypassPermissions`,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler,additionalTools:e.additionalTools,...e.responseFormat?{responseFormat:e.responseFormat}:{}});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 md=[`preferences`,`view-state`,`memory-projections`,`task-associations`,`workflow-metadata`,`inspection-index`],hd=[{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 gd(e){return e.toISOString()}function _d(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!b.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function vd(){return process.env.HOME??T()}function yd(e,t){let n=b.relative(e,t);return n===``||!n.startsWith(`..`)&&!b.isAbsolute(n)}async function bd(e,t){let n=e;for(;b.dirname(n)!==n;)try{let r=await t.realpath(n),i=b.relative(n,e);return b.resolve(r,i)}catch{n=b.dirname(n)}try{return await t.realpath(n)}catch{return b.resolve(e)}}async function xd(e){let t=e.fsAsync??new B,n=b.resolve(e.activeRepositoryRoot);_d(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?b.join(e.homeDir??vd(),`.robota`):e.storageRoot;_d(`userLocalStorageRoot`,r);let i=b.resolve(r),a=await bd(i,t);if(yd(await bd(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function Sd(e,t){return b.join(e,t)}async function Cd(e,t,n){let r=Sd(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=b.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:gd(new Date(o.birthtimeMs)),lastUsedAt:gd(new Date(o.mtimeMs)),enabled:!0,deleteAvailable:!0,disableAvailable:!1}}))).sort((e,t)=>e.key.localeCompare(t.key))}async function wd(e){let t=e.fsAsync??new B,n=await xd(e),r=b.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all(hd.map(async e=>{let r=Sd(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await Cd(n,e.category,t);return{category:e.category,purpose:e.purpose,mayExecuteCommands:e.mayExecuteCommands,storageLocation:r,itemCount:a.length,items:a}})),generatedAt:gd((e.now??(()=>new Date))())}}const Td=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],Ed=`.json`,Dd=/^[a-z0-9][a-z0-9._-]*$/u,Od={"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 kd(e){return e.toISOString()}function Ad(e){return Td.includes(e)}function jd(e){if(!Ad(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function Md(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!Dd.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function Nd(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 Pd(e){return Nd(`value`,e,240)}function Fd(e,t){return`${e}__${t}${Ed}`}async function Id(e){let t=await xd(e);return{root:t,memoryRoot:b.join(t,`memory-projections`)}}function Ld(e,t){let n=JSON.parse(e),r=$(n,`category`);if(n.schemaVersion!==1)throw Error(`Unsupported user-local memory schema at ${t}`);return{schemaVersion:1,category:jd(r),key:$(n,`key`),value:$(n,`value`),summary:$(n,`summary`),source:$(n,`source`),scope:$(n,`scope`),createdAt:$(n,`createdAt`),lastUsedAt:$(n,`lastUsedAt`),enabled:Rd(n,`enabled`)}}function $(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function Rd(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function zd(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:Pd(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:Od[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function Bd(e,t,n){return zd(e,t,Ld(await n.readFile(t,`utf8`),t))}async function Vd(e){let t=jd(e.category),n=Md(`key`,e.key),{root:r,memoryRoot:i}=await Id(e);return{root:r,storageLocation:b.join(i,Fd(t,n))}}async function Hd(e){let t=e.fsAsync??new B,n=jd(e.category),r=Md(`key`,e.key),i=Nd(`summary`,e.summary,240),a=Nd(`source`,e.source,80),o=Nd(`scope`,e.scope??`user`,120),s=Pd(e.value),c=kd((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await Id(e),d=b.join(u,Fd(n,r)),f=c;try{f=Ld(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`),zd(l,d,p)}async function Ud(e){let t=e.fsAsync??new B,{root:n,memoryRoot:r}=await Id(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(Ed)).map(e=>Bd(n,b.join(r,e.name),t)));return{root:n,activeRepositoryRoot:b.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function Wd(e){let t=e.fsAsync??new B,{root:n,storageLocation:r}=await Vd(e);return Bd(n,r,t)}async function Gd(e){let t=e.fsAsync??new B,{root:n,storageLocation:r}=await Vd(e),i={...Ld(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:kd((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),zd(n,r,i)}async function Kd(e){let t=e.fsAsync??new B,{storageLocation:n}=await Vd(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}async function qd(e){let t=await Wd(e);return t.enabled?t:null}const Jd=[`test`,`typecheck`,`build`],Yd={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 Xd(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))):[]}function Zd(e){return e.flatMap(e=>Jd.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 Qd(){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 $d(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 ef(){return{id:`rollback-on-failure`,phase:`recover`,description:`Use the existing edit checkpoint restore path if verification fails.`,required:!0}}function tf(e){if(e.changedFiles.length===0)throw Error(`Self-hosting verification requires at least one changed file.`);let t=e.baseRef??`origin/develop`,n=Xd(e.packageScopes),r=[...Qd(),...Zd(n),$d(t),ef()];return{changedFiles:[...e.changedFiles],packageScopes:n,baseRef:t,steps:r}}function nf(e,t){let n=Yd[e][t];if(!n)throw Error(`Invalid self-hosting loop transition: ${e} -> ${t}`);return n}function rf(e){return e}function af(e){if(!e||e.length===0)return;let[t,...n]=e;if(t!==void 0)return[t,...n]}function of(e){let t=af(e),n=t===void 0?g.string().describe(`Registered model-invocable command name to execute`):g.enum(t).describe(`Registered model-invocable command name to execute`);return g.object({command:n,args:g.string().optional().describe(`Arguments to pass to the command`)})}function sf(e){if(e.commandNames!==void 0)return e.commandNames;if(e.commandDescriptors!==void 0)return e.commandDescriptors.map(e=>I(e.name))}function cf(e){return`- ${I(e.name)}${e.argumentHint?` ${e.argumentHint}`:``}: ${e.description}`}function lf(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(cf)].join(`
100
+ `)}function vu(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(`, `)})`:``}const yu=`List, inspect, restore, or rollback edit checkpoints.`,bu=`list | inspect CHECKPOINT_ID | restore CHECKPOINT_ID | code CHECKPOINT_ID | rollback CHECKPOINT_ID`;function xu(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 Su(e){return e.listEditCheckpoints()}function Cu(e,t){if(!e.inspectEditCheckpoint)throw Error(`Checkpoint inspection is not available in this command host.`);return e.inspectEditCheckpoint(t)}function wu(e,t){return e.restoreEditCheckpoint(t)}function Tu(e,t){return e.rollbackEditCheckpoint(t)}const Eu=[/\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 Du(e){return Eu.some(t=>t.test(e))}function Ou(e){return S(e,`.robota`,`memory`)}function ku(){return{version:1,records:[]}}var Au=class{fs;path;now;constructor(e,t=()=>new Date,n=new z){this.fs=n,this.path=S(Ou(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 ku();try{return{version:1,records:JSON.parse(this.fs.readFileSync(this.path,`utf8`)).records??[]}}catch{return ku()}}write(e){this.fs.mkdirSync(x(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,JSON.stringify(e,null,2),`utf8`)}};const ju=`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.`,Mu=`list | show [topic] | add <user|feedback|project|reference> <topic> <text> | pending | approve <id> | reject <id> | used`,Nu=`Usage: memory list | memory show [topic] | memory add <user|feedback|project|reference> <topic> <text> | memory pending | memory approve <id> | memory reject <id> | memory used`;function Pu(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 Fu(e,t){return new ws(e,t)}function Iu(e,t){return new Au(e,t)}function Lu(e,t){let n=e.getCwd();return{project:Fu(n,t),pending:Iu(n,t)}}function Ru(e){return _s(e)}function zu(e){return Du(e)}function Bu(e){return e.getUsedMemoryReferences()}function Vu(e,t,n=()=>new Date){e.recordMemoryEvent({...t,at:n().toISOString()})}function Hu(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 Uu(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 Wu(e,t,n,r){return e.skillContent?Hu(await Uu(e.skillContent,n.shellExec),t,r):null}async function Gu(e,t,n,r){let i=await Wu(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 Ku(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 Wu(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 Gu(e,t,n,r)}}function qu(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Ju(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Yu(e,t){let n=t.trim();return n.length>0?`${e} ${n}`:e}function Xu(e){if(!e?.startsWith(`/`))return;let t=e.slice(1).trim().split(/\s+/)[0];return t&&t.length>0?t:void 0}var Zu=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 tc(e.flatMap(e=>e.systemCommands??[])),this.skillCommandSource=new Ua(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,...e.example===void 0?{}:{example:e.example}}))}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=qu(e);return this.skillCommandSource.getCommands().find(e=>e.name.toLowerCase()===t.toLowerCase())}async executeCommand(e,t){let n=Ju(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,Yu(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=Xu(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 Ku(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=Fi({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)}`}}}};function Qu(){let e=S(T(),`.robota`,`org-policy.json`);if(!v(e))return null;try{let t=y(e,`utf8`);return JSON.parse(t)}catch{return null}}function $u(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function ed(e){return e?!e.startsWith(`$ENV:`):!1}var td=class extends er{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;providerDefinitions=[];orgPolicy=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 Di({cwd:t})),this.bgTracker=new Bn(()=>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 Li(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 Zu(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)=>gi(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 mi(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()}),`providerDefinitions`in e&&(this.providerDefinitions=e.providerDefinitions??[]),`orgPolicy`in e&&(this.orgPolicy=e.orgPolicy??null);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=Hi(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,this.session&&t.pendingRestoreMessages===null&&(this.session.syncContextFromHistory(),this.emit(`context_update`,this.getContextState()))}startAsyncInitializationIfNeeded(e,t){if(t)return;let n=e;this.initPromise=this.initializeAsync(n)}async initializeAsync(e){let t=await Gs(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.histTracker.recordSystemContextFiles([...t.agentsFileEntries,...t.claudeFileEntries]),this.pendingRestoreMessages=null,this.initialized=!0,this.bgTracker.subscribe(this.session),this.persistCurrentSession(),this.emit(`context_update`,this.getContextState())}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,this.histTracker.recordSystemContextFiles([...e,...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.listeners.clear()})(),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 Vt(this.session)??L(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(h(o(`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();Ks(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})}async switchProvider(e){let t=this.getSessionOrThrow(),n=this.getCwd(),r=Hc(n,{providerOverride:e,providerDefinitions:this.providerDefinitions}),i=Uc(n,void 0,{providerOverride:e,providerDefinitions:this.providerDefinitions});t.swapProvider(i,r.model)}async executeCommand(e,t){if(this.orgPolicy?.blockedCommands?.includes(e))return{message:$u(`Command /${e} is blocked by your organization policy.`,this.orgPolicy.adminContact),success:!1};let n=await super.executeCommand(e,t);if(n===null)return null;let r=n.effects?.find(e=>e.type===`provider-hot-swap-requested`);if(r){let{orgPolicy:e}=this;return e?.allowedProviders&&!e.allowedProviders.includes(r.profileName)?{message:$u(`Provider "${r.profileName}" is not allowed by your organization policy. Allowed: ${e.allowedProviders.join(`, `)}.`,e.adminContact),success:!1}:(await this.switchProvider(r.profileName),{...n,effects:n.effects?.filter(e=>e.type!==`provider-hot-swap-requested`)})}return n}};function nd(e,t=new z){let n=U(e);return new od(n.sessions,n.logs,t)}function rd(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:sd(e.messages)}))}function id(e,t){return rd(e,t)[0]?.id}function ad(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var od=class{store;logsDir;fs;constructor(e,t,n=new z){this.store=new xe(e),this.logsDir=t,this.fs=n}save(e){this.store.save(cd(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):ld(t)}list(){let e=this.store.list().map(ld),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=Ce(Se(S(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:ud(n),backgroundTaskEvents:n,backgroundJobGroups:fd(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 sd(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 cd(e){return{...e}}function ld(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 ud(e){let t=new Map;for(let n of e){let e=dd(n);e&&t.set(e.id,e)}return[...t.values()]}function dd(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 fd(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function pd(e){let t=new td({cwd:e.cwd??process.cwd(),provider:e.provider,permissionMode:e.permissionMode??`bypassPermissions`,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler,additionalTools:e.additionalTools,...e.responseFormat?{responseFormat:e.responseFormat}:{}});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 md=[`preferences`,`view-state`,`memory-projections`,`task-associations`,`workflow-metadata`,`inspection-index`],hd=[{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 gd(e){return e.toISOString()}function _d(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!b.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function vd(){return process.env.HOME??T()}function yd(e,t){let n=b.relative(e,t);return n===``||!n.startsWith(`..`)&&!b.isAbsolute(n)}async function bd(e,t){let n=e;for(;b.dirname(n)!==n;)try{let r=await t.realpath(n),i=b.relative(n,e);return b.resolve(r,i)}catch{n=b.dirname(n)}try{return await t.realpath(n)}catch{return b.resolve(e)}}async function xd(e){let t=e.fsAsync??new B,n=b.resolve(e.activeRepositoryRoot);_d(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?b.join(e.homeDir??vd(),`.robota`):e.storageRoot;_d(`userLocalStorageRoot`,r);let i=b.resolve(r),a=await bd(i,t);if(yd(await bd(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function Sd(e,t){return b.join(e,t)}async function Cd(e,t,n){let r=Sd(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=b.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:gd(new Date(o.birthtimeMs)),lastUsedAt:gd(new Date(o.mtimeMs)),enabled:!0,deleteAvailable:!0,disableAvailable:!1}}))).sort((e,t)=>e.key.localeCompare(t.key))}async function wd(e){let t=e.fsAsync??new B,n=await xd(e),r=b.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all(hd.map(async e=>{let r=Sd(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await Cd(n,e.category,t);return{category:e.category,purpose:e.purpose,mayExecuteCommands:e.mayExecuteCommands,storageLocation:r,itemCount:a.length,items:a}})),generatedAt:gd((e.now??(()=>new Date))())}}const Td=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],Ed=`.json`,Dd=/^[a-z0-9][a-z0-9._-]*$/u,Od={"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 kd(e){return e.toISOString()}function Ad(e){return Td.includes(e)}function jd(e){if(!Ad(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function Md(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!Dd.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function Nd(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 Pd(e){return Nd(`value`,e,240)}function Fd(e,t){return`${e}__${t}${Ed}`}async function Id(e){let t=await xd(e);return{root:t,memoryRoot:b.join(t,`memory-projections`)}}function Ld(e,t){let n=JSON.parse(e),r=$(n,`category`);if(n.schemaVersion!==1)throw Error(`Unsupported user-local memory schema at ${t}`);return{schemaVersion:1,category:jd(r),key:$(n,`key`),value:$(n,`value`),summary:$(n,`summary`),source:$(n,`source`),scope:$(n,`scope`),createdAt:$(n,`createdAt`),lastUsedAt:$(n,`lastUsedAt`),enabled:Rd(n,`enabled`)}}function $(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function Rd(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function zd(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:Pd(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:Od[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function Bd(e,t,n){return zd(e,t,Ld(await n.readFile(t,`utf8`),t))}async function Vd(e){let t=jd(e.category),n=Md(`key`,e.key),{root:r,memoryRoot:i}=await Id(e);return{root:r,storageLocation:b.join(i,Fd(t,n))}}async function Hd(e){let t=e.fsAsync??new B,n=jd(e.category),r=Md(`key`,e.key),i=Nd(`summary`,e.summary,240),a=Nd(`source`,e.source,80),o=Nd(`scope`,e.scope??`user`,120),s=Pd(e.value),c=kd((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await Id(e),d=b.join(u,Fd(n,r)),f=c;try{f=Ld(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`),zd(l,d,p)}async function Ud(e){let t=e.fsAsync??new B,{root:n,memoryRoot:r}=await Id(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(Ed)).map(e=>Bd(n,b.join(r,e.name),t)));return{root:n,activeRepositoryRoot:b.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function Wd(e){let t=e.fsAsync??new B,{root:n,storageLocation:r}=await Vd(e);return Bd(n,r,t)}async function Gd(e){let t=e.fsAsync??new B,{root:n,storageLocation:r}=await Vd(e),i={...Ld(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:kd((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),zd(n,r,i)}async function Kd(e){let t=e.fsAsync??new B,{storageLocation:n}=await Vd(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}async function qd(e){let t=await Wd(e);return t.enabled?t:null}const Jd=[`test`,`typecheck`,`build`],Yd={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 Xd(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))):[]}function Zd(e){return e.flatMap(e=>Jd.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 Qd(){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 $d(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 ef(){return{id:`rollback-on-failure`,phase:`recover`,description:`Use the existing edit checkpoint restore path if verification fails.`,required:!0}}function tf(e){if(e.changedFiles.length===0)throw Error(`Self-hosting verification requires at least one changed file.`);let t=e.baseRef??`origin/develop`,n=Xd(e.packageScopes),r=[...Qd(),...Zd(n),$d(t),ef()];return{changedFiles:[...e.changedFiles],packageScopes:n,baseRef:t,steps:r}}function nf(e,t){let n=Yd[e][t];if(!n)throw Error(`Invalid self-hosting loop transition: ${e} -> ${t}`);return n}function rf(e){return e}function af(e){if(!e||e.length===0)return;let[t,...n]=e;if(t!==void 0)return[t,...n]}function of(e){let t=af(e),n=t===void 0?g.string().describe(`Registered model-invocable command name to execute`):g.enum(t).describe(`Registered model-invocable command name to execute`);return g.object({command:n,args:g.string().optional().describe(`Arguments to pass to the command`)})}function sf(e){if(e.commandNames!==void 0)return e.commandNames;if(e.commandDescriptors!==void 0)return e.commandDescriptors.map(e=>I(e.name))}function cf(e){return`- ${I(e.name)}${e.argumentHint?` ${e.argumentHint}`:``}: ${e.description}`}function lf(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(cf)].join(`
101
101
  `)}function uf(e){let t=of(sf(e));return pe(`ExecuteCommand`,lf(e.commandDescriptors),rf(t),async n=>{let r=t.parse(n),i=I(r.command);return e.isModelInvocable(i)?hn(i,await e.execute(i,r.args??``)):JSON.stringify({success:!1,command:i,error:`Command is not model-invocable: ${i}`})})}function df(e){return/^\/\S/.test(e)}function ff(e){let t=e.slice(1).trim().split(/\s+/);return{name:t[0]??``,args:t.slice(1).filter(e=>e.length>0)}}function pf(e){if(!df(e))return{type:`user-message`,text:e};let{name:t,args:n}=ff(e);return{type:`slash-command`,name:t,args:n}}function mf(e,t){return t.type===`pick`?{type:`pick`,id:e,title:`/${e}`,items:t.getItems()}:{type:`confirm`,id:e,message:t.message}}function hf(e,t){return t.type===`cancelled`?null:e.type===`pick`&&t.type===`pick`?[t.item.value]:e.type===`confirm`&&t.type===`confirm`?[]:null}function gf(e){return e.map(e=>({name:e.name,description:e.description}))}function _f(e,t){let n=``,r=e=>{n+=e,t.write({type:`assistant-chunk`,chunk:e})},i=()=>{t.write({type:`assistant-done`,fullText:n}),n=``,t.setBusy(!1)},a=e=>{t.write({type:`tool-call`,id:e.executionId??e.toolName,name:e.toolName,args:e.firstArg})},o=e=>{t.write({type:`tool-result`,id:e.executionId??e.toolName,name:e.toolName,result:e.toolResultData??e.result})},s=e=>{t.setBusy(!1),t.write({type:`error`,error:e})},c=()=>{t.setBusy(!1)};return e.on(`text_delta`,r),e.on(`complete`,i),e.on(`tool_start`,a),e.on(`tool_end`,o),e.on(`error`,s),e.on(`interrupted`,c),()=>{e.off(`text_delta`,r),e.off(`complete`,i),e.off(`tool_start`,a),e.off(`tool_end`,o),e.off(`error`,s),e.off(`interrupted`,c)}}function vf(e){let{channel:t,commandModules:n,_testSession:r}=e,i=null,a=null,o={};for(let e of n)e.interactionHints&&Object.assign(o,e.interactionHints);async function s(e){if(!i)return;let n=pf(e);if(n.type===`user-message`){t.write({type:`user-message`,text:e}),t.setBusy(!0),await i.submit(e);return}let{name:r,args:a}=n,s=o[r],c=a;if(s&&a.length===0){let e=hf(s,await t.requestAction(mf(r,s)));if(e===null)return;c=e}let l=await i.executeCommand(r,c.join(` `));l?t.write({type:`command-result`,name:r,output:l.message}):t.write({type:`error`,error:Error(`Unknown command "/${r}". Type /help for help.`)})}return{async start(){if(r)i=r;else{let{provider:t,cwd:r,sessionStore:a}=e;if(!t)throw Error(`createInteractiveRuntime: provider is required`);if(!r)throw Error(`createInteractiveRuntime: cwd is required`);i=new td({provider:t,cwd:r,sessionStore:a,commandModules:n})}a=_f(i,t);let o=i.listCommands();t.setAvailableCommands(gf(o)),t.onSubmit(s),await t.start()},async stop(){a?.(),await t.stop(),await i?.shutdown(),i=null}}}const yf=[`Allow once`,`Allow for this session`,`Deny`];function bf(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 xf(e,t,n){e.writeLine(``),e.writeError(`[Permission Required] Tool: ${t}`),e.writeLine(` ${bf(n)}`),e.writeLine(``);let r=await e.select(yf,0);return r===1?`allow-session`:r===0}const Sf={usedTokens:0,maxTokens:2e5,usedPercentage:0,remainingPercentage:100},Cf={sessionId:`test-session-id`,updatedAt:new Date().toISOString(),entries:[]},wf={id:``,parentSessionId:`test-session-id`,waitPolicy:`wait_all`,taskIds:[],status:`completed`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),results:[]};function Tf(e){return{submit:()=>Promise.resolve(),abort:()=>{},cancelQueue:()=>{},shutdown:()=>Promise.resolve(),isExecuting:()=>!1,getPendingPrompt:()=>null,getMessages:()=>[],getContextState:()=>({...Sf}),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:()=>({...wf}),waitBackgroundJobGroup:()=>Promise.resolve({...wf}),getExecutionWorkspaceSnapshot:()=>({...Cf}),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 Ef(){let e=Wa();return{deleted:Ja(e),path:e}}function Df(e){try{let t=Of(e);if(!t)return;let n=y(S(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 Of(e){let t=w(e),n=x(t);for(;n!==t;){let e=kf(S(t,`.git`),t);if(e)return e;t=n,n=x(t)}return kf(S(t,`.git`),t)}function kf(e,t){if(!v(e))return;let n=Oe(e);if(n.isDirectory())return e;if(!n.isFile())return;let r=y(e,`utf8`).trim();if(!r.startsWith(`gitdir:`))return;let i=r.slice(7).trim();return qe(i)?i:w(t,i)}function Af(e,t){let n=Mf(e),r=Mf(t);if(n===void 0||r===void 0)return Math.sign(e.localeCompare(t));let i=Pf(n.major,r.major)||Pf(n.minor,r.minor)||Pf(n.patch,r.patch);return i===0?Ff(n.prerelease,r.prerelease):i}function jf(e,t){return Af(e,t)>0}function Mf(e){let[t,n]=(e.trim().replace(/^v/,``).split(`+`)[0]??``).split(`-`,2),[r,i,a]=t.split(`.`),o=Nf(r),s=Nf(i),c=Nf(a);if(!(o===void 0||s===void 0||c===void 0))return{major:o,minor:s,patch:c,prerelease:n?n.split(`.`):[]}}function Nf(e){if(!(e===void 0||!/^\d+$/.test(e)))return Number(e)}function Pf(e,t){return Math.sign(e-t)}function Ff(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=If(n,i);if(a!==0)return a}return 0}function If(e,t){let n=Nf(e),r=Nf(t);return n!==void 0&&r!==void 0?Pf(n,r):n===void 0?r===void 0?Math.sign(e.localeCompare(t)):1:-1}function Lf(e){let t=x(nt(e)),n=[S(t,`..`,`..`,`package.json`),S(t,`..`,`package.json`)];for(let e of n)try{let t=y(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`}const Rf=`@robota-sdk/agent-cli`,zf=`https://registry.npmjs.org`,Bf=1440*60*1e3,Vf=1500;function Hf(e=process.env.HOME??process.env.USERPROFILE??`/`){return S(e,`.robota`,`update-check.json`)}function Uf(e){if(v(e))try{return ip(JSON.parse(y(e,`utf8`)))}catch{return}}function Wf(e,t){ke(x(e),{recursive:!0}),Fe(e,JSON.stringify(t,null,2)+`
102
102
  `,`utf8`)}async function Gf(e){if(e.disabled===!0)return{status:`skipped`,reason:`disabled`};let t=e.packageName??`@robota-sdk/agent-cli`,n=e.cachePath??Hf(),r=e.now??new Date,i=e.ttlMs??864e5;if(e.force!==!0){let a=Uf(n);if(a!==void 0&&ep(a,r,i,t))return Qf(a,e.currentVersion)}let a=await Kf(e,t,n,r);return typeof a==`string`?$f(e.currentVersion,a):a}async function Kf(e,t,n,r){let i=await tp({fetchImpl:e.fetchImpl??fetch,packageName:t,registryUrl:e.registryUrl??`https://registry.npmjs.org`,timeoutMs:e.timeoutMs??1500});return i.ok?(qf(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,latestVersion:i.version}),i.version):(qf(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,errorMessage:i.errorMessage}),{status:`error`,errorMessage:i.errorMessage})}function qf(e,t){try{Wf(e,t)}catch{}}async function Jf(e){let t=await Gf(e);return t.status===`update_available`?t.notice:void 0}function Yf(e){return e.printMode===!1&&e.disableUpdateCheck===!1}function Xf(e){return[`Robota update available: ${e.currentVersion} -> ${e.latestVersion}.`,`Run ${e.installCommand}`].join(` `)}function Zf(e){return e.status===`update_available`?Xf(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 Qf(e,t){return e.errorMessage===void 0?e.latestVersion===void 0?{status:`error`,errorMessage:`Cached update check has no latest version`}:$f(t,e.latestVersion):{status:`error`,errorMessage:e.errorMessage}}function $f(e,t){return jf(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 ep(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 tp(e){try{return{ok:!0,version:await np(e)}}catch(e){return{ok:!1,errorMessage:e instanceof Error?e.message:String(e)}}}async function np(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=rp(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 rp(e,t){return`${e.replace(/\/+$/,``)}/${encodeURIComponent(t)}`}function ip(e){if(!ap(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 ap(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function op(e){let t=Wa(),n={settings:{read:()=>q(t),write:e=>J(t,e)}},r=e.backgroundTaskRunners??ie(),i=e.commandModules??[],a=e.commandHostAdapters??n,o=`sessionStore`in e?e.sessionStore:nd(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 td({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,deniedTools:t.deniedTools,model:t.model,appendSystemPrompt:t.appendSystemPrompt,systemPrompt:t.systemPrompt,shellExec:t.shellExec,agentName:t.agentName,orgPolicy:e.orgPolicy,additionalTools:t.additionalTools,resumeSessionId:t.resumeSessionId,...t.responseFormat?{responseFormat:t.responseFormat}:{}})}}}function sp(e){let t=op({cwd:e.cwd??process.cwd(),provider:e.provider,sessionStore:void 0,commandHostAdapters:{settings:{read:()=>({}),write:()=>{}}}}),n=t.createSession.bind(t);return{...t,createSession(e){return n({bare:!0,...e})}}}export{Kc as AUTO_COMPACT_THRESHOLD_SETTINGS_KEY,Xa as AgentExecutor,ul as BACKGROUND_COMMAND_DESCRIPTION,dl as BACKGROUND_COMMAND_USAGE,rn as BUILT_IN_AGENTS,it as BackgroundJobOrchestrator,ic as BuiltinCommandSource,Ns as BundlePluginInstaller,Ms as BundlePluginLoader,ru as CLEAR_COMMAND_DESCRIPTION,Bf as CLI_UPDATE_CACHE_TTL_MS,Rf as CLI_UPDATE_PACKAGE_NAME,zf as CLI_UPDATE_REGISTRY_URL,Vf as CLI_UPDATE_TIMEOUT_MS,su as COST_COMMAND_DESCRIPTION,ec as CommandRegistry,Gc as DEFAULT_AUTO_COMPACT_THRESHOLD,Wl as DEFAULT_STATUS_LINE_COMMAND_SETTINGS,A as EXECUTION_ORIGIN_METADATA_KEYS,lu as EXIT_COMMAND_DESCRIPTION,Di as EditCheckpointStore,sl as HELP_COMMAND_DESCRIPTION,td as InteractiveSession,Cl as LANGUAGE_COMMAND_ARGUMENT_HINT,Sl as LANGUAGE_COMMAND_DESCRIPTION,Mu as MEMORY_COMMAND_ARGUMENT_HINT,ju as MEMORY_COMMAND_DESCRIPTION,Nu as MEMORY_COMMAND_USAGE,hs as MEMORY_INDEX_MAX_BYTES,ms as MEMORY_INDEX_MAX_LINES,ln as MODEL_COMMAND_TOOL_PREFIX,Ls as MarketplaceClient,Al as PERMISSIONS_COMMAND_DESCRIPTION,kl as PERMISSION_MODE_ARGUMENT_HINT,Ol as PERMISSION_MODE_COMMAND_DESCRIPTION,Zl as PLUGIN_COMMAND_ARGUMENT_HINT,Xl as PLUGIN_COMMAND_DESCRIPTION,un as PROVIDER_SAFE_TOOL_NAME_PATTERN,Wc as PluginCommandSource,Os as PluginSettingsStore,ws as ProjectMemoryStore,Qa as PromptExecutor,wl as RECOMMENDED_RESPONSE_LANGUAGES,Ql as RELOAD_PLUGINS_COMMAND_DESCRIPTION,iu as RENAME_COMMAND_DESCRIPTION,au as RENAME_COMMAND_USAGE,ou as RESUME_COMMAND_DESCRIPTION,bu as REWIND_COMMAND_ARGUMENT_HINT,yu as REWIND_COMMAND_DESCRIPTION,Ul as STATUSLINE_COMMAND_ARGUMENT_HINT,Hl as STATUSLINE_COMMAND_DESCRIPTION,Ua as SkillCommandSource,tc as SystemCommandExecutor,Td as USER_LOCAL_MEMORY_CATEGORIES,md as USER_LOCAL_STORAGE_CATEGORIES,hd as USER_LOCAL_STORAGE_CATEGORY_DEFINITIONS,cu as VALIDATE_SESSION_COMMAND_DESCRIPTION,jl as VALID_PERMISSION_MODES,tl as addCommandContextReference,Lc as applyActiveModelChange,Fc as applyProviderConfiguration,Ic as applyProviderSwitch,Jl as applyStatusLineSettings,cn as assembleSubagentPrompt,fl as buildBackgroundCommandSubcommands,Tl as buildLanguageCommandSubcommands,Pu as buildMemoryCommandSubcommands,Ml as buildPermissionModeSubcommands,nu as buildPluginCommandSubcommands,vr as buildPromptWithFileReferences,dc as buildProviderProfile,uc as buildProviderSetupPatch,xu as buildRewindCommandSubcommands,Gl as buildStatusLineCommandSubcommands,bl as cancelCommandBackgroundTask,Gf as checkForCliUpdate,bc as checkSettingsDocument,Tc as checkSettingsFile,rl as clearCommandContextReferences,lr as clearContextReferences,uu as clearConversationHistory,xl as closeCommandBackgroundTask,$c as compactCommandContext,Af as compareSemverVersions,op as createAgentRuntime,zn as createAgentTool,pt as createBackgroundGroupExecutionEntryId,Ta as createBackgroundProcessTool,M as createBackgroundTaskExecutionEntryId,ac as createBuiltinCommandModule,uf as createCommandExecutionTool,Lu as createCommandMemoryStores,Iu as createCommandPendingMemoryStore,Fu as createCommandProjectMemoryStore,or as createContextReferenceItem,Ji as createDefaultTools,N as createExecutionOriginMetadata,ht as createExecutionWorkspaceSnapshot,It as createExecutionWorkspaceTaskSpawner,kn as createInProcessSubagentRunner,vf as createInteractiveRuntime,Nt as createLineDetailPage,Mt as createMainThreadDetailPage,j as createMainThreadExecutionEntryId,pn as createModelCommandToolProjection,eu as createPluginRegistryReloadRequestedEffect,$l as createPluginTuiRequestedEffect,nd as createProjectSessionStore,gn as createProjectedCommandExecutionTools,xr as createPromptFileReferenceHistoryEntry,Uc as createProviderFromSettings,fn as createProviderSafeModelCommandToolName,pd as createQuery,mu as createSessionExitRequestedEffect,pu as createSessionPickerRequestedEffect,fu as createSessionRenamedEffect,sp as createStatelessRuntime,vo as createSubagentLogger,Cn as createSubagentSession,nc as createSystemCommands,Tf as createTestInteractiveSession,cc as deleteProviderProfile,Ja as deleteSettings,Kd as deleteUserLocalMemoryItem,Gd as disableUserLocalMemoryItem,cs as discoverTaskFiles,no as evaluateReversibleToolSafety,Ku as executeSkill,Zf as formatCliUpdateCheckMessage,Xf as formatCliUpdateNotice,pl as formatCommandBackgroundTask,ml as formatCommandBackgroundTaskList,ll as formatCommandHelpMessage,Vl as formatCommandPermissionsMessage,_u as formatCommandSessionReplayValidationReport,l as formatEnvReference,Fl as formatInvalidPermissionModeMessage,Dl as formatLanguageUsageMessage,$u as formatOrgPolicyViolationMessage,mn as formatProjectedModelCommandToolPromptDescription,br as formatPromptFileReferenceDiagnostics,ds as formatTaskContext,an as getBuiltInAgent,sn as getForkWorkerSuffix,Mc as getProviderSettingsPaths,Jf as getStartupCliUpdateNotice,on as getSubagentSuffix,Wa as getUserSettingsPath,Hf as getUserUpdateCheckCachePath,yr as hasBlockingPromptFileReferenceDiagnostics,zu as hasSensitiveCommandMemoryContent,f as hasUsableSecretReference,Cu as inspectCommandEditCheckpoint,Wd as inspectUserLocalMemoryItem,wd as inspectUserLocalStorage,ed as isApiKeyPlaintext,Ru as isCommandMemoryType,m as isEnvReference,_s as isMemoryType,jf as isNewerSemverVersion,Pl as isPermissionMode,df as isSlashCommand,Kl as isStatusLineCommandSettingsPatch,ur as listActiveContextReferences,vl as listCommandBackgroundTasks,el as listCommandContextReferences,Su as listCommandEditCheckpoints,zl as listCommandSessionAllowedTools,Bu as listCommandUsedMemoryReferences,rd as listResumableSessionSummaries,Ud as listUserLocalMemoryItems,Qu as loadOrgPolicy,fs as loadTaskContext,fc as mergeProviderPatch,kc as mergeProviders,Oc as mergeSettings,I as normalizeModelCommandName,hl as parseCommandBackgroundLogCursor,mt as parseExecutionWorkspaceEntryId,za as parseFrontmatter,pf as parseInput,El as parseLanguageArgument,Nl as parsePermissionModeArgument,Tr as parsePromptFileReferences,du as parseSessionNameArgument,ls as parseTaskFile,tf as planSelfHostingVerification,Uu as preprocessShellCommands,yc as probeProviderProfile,U as projectPaths,xf as promptForApproval,Jc as readAutoCompactThreshold,Yc as readAutoCompactThresholdSource,yl as readCommandBackgroundTaskLog,qc as readCommandContextState,Ll as readCommandPermissionMode,Bl as readCommandPermissionsState,hu as readCommandSessionInfo,ss as readCurrentGitBranch,qd as readEnabledUserLocalMemoryItem,Vc as readMergedProviderSettings,Ec as readMergedProviderSettingsFromPaths,Lf as readPackageVersion,Hc as readProviderSettings,q as readSettings,ql as readStatusLineSettings,Uf as readUpdateCheckCache,Vu as recordCommandMemoryEvent,nl as removeCommandContextReference,cr as removeContextReference,Qc as resetAutoCompactThresholdSetting,Ef as resetUserConfig,Ac as resolveActiveProvider,ee as resolveEnvReference,Df as resolveGitBranch,id as resolveLatestSessionId,Il as resolvePermissionModeAdapter,tu as resolvePluginCommandAdapter,Nr as resolvePromptFileReferencePaths,Mr as resolvePromptFileReferences,Nc as resolveProviderSettingsWriteTargetPath,ad as resolveSessionIdByIdOrName,Ga as resolveSettingsPathForScope,yo as resolveSubagentLogDir,xd as resolveUserLocalStorageRoot,wu as restoreCommandEditCheckpoint,L as retrieveAgentToolDeps,Tu as rollbackCommandEditCheckpoint,ol as sanitizeProviderProfileName,us as selectRelevantTasks,Xc as setCommandAutoCompactThreshold,sc as setCurrentProvider,Hd as setUserLocalMemoryItem,Yf as shouldRunStartupCliUpdateCheck,Pn as storeAgentToolDeps,Hu as substituteVariables,al as suggestProviderProfileName,lt as summarizeBackgroundJobGroup,vc as testProviderProfileCommand,dr as toContextReferenceRecords,V as toPromptFileReferenceRecords,ff as tokeniseSlashCommand,nf as transitionSelfHostingLoop,Ka as updateModelInSettings,ps as updateTaskFileStatus,sr as upsertContextReference,oc as upsertProviderProfile,bi as userPaths,gu as validateCommandSessionReplayLog,lc as validateProviderProfile,Ma as wrapEditCheckpointTools,ro as wrapReversibleExecutionTools,Zc as writeAutoCompactThresholdSetting,Rl as writeCommandPermissionMode,J as writeSettings,Wf as writeUpdateCheckCache};
103
103
  //# sourceMappingURL=index.js.map