@robota-sdk/agent-framework 3.0.0-beta.68 → 3.0.0-beta.69

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.
@@ -1,6 +1,6 @@
1
- import{AuthenticationError as e,NetworkError as t,ProviderError as n,RateLimitError as r,collectAssistantUsageMetadata as i,createAssistantMessage as a,createSystemMessage as o,createUserMessage as s,findProviderDefinition as c,formatEnvReference as l,formatEnvReference as u,getProviderCredentialRequirement as d,hasUsableSecretReference as f,hasUsableSecretReference as p,isEnvReference as m,messageToHistoryEntry as h,resolveEnvReference as ee,runHooks as te}from"@robota-sdk/agent-core";import{BackgroundTaskManager as g,SubagentManager as ne,createDefaultBackgroundTaskRunners as re,createProviderFromConfig as ie,isTerminalBackgroundTaskStatus as ae,normalizeProviderConfig as oe}from"@robota-sdk/agent-executor";import{applyWorkspaceManifest as se,createBashTool as ce,createEditTool as le,createReadTool as ue,createWriteTool as de,createZodFunctionTool as fe,globTool as pe,grepTool as me,webFetchTool as he,webSearchTool as ge}from"@robota-sdk/agent-tools";import{z as _}from"zod";import{AUTO_COMPACT_THRESHOLD as _e,FileSessionLogger as ve,Session as ye,SessionStore as be,loadSessionLogEntries as xe,replaySessionLogEntries as Se,validateSessionReplayLogEntries as Ce}from"@robota-sdk/agent-session";import{createHash as we,randomUUID as v}from"node:crypto";import{constants as Te,cpSync as Ee,existsSync as y,lstatSync as De,mkdirSync as Oe,readFileSync as b,readdirSync as ke,renameSync as Ae,rmSync as je,statSync as Me,unlinkSync as Ne,writeFileSync as Pe}from"node:fs";import{access as Fe,copyFile as Ie,mkdir as Le,readFile as Re,readdir as ze,realpath as Be,rename as Ve,rm as He,stat as Ue,writeFile as We}from"node:fs/promises";import x,{basename as Ge,dirname as S,isAbsolute as Ke,join as C,relative as w,resolve as T,sep as qe}from"node:path";import{homedir as E}from"node:os";import{appendFileSync as Je,existsSync as D,mkdirSync as Ye,readFileSync as O,readdirSync as Xe,writeFileSync as Ze}from"fs";import{basename as Qe,dirname as $e,join as k,resolve as et}from"path";import{fileURLToPath as tt}from"node:url";const nt=1e3;var rt=class{manager;now;idFactory;unsubscribeManager;listeners=new Set;groups=new Map;sequence=0;constructor(e){this.manager=e.manager,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(()=>this.nextGroupId()),this.sequence=e.initialGroups?.length??0;for(let t of e.initialGroups??[])this.restoreGroup(t);this.unsubscribeManager=this.manager.subscribe(e=>this.handleTaskEvent(e))}createGroup(e){let t=this.now(),n={id:this.idFactory(e),parentSessionId:e.parentSessionId,waitPolicy:e.waitPolicy,taskIds:[...e.taskIds],status:`running`,createdAt:t,updatedAt:t,results:[],...e.label?{label:e.label}:{}},r=this.createRecord(n);return this.groups.set(n.id,r),this.captureExistingTerminalTasks(r),this.emit({type:`background_job_group_created`,group:A(r.state)}),this.evaluateCompletion(r),A(r.state)}listGroups(){return[...this.groups.values()].map(e=>A(e.state))}getGroup(e){let t=this.groups.get(e);return t?A(t.state):void 0}waitGroup(e){let t=this.groups.get(e);return t?t.completion:Promise.reject(Error(`Unknown background job group: ${e}`))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.unsubscribeManager(),this.listeners.clear()}nextGroupId(){return this.sequence+=1,`group_${this.sequence}`}restoreGroup(e){let t=this.createRecord(A(e));this.groups.set(e.id,t),e.status===`completed`&&t.resolve(A(e))}createRecord(e){let t=()=>{};return{state:e,completion:new Promise(e=>{t=e}),resolve:t}}captureExistingTerminalTasks(e){for(let t of e.state.taskIds){let n=this.manager.get(t);n&&ae(n.status)&&this.captureTask(e,n)}}handleTaskEvent(e){let t=it(e);if(t)for(let e of this.groups.values())e.state.taskIds.includes(t.id)&&this.captureTask(e,t)&&(e.state.status===`running`?this.evaluateCompletion(e):this.emit({type:`background_job_group_updated`,group:A(e.state)}))}captureTask(e,t){return e.state.results.some(e=>e.taskId===t.id)?!1:(e.state.results=[...e.state.results,ot(t)],e.state.updatedAt=this.now(),!0)}evaluateCompletion(e){if(e.state.status===`completed`)return;if(!at(e.state)){this.emit({type:`background_job_group_updated`,group:A(e.state)});return}let t=this.now();e.state.status=`completed`,e.state.completedAt=t,e.state.updatedAt=t;let n=A(e.state);e.resolve(n),this.emit({type:`background_job_group_completed`,group:n})}emit(e){for(let t of this.listeners)t(e)}};function it(e){if(e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)return e.task}function at(e){return e.waitPolicy===`manual`?!1:e.waitPolicy===`wait_any`?e.results.length>0:e.taskIds.every(t=>e.results.some(e=>e.taskId===t))}function ot(e){return{taskId:e.id,label:e.label,status:e.status,...e.result?.output?{summary:st(e.result.output)}:{},...e.transcriptPath||e.logPath?{outputRef:e.transcriptPath??e.logPath}:{},...e.error?{error:{...e.error}}:{},...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{}}}function st(e){let t=e.trim();return t.length<=nt?t:`${t.slice(0,nt)}...`}function ct(e){let t=lt(e,`completed`),n=lt(e,`failed`),r=lt(e,`cancelled`);return{groupId:e.id,status:e.status,total:e.taskIds.length,completed:t,failed:n,cancelled:r,pending:Math.max(e.taskIds.length-e.results.length,0),lines:e.results.map(e=>ut(e))}}function lt(e,t){return e.results.filter(e=>e.status===t).length}function ut(e){let t=dt(e),n=e.outputRef&&e.summary?` (output: ${e.outputRef})`:``;return`[${e.status}] ${e.label} ${e.taskId}: ${t}${n}`}function dt(e){let t=(e.error?.message??e.summary??``).replace(/\s+/g,` `).trim();return t.length>0?t:`(no summary)`}function A(e){return{...e,taskIds:[...e.taskIds],results:e.results.map(e=>({...e,...e.error?{error:{...e.error}}:{}}))}}const j={kind:`executionOriginKind`,sessionId:`executionOriginSessionId`,turnId:`executionOriginTurnId`,commandName:`executionOriginCommandName`,toolCallId:`executionOriginToolCallId`,skillId:`executionOriginSkillId`,label:`executionOriginLabel`};function M(e){return[`main`,e].join(`:`)}function N(e){return[`task`,e].join(`:`)}function ft(e){return[`group`,e].join(`:`)}function pt(e){let[t,n]=e.split(`:`,2);if(n){if(t===`main`)return{kind:`main_thread`,sourceId:n};if(t===`task`)return{kind:`background_task`,sourceId:n};if(t===`group`)return{kind:`background_group`,sourceId:n}}}function P(e){return{[j.kind]:e.kind,[j.sessionId]:e.sessionId,...e.turnId?{[j.turnId]:e.turnId}:{},...e.commandName?{[j.commandName]:e.commandName}:{},...e.toolCallId?{[j.toolCallId]:e.toolCallId}:{},...e.skillId?{[j.skillId]:e.skillId}:{},...e.label?{[j.label]:e.label}:{}}}function mt(e){let t=yt(e.groups),n=[ht(e.mainThread),...kt(e.groups).map(e=>_t(e)),...Ot(e.tasks).map(e=>gt(e,t.get(e.id)))].filter(t=>Dt(t,e.filter));return{sessionId:e.sessionId,selectedEntryId:e.selectedEntryId??n.find(e=>e.kind===`main_thread`)?.id??M(e.sessionId),updatedAt:n[0]?.updatedAt??e.mainThread.updatedAt,entries:n}}function ht(e){return{id:M(e.sessionId),sourceId:e.sessionId,kind:`main_thread`,origin:{kind:`user_prompt`,sessionId:e.sessionId},status:e.isExecuting?`active`:`idle`,title:`Main thread`,subtitle:e.hasPendingPrompt?`prompt queued`:`${e.historyLength} history entries`,preview:F(e.preview),unread:!1,attention:`none`,visibility:`default`,updatedAt:e.updatedAt,controls:[`select`]}}function gt(e,t){return{id:N(e.id),sourceId:e.id,kind:`background_task`,parentId:e.parentTaskId?N(e.parentTaskId):M(e.parentSessionId),...t?{groupId:ft(t)}:{},origin:vt(e.metadata,{kind:`system`,sessionId:e.parentSessionId}),taskKind:e.kind,status:e.status,title:e.label,subtitle:xt(e),preview:Ct(e),currentAction:e.currentAction,unread:e.unread,attention:wt(e),visibility:Tt(e),updatedAt:e.lastActivityAt??e.updatedAt,controls:bt(e)}}function _t(e){let t=F(e.results.map(e=>e.summary??e.error?.message).join(` `));return{id:ft(e.id),sourceId:e.id,kind:`background_group`,parentId:M(e.parentSessionId),origin:{kind:`system`,sessionId:e.parentSessionId,label:e.label},status:e.status,title:e.label??e.id,subtitle:`${e.results.length}/${e.taskIds.length} tasks`,preview:t,unread:!1,attention:Et(e),visibility:e.status===`completed`?`collapsed`:`default`,updatedAt:e.updatedAt,controls:e.status===`running`?[`select`,`wait`]:[`select`]}}function vt(e,t){let n=At(e?.[j.kind]),r=I(e?.[j.sessionId]);return{kind:n??t.kind,sessionId:r??t.sessionId,turnId:I(e?.[j.turnId])??t.turnId,commandName:I(e?.[j.commandName])??t.commandName,toolCallId:I(e?.[j.toolCallId])??t.toolCallId,skillId:I(e?.[j.skillId])??t.skillId,label:I(e?.[j.label])??t.label}}function yt(e){return new Map(e.flatMap(e=>e.taskIds.map(t=>[t,e.id])))}function bt(e){let t=[`select`];return ae(e.status)?t.push(`close`):t.push(`cancel`),e.kind===`agent`&&e.status===`running`&&t.push(`send`),(e.logPath||e.transcriptPath)&&t.push(`read_log`),t}function xt(e){return e.kind===`agent`?e.agentType??e.cwd:e.status===`sleeping`&&e.nextFireAt!==void 0?`next: ${St(e.nextFireAt)}`:e.cwd}function St(e){let t=new Date(e),n=new Date,r=t.getTime()-n.getTime();if(r<=0)return`now`;let i=Math.round(r/1e3);if(i<60)return`${i}s`;let a=Math.round(i/60);return a<60?`${a}m`:`${Math.round(a/60)}h`}function Ct(e){return e.status===`failed`?F(e.error?.message):e.status===`completed`?F(e.result?.output):F(e.promptPreview??e.commandPreview)}function wt(e){return e.status===`failed`?`failed`:e.status===`waiting_permission`?`permission`:e.unread?`unread`:e.status===`completed`?`completed`:`none`}function Tt(e){return e.status===`completed`&&!e.unread&&!e.error&&(e.result?.exitCode??0)===0&&!e.result?.signalCode&&!e.worktreePath&&!e.branchName?`collapsed`:`default`}function Et(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`none`}function Dt(e,t){return t?!(t.includeMainThread===!1&&e.kind===`main_thread`||t.kinds&&!t.kinds.includes(e.kind)||t.visibility&&!t.visibility.includes(e.visibility)):!0}function Ot(e){return[...e].sort((e,t)=>(t.lastActivityAt??t.updatedAt).localeCompare(e.lastActivityAt??e.updatedAt))}function kt(e){return[...e].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}function F(e){let t=e?.trim().replace(/\s+/g,` `);if(t)return t.length>120?`${t.slice(0,120)}...`:t}function I(e){return typeof e==`string`?e:void 0}function At(e){if(e===`user_prompt`||e===`slash_command`||e===`model_command`||e===`tool_call`||e===`skill`||e===`transport`||e===`system`)return e}function jt(e){let t=Nt(e.cursor?.offset),n=e.history.slice(t,t+80),r=n.map(e=>({id:e.id,kind:e.category===`chat`?`message`:`progress`,text:Pt(e),timestamp:e.timestamp.toISOString(),sourceId:e.type}));return{entryId:e.entryId,...e.cursor?{cursor:e.cursor}:{},...t+n.length<e.history.length?{nextCursor:{offset:t+n.length}}:{},records:r}}function Mt(e){let t=e.cursor?.offset??0,n=e.lines.map((n,r)=>({id:`${e.entryId}:${t}:${r}`,kind:e.kind??`process_output`,text:n}));return{entryId:e.entryId,...e.cursor?{cursor:e.cursor}:{},...e.nextCursor?{nextCursor:e.nextCursor}:{},records:n}}function Nt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function Pt(e){return typeof e.data==`string`?e.data:e.type}function Ft(e){return{spawnAgent:t=>e.manager.spawn(It(e,t)),spawnProcess:t=>e.manager.spawn(Lt(e,t)),createGroup:t=>e.groupOrchestrator.createGroup({parentSessionId:e.sessionId,waitPolicy:t.waitPolicy,taskIds:[...t.taskIds],label:t.label})}}function It(e,t){return{kind:`agent`,label:t.label,mode:t.mode??`background`,parentSessionId:e.sessionId,parentTaskId:t.parentTaskId,depth:t.depth??1,cwd:t.cwd??e.cwd,agentType:t.agentType,prompt:t.prompt,model:t.model,isolation:t.isolation,allowedTools:t.allowedTools?[...t.allowedTools]:void 0,disallowedTools:t.disallowedTools?[...t.disallowedTools]:void 0,permissionPolicy:t.permissionPolicy??`inherit-allowlist`,timeoutMs:t.timeoutMs,idleTimeoutMs:t.idleTimeoutMs,maxRuntimeMs:t.maxRuntimeMs,outputLimitBytes:t.outputLimitBytes,maxTextDeltas:t.maxTextDeltas,repetitionWindow:t.repetitionWindow,repetitionThreshold:t.repetitionThreshold,metadata:P(e.origin)}}function Lt(e,t){return{kind:`process`,label:t.label??t.command,mode:t.mode??`background`,parentSessionId:e.sessionId,parentTaskId:t.parentTaskId,depth:t.depth??0,cwd:t.cwd??e.cwd,command:t.command,shell:t.shell,env:t.env,stdin:t.stdin,timeoutMs:t.timeoutMs,idleTimeoutMs:t.idleTimeoutMs,maxRuntimeMs:t.maxRuntimeMs,outputLimitBytes:t.outputLimitBytes,metadata:P(e.origin)}}const Rt=new WeakMap;function zt(e,t){Rt.set(e,t)}function Bt(e){return Rt.get(e)}function Vt(e){let t=e.jobs.filter(e=>e.success),n=e.jobs.map(e=>e.agentId).filter(e=>typeof e==`string`&&e.length>0),r=e.jobs.filter(e=>!e.success).length;return JSON.stringify({success:e.jobs.every(e=>e.success),mode:`batch`,output:t.map(e=>e.output??``).filter(Boolean).join(`
1
+ import{AuthenticationError as e,NetworkError as t,ProviderError as n,RateLimitError as r,collectAssistantUsageMetadata as i,createAssistantMessage as a,createSystemMessage as o,createUserMessage as s,findProviderDefinition as c,formatEnvReference as l,formatEnvReference as u,getProviderCredentialRequirement as d,hasUsableSecretReference as f,hasUsableSecretReference as p,isEnvReference as m,messageToHistoryEntry as h,resolveEnvReference as ee,runHooks as te}from"@robota-sdk/agent-core";import{BackgroundTaskManager as ne,SubagentManager as re,createDefaultBackgroundTaskRunners as ie,createProviderFromConfig as ae,isTerminalBackgroundTaskStatus as oe,normalizeProviderConfig as se}from"@robota-sdk/agent-executor";import{applyWorkspaceManifest as ce,createBashTool as le,createEditTool as ue,createReadTool as de,createWriteTool as fe,createZodFunctionTool as pe,globTool as me,grepTool as he,webFetchTool as ge,webSearchTool as _e}from"@robota-sdk/agent-tools";import{z as g}from"zod";import{AUTO_COMPACT_THRESHOLD as ve,FileSessionLogger as ye,Session as be,SessionStore as xe,loadSessionLogEntries as Se,replaySessionLogEntries as Ce,validateSessionReplayLogEntries as we}from"@robota-sdk/agent-session";import{createHash as Te,randomUUID as _}from"node:crypto";import{constants as Ee,cpSync as De,existsSync as v,lstatSync as Oe,mkdirSync as ke,readFileSync as y,readdirSync as Ae,renameSync as je,rmSync as Me,statSync as Ne,unlinkSync as Pe,writeFileSync as Fe}from"node:fs";import{access as Ie,copyFile as Le,mkdir as Re,readFile as ze,readdir as Be,realpath as Ve,rename as He,rm as Ue,stat as We,writeFile as Ge}from"node:fs/promises";import b,{basename as Ke,dirname as x,isAbsolute as qe,join as S,relative as C,resolve as w,sep as Je}from"node:path";import{homedir as T}from"node:os";import{appendFileSync as Ye,existsSync as E,mkdirSync as Xe,readFileSync as D,readdirSync as Ze,writeFileSync as Qe}from"fs";import{basename as $e,dirname as et,join as O,resolve as tt}from"path";import{fileURLToPath as nt}from"node:url";const rt=1e3;var it=class{manager;now;idFactory;unsubscribeManager;listeners=new Set;groups=new Map;sequence=0;constructor(e){this.manager=e.manager,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(()=>this.nextGroupId()),this.sequence=e.initialGroups?.length??0;for(let t of e.initialGroups??[])this.restoreGroup(t);this.unsubscribeManager=this.manager.subscribe(e=>this.handleTaskEvent(e))}createGroup(e){let t=this.now(),n={id:this.idFactory(e),parentSessionId:e.parentSessionId,waitPolicy:e.waitPolicy,taskIds:[...e.taskIds],status:`running`,createdAt:t,updatedAt:t,results:[],...e.label?{label:e.label}:{}},r=this.createRecord(n);return this.groups.set(n.id,r),this.captureExistingTerminalTasks(r),this.emit({type:`background_job_group_created`,group:k(r.state)}),this.evaluateCompletion(r),k(r.state)}listGroups(){return[...this.groups.values()].map(e=>k(e.state))}getGroup(e){let t=this.groups.get(e);return t?k(t.state):void 0}waitGroup(e){let t=this.groups.get(e);return t?t.completion:Promise.reject(Error(`Unknown background job group: ${e}`))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.unsubscribeManager(),this.listeners.clear()}nextGroupId(){return this.sequence+=1,`group_${this.sequence}`}restoreGroup(e){let t=this.createRecord(k(e));this.groups.set(e.id,t),e.status===`completed`&&t.resolve(k(e))}createRecord(e){let t=()=>{};return{state:e,completion:new Promise(e=>{t=e}),resolve:t}}captureExistingTerminalTasks(e){for(let t of e.state.taskIds){let n=this.manager.get(t);n&&oe(n.status)&&this.captureTask(e,n)}}handleTaskEvent(e){let t=at(e);if(t)for(let e of this.groups.values())e.state.taskIds.includes(t.id)&&this.captureTask(e,t)&&(e.state.status===`running`?this.evaluateCompletion(e):this.emit({type:`background_job_group_updated`,group:k(e.state)}))}captureTask(e,t){return e.state.results.some(e=>e.taskId===t.id)?!1:(e.state.results=[...e.state.results,st(t)],e.state.updatedAt=this.now(),!0)}evaluateCompletion(e){if(e.state.status===`completed`)return;if(!ot(e.state)){this.emit({type:`background_job_group_updated`,group:k(e.state)});return}let t=this.now();e.state.status=`completed`,e.state.completedAt=t,e.state.updatedAt=t;let n=k(e.state);e.resolve(n),this.emit({type:`background_job_group_completed`,group:n})}emit(e){for(let t of this.listeners)t(e)}};function at(e){if(e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)return e.task}function ot(e){return e.waitPolicy===`manual`?!1:e.waitPolicy===`wait_any`?e.results.length>0:e.taskIds.every(t=>e.results.some(e=>e.taskId===t))}function st(e){return{taskId:e.id,label:e.label,status:e.status,...e.result?.output?{summary:ct(e.result.output)}:{},...e.transcriptPath||e.logPath?{outputRef:e.transcriptPath??e.logPath}:{},...e.error?{error:{...e.error}}:{},...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{}}}function ct(e){let t=e.trim();return t.length<=rt?t:`${t.slice(0,rt)}...`}function lt(e){let t=ut(e,`completed`),n=ut(e,`failed`),r=ut(e,`cancelled`);return{groupId:e.id,status:e.status,total:e.taskIds.length,completed:t,failed:n,cancelled:r,pending:Math.max(e.taskIds.length-e.results.length,0),lines:e.results.map(e=>dt(e))}}function ut(e,t){return e.results.filter(e=>e.status===t).length}function dt(e){let t=ft(e),n=e.outputRef&&e.summary?` (output: ${e.outputRef})`:``;return`[${e.status}] ${e.label} ${e.taskId}: ${t}${n}`}function ft(e){let t=(e.error?.message??e.summary??``).replace(/\s+/g,` `).trim();return t.length>0?t:`(no summary)`}function k(e){return{...e,taskIds:[...e.taskIds],results:e.results.map(e=>({...e,...e.error?{error:{...e.error}}:{}}))}}const A={kind:`executionOriginKind`,sessionId:`executionOriginSessionId`,turnId:`executionOriginTurnId`,commandName:`executionOriginCommandName`,toolCallId:`executionOriginToolCallId`,skillId:`executionOriginSkillId`,label:`executionOriginLabel`};function j(e){return[`main`,e].join(`:`)}function M(e){return[`task`,e].join(`:`)}function pt(e){return[`group`,e].join(`:`)}function mt(e){let[t,n]=e.split(`:`,2);if(n){if(t===`main`)return{kind:`main_thread`,sourceId:n};if(t===`task`)return{kind:`background_task`,sourceId:n};if(t===`group`)return{kind:`background_group`,sourceId:n}}}function N(e){return{[A.kind]:e.kind,[A.sessionId]:e.sessionId,...e.turnId?{[A.turnId]:e.turnId}:{},...e.commandName?{[A.commandName]:e.commandName}:{},...e.toolCallId?{[A.toolCallId]:e.toolCallId}:{},...e.skillId?{[A.skillId]:e.skillId}:{},...e.label?{[A.label]:e.label}:{}}}function ht(e){let t=bt(e.groups),n=[gt(e.mainThread),...At(e.groups).map(e=>vt(e)),...kt(e.tasks).map(e=>_t(e,t.get(e.id)))].filter(t=>Ot(t,e.filter));return{sessionId:e.sessionId,selectedEntryId:e.selectedEntryId??n.find(e=>e.kind===`main_thread`)?.id??j(e.sessionId),updatedAt:n[0]?.updatedAt??e.mainThread.updatedAt,entries:n}}function gt(e){return{id:j(e.sessionId),sourceId:e.sessionId,kind:`main_thread`,origin:{kind:`user_prompt`,sessionId:e.sessionId},status:e.isExecuting?`active`:`idle`,title:`Main thread`,subtitle:e.hasPendingPrompt?`prompt queued`:`${e.historyLength} history entries`,preview:P(e.preview),unread:!1,attention:`none`,visibility:`default`,updatedAt:e.updatedAt,controls:[`select`]}}function _t(e,t){return{id:M(e.id),sourceId:e.id,kind:`background_task`,parentId:e.parentTaskId?M(e.parentTaskId):j(e.parentSessionId),...t?{groupId:pt(t)}:{},origin:yt(e.metadata,{kind:`system`,sessionId:e.parentSessionId}),taskKind:e.kind,status:e.status,title:e.label,subtitle:St(e),preview:wt(e),currentAction:e.currentAction,unread:e.unread,attention:Tt(e),visibility:Et(e),updatedAt:e.lastActivityAt??e.updatedAt,controls:xt(e)}}function vt(e){let t=P(e.results.map(e=>e.summary??e.error?.message).join(` `));return{id:pt(e.id),sourceId:e.id,kind:`background_group`,parentId:j(e.parentSessionId),origin:{kind:`system`,sessionId:e.parentSessionId,label:e.label},status:e.status,title:e.label??e.id,subtitle:`${e.results.length}/${e.taskIds.length} tasks`,preview:t,unread:!1,attention:Dt(e),visibility:e.status===`completed`?`collapsed`:`default`,updatedAt:e.updatedAt,controls:e.status===`running`?[`select`,`wait`]:[`select`]}}function yt(e,t){let n=jt(e?.[A.kind]),r=F(e?.[A.sessionId]);return{kind:n??t.kind,sessionId:r??t.sessionId,turnId:F(e?.[A.turnId])??t.turnId,commandName:F(e?.[A.commandName])??t.commandName,toolCallId:F(e?.[A.toolCallId])??t.toolCallId,skillId:F(e?.[A.skillId])??t.skillId,label:F(e?.[A.label])??t.label}}function bt(e){return new Map(e.flatMap(e=>e.taskIds.map(t=>[t,e.id])))}function xt(e){let t=[`select`];return oe(e.status)?t.push(`close`):t.push(`cancel`),e.kind===`agent`&&e.status===`running`&&t.push(`send`),(e.logPath||e.transcriptPath)&&t.push(`read_log`),t}function St(e){return e.kind===`agent`?e.agentType??e.cwd:e.status===`sleeping`&&e.nextFireAt!==void 0?`next: ${Ct(e.nextFireAt)}`:e.cwd}function Ct(e){let t=new Date(e),n=new Date,r=t.getTime()-n.getTime();if(r<=0)return`now`;let i=Math.round(r/1e3);if(i<60)return`${i}s`;let a=Math.round(i/60);return a<60?`${a}m`:`${Math.round(a/60)}h`}function wt(e){return e.status===`failed`?P(e.error?.message):e.status===`completed`?P(e.result?.output):P(e.promptPreview??e.commandPreview)}function Tt(e){return e.status===`failed`?`failed`:e.status===`waiting_permission`?`permission`:e.unread?`unread`:e.status===`completed`?`completed`:`none`}function Et(e){return e.status===`completed`&&!e.unread&&!e.error&&(e.result?.exitCode??0)===0&&!e.result?.signalCode&&!e.worktreePath&&!e.branchName?`collapsed`:`default`}function Dt(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`none`}function Ot(e,t){return t?!(t.includeMainThread===!1&&e.kind===`main_thread`||t.kinds&&!t.kinds.includes(e.kind)||t.visibility&&!t.visibility.includes(e.visibility)):!0}function kt(e){return[...e].sort((e,t)=>(t.lastActivityAt??t.updatedAt).localeCompare(e.lastActivityAt??e.updatedAt))}function At(e){return[...e].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}function P(e){let t=e?.trim().replace(/\s+/g,` `);if(t)return t.length>120?`${t.slice(0,120)}...`:t}function F(e){return typeof e==`string`?e:void 0}function jt(e){if(e===`user_prompt`||e===`slash_command`||e===`model_command`||e===`tool_call`||e===`skill`||e===`transport`||e===`system`)return e}function Mt(e){let t=Pt(e.cursor?.offset),n=e.history.slice(t,t+80),r=n.map(e=>({id:e.id,kind:e.category===`chat`?`message`:`progress`,text:Ft(e),timestamp:e.timestamp.toISOString(),sourceId:e.type}));return{entryId:e.entryId,...e.cursor?{cursor:e.cursor}:{},...t+n.length<e.history.length?{nextCursor:{offset:t+n.length}}:{},records:r}}function Nt(e){let t=e.cursor?.offset??0,n=e.lines.map((n,r)=>({id:`${e.entryId}:${t}:${r}`,kind:e.kind??`process_output`,text:n}));return{entryId:e.entryId,...e.cursor?{cursor:e.cursor}:{},...e.nextCursor?{nextCursor:e.nextCursor}:{},records:n}}function Pt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function Ft(e){return typeof e.data==`string`?e.data:e.type}function It(e){return{spawnAgent:t=>e.manager.spawn(Lt(e,t)),spawnProcess:t=>e.manager.spawn(Rt(e,t)),createGroup:t=>e.groupOrchestrator.createGroup({parentSessionId:e.sessionId,waitPolicy:t.waitPolicy,taskIds:[...t.taskIds],label:t.label})}}function Lt(e,t){return{kind:`agent`,label:t.label,mode:t.mode??`background`,parentSessionId:e.sessionId,parentTaskId:t.parentTaskId,depth:t.depth??1,cwd:t.cwd??e.cwd,agentType:t.agentType,prompt:t.prompt,model:t.model,isolation:t.isolation,allowedTools:t.allowedTools?[...t.allowedTools]:void 0,disallowedTools:t.disallowedTools?[...t.disallowedTools]:void 0,permissionPolicy:t.permissionPolicy??`inherit-allowlist`,timeoutMs:t.timeoutMs,idleTimeoutMs:t.idleTimeoutMs,maxRuntimeMs:t.maxRuntimeMs,outputLimitBytes:t.outputLimitBytes,maxTextDeltas:t.maxTextDeltas,repetitionWindow:t.repetitionWindow,repetitionThreshold:t.repetitionThreshold,metadata:N(e.origin)}}function Rt(e,t){return{kind:`process`,label:t.label??t.command,mode:t.mode??`background`,parentSessionId:e.sessionId,parentTaskId:t.parentTaskId,depth:t.depth??0,cwd:t.cwd??e.cwd,command:t.command,shell:t.shell,env:t.env,stdin:t.stdin,timeoutMs:t.timeoutMs,idleTimeoutMs:t.idleTimeoutMs,maxRuntimeMs:t.maxRuntimeMs,outputLimitBytes:t.outputLimitBytes,metadata:N(e.origin)}}const zt=new WeakMap;function Bt(e,t){zt.set(e,t)}function Vt(e){return zt.get(e)}function Ht(e){let t=e.jobs.filter(e=>e.success),n=e.jobs.map(e=>e.agentId).filter(e=>typeof e==`string`&&e.length>0),r=e.jobs.filter(e=>!e.success).length;return JSON.stringify({success:e.jobs.every(e=>e.success),mode:`batch`,output:t.map(e=>e.output??``).filter(Boolean).join(`
2
2
 
3
- `),groupId:e.groupId,requestedJobCount:e.requestedJobCount,startedJobCount:n.length,failedJobCount:r,agentIds:n,jobs:e.jobs,provenance:{source:`agent-tool-batch`,groupId:e.groupId,requestedJobCount:e.requestedJobCount,startedJobCount:n.length,failedJobCount:r}})}function Ht(){return`agent_group_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function Ut(e,t){let n=e?.trim();return n&&n.length>0?n:t}function Wt(e,t,n){let r=e.subagent_type??`general-purpose`,i=n.resolveAgentDefinition(r,n.deps.customAgentRegistry);return{index:t,job:e,agentType:r,agentDef:i,label:Ut(e.label,i?.name??r)}}function Gt(e){return e.agentDef!==void 0}function Kt(e,t){return{index:e.index,success:!1,groupId:t,label:e.label,subagent_type:e.agentType,prompt:e.job.prompt,error:`Unknown agent type: ${e.agentType}`}}async function qt(e,t){try{let n=await t.manager.spawn(t.createSpawnRequest(e.job,e.agentType,e.agentDef,t.deps,e.label,t.toolCallId));return{...e,agentId:n.id}}catch(t){let n=t instanceof Error?t.message:String(t);return{...e,spawnError:n}}}function Jt(e,t){return{index:e.index,success:!1,groupId:t,label:e.label,subagent_type:e.agentType,prompt:e.job.prompt,error:`Sub-agent error: ${e.spawnError??`missing agent id`}`}}function Yt(e,t,n){return{index:e.index,success:!0,groupId:t,label:e.label,agentId:n.jobId,subagent_type:e.agentType,prompt:e.job.prompt,output:n.output,metadata:n.metadata}}function Xt(e,t,n){return{index:e.index,success:!1,groupId:t,label:e.label,agentId:e.agentId,subagent_type:e.agentType,prompt:e.job.prompt,error:`Sub-agent error: ${n}`}}async function Zt(e,t,n){if(e.agentId===void 0)return Jt(e,t);try{let r=await n.wait(e.agentId);return Yt({...e,agentId:e.agentId},t,r)}catch(n){let r=n instanceof Error?n.message:String(n);return Xt({...e,agentId:e.agentId},t,r)}}async function Qt(e){let t=Ht(),n=e.jobs.map((t,n)=>Wt(t,n,e)),r=n.filter(e=>!Gt(e)).map(e=>Kt(e,t)),i=await Promise.all(n.filter(Gt).map(t=>qt(t,e))),a=await Promise.all(i.map(n=>Zt(n,t,e.manager))),o=[...r,...a].sort((e,t)=>e.index-t.index);return Vt({groupId:t,requestedJobCount:e.jobs.length,jobs:o})}function $t(e){return JSON.stringify({success:!1,mode:`single`,requestedJobCount:1,startedJobCount:0,failedJobCount:1,output:``,error:`Unknown agent type: ${e}`,provenance:{source:`agent-tool-single`,requestedJobCount:1,startedJobCount:0,failedJobCount:1}})}function en(e){let t=e.metadata?.worktreePath,n=e.metadata?.branchName,r=e.metadata?.worktreeStatus,i=e.metadata?.worktreeNextAction;return JSON.stringify({success:!0,mode:`single`,requestedJobCount:1,startedJobCount:1,failedJobCount:0,output:e.output,agentId:e.jobId,agentIds:[e.jobId],provenance:{source:`agent-tool-single`,requestedJobCount:1,startedJobCount:1,failedJobCount:0},metadata:e.metadata,...typeof t==`string`?{worktreePath:t}:{},...typeof n==`string`?{branchName:n}:{},...typeof r==`string`?{worktreeStatus:r}:{},...typeof i==`string`?{worktreeNextAction:i}:{}})}function tn(e,t){let n=t===void 0?0:1;return JSON.stringify({success:!1,mode:`single`,requestedJobCount:1,startedJobCount:n,failedJobCount:1,output:``,error:`Sub-agent error: ${e}`,agentId:t,...t===void 0?{}:{agentIds:[t]},provenance:{source:`agent-tool-single`,requestedJobCount:1,startedJobCount:n,failedJobCount:1}})}const nn=[{name:`general-purpose`,description:`General-purpose task execution agent with full tool access.`,systemPrompt:`You are a general-purpose task execution agent. You have access to all tools available in the parent session and can perform any task delegated to you.
3
+ `),groupId:e.groupId,requestedJobCount:e.requestedJobCount,startedJobCount:n.length,failedJobCount:r,agentIds:n,jobs:e.jobs,provenance:{source:`agent-tool-batch`,groupId:e.groupId,requestedJobCount:e.requestedJobCount,startedJobCount:n.length,failedJobCount:r}})}function Ut(){return`agent_group_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function Wt(e,t){let n=e?.trim();return n&&n.length>0?n:t}function Gt(e,t,n){let r=e.subagent_type??`general-purpose`,i=n.resolveAgentDefinition(r,n.deps.customAgentRegistry);return{index:t,job:e,agentType:r,agentDef:i,label:Wt(e.label,i?.name??r)}}function Kt(e){return e.agentDef!==void 0}function qt(e,t){return{index:e.index,success:!1,groupId:t,label:e.label,subagent_type:e.agentType,prompt:e.job.prompt,error:`Unknown agent type: ${e.agentType}`}}async function Jt(e,t){try{let n=await t.manager.spawn(t.createSpawnRequest(e.job,e.agentType,e.agentDef,t.deps,e.label,t.toolCallId));return{...e,agentId:n.id}}catch(t){let n=t instanceof Error?t.message:String(t);return{...e,spawnError:n}}}function Yt(e,t){return{index:e.index,success:!1,groupId:t,label:e.label,subagent_type:e.agentType,prompt:e.job.prompt,error:`Sub-agent error: ${e.spawnError??`missing agent id`}`}}function Xt(e,t,n){return{index:e.index,success:!0,groupId:t,label:e.label,agentId:n.jobId,subagent_type:e.agentType,prompt:e.job.prompt,output:n.output,metadata:n.metadata}}function Zt(e,t,n){return{index:e.index,success:!1,groupId:t,label:e.label,agentId:e.agentId,subagent_type:e.agentType,prompt:e.job.prompt,error:`Sub-agent error: ${n}`}}async function Qt(e,t,n){if(e.agentId===void 0)return Yt(e,t);try{let r=await n.wait(e.agentId);return Xt({...e,agentId:e.agentId},t,r)}catch(n){let r=n instanceof Error?n.message:String(n);return Zt({...e,agentId:e.agentId},t,r)}}async function $t(e){let t=Ut(),n=e.jobs.map((t,n)=>Gt(t,n,e)),r=n.filter(e=>!Kt(e)).map(e=>qt(e,t)),i=await Promise.all(n.filter(Kt).map(t=>Jt(t,e))),a=await Promise.all(i.map(n=>Qt(n,t,e.manager))),o=[...r,...a].sort((e,t)=>e.index-t.index);return Ht({groupId:t,requestedJobCount:e.jobs.length,jobs:o})}function en(e){return JSON.stringify({success:!1,mode:`single`,requestedJobCount:1,startedJobCount:0,failedJobCount:1,output:``,error:`Unknown agent type: ${e}`,provenance:{source:`agent-tool-single`,requestedJobCount:1,startedJobCount:0,failedJobCount:1}})}function tn(e){let t=e.metadata?.worktreePath,n=e.metadata?.branchName,r=e.metadata?.worktreeStatus,i=e.metadata?.worktreeNextAction;return JSON.stringify({success:!0,mode:`single`,requestedJobCount:1,startedJobCount:1,failedJobCount:0,output:e.output,agentId:e.jobId,agentIds:[e.jobId],provenance:{source:`agent-tool-single`,requestedJobCount:1,startedJobCount:1,failedJobCount:0},metadata:e.metadata,...typeof t==`string`?{worktreePath:t}:{},...typeof n==`string`?{branchName:n}:{},...typeof r==`string`?{worktreeStatus:r}:{},...typeof i==`string`?{worktreeNextAction:i}:{}})}function nn(e,t){let n=t===void 0?0:1;return JSON.stringify({success:!1,mode:`single`,requestedJobCount:1,startedJobCount:n,failedJobCount:1,output:``,error:`Sub-agent error: ${e}`,agentId:t,...t===void 0?{}:{agentIds:[t]},provenance:{source:`agent-tool-single`,requestedJobCount:1,startedJobCount:n,failedJobCount:1}})}const rn=[{name:`general-purpose`,description:`General-purpose task execution agent with full tool access.`,systemPrompt:`You are a general-purpose task execution agent. You have access to all tools available in the parent session and can perform any task delegated to you.
4
4
 
5
5
  Your role is to complete the assigned task thoroughly and accurately. Follow these guidelines:
6
6
 
@@ -33,71 +33,71 @@ Your role is to:
33
33
  - Produce a structured implementation plan with clear steps, file lists, and ordering.
34
34
  - Consider edge cases, error handling, and test coverage requirements.
35
35
 
36
- Output your plan in a structured format with numbered steps. For each step, specify which files are involved and what changes are needed. Flag any decisions that require human judgment or clarification.`,disallowedTools:[`Write`,`Edit`]}];function rn(e){return nn.find(t=>t.name===e)}function an(){return`When you complete the task, respond with a concise report covering what was done and any key findings — the caller will relay this to the user, so it only needs the essentials.
36
+ Output your plan in a structured format with numbered steps. For each step, specify which files are involved and what changes are needed. Flag any decisions that require human judgment or clarification.`,disallowedTools:[`Write`,`Edit`]}];function an(e){return rn.find(t=>t.name===e)}function on(){return`When you complete the task, respond with a concise report covering what was done and any key findings — the caller will relay this to the user, so it only needs the essentials.
37
37
 
38
38
  In your final response, share file paths (always absolute, never relative) that are relevant to the task. Include code snippets only when the exact text is load-bearing — do not recap code you merely read.
39
39
 
40
- Do not use emojis.`}function on(){return`You are a worker subagent executing a specific task. Do NOT spawn sub-agents; execute directly. Keep your report under 500 words. Use this structure:
40
+ Do not use emojis.`}function sn(){return`You are a worker subagent executing a specific task. Do NOT spawn sub-agents; execute directly. Keep your report under 500 words. Use this structure:
41
41
  - Scope: What was requested
42
42
  - Result: What was done
43
43
  - Key files: Relevant file paths (absolute)
44
44
  - Files changed: List of modifications
45
- - Issues: Any problems encountered`}function sn(e){let t=[e.agentBody];e.claudeMd&&t.push(e.claudeMd),e.agentsMd&&t.push(e.agentsMd);let n=e.isForkWorker?on():an();return t.push(n),t.join(`
45
+ - Issues: Any problems encountered`}function cn(e){let t=[e.agentBody];e.claudeMd&&t.push(e.claudeMd),e.agentsMd&&t.push(e.agentsMd);let n=e.isForkWorker?sn():on();return t.push(n),t.join(`
46
46
 
47
- `)}const cn=`robota_command_`,ln=/^[A-Za-z0-9_-]{1,64}$/;function un(e){return e}function L(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function dn(e){let t=L(e);if(!t)throw Error(`Model command descriptor name must not be empty.`);let n=t.replace(/[^A-Za-z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``);if(!n)throw Error(`Model command descriptor name cannot be projected safely: ${e}`);let r=`${cn}${n}`;if(ln.test(r))return r;let i=we(`sha256`).update(t).digest(`hex`).slice(0,8),a=`${cn}${n.slice(0,40).replace(/[_-]+$/g,``)||`command`}_${i}`;if(!ln.test(a))throw Error(`Projected model command tool name is not provider-safe: ${a}`);return a}function fn(e){let t=new Set,n=new Map,r=new Map,i=[];for(let a of e){let e=L(a.name);if(!e)throw Error(`Model command descriptor name must not be empty.`);if(t.has(e))throw Error(`Duplicate model command descriptor: ${e}`);t.add(e);let o=dn(e),s=n.get(o);if(s!==void 0)throw Error(`Model command projection collision: ${s} and ${e} both map to ${o}`);n.set(o,e),r.set(e,o),i.push({commandName:e,toolName:o,description:_n(e,a),descriptor:a,requiresPermission:a.requiresPermission!==!1})}return{commandTools:i,toolNameToCommandName:n,commandNameToToolName:r}}function pn(e){return`${e.toolName} — ${e.descriptor.description}`}function mn(e,t){return JSON.stringify(t?{success:t.success,command:e,message:t.message,data:t.data}:{success:!1,command:e,error:`Unknown command: ${e}`})}function hn(e){return fn(e.commandDescriptors).commandTools.map(t=>{let n=gn(t.descriptor);return fe(t.toolName,t.description,un(n),async r=>{let i=n.parse(r);return e.isModelInvocable(t.commandName)?mn(t.commandName,await e.execute(t.commandName,i.args??``)):JSON.stringify({success:!1,command:t.commandName,error:`Command is not model-invocable: ${t.commandName}`})})})}function gn(e){let t=e.argumentHint?`Arguments for the command. Expected grammar: ${e.argumentHint}`:`Arguments for the command as a single string.`;return _.object({args:_.string().optional().describe(t)})}function _n(e,t){let n=[t.description.trim(),`Robota command id: ${e}.`];return t.argumentHint&&n.push(`Argument grammar: ${t.argumentHint}`),n.filter(e=>e.length>0).join(`
47
+ `)}const ln=`robota_command_`,un=/^[A-Za-z0-9_-]{1,64}$/;function dn(e){return e}function I(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function fn(e){let t=I(e);if(!t)throw Error(`Model command descriptor name must not be empty.`);let n=t.replace(/[^A-Za-z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``);if(!n)throw Error(`Model command descriptor name cannot be projected safely: ${e}`);let r=`${ln}${n}`;if(un.test(r))return r;let i=Te(`sha256`).update(t).digest(`hex`).slice(0,8),a=`${ln}${n.slice(0,40).replace(/[_-]+$/g,``)||`command`}_${i}`;if(!un.test(a))throw Error(`Projected model command tool name is not provider-safe: ${a}`);return a}function pn(e){let t=new Set,n=new Map,r=new Map,i=[];for(let a of e){let e=I(a.name);if(!e)throw Error(`Model command descriptor name must not be empty.`);if(t.has(e))throw Error(`Duplicate model command descriptor: ${e}`);t.add(e);let o=fn(e),s=n.get(o);if(s!==void 0)throw Error(`Model command projection collision: ${s} and ${e} both map to ${o}`);n.set(o,e),r.set(e,o),i.push({commandName:e,toolName:o,description:vn(e,a),descriptor:a,requiresPermission:a.requiresPermission!==!1})}return{commandTools:i,toolNameToCommandName:n,commandNameToToolName:r}}function mn(e){return`${e.toolName} — ${e.descriptor.description}`}function hn(e,t){return JSON.stringify(t?{success:t.success,command:e,message:t.message,data:t.data}:{success:!1,command:e,error:`Unknown command: ${e}`})}function gn(e){return pn(e.commandDescriptors).commandTools.map(t=>{let n=_n(t.descriptor);return pe(t.toolName,t.description,dn(n),async r=>{let i=n.parse(r);return e.isModelInvocable(t.commandName)?hn(t.commandName,await e.execute(t.commandName,i.args??``)):JSON.stringify({success:!1,command:t.commandName,error:`Command is not model-invocable: ${t.commandName}`})})})}function _n(e){let t=e.argumentHint?`Arguments for the command. Expected grammar: ${e.argumentHint}`:`Arguments for the command as a single string.`;return g.object({args:g.string().optional().describe(t)})}function vn(e,t){let n=[t.description.trim(),`Robota command id: ${e}.`];return t.argumentHint&&n.push(`Argument grammar: ${t.argumentHint}`),n.filter(e=>e.length>0).join(`
48
48
 
49
- `)}const vn={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`,opus:`claude-opus-4-6`},yn=dn(`agent`);function bn(e,t){return vn[e]??e}function xn(e,t){let n=[...e];if(t.disallowedTools){let e=new Set(t.disallowedTools);n=n.filter(t=>!e.has(t.getName()))}if(t.tools){let e=new Set(t.tools);n=n.filter(t=>e.has(t.getName()))}return n=n.filter(e=>e.getName()!==`Agent`&&e.getName()!==yn),n}function Sn(e){let{agentDefinition:t,parentConfig:n,parentContext:r,parentTools:i,terminal:a}=e,o=xn(i,t),s=t.model?bn(t.model,n.provider.model):n.provider.model,c=sn({agentBody:t.systemPrompt,claudeMd:r.claudeMd,agentsMd:r.agentsMd,isForkWorker:e.isForkWorker??!1}),l=e.provider;return new ye({tools:o,provider:l,systemMessage:c,terminal:a,...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.sessionLogger===void 0?{}:{sessionLogger:e.sessionLogger},model:s,maxTurns:t.maxTurns,permissions:n.permissions,permissionMode:e.permissionMode,defaultTrustLevel:n.defaultTrustLevel,permissionHandler:e.permissionHandler,hooks:e.hooks,hookTypeExecutors:e.hookTypeExecutors,onTextDelta:e.onTextDelta,onToolExecution:e.onToolExecution})}function Cn(e,t){let n=t?.(e)??rn(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function wn(e,t){return{...e,...t.request.model?{model:t.request.model}:{},...t.request.allowedTools?{tools:t.request.allowedTools}:{},...t.request.disallowedTools?{disallowedTools:t.request.disallowedTools}:{}}}function Tn(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function En(e){if(e.request.isolation===`worktree`)throw Error(`Worktree isolation requires a runtime shell subagent runner`)}function Dn(e,t){if(t.type===`start`){e.emit?.({type:`background_task_tool_start`,toolName:t.toolName,firstArg:Tn(t.toolArgs)});return}e.emit?.({type:`background_task_tool_end`,toolName:t.toolName,success:t.success??!0})}function On(e){return{start(t){En(t);let n=Sn({agentDefinition:wn(Cn(t.request.type,e.customAgentRegistry),t),parentConfig:e.config,parentContext:e.context,parentTools:e.tools,provider:e.provider,terminal:e.terminal,permissionMode:e.permissionMode,permissionHandler:e.permissionHandler,hooks:e.hooks,hookTypeExecutors:e.hookTypeExecutors,onTextDelta:n=>{t.emit?.({type:`background_task_text_delta`,delta:n}),e.onTextDelta?.(n)},onToolExecution:n=>{Dn(t,n),e.onToolExecution?.(n)}});return{jobId:t.jobId,result:n.run(t.request.prompt).then(e=>({jobId:t.jobId,output:e})),cancel:()=>(n.abort(),Promise.resolve())}}}}const kn=[`Creates delegated subagent jobs in isolated contexts.`,`Without jobs, one tool call creates one subagent job from prompt.`,`For explicit multi-agent or parallel-agent requests, use one Agent tool call with jobs containing one entry per requested role and a stable label for each role.`,`When the user explicitly asks to create, run, spawn, delegate to, or use agents/subagents, start the requested subagent job immediately.`,`Do not ask a follow-up question unless execution is impossible or unsafe.`,`Subagent jobs run as background tasks by default.`,`The tool waits for a terminal result and returns completed, failed, or timed-out outcome data with structured requested/started job counts.`,`After the tool returns, base user-facing claims on returned mode and counts; do not say parallel or multiple jobs started unless the result proves those jobs started.`,`Execution is represented by a real tool call and runtime background task event.`].join(` `);function An(e){return e}const jn=_.object({prompt:_.string().optional().describe(`The task for a single subagent to perform. Required when jobs is omitted.`),subagent_type:_.string().optional().describe(`Agent type: "general-purpose", "Explore", "Plan", or a custom agent name`),model:_.string().optional().describe(`Optional model override`),isolation:_.enum([`none`,`worktree`]).optional().describe(`Optional runtime isolation mode. "worktree" runs in a Git worktree.`),jobs:_.array(_.object({label:_.string().optional().describe(`Stable role label for this batch job`),prompt:_.string().describe(`The task for this subagent to perform`),subagent_type:_.string().optional().describe(`Agent type for this job`),model:_.string().optional().describe(`Optional model override for this job`),isolation:_.enum([`none`,`worktree`]).optional().describe(`Isolation for this job`)}).passthrough()).optional().describe(`Batch of subagent jobs to start in one Agent tool call`)}).passthrough(),Mn=new WeakMap;function Nn(e,t){Mn.set(e,t)}function R(e){return Mn.get(e)}function Pn(e,t){if(t){let n=t(e);if(n)return n}let n=rn(e);if(n)return n}function Fn(e){return e.subagentManager??new ne({runner:On(e)})}function In(e,t,n,r,i=n.name,a){return{type:t,label:i,parentSessionId:r.parentSessionId??`unknown-session`,mode:`background`,depth:r.subagentDepth??1,cwd:r.cwd??process.cwd(),prompt:e.prompt,model:e.model,isolation:e.isolation,metadata:P({kind:`tool_call`,sessionId:r.parentSessionId??`unknown-session`,label:i,...a?{toolCallId:a}:{}})}}async function Ln(e,t,n,r){if(typeof e.prompt!=`string`||e.prompt.length===0)return tn(`prompt is required when jobs is omitted`);let i={...e,prompt:e.prompt},a=e.subagent_type??`general-purpose`,o=Pn(a,t.customAgentRegistry);if(!o)return $t(a);let s;try{let e=await n.spawn(In(i,a,o,t,void 0,r));return s=e.id,en(await n.wait(e.id))}catch(e){return tn(e instanceof Error?e.message:String(e),s)}}function Rn(e){let t=Fn(e);return fe(`Agent`,kn,An(jn),async(n,r)=>{let i=n,a=r?.executionId;return Array.isArray(i.jobs)&&i.jobs.length>0?Qt({jobs:i.jobs,deps:e,manager:t,resolveAgentDefinition:Pn,createSpawnRequest:In,toolCallId:a}):Ln({prompt:i.prompt,...i.subagent_type===void 0?{}:{subagent_type:i.subagent_type},...i.model===void 0?{}:{model:i.model},...i.isolation===void 0?{}:{isolation:i.isolation}},e,t,a)})}var zn=class{getManager;onChanged;emitTaskEvent;emitGroupEvent;persistSession;backgroundTasks=[];backgroundTaskEvents=[];backgroundJobGroups=[];backgroundJobGroupEvents=[];backgroundTaskUnsubscribe=null;backgroundJobUnsubscribe=null;backgroundJobOrchestrator=null;constructor(e,t,n,r,i){this.getManager=e,this.onChanged=t,this.emitTaskEvent=n,this.emitGroupEvent=r,this.persistSession=i}subscribe(e){if(this.backgroundTaskUnsubscribe)return;let t=Bt(e)??R(e)?.backgroundTaskManager;t&&(this.backgroundTaskUnsubscribe=t.subscribe(e=>{this.recordTaskEvent(e),this.emitTaskEvent(e)}))}dispose(){this.backgroundTaskUnsubscribe?.(),this.backgroundTaskUnsubscribe=null,this.backgroundJobUnsubscribe?.(),this.backgroundJobUnsubscribe=null,this.backgroundJobOrchestrator?.dispose(),this.backgroundJobOrchestrator=null}restoreState(e){this.backgroundTasks=e.tasks,this.backgroundTaskEvents=e.taskEvents,this.backgroundJobGroups=e.groups,this.backgroundJobGroupEvents=e.groupEvents}getState(){return{tasks:this.getTaskSnapshots(),taskEvents:this.backgroundTaskEvents,groups:this.getGroupSnapshots(),groupEvents:this.backgroundJobGroupEvents}}getManagerOrThrow(){let e=this.getManager();if(!e)throw Error(`Background task manager is not available for this session.`);return e}getOrchestratorOrThrow(e){if(this.backgroundJobOrchestrator)return this.backgroundJobOrchestrator;let t=this.getManagerOrThrow();return this.backgroundJobOrchestrator=new rt({manager:t,initialGroups:this.backgroundJobGroups}),this.subscribeGroupEvents(e),this.backgroundJobOrchestrator}async cancelTask(e,t){await this.getManagerOrThrow().cancel(e,t)}async closeTask(e){await this.getManagerOrThrow().close(e)}async sendTask(e,t){await this.getManagerOrThrow().send(e,t)}async readTaskLog(e,t){return this.getManagerOrThrow().readLog(e,t)}listTasks(e){return this.getManagerOrThrow().list(e)}getTask(e){return this.getManagerOrThrow().get(e)}createGroup(e,t){return this.getOrchestratorOrThrow(t).createGroup({...e,parentSessionId:t})}listGroups(e){return this.getOrchestratorOrThrow(e).listGroups()}getGroup(e,t){return this.getOrchestratorOrThrow(t).getGroup(e)}async waitGroup(e,t){return this.getOrchestratorOrThrow(t).waitGroup(e)}async readTaskDetail(e,t,n){let r=this.getManagerOrThrow().get(t);if(!r)throw Error(`Unknown background task: ${t}`);if(r.logPath||r.transcriptPath){let i=await this.getManagerOrThrow().readLog(t,n);return Mt({entryId:e,lines:i.lines,cursor:i.cursor,nextCursor:i.nextCursor,kind:r.kind===`process`?`process_output`:`progress`})}let i=r.status===`failed`?`error`:r.status===`completed`?`result`:`progress`;return Mt({entryId:e,lines:[r.error?.message??r.result?.output??r.currentAction??r.promptPreview??r.commandPreview??r.status],cursor:n,kind:i})}readGroupDetail(e,t,n){let r=this.getOrchestratorOrThrow(n).getGroup(t);if(!r)throw Error(`Unknown background job group: ${t}`);return Mt({entryId:e,lines:ct(r).lines,kind:`group_summary`})}getTaskSnapshots(){try{return this.getManagerOrThrow().list()}catch{return this.backgroundTasks}}getGroupSnapshots(){try{return this.backgroundJobOrchestrator?.listGroups()??this.backgroundJobGroups}catch{return this.backgroundJobGroups}}subscribeGroupEvents(e){this.backgroundJobUnsubscribe||!this.backgroundJobOrchestrator||(this.backgroundJobUnsubscribe=this.backgroundJobOrchestrator.subscribe(t=>{this.recordGroupEvent(t,e),this.emitGroupEvent(t)}))}recordTaskEvent(e){this.backgroundTasks=this.getTaskSnapshots(),this.backgroundTaskEvents.push(e),this.persistSession(),this.onChanged(`background_task`,Bn(e))}recordGroupEvent(e,t){this.backgroundJobGroups=this.getGroupSnapshots(),this.backgroundJobGroupEvents.push(e),this.persistSession(),this.onChanged(`background_group`,ft(e.group.id))}};function Bn(e){if(`task`in e)return N(e.task.id);if(`taskId`in e)return N(e.taskId)}function Vn(e){let t=R(e);if(!t)throw Error(`Agent runtime dependencies are not available for this session.`);if(!t.backgroundTaskManager)throw Error(`Background task manager is not available for this session.`);return t}function z(e){let t=Vn(e);if(!t.subagentManager)throw Error(`Subagent manager is not available for this session.`);return t.subagentManager}function Hn(e,t){let n=t.customAgentRegistry?.(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Un(e){return(R(e)?.agentDefinitions??[]).map(e=>({name:e.name,description:e.description}))}async function Wn(e,t,n,r){let i=Vn(e),a=Hn(t.agentType,i),o=e.getSessionId();return z(e).spawn({type:t.agentType,label:t.label,parentSessionId:o,mode:t.mode,depth:(i.subagentDepth??0)+1,cwd:i.cwd??n??process.cwd(),prompt:t.prompt,model:t.model??a.model,isolation:t.isolation,allowedTools:a.tools,disallowedTools:a.disallowedTools,metadata:P({kind:r===`model`?`model_command`:`slash_command`,sessionId:o,commandName:`agent`,label:t.label})})}async function Gn(e,t){return z(e).wait(t)}async function Kn(e,t,n){await z(e).send(t,n)}async function qn(e,t,n){await z(e).cancel(t,n)}async function Jn(e,t){await z(e).close(t)}function Yn(e){return z(e).list()}function Xn(e,t={}){let{sessionId:n,execCtrl:r,histTracker:i,bgTracker:a}=e,o=i.getHistory();return mt({sessionId:n,mainThread:{sessionId:n,isExecuting:r.executing,hasPendingPrompt:r.pendingPrompt!==null,historyLength:o.length,updatedAt:o.at(-1)?.timestamp.toISOString()??new Date(0).toISOString(),preview:r.streamingText.trim().length>0?r.streamingText:o.at(-1)?.type},tasks:a.getTaskSnapshots(),groups:a.getGroupSnapshots(),selectedEntryId:t.selectedEntryId,filter:t.filter})}async function Zn(e,t,n,r,i){let a=pt(e);if(!a)throw Error(`Unknown execution workspace entry: ${e}`);return a.kind===`main_thread`?jt({entryId:e,history:t(),cursor:i}):a.kind===`background_group`?n.readGroupDetail(e,a.sourceId,r):n.readTaskDetail(e,a.sourceId,i)}function Qn(e,t,n,r){return Ft({manager:e.getManagerOrThrow(),groupOrchestrator:e.getOrchestratorOrThrow(t),sessionId:t,cwd:n,origin:{...r,sessionId:r.sessionId||t}})}var $n=class{isExecuting(){return this.execCtrl.executing}getPendingPrompt(){return this.execCtrl.pendingPrompt}getStreamingText(){return this.execCtrl.streamingText}getActiveTools(){return this.execCtrl.activeTools}cancelQueue(){this.execCtrl.clearPendingQueue()}async executeCommand(e,t){return await this.ensureInitialized(),this.execCtrl.executing?{success:!1,message:`Another prompt or command is already running. Wait for it to finish.`}:this.skillRouter.executeCommand(e,t)}async executeModelCommand(e,t){return await this.ensureInitialized(),this.skillRouter.executeModelCommand(e,t)}getCommandInvocationSource(){return this.skillRouter.getCommandInvocationSource()}async executeSkillCommandByName(e,t,n){return await this.ensureInitialized(),this.skillRouter.executeSkillCommandByName(e,t,n)}listCommands(){return this.skillRouter.listCommands()}listSkills(){return this.skillRouter.listSkills()}listModelInvocableCommands(){return this.skillRouter.listModelInvocableCommands()}getCommandHostAdapters(){return this.skillRouter.getCommandHostAdapters()}getSkillActivationEvents(){return this.histTracker.getSkillActivationEvents()}getContextState(){return this.getSessionOrThrow().getContextState()}async compactContext(e){await this.getSessionOrThrow().compact(e)}getFullHistory(){return this.histTracker.getHistory()}getMessages(){return this.histTracker.getHistory().filter(e=>e.category===`chat`).map(e=>e.data)}listEditCheckpoints(){return this.histTracker.listEditCheckpoints()}inspectEditCheckpoint(e){return this.histTracker.inspectEditCheckpoint(e)}async restoreEditCheckpoint(e){return await this.ensureInitialized(),this.histTracker.restoreEditCheckpoint(e)}async rollbackEditCheckpoint(e){return await this.ensureInitialized(),this.histTracker.rollbackEditCheckpoint(e)}getUsedMemoryReferences(){return this.histTracker.getUsedMemoryReferences()}recordMemoryEvent(e){this.histTracker.recordMemoryEvent(e)}listContextReferences(){return this.histTracker.listContextReferences()}async addContextReference(e){return this.histTracker.addContextReference(e)}removeContextReference(e){return this.histTracker.removeContextReference(e)}clearContextReferences(){return this.histTracker.clearContextReferences()}listBackgroundTasks(e){return this.bgTracker.listTasks(e)}getBackgroundTask(e){return this.bgTracker.getTask(e)}async cancelBackgroundTask(e,t){await this.ensureInitialized(),await this.bgTracker.cancelTask(e,t)}async closeBackgroundTask(e){await this.ensureInitialized(),await this.bgTracker.closeTask(e)}async sendBackgroundTask(e,t){await this.ensureInitialized(),await this.bgTracker.sendTask(e,t)}async readBackgroundTaskLog(e,t){return await this.ensureInitialized(),this.bgTracker.readTaskLog(e,t)}createBackgroundJobGroup(e){return this.bgTracker.createGroup(e,this.getSessionOrThrow().getSessionId())}listBackgroundJobGroups(){return this.bgTracker.listGroups(this.getSessionOrThrow().getSessionId())}getBackgroundJobGroup(e){return this.bgTracker.getGroup(e,this.getSessionOrThrow().getSessionId())}async waitBackgroundJobGroup(e){return await this.ensureInitialized(),this.bgTracker.waitGroup(e,this.getSessionOrThrow().getSessionId())}getExecutionWorkspaceSnapshot(e={}){return Xn({sessionId:this.getSessionOrThrow().getSessionId(),execCtrl:this.execCtrl,histTracker:this.histTracker,bgTracker:this.bgTracker},e)}listExecutionWorkspaceEntries(e){return[...this.getExecutionWorkspaceSnapshot({filter:e}).entries]}getExecutionWorkspaceEntry(e){return this.getExecutionWorkspaceSnapshot().entries.find(t=>t.id===e)}async readExecutionWorkspaceDetail(e,t){return await this.ensureInitialized(),Zn(e,()=>this.histTracker.getHistory(),this.bgTracker,this.getSessionOrThrow().getSessionId(),t)}createExecutionWorkspaceTaskSpawner(e){return Qn(this.bgTracker,this.getSessionOrThrow().getSessionId(),this.getCwd(),e)}listAgentDefinitions(){return Un(this.getSessionOrThrow())}listAgentJobs(){return Yn(this.getSessionOrThrow())}async spawnAgentJob(e){return await this.ensureInitialized(),Wn(this.getSessionOrThrow(),e,this.getCwd(),this.skillRouter.getCommandInvocationSource())}async waitAgentJob(e){return await this.ensureInitialized(),Gn(this.getSessionOrThrow(),e)}async sendAgentJob(e,t){await this.ensureInitialized(),await Kn(this.getSessionOrThrow(),e,t)}async cancelAgentJob(e,t){await this.ensureInitialized(),await qn(this.getSessionOrThrow(),e,t)}async closeAgentJob(e){await this.ensureInitialized(),await Jn(this.getSessionOrThrow(),e)}},B=class{existsSync(e){return y(e)}readFileSync(e,t){return b(e,t)}writeFileSync(e,t,n){Pe(e,t,n??`utf8`)}mkdirSync(e,t){Oe(e,t)}readdirSync(e,t){return t?.withFileTypes?ke(e,{withFileTypes:!0}):ke(e)}statSync(e){return Me(e)}rmSync(e,t){je(e,t)}cpSync(e,t,n){Ee(e,t,n)}renameSync(e,t){Ae(e,t)}get constants(){return Te}},V=class{async access(e,t){await Fe(e,t)}async copyFile(e,t,n){await Ie(e,t,n)}async mkdir(e,t){await Le(e,t)}async readFile(e,t){return Re(e,t)}async readdir(e,t){return t?.withFileTypes?await ze(e,{withFileTypes:!0}):ze(e)}async realpath(e){return Be(e)}async rename(e,t){await Ve(e,t)}async rm(e,t){await He(e,t)}async stat(e){return Ue(e)}async writeFile(e,t,n){await We(e,t,n??`utf8`)}};function er(e){return we(`sha256`).update(e,`utf-8`).digest(`hex`)}function tr(e,t=new B){let n=t.readFileSync(e,`utf-8`);return{filePath:e,content:n,contentHash:er(n)}}async function nr(e,t=new B){let n=[],r=[];for(let i of e){if(!t.existsSync(i.filePath)){r.push(i);continue}er(t.readFileSync(i.filePath,`utf-8`))===i.contentHash?r.push(i):n.push(i)}return{stale:n,fresh:r}}async function rr(e,t=new B){let{stale:n}=await nr(e,t),r=new Set(n.map(e=>e.filePath)),i=[];return{updated:e.map(e=>{if(!r.has(e.filePath))return e;let n=t.readFileSync(e.filePath,`utf-8`);return i.push(e.filePath),{filePath:e.filePath,content:n,contentHash:er(n)}}),refreshed:i}}async function ir(e,t,n,r,i,a){if(!n)return;let o=[...e,...t];if(o.length===0)return;let s=e.length,{updated:c,refreshed:l}=await rr(o);if(l.length===0)return;let u=c.slice(0,s),d=c.slice(s);r(u,d);let f=n(u.map(e=>e.content).join(`
49
+ `)}const yn={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`,opus:`claude-opus-4-6`},bn=fn(`agent`);function xn(e,t){return yn[e]??e}function Sn(e,t){let n=[...e];if(t.disallowedTools){let e=new Set(t.disallowedTools);n=n.filter(t=>!e.has(t.getName()))}if(t.tools){let e=new Set(t.tools);n=n.filter(t=>e.has(t.getName()))}return n=n.filter(e=>e.getName()!==`Agent`&&e.getName()!==bn),n}function Cn(e){let{agentDefinition:t,parentConfig:n,parentContext:r,parentTools:i,terminal:a}=e,o=Sn(i,t),s=t.model?xn(t.model,n.provider.model):n.provider.model,c=cn({agentBody:t.systemPrompt,claudeMd:r.claudeMd,agentsMd:r.agentsMd,isForkWorker:e.isForkWorker??!1}),l=e.provider;return new be({tools:o,provider:l,systemMessage:c,terminal:a,...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.sessionLogger===void 0?{}:{sessionLogger:e.sessionLogger},model:s,maxTurns:t.maxTurns,permissions:n.permissions,permissionMode:e.permissionMode,defaultTrustLevel:n.defaultTrustLevel,permissionHandler:e.permissionHandler,hooks:e.hooks,hookTypeExecutors:e.hookTypeExecutors,onTextDelta:e.onTextDelta,onToolExecution:e.onToolExecution})}function wn(e,t){let n=t?.(e)??an(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Tn(e,t){return{...e,...t.request.model?{model:t.request.model}:{},...t.request.allowedTools?{tools:t.request.allowedTools}:{},...t.request.disallowedTools?{disallowedTools:t.request.disallowedTools}:{}}}function En(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function Dn(e){if(e.request.isolation===`worktree`)throw Error(`Worktree isolation requires a runtime shell subagent runner`)}function On(e,t){if(t.type===`start`){e.emit?.({type:`background_task_tool_start`,toolName:t.toolName,firstArg:En(t.toolArgs)});return}e.emit?.({type:`background_task_tool_end`,toolName:t.toolName,success:t.success??!0})}function kn(e){return{start(t){Dn(t);let n=Cn({agentDefinition:Tn(wn(t.request.type,e.customAgentRegistry),t),parentConfig:e.config,parentContext:e.context,parentTools:e.tools,provider:e.provider,terminal:e.terminal,permissionMode:e.permissionMode,permissionHandler:e.permissionHandler,hooks:e.hooks,hookTypeExecutors:e.hookTypeExecutors,onTextDelta:n=>{t.emit?.({type:`background_task_text_delta`,delta:n}),e.onTextDelta?.(n)},onToolExecution:n=>{On(t,n),e.onToolExecution?.(n)}});return{jobId:t.jobId,result:n.run(t.request.prompt).then(e=>({jobId:t.jobId,output:e})),cancel:()=>(n.abort(),Promise.resolve())}}}}const An=[`Creates delegated subagent jobs in isolated contexts.`,`Without jobs, one tool call creates one subagent job from prompt.`,`For explicit multi-agent or parallel-agent requests, use one Agent tool call with jobs containing one entry per requested role and a stable label for each role.`,`When the user explicitly asks to create, run, spawn, delegate to, or use agents/subagents, start the requested subagent job immediately.`,`Do not ask a follow-up question unless execution is impossible or unsafe.`,`Subagent jobs run as background tasks by default.`,`The tool waits for a terminal result and returns completed, failed, or timed-out outcome data with structured requested/started job counts.`,`After the tool returns, base user-facing claims on returned mode and counts; do not say parallel or multiple jobs started unless the result proves those jobs started.`,`Execution is represented by a real tool call and runtime background task event.`].join(` `);function jn(e){return e}const Mn=g.object({prompt:g.string().optional().describe(`The task for a single subagent to perform. Required when jobs is omitted.`),subagent_type:g.string().optional().describe(`Agent type: "general-purpose", "Explore", "Plan", or a custom agent name`),model:g.string().optional().describe(`Optional model override`),isolation:g.enum([`none`,`worktree`]).optional().describe(`Optional runtime isolation mode. "worktree" runs in a Git worktree.`),jobs:g.array(g.object({label:g.string().optional().describe(`Stable role label for this batch job`),prompt:g.string().describe(`The task for this subagent to perform`),subagent_type:g.string().optional().describe(`Agent type for this job`),model:g.string().optional().describe(`Optional model override for this job`),isolation:g.enum([`none`,`worktree`]).optional().describe(`Isolation for this job`)}).passthrough()).optional().describe(`Batch of subagent jobs to start in one Agent tool call`)}).passthrough(),Nn=new WeakMap;function Pn(e,t){Nn.set(e,t)}function L(e){return Nn.get(e)}function Fn(e,t){if(t){let n=t(e);if(n)return n}let n=an(e);if(n)return n}function In(e){return e.subagentManager??new re({runner:kn(e)})}function Ln(e,t,n,r,i=n.name,a){return{type:t,label:i,parentSessionId:r.parentSessionId??`unknown-session`,mode:`background`,depth:r.subagentDepth??1,cwd:r.cwd??process.cwd(),prompt:e.prompt,model:e.model,isolation:e.isolation,metadata:N({kind:`tool_call`,sessionId:r.parentSessionId??`unknown-session`,label:i,...a?{toolCallId:a}:{}})}}async function Rn(e,t,n,r){if(typeof e.prompt!=`string`||e.prompt.length===0)return nn(`prompt is required when jobs is omitted`);let i={...e,prompt:e.prompt},a=e.subagent_type??`general-purpose`,o=Fn(a,t.customAgentRegistry);if(!o)return en(a);let s;try{let e=await n.spawn(Ln(i,a,o,t,void 0,r));return s=e.id,tn(await n.wait(e.id))}catch(e){return nn(e instanceof Error?e.message:String(e),s)}}function zn(e){let t=In(e);return pe(`Agent`,An,jn(Mn),async(n,r)=>{let i=n,a=r?.executionId;return Array.isArray(i.jobs)&&i.jobs.length>0?$t({jobs:i.jobs,deps:e,manager:t,resolveAgentDefinition:Fn,createSpawnRequest:Ln,toolCallId:a}):Rn({prompt:i.prompt,...i.subagent_type===void 0?{}:{subagent_type:i.subagent_type},...i.model===void 0?{}:{model:i.model},...i.isolation===void 0?{}:{isolation:i.isolation}},e,t,a)})}var Bn=class{getManager;onChanged;emitTaskEvent;emitGroupEvent;persistSession;backgroundTasks=[];backgroundTaskEvents=[];backgroundJobGroups=[];backgroundJobGroupEvents=[];backgroundTaskUnsubscribe=null;backgroundJobUnsubscribe=null;backgroundJobOrchestrator=null;constructor(e,t,n,r,i){this.getManager=e,this.onChanged=t,this.emitTaskEvent=n,this.emitGroupEvent=r,this.persistSession=i}subscribe(e){if(this.backgroundTaskUnsubscribe)return;let t=Vt(e)??L(e)?.backgroundTaskManager;t&&(this.backgroundTaskUnsubscribe=t.subscribe(e=>{this.recordTaskEvent(e),this.emitTaskEvent(e)}))}dispose(){this.backgroundTaskUnsubscribe?.(),this.backgroundTaskUnsubscribe=null,this.backgroundJobUnsubscribe?.(),this.backgroundJobUnsubscribe=null,this.backgroundJobOrchestrator?.dispose(),this.backgroundJobOrchestrator=null}restoreState(e){this.backgroundTasks=e.tasks,this.backgroundTaskEvents=e.taskEvents,this.backgroundJobGroups=e.groups,this.backgroundJobGroupEvents=e.groupEvents}getState(){return{tasks:this.getTaskSnapshots(),taskEvents:this.backgroundTaskEvents,groups:this.getGroupSnapshots(),groupEvents:this.backgroundJobGroupEvents}}getManagerOrThrow(){let e=this.getManager();if(!e)throw Error(`Background task manager is not available for this session.`);return e}getOrchestratorOrThrow(e){if(this.backgroundJobOrchestrator)return this.backgroundJobOrchestrator;let t=this.getManagerOrThrow();return this.backgroundJobOrchestrator=new it({manager:t,initialGroups:this.backgroundJobGroups}),this.subscribeGroupEvents(e),this.backgroundJobOrchestrator}async cancelTask(e,t){await this.getManagerOrThrow().cancel(e,t)}async closeTask(e){await this.getManagerOrThrow().close(e)}async sendTask(e,t){await this.getManagerOrThrow().send(e,t)}async readTaskLog(e,t){return this.getManagerOrThrow().readLog(e,t)}listTasks(e){return this.getManagerOrThrow().list(e)}getTask(e){return this.getManagerOrThrow().get(e)}createGroup(e,t){return this.getOrchestratorOrThrow(t).createGroup({...e,parentSessionId:t})}listGroups(e){return this.getOrchestratorOrThrow(e).listGroups()}getGroup(e,t){return this.getOrchestratorOrThrow(t).getGroup(e)}async waitGroup(e,t){return this.getOrchestratorOrThrow(t).waitGroup(e)}async readTaskDetail(e,t,n){let r=this.getManagerOrThrow().get(t);if(!r)throw Error(`Unknown background task: ${t}`);if(r.logPath||r.transcriptPath){let i=await this.getManagerOrThrow().readLog(t,n);return Nt({entryId:e,lines:i.lines,cursor:i.cursor,nextCursor:i.nextCursor,kind:r.kind===`process`?`process_output`:`progress`})}let i=r.status===`failed`?`error`:r.status===`completed`?`result`:`progress`;return Nt({entryId:e,lines:[r.error?.message??r.result?.output??r.currentAction??r.promptPreview??r.commandPreview??r.status],cursor:n,kind:i})}readGroupDetail(e,t,n){let r=this.getOrchestratorOrThrow(n).getGroup(t);if(!r)throw Error(`Unknown background job group: ${t}`);return Nt({entryId:e,lines:lt(r).lines,kind:`group_summary`})}getTaskSnapshots(){try{return this.getManagerOrThrow().list()}catch{return this.backgroundTasks}}getGroupSnapshots(){try{return this.backgroundJobOrchestrator?.listGroups()??this.backgroundJobGroups}catch{return this.backgroundJobGroups}}subscribeGroupEvents(e){this.backgroundJobUnsubscribe||!this.backgroundJobOrchestrator||(this.backgroundJobUnsubscribe=this.backgroundJobOrchestrator.subscribe(t=>{this.recordGroupEvent(t,e),this.emitGroupEvent(t)}))}recordTaskEvent(e){this.backgroundTasks=this.getTaskSnapshots(),this.backgroundTaskEvents.push(e),this.persistSession(),this.onChanged(`background_task`,Vn(e))}recordGroupEvent(e,t){this.backgroundJobGroups=this.getGroupSnapshots(),this.backgroundJobGroupEvents.push(e),this.persistSession(),this.onChanged(`background_group`,pt(e.group.id))}};function Vn(e){if(`task`in e)return M(e.task.id);if(`taskId`in e)return M(e.taskId)}function Hn(e){let t=L(e);if(!t)throw Error(`Agent runtime dependencies are not available for this session.`);if(!t.backgroundTaskManager)throw Error(`Background task manager is not available for this session.`);return t}function R(e){let t=Hn(e);if(!t.subagentManager)throw Error(`Subagent manager is not available for this session.`);return t.subagentManager}function Un(e,t){let n=t.customAgentRegistry?.(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Wn(e){return(L(e)?.agentDefinitions??[]).map(e=>({name:e.name,description:e.description}))}async function Gn(e,t,n,r){let i=Hn(e),a=Un(t.agentType,i),o=e.getSessionId();return R(e).spawn({type:t.agentType,label:t.label,parentSessionId:o,mode:t.mode,depth:(i.subagentDepth??0)+1,cwd:i.cwd??n??process.cwd(),prompt:t.prompt,model:t.model??a.model,isolation:t.isolation,allowedTools:a.tools,disallowedTools:a.disallowedTools,metadata:N({kind:r===`model`?`model_command`:`slash_command`,sessionId:o,commandName:`agent`,label:t.label})})}async function Kn(e,t){return R(e).wait(t)}async function qn(e,t,n){await R(e).send(t,n)}async function Jn(e,t,n){await R(e).cancel(t,n)}async function Yn(e,t){await R(e).close(t)}function Xn(e){return R(e).list()}function Zn(e,t={}){let{sessionId:n,execCtrl:r,histTracker:i,bgTracker:a}=e,o=i.getHistory();return ht({sessionId:n,mainThread:{sessionId:n,isExecuting:r.executing,hasPendingPrompt:r.pendingPrompt!==null,historyLength:o.length,updatedAt:o.at(-1)?.timestamp.toISOString()??new Date(0).toISOString(),preview:r.streamingText.trim().length>0?r.streamingText:o.at(-1)?.type},tasks:a.getTaskSnapshots(),groups:a.getGroupSnapshots(),selectedEntryId:t.selectedEntryId,filter:t.filter})}async function Qn(e,t,n,r,i){let a=mt(e);if(!a)throw Error(`Unknown execution workspace entry: ${e}`);return a.kind===`main_thread`?Mt({entryId:e,history:t(),cursor:i}):a.kind===`background_group`?n.readGroupDetail(e,a.sourceId,r):n.readTaskDetail(e,a.sourceId,i)}function $n(e,t,n,r){return It({manager:e.getManagerOrThrow(),groupOrchestrator:e.getOrchestratorOrThrow(t),sessionId:t,cwd:n,origin:{...r,sessionId:r.sessionId||t}})}var er=class{isExecuting(){return this.execCtrl.executing}getPendingPrompt(){return this.execCtrl.pendingPrompt}getStreamingText(){return this.execCtrl.streamingText}getActiveTools(){return this.execCtrl.activeTools}cancelQueue(){this.execCtrl.clearPendingQueue()}async executeCommand(e,t){return await this.ensureInitialized(),this.execCtrl.executing?{success:!1,message:`Another prompt or command is already running. Wait for it to finish.`}:this.skillRouter.executeCommand(e,t)}async executeModelCommand(e,t){return await this.ensureInitialized(),this.skillRouter.executeModelCommand(e,t)}getCommandInvocationSource(){return this.skillRouter.getCommandInvocationSource()}async executeSkillCommandByName(e,t,n){return await this.ensureInitialized(),this.skillRouter.executeSkillCommandByName(e,t,n)}listCommands(){return this.skillRouter.listCommands()}listSkills(){return this.skillRouter.listSkills()}listModelInvocableCommands(){return this.skillRouter.listModelInvocableCommands()}getCommandHostAdapters(){return this.skillRouter.getCommandHostAdapters()}getSkillActivationEvents(){return this.histTracker.getSkillActivationEvents()}getContextState(){return this.getSessionOrThrow().getContextState()}async compactContext(e){await this.getSessionOrThrow().compact(e)}getFullHistory(){return this.histTracker.getHistory()}getMessages(){return this.histTracker.getHistory().filter(e=>e.category===`chat`).map(e=>e.data)}listEditCheckpoints(){return this.histTracker.listEditCheckpoints()}inspectEditCheckpoint(e){return this.histTracker.inspectEditCheckpoint(e)}async restoreEditCheckpoint(e){return await this.ensureInitialized(),this.histTracker.restoreEditCheckpoint(e)}async rollbackEditCheckpoint(e){return await this.ensureInitialized(),this.histTracker.rollbackEditCheckpoint(e)}getUsedMemoryReferences(){return this.histTracker.getUsedMemoryReferences()}recordMemoryEvent(e){this.histTracker.recordMemoryEvent(e)}listContextReferences(){return this.histTracker.listContextReferences()}async addContextReference(e){return this.histTracker.addContextReference(e)}removeContextReference(e){return this.histTracker.removeContextReference(e)}clearContextReferences(){return this.histTracker.clearContextReferences()}listBackgroundTasks(e){return this.bgTracker.listTasks(e)}getBackgroundTask(e){return this.bgTracker.getTask(e)}async cancelBackgroundTask(e,t){await this.ensureInitialized(),await this.bgTracker.cancelTask(e,t)}async closeBackgroundTask(e){await this.ensureInitialized(),await this.bgTracker.closeTask(e)}async sendBackgroundTask(e,t){await this.ensureInitialized(),await this.bgTracker.sendTask(e,t)}async readBackgroundTaskLog(e,t){return await this.ensureInitialized(),this.bgTracker.readTaskLog(e,t)}createBackgroundJobGroup(e){return this.bgTracker.createGroup(e,this.getSessionOrThrow().getSessionId())}listBackgroundJobGroups(){return this.bgTracker.listGroups(this.getSessionOrThrow().getSessionId())}getBackgroundJobGroup(e){return this.bgTracker.getGroup(e,this.getSessionOrThrow().getSessionId())}async waitBackgroundJobGroup(e){return await this.ensureInitialized(),this.bgTracker.waitGroup(e,this.getSessionOrThrow().getSessionId())}getExecutionWorkspaceSnapshot(e={}){return Zn({sessionId:this.getSessionOrThrow().getSessionId(),execCtrl:this.execCtrl,histTracker:this.histTracker,bgTracker:this.bgTracker},e)}listExecutionWorkspaceEntries(e){return[...this.getExecutionWorkspaceSnapshot({filter:e}).entries]}getExecutionWorkspaceEntry(e){return this.getExecutionWorkspaceSnapshot().entries.find(t=>t.id===e)}async readExecutionWorkspaceDetail(e,t){return await this.ensureInitialized(),Qn(e,()=>this.histTracker.getHistory(),this.bgTracker,this.getSessionOrThrow().getSessionId(),t)}createExecutionWorkspaceTaskSpawner(e){return $n(this.bgTracker,this.getSessionOrThrow().getSessionId(),this.getCwd(),e)}listAgentDefinitions(){return Wn(this.getSessionOrThrow())}listAgentJobs(){return Xn(this.getSessionOrThrow())}async spawnAgentJob(e){return await this.ensureInitialized(),Gn(this.getSessionOrThrow(),e,this.getCwd(),this.skillRouter.getCommandInvocationSource())}async waitAgentJob(e){return await this.ensureInitialized(),Kn(this.getSessionOrThrow(),e)}async sendAgentJob(e,t){await this.ensureInitialized(),await qn(this.getSessionOrThrow(),e,t)}async cancelAgentJob(e,t){await this.ensureInitialized(),await Jn(this.getSessionOrThrow(),e,t)}async closeAgentJob(e){await this.ensureInitialized(),await Yn(this.getSessionOrThrow(),e)}},z=class{existsSync(e){return v(e)}readFileSync(e,t){return y(e,t)}writeFileSync(e,t,n){Fe(e,t,n??`utf8`)}mkdirSync(e,t){ke(e,t)}readdirSync(e,t){return t?.withFileTypes?Ae(e,{withFileTypes:!0}):Ae(e)}statSync(e){return Ne(e)}rmSync(e,t){Me(e,t)}cpSync(e,t,n){De(e,t,n)}renameSync(e,t){je(e,t)}get constants(){return Ee}},B=class{async access(e,t){await Ie(e,t)}async copyFile(e,t,n){await Le(e,t,n)}async mkdir(e,t){await Re(e,t)}async readFile(e,t){return ze(e,t)}async readdir(e,t){return t?.withFileTypes?await Be(e,{withFileTypes:!0}):Be(e)}async realpath(e){return Ve(e)}async rename(e,t){await He(e,t)}async rm(e,t){await Ue(e,t)}async stat(e){return We(e)}async writeFile(e,t,n){await Ge(e,t,n??`utf8`)}};function tr(e){return Te(`sha256`).update(e,`utf-8`).digest(`hex`)}function nr(e,t=new z){let n=t.readFileSync(e,`utf-8`);return{filePath:e,content:n,contentHash:tr(n)}}async function rr(e,t=new z){let n=[],r=[];for(let i of e){if(!t.existsSync(i.filePath)){r.push(i);continue}tr(t.readFileSync(i.filePath,`utf-8`))===i.contentHash?r.push(i):n.push(i)}return{stale:n,fresh:r}}async function ir(e,t=new z){let{stale:n}=await rr(e,t),r=new Set(n.map(e=>e.filePath)),i=[];return{updated:e.map(e=>{if(!r.has(e.filePath))return e;let n=t.readFileSync(e.filePath,`utf-8`);return i.push(e.filePath),{filePath:e.filePath,content:n,contentHash:tr(n)}}),refreshed:i}}async function ar(e,t,n,r,i,a){if(!n)return;let o=[...e,...t];if(o.length===0)return;let s=e.length,{updated:c,refreshed:l}=await ir(o);if(l.length===0)return;let u=c.slice(0,s),d=c.slice(s);r(u,d);let f=n(u.map(e=>e.content).join(`
50
50
 
51
51
  `),d.map(e=>e.content).join(`
52
52
 
53
- `));i().updateSystemMessage(f);for(let e of l)a(`context_file_refreshed`,{filePath:e})}function ar(e,t,n,r=new Date().toISOString()){return{id:`${t}:${e.relativePath}`,sourcePath:e.sourcePath,relativePath:e.relativePath,originalReference:e.originalReference,loadType:t,status:n,byteLength:e.byteLength,loadedAt:r,lastUsedAt:r}}function or(e,t,n){let r=e.find(e=>e.sourcePath===t.sourcePath),i=e.filter(e=>e.sourcePath!==t.sourcePath),a=r?dr(r,t):t;return fr([...i,a],n)}function sr(e,t){let n=hr(t),r=e.find(e=>gr(e,n));return r?{references:e.filter(e=>e.sourcePath!==r.sourcePath),result:{removed:r}}:{references:[...e],result:{}}}function cr(e){return{removed:[...e]}}function lr(e){return e.filter(e=>e.status===`active`)}function ur(e){return e.map(e=>({originalReference:e.originalReference,sourcePath:e.sourcePath,relativePath:e.relativePath,reason:e.loadType,depth:0,byteLength:e.byteLength}))}function dr(e,t){return t.status===`active`?{...t,loadedAt:e.loadedAt}:{...e,byteLength:t.byteLength,originalReference:t.originalReference,lastUsedAt:t.lastUsedAt}}function fr(e,t){let n=t?.maxActiveReferences??8,r=t?.maxActiveBytes??262144,i=t?.maxObservedReferences??32,a=[],o=[...e];for(;pr(o)>n||mr(o)>r;){let e=o.find(e=>e.status===`active`);if(!e)break;a.push(e),o=o.filter(t=>t.sourcePath!==e.sourcePath)}let s=o.filter(e=>e.status===`observed`);if(s.length>i){let e=s.slice(0,s.length-i);a.push(...e),o=o.filter(t=>t.status!==`observed`||!e.some(e=>e.sourcePath===t.sourcePath))}return{references:o,evicted:a}}function pr(e){return e.filter(e=>e.status===`active`).length}function mr(e){return e.reduce((e,t)=>e+(t.status===`active`?t.byteLength:0),0)}function hr(e){return e.startsWith(`@`)?e.slice(1):e}function gr(e,t){return e.relativePath===t||e.sourcePath===t||e.originalReference===t||e.originalReference===`@${t}`}function _r(e,t){return t.length===0?e:[e,`<robota_file_references>`,...t.map(e=>{let t=e.content.replaceAll(`</file>`,`<\\/file>`);return[`<file path="${xr(e.relativePath)}" bytes="${e.byteLength}" reason="${e.reason}">`,t,`</file>`].join(`
53
+ `));i().updateSystemMessage(f);for(let e of l)a(`context_file_refreshed`,{filePath:e})}function or(e,t,n,r=new Date().toISOString()){return{id:`${t}:${e.relativePath}`,sourcePath:e.sourcePath,relativePath:e.relativePath,originalReference:e.originalReference,loadType:t,status:n,byteLength:e.byteLength,loadedAt:r,lastUsedAt:r}}function sr(e,t,n){let r=e.find(e=>e.sourcePath===t.sourcePath),i=e.filter(e=>e.sourcePath!==t.sourcePath),a=r?fr(r,t):t;return pr([...i,a],n)}function cr(e,t){let n=gr(t),r=e.find(e=>_r(e,n));return r?{references:e.filter(e=>e.sourcePath!==r.sourcePath),result:{removed:r}}:{references:[...e],result:{}}}function lr(e){return{removed:[...e]}}function ur(e){return e.filter(e=>e.status===`active`)}function dr(e){return e.filter(e=>e.loadType!==`system`).map(e=>({originalReference:e.originalReference,sourcePath:e.sourcePath,relativePath:e.relativePath,reason:e.loadType,depth:0,byteLength:e.byteLength}))}function fr(e,t){return t.status===`active`?{...t,loadedAt:e.loadedAt}:{...e,byteLength:t.byteLength,originalReference:t.originalReference,lastUsedAt:t.lastUsedAt}}function pr(e,t){let n=t?.maxActiveReferences??8,r=t?.maxActiveBytes??262144,i=t?.maxObservedReferences??32,a=[],o=[...e];for(;mr(o)>n||hr(o)>r;){let e=o.find(e=>e.status===`active`);if(!e)break;a.push(e),o=o.filter(t=>t.sourcePath!==e.sourcePath)}let s=o.filter(e=>e.status===`observed`);if(s.length>i){let e=s.slice(0,s.length-i);a.push(...e),o=o.filter(t=>t.status!==`observed`||!e.some(e=>e.sourcePath===t.sourcePath))}return{references:o,evicted:a}}function mr(e){return e.filter(e=>e.status===`active`).length}function hr(e){return e.reduce((e,t)=>e+(t.status===`active`?t.byteLength:0),0)}function gr(e){return e.startsWith(`@`)?e.slice(1):e}function _r(e,t){return e.relativePath===t||e.sourcePath===t||e.originalReference===t||e.originalReference===`@${t}`}function vr(e,t){return t.length===0?e:[e,`<robota_file_references>`,...t.map(e=>{let t=e.content.replaceAll(`</file>`,`<\\/file>`);return[`<file path="${Sr(e.relativePath)}" bytes="${e.byteLength}" reason="${e.reason}">`,t,`</file>`].join(`
54
54
  `)}),`</robota_file_references>`].join(`
55
55
 
56
- `)}function vr(e){return e.some(e=>e.severity===`error`)}function yr(e){return e.length===0?``:[`File reference error:`,...e.map(e=>`- ${e.reference}: ${e.message}`)].join(`
57
- `)}function H(e){return e.map(({content:e,...t})=>t)}function br(e){let t=H(e);return{id:`prompt_file_reference_${v()}`,timestamp:new Date,category:`event`,type:`prompt-file-reference`,data:{message:Sr(t),references:t}}}function xr(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function Sr(e){return`Loaded file references: ${e.map(e=>`${e.relativePath} (${e.byteLength} B)`).join(`, `)}`}const Cr=/(^|[\s([{])@([^\s)\]}>,;"'`]+)/g;function wr(e){let t=[];for(let n of e.matchAll(Cr)){let e=Tr(n[2]??``);Er(e)&&t.push({original:`@${e}`,path:e,index:n.index??0})}return t}function Tr(e){let t=e.length;for(;t>0&&/[.,:;!?]/.test(e[t-1]??``);)--t;return e.slice(0,t)}function Er(e){return e.length===0||e.includes(`://`)?!1:e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)||e.startsWith(`~/`)||e.startsWith(`.`)||e.includes(`.`)}function Dr(e,t){return e.startsWith(`~/`)?T(E(),e.slice(2)):Ke(e)?T(e):T(t,e)}function Or(e,t){let n=w(t,e);return n===``||!n.startsWith(`..`)&&!Ke(n)}function kr(e,t){return w(e,t).split(qe).join(`/`)}const Ar=1024;64*Ar,256*Ar;async function jr(e,t){let n=await Nr(t);for(let t of wr(e))await Lr(t,0,[],n);return Pr(n)}async function Mr(e,t){let n=await Nr(t);for(let t of e)await Lr({original:`@${t}`,path:t,index:0},0,[],n);return Pr(n)}async function Nr(e){let t=e.fsAsync??new V;return{rootPath:await Ir(e.cwd,t),limits:Fr(e.limits),reason:e.reason??`prompt-reference`,references:[],diagnostics:[],loadedPaths:new Set,totalBytes:0,fsAsync:t}}function Pr(e){return{references:e.references,diagnostics:e.diagnostics}}function Fr(e){return{maxDepth:e?.maxDepth??2,maxReferences:e?.maxReferences??8,maxFileBytes:e?.maxFileBytes??65536,maxTotalBytes:e?.maxTotalBytes??262144}}async function Ir(e,t){try{return await t.realpath(e)}catch{return T(e)}}async function Lr(e,t,n,r){if(!Rr(e,t,r))return;let i=await zr(e,r);if(i===void 0||!Br(e,i,n,r))return;let a=await Vr(e,i,r);if(a===void 0)return;let o=await Hr(e,i,r);o!==void 0&&(r.loadedPaths.add(i),r.totalBytes+=a.byteLength,r.references.push(Ur(e,a,t,o,r)),await Wr(o,t,[...n,i],r))}function Rr(e,t,n){return n.references.length>=n.limits.maxReferences?(U(n,`too-many-references`,e,`Too many file references.`),!1):t>n.limits.maxDepth?(U(n,`max-depth`,e,`File reference nesting is too deep.`),!1):!0}async function zr(e,t){let n=Dr(e.path,t.rootPath);if(!Or(n,t.rootPath)){U(t,`outside-root`,e,`Referenced path is outside the workspace.`);return}try{let r=await t.fsAsync.realpath(n);if(Or(r,t.rootPath))return r;U(t,`outside-root`,e,`Referenced path resolves outside the workspace.`)}catch{U(t,`not-found`,e,`Referenced file was not found.`)}}function Br(e,t,n,r){return n.includes(t)?(U(r,`circular-reference`,e,`Circular file reference detected.`),!1):!r.loadedPaths.has(t)}async function Vr(e,t,n){try{let r=await n.fsAsync.stat(t);if(r.isDirectory()){U(n,`directory-not-supported`,e,`Directory references are not supported.`);return}if(r.size>n.limits.maxFileBytes){U(n,`file-too-large`,e,`Referenced file exceeds the per-file size limit.`);return}if(n.totalBytes+r.size>n.limits.maxTotalBytes){U(n,`total-too-large`,e,`Referenced files exceed the total size limit.`);return}return{sourcePath:t,byteLength:r.size}}catch{U(n,`unreadable`,e,`Referenced file could not be inspected.`);return}}async function Hr(e,t,n){try{return await n.fsAsync.readFile(t,`utf8`)}catch{U(n,`unreadable`,e,`Referenced file could not be read.`);return}}function Ur(e,t,n,r,i){return{originalReference:e.original,sourcePath:t.sourcePath,relativePath:kr(i.rootPath,t.sourcePath),reason:i.reason,depth:n,byteLength:t.byteLength,content:r}}async function Wr(e,t,n,r){for(let i of wr(e))await Lr(i,t+1,n,r)}function U(e,t,n,r){e.diagnostics.push({code:t,severity:`error`,reference:n.original,message:r,path:n.path})}function Gr(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&(e.message.includes(`aborted`)||e.message.includes(`abort`))}function Kr(e,t){let n=[];for(let r=t;r<e.length;r++){let t=e[r];if(t?.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)n.push({name:e.function.name,args:e.function.arguments})}return n}function qr(e,t,n,r,i,a){let o=Kr(t,r),s=Qr(t,r,i);return{response:e,history:n,toolSummaries:o,contextState:i,...s&&{usage:s},...a&&a.length>0?{promptFileReferences:[...a]}:{}}}function Jr(e,t,n,r){let i=Kr(e,n),a=[];for(let t=n;t<e.length;t++){let n=e[t];n?.role===`assistant`&&n.content&&a.push(n.content)}let o=Qr(e,n,r);return{response:a.join(`
56
+ `)}function yr(e){return e.some(e=>e.severity===`error`)}function br(e){return e.length===0?``:[`File reference error:`,...e.map(e=>`- ${e.reference}: ${e.message}`)].join(`
57
+ `)}function V(e){return e.map(({content:e,...t})=>t)}function xr(e){let t=V(e);return{id:`prompt_file_reference_${_()}`,timestamp:new Date,category:`event`,type:`prompt-file-reference`,data:{message:Cr(t),references:t}}}function Sr(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function Cr(e){return`Loaded file references: ${e.map(e=>`${e.relativePath} (${e.byteLength} B)`).join(`, `)}`}const wr=/(^|[\s([{])@([^\s)\]}>,;"'`]+)/g;function Tr(e){let t=[];for(let n of e.matchAll(wr)){let e=Er(n[2]??``);Dr(e)&&t.push({original:`@${e}`,path:e,index:n.index??0})}return t}function Er(e){let t=e.length;for(;t>0&&/[.,:;!?]/.test(e[t-1]??``);)--t;return e.slice(0,t)}function Dr(e){return e.length===0||e.includes(`://`)?!1:e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)||e.startsWith(`~/`)||e.startsWith(`.`)||e.includes(`.`)}function Or(e,t){return e.startsWith(`~/`)?w(T(),e.slice(2)):qe(e)?w(e):w(t,e)}function kr(e,t){let n=C(t,e);return n===``||!n.startsWith(`..`)&&!qe(n)}function Ar(e,t){return C(e,t).split(Je).join(`/`)}const jr=1024;64*jr,256*jr;async function Mr(e,t){let n=await Pr(t);for(let t of Tr(e))await Rr(t,0,[],n);return Fr(n)}async function Nr(e,t){let n=await Pr(t);for(let t of e)await Rr({original:`@${t}`,path:t,index:0},0,[],n);return Fr(n)}async function Pr(e){let t=e.fsAsync??new B;return{rootPath:await Lr(e.cwd,t),limits:Ir(e.limits),reason:e.reason??`prompt-reference`,references:[],diagnostics:[],loadedPaths:new Set,totalBytes:0,fsAsync:t}}function Fr(e){return{references:e.references,diagnostics:e.diagnostics}}function Ir(e){return{maxDepth:e?.maxDepth??2,maxReferences:e?.maxReferences??8,maxFileBytes:e?.maxFileBytes??65536,maxTotalBytes:e?.maxTotalBytes??262144}}async function Lr(e,t){try{return await t.realpath(e)}catch{return w(e)}}async function Rr(e,t,n,r){if(!zr(e,t,r))return;let i=await Br(e,r);if(i===void 0||!Vr(e,i,n,r))return;let a=await Hr(e,i,r);if(a===void 0)return;let o=await Ur(e,i,r);o!==void 0&&(r.loadedPaths.add(i),r.totalBytes+=a.byteLength,r.references.push(Wr(e,a,t,o,r)),await Gr(o,t,[...n,i],r))}function zr(e,t,n){return n.references.length>=n.limits.maxReferences?(H(n,`too-many-references`,e,`Too many file references.`),!1):t>n.limits.maxDepth?(H(n,`max-depth`,e,`File reference nesting is too deep.`),!1):!0}async function Br(e,t){let n=Or(e.path,t.rootPath);if(!kr(n,t.rootPath)){H(t,`outside-root`,e,`Referenced path is outside the workspace.`);return}try{let r=await t.fsAsync.realpath(n);if(kr(r,t.rootPath))return r;H(t,`outside-root`,e,`Referenced path resolves outside the workspace.`)}catch{H(t,`not-found`,e,`Referenced file was not found.`)}}function Vr(e,t,n,r){return n.includes(t)?(H(r,`circular-reference`,e,`Circular file reference detected.`),!1):!r.loadedPaths.has(t)}async function Hr(e,t,n){try{let r=await n.fsAsync.stat(t);if(r.isDirectory()){H(n,`directory-not-supported`,e,`Directory references are not supported.`);return}if(r.size>n.limits.maxFileBytes){H(n,`file-too-large`,e,`Referenced file exceeds the per-file size limit.`);return}if(n.totalBytes+r.size>n.limits.maxTotalBytes){H(n,`total-too-large`,e,`Referenced files exceed the total size limit.`);return}return{sourcePath:t,byteLength:r.size}}catch{H(n,`unreadable`,e,`Referenced file could not be inspected.`);return}}async function Ur(e,t,n){try{return await n.fsAsync.readFile(t,`utf8`)}catch{H(n,`unreadable`,e,`Referenced file could not be read.`);return}}function Wr(e,t,n,r,i){return{originalReference:e.original,sourcePath:t.sourcePath,relativePath:Ar(i.rootPath,t.sourcePath),reason:i.reason,depth:n,byteLength:t.byteLength,content:r}}async function Gr(e,t,n,r){for(let i of Tr(e))await Rr(i,t+1,n,r)}function H(e,t,n,r){e.diagnostics.push({code:t,severity:`error`,reference:n.original,message:r,path:n.path})}function Kr(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&(e.message.includes(`aborted`)||e.message.includes(`abort`))}function qr(e,t){let n=[];for(let r=t;r<e.length;r++){let t=e[r];if(t?.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)n.push({name:e.function.name,args:e.function.arguments})}return n}function Jr(e,t,n,r,i,a){let o=qr(t,r),s=$r(t,r,i);return{response:e,history:n,toolSummaries:o,contextState:i,...s&&{usage:s},...a&&a.length>0?{promptFileReferences:[...a]}:{}}}function Yr(e,t,n,r){let i=qr(e,n),a=[];for(let t=n;t<e.length;t++){let n=e[t];n?.role===`assistant`&&n.content&&a.push(n.content)}let o=$r(e,n,r);return{response:a.join(`
58
58
 
59
- `),history:t,toolSummaries:i,contextState:r,...o&&{usage:o}}}function Yr(e){return{id:`usage_${v()}`,timestamp:new Date,category:`event`,type:`usage-summary`,data:e}}async function Xr(e,t,n,r=[]){let i=await Mr(lr(r).map(e=>e.sourcePath),{cwd:t,reason:`manual`}),a=await jr(e,{cwd:t}),o=[...i.diagnostics,...a.diagnostics];if(vr(o))throw Error(yr(o));let s=_r(e,Zr([...i.references,...a.references])),c=n??(s===e?void 0:e),l=H(i.references),u=H(a.references),d=a.references.length>0?br(a.references):void 0;return{modelInput:s,...c===void 0?{}:{hookInput:c},activeContextReferenceRecords:l,promptFileReferenceRecords:u,...d===void 0?{}:{promptFileReferenceEntry:d}}}function Zr(e){return[...new Map(e.map(e=>[e.sourcePath,e])).values()]}function Qr(e,t,n){let r=e.slice(t),a=0,o=0,s=!1;for(let e of r){if(e.role!==`assistant`)continue;let t=i(e);t&&(s=!0,a+=t.inputTokens,o+=t.outputTokens)}if(s)return{kind:`exact`,scope:`turn`,promptTokens:a,completionTokens:o,totalTokens:a+o,contextUsedTokens:n.usedTokens,contextMaxTokens:n.maxTokens,contextUsedPercentage:n.usedPercentage,costStatus:`unknown`}}const $r={write:()=>{},writeLine:()=>{},writeMarkdown:()=>{},writeError:()=>{},prompt:()=>Promise.resolve(``),select:()=>Promise.resolve(0),spinner:()=>({stop:()=>{},update:()=>{}})};function ei(e){if(!e)return``;let t=Object.values(e)[0],n=typeof t==`string`?t:JSON.stringify(t??``);return n.length>80?n.slice(0,47)+`...`+n.slice(-30):n}function ti(e,t,n){let r=e?.[t]??e?.[n];return typeof r==`string`?r:null}function ni(e){if(!e)return 1;try{let t=JSON.parse(e);return typeof t.startLine==`number`&&Number.isFinite(t.startLine)?t.startLine:1}catch{return 1}}function ri(e){if(e.toolName!==`Edit`)return{};let t=ti(e.toolArgs,`file_path`,`filePath`),n=ti(e.toolArgs,`old_string`,`oldString`),r=ti(e.toolArgs,`new_string`,`newString`);return!t||n===null||r===null||n===r?{}:{diffFile:t,diffLines:ai(n,r,ni(e.toolResultData),t)}}function ii(e,t,n){return[...e.split(`
59
+ `),history:t,toolSummaries:i,contextState:r,...o&&{usage:o}}}function Xr(e){return{id:`usage_${_()}`,timestamp:new Date,category:`event`,type:`usage-summary`,data:e}}async function Zr(e,t,n,r=[]){let i=await Nr(ur(r).map(e=>e.sourcePath),{cwd:t,reason:`manual`}),a=await Mr(e,{cwd:t}),o=[...i.diagnostics,...a.diagnostics];if(yr(o))throw Error(br(o));let s=vr(e,Qr([...i.references,...a.references])),c=n??(s===e?void 0:e),l=V(i.references),u=V(a.references),d=a.references.length>0?xr(a.references):void 0;return{modelInput:s,...c===void 0?{}:{hookInput:c},activeContextReferenceRecords:l,promptFileReferenceRecords:u,...d===void 0?{}:{promptFileReferenceEntry:d}}}function Qr(e){return[...new Map(e.map(e=>[e.sourcePath,e])).values()]}function $r(e,t,n){let r=e.slice(t),a=0,o=0,s=!1;for(let e of r){if(e.role!==`assistant`)continue;let t=i(e);t&&(s=!0,a+=t.inputTokens,o+=t.outputTokens)}if(s)return{kind:`exact`,scope:`turn`,promptTokens:a,completionTokens:o,totalTokens:a+o,contextUsedTokens:n.usedTokens,contextMaxTokens:n.maxTokens,contextUsedPercentage:n.usedPercentage,costStatus:`unknown`}}const ei={write:()=>{},writeLine:()=>{},writeMarkdown:()=>{},writeError:()=>{},prompt:()=>Promise.resolve(``),select:()=>Promise.resolve(0),spinner:()=>({stop:()=>{},update:()=>{}})};function ti(e){if(!e)return``;let t=Object.values(e)[0],n=typeof t==`string`?t:JSON.stringify(t??``);return n.length>80?n.slice(0,47)+`...`+n.slice(-30):n}function ni(e,t,n){let r=e?.[t]??e?.[n];return typeof r==`string`?r:null}function ri(e){if(!e)return 1;try{let t=JSON.parse(e);return typeof t.startLine==`number`&&Number.isFinite(t.startLine)?t.startLine:1}catch{return 1}}function ii(e){if(e.toolName!==`Edit`)return{};let t=ni(e.toolArgs,`file_path`,`filePath`),n=ni(e.toolArgs,`old_string`,`oldString`),r=ni(e.toolArgs,`new_string`,`newString`);return!t||n===null||r===null||n===r?{}:{diffFile:t,diffLines:oi(n,r,ri(e.toolResultData),t)}}function ai(e,t,n){return[...e.split(`
60
60
  `).map((e,t)=>({type:`remove`,text:e,lineNumber:n+t})),...t.split(`
61
- `).map((e,t)=>({type:`add`,text:e,lineNumber:n+t}))]}function ai(e,t,n,r,i=new B){let a=ii(e,t,n),o;try{o=i.readFileSync(r,`utf8`).split(`
61
+ `).map((e,t)=>({type:`add`,text:e,lineNumber:n+t}))]}function oi(e,t,n,r,i=new z){let a=ai(e,t,n),o;try{o=i.readFileSync(r,`utf8`).split(`
62
62
  `)}catch{return a}let s=[],c=Math.max(0,n-1-3);for(let e=c;e<n-1;e++)e<o.length&&s.push({type:`context`,text:o[e],lineNumber:e+1});let l=[],u=n-1+t.split(`
63
63
  `).length;for(let e=u;e<u+3;e++)e<o.length&&l.push({type:`context`,text:o[e],lineNumber:e+1});let d=s[0]?.lineNumber??a[0]?.lineNumber??l[0]?.lineNumber??n,f=e.split(`
64
64
  `).length,p=t.split(`
65
- `).length;return[{type:`hunk`,text:`@@ -${d},${s.length+f+l.length} +${d},${s.length+p+l.length} @@`,lineNumber:d},...s,...a,...l]}function oi(e){if(e.activeTools.length===0)return;let t=e.activeTools.map(e=>`${e.isRunning?`⟳`:e.result===`success`?`✓`:e.result===`error`?`✗`:`⊘`} ${e.toolName}${e.firstArg?`(${e.firstArg})`:``}`).join(`
66
- `);e.history.push({id:v(),timestamp:new Date,category:`event`,type:`tool-summary`,data:{tools:e.activeTools.map(e=>({toolName:e.toolName,firstArg:e.firstArg,isRunning:e.isRunning,result:e.result,diffFile:e.diffFile,diffLines:e.diffLines,toolResultData:e.toolResultData})),summary:t}})}function si(e){let t=e.filter(e=>!e.isRunning);if(t.length<=50)return e;let n=t.length-50,r=0;return e.filter(e=>!e.isRunning&&r<n?(r++,!1):!0)}function ci(e,t){let n=ei(t.toolArgs),r={toolName:t.toolName,firstArg:n,isRunning:!0,...t.executionId?{executionId:t.executionId}:{}};return e.activeTools.push(r),e.history.push({id:v(),timestamp:new Date,category:`event`,type:`tool-start`,data:{toolName:t.toolName,firstArg:n,isRunning:!0}}),r}function li(e,t){let n=t.denied?`denied`:t.success===!1?`error`:`success`,r=e.activeTools.findIndex(e=>e.toolName===t.toolName&&e.isRunning);if(r===-1)return null;let i={...e.activeTools[r],...ri(t),isRunning:!1,result:n,toolResultData:t.toolResultData};return e.activeTools[r]=i,e.activeTools=si(e.activeTools),e.history.push({id:v(),timestamp:new Date,category:`event`,type:`tool-end`,data:{toolName:i.toolName,firstArg:i.firstArg,isRunning:!1,result:n,toolResultData:t.toolResultData}}),i}const ui=[{pattern:/\b401\b|invalid.*api.?key|authentication.*fail|unauthorized/i,message:"Invalid API key. Run `/provider` to reconfigure, or check your settings file (~/.robota/settings.json)."},{pattern:/\b403\b|permission.*denied|forbidden/i,message:"Access denied. Your API key may lack permission for this model. Check your provider plan or run `/provider` to switch accounts."},{pattern:/\b429\b|rate.?limit|too many requests|quota.*exceeded/i,message:"Rate limit reached. Wait a moment and try again. Consider switching to a different model with `/model`."},{pattern:/\b500\b|internal server error/i,message:`The AI provider returned an internal error. This is usually temporary — try again.`},{pattern:/\b503\b|service.*unavailable|overloaded/i,message:`The AI provider is temporarily unavailable or overloaded. Try again in a few seconds.`},{pattern:/\b502\b|bad gateway/i,message:`The AI provider gateway is unreachable. Check your network or try again shortly.`},{pattern:/\btimeout\b|timed.?out|ETIMEDOUT/i,message:`The request timed out. Check your internet connection, or try a shorter prompt to reduce response time.`},{pattern:/ENOTFOUND|ECONNREFUSED|ECONNRESET|network.*error|fetch.*fail/i,message:`Network connection failed. Check your internet connection and verify your provider URL in settings.`}];function di(i){if(i instanceof e)return"Invalid API key. Run `/provider` to reconfigure, or check your settings file (~/.robota/settings.json).";if(i instanceof r)return`Rate limit reached${i.retryAfter?` (retry after ${i.retryAfter}s)`:``}. Wait a moment and try again. Consider switching to a different model with \`/model\`.`;if(i instanceof t)return`Network connection failed. Check your internet connection and verify your provider URL in settings.`;if(i instanceof n&&i.originalError)return di(i.originalError);let a=i.message;for(let{pattern:e,message:t}of ui)if(e.test(a))return t;return a}async function fi(e,t,n,r){let i=r.getHistory();i.push(h(s(t??e))),r.onWorkspaceUpdated();let c=r.getSession().getHistory().length;r.resetUsedMemoryReferences();try{let o=await Xr(e,r.getCwd(),n,r.getContextReferences());o.promptFileReferenceEntry&&i.push(o.promptFileReferenceEntry),r.recordContextReferenceUsage(o.activeContextReferenceRecords),r.recordPromptContextReferences(o.promptFileReferenceRecords),await r.beginEditCheckpointTurn(t??e);let s=await r.getSession().run(o.modelInput,o.hookInput);r.flushStreaming(),oi({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let l=qr(s||`(empty response)`,r.getSession().getHistory(),i,c,r.getSession().getContextState(),o.promptFileReferenceRecords);i.push(h(a(l.response))),l.usage&&i.push(Yr(l.usage)),r.onComplete(l),r.onContextUpdate()}catch(e){if(r.flushStreaming(),Gr(e)){let e=Jr(r.getSession().getHistory(),i,c,r.getSession().getContextState());oi({activeTools:r.getActiveTools(),history:i}),r.clearStreaming(),e.response&&i.push(h(a(e.response))),e.usage&&i.push(Yr(e.usage)),i.push(h(o(`Interrupted by user.`))),r.onInterrupted(e)}else{oi({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let t=e instanceof Error?e:Error(String(e)),n=di(t);i.push(h(o(`Error: ${n}`))),r.onError(t)}}}var pi=class{histTracker;skillRouter;callbacks;executing=!1;streamingText=``;flushTimer=null;activeTools=[];pendingPrompt=null;pendingDisplayInput;pendingRawInput;shuttingDown=!1;constructor(e,t,n){this.histTracker=e,this.skillRouter=t,this.callbacks=n}clearPendingQueue(){this.pendingPrompt=null,this.pendingDisplayInput=void 0,this.pendingRawInput=void 0}clearStreaming(){this.streamingText=``,this.activeTools=[],this.flushTimer&&=(clearTimeout(this.flushTimer),null)}flushStreaming(){this.flushTimer&&=(clearTimeout(this.flushTimer),null)}handleTextDelta(e){this.streamingText+=e,this.callbacks.emit(`text_delta`,e),this.flushTimer||=setTimeout(()=>{this.flushTimer=null},16)}handleCompactEvent(e){e.trigger===`auto`&&this.histTracker.append(h(o(`Auto compacted context: ${Math.round(e.before.usedPercentage)}% -> ${Math.round(e.after.usedPercentage)}%`))),this.callbacks.emit(`compact`,e),this.callbacks.emit(`context_update`,e.after)}handleToolExecution(e){let t={activeTools:this.activeTools,history:this.histTracker.getHistory()};if(e.type===`start`){let n=ci(t,e);this.activeTools=t.activeTools,this.callbacks.emit(`tool_start`,n)}else{let n=li(t,e);this.activeTools=t.activeTools,n&&this.callbacks.emit(`tool_end`,n)}}emitExecutionWorkspaceUpdated(e,t){this.callbacks.getSession()&&this.callbacks.emit(`execution_workspace_event`,{type:`execution_workspace_updated`,cause:e,...t?{entryId:t}:{},snapshot:this.callbacks.getExecutionWorkspaceSnapshot()})}drainPendingQueue(e){if(!this.shuttingDown&&this.pendingPrompt){let t=this.pendingPrompt,n=this.pendingDisplayInput,r=this.pendingRawInput;this.clearPendingQueue(),setTimeout(()=>void e(t,n,r),0)}}async executePrompt(e,t,n,r,i,a,o,s){await ir(r,i,a,o,()=>this.callbacks.getSessionOrThrow(),(e,t)=>this.callbacks.emit(e,t)),this.executing=!0,this.clearStreaming(),this.callbacks.emit(`user_message`,t??e),this.callbacks.emit(`thinking`,!0);try{await fi(e,t,n,{getSession:()=>this.callbacks.getSessionOrThrow(),getCwd:()=>this.callbacks.getCwd(),getHistory:()=>this.histTracker.getHistory(),getContextReferences:()=>this.histTracker.listContextReferences(),getActiveTools:()=>this.activeTools,resetUsedMemoryReferences:()=>this.histTracker.resetUsedMemoryReferences(),recordContextReferenceUsage:e=>this.histTracker.recordContextReferenceUsage(e),recordPromptContextReferences:e=>this.histTracker.recordPromptContextReferences(e),beginEditCheckpointTurn:e=>this.histTracker.beginEditCheckpointTurn(e),flushStreaming:()=>this.flushStreaming(),clearStreaming:()=>this.clearStreaming(),onWorkspaceUpdated:()=>this.emitExecutionWorkspaceUpdated(`main_thread`),onComplete:e=>{this.callbacks.emit(`complete`,e)},onInterrupted:e=>{this.callbacks.emit(`interrupted`,e)},onError:e=>{this.callbacks.emit(`error`,e)},onContextUpdate:()=>{this.callbacks.emit(`context_update`,this.callbacks.getContextState())}})}finally{try{await this.histTracker.finalizeEditCheckpointTurn()}catch(e){this.callbacks.emit(`error`,e instanceof Error?e:Error(String(e)))}this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(s)}}async executeForkSkillCommand(e,t,n,r,i,a){if(this.executing)throw Error(`Cannot execute fork skill while another prompt is running.`);this.executing=!0,this.clearStreaming(),this.callbacks.emit(`thinking`,!0),this.histTracker.append(h(s(n??`/${e.name}`))),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let n=await this.skillRouter.executeSkillWithActivation(e,t,i,r);return await this.applyForkSkillResult(n.result??`(empty response)`),n}catch(e){let t=e instanceof Error?e:Error(String(e));return this.histTracker.append(h(o(`Error: ${di(t)}`))),this.callbacks.emit(`error`,t),{mode:`fork`,result:``}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(a)}}async executeForegroundCommand(e,t){this.executing=!0,this.clearStreaming(),this.callbacks.emit(`thinking`,!0),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let t=await e();return this.callbacks.emit(`context_update`,this.callbacks.getContextState()),t}catch(e){return{success:!1,message:`Error: ${e instanceof Error?e.message:String(e)}`}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(t)}}async applyForkSkillResult(e){this.flushStreaming(),oi({activeTools:this.activeTools,history:this.histTracker.getHistory()}),this.clearStreaming();let t={response:e,history:this.histTracker.getHistory(),toolSummaries:[],contextState:this.callbacks.getContextState()};this.histTracker.append(h(a(e))),this.callbacks.emit(`complete`,t),this.callbacks.emit(`context_update`,this.callbacks.getContextState())}};function mi(e,t,n){let r=R(n)?.customAgentRegistry?.(e)??rn(e);if(!r)throw Error(`Unknown agent type: ${e}`);return t.allowedTools?{...r,tools:t.allowedTools}:r}async function hi(e,t,n){let r=R(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);return Sn({agentDefinition:mi(t.agent??`general-purpose`,t,n),parentConfig:r.config,parentContext:r.context,parentTools:r.tools,provider:r.provider,terminal:r.terminal,isForkWorker:!0,permissionMode:r.permissionMode,permissionHandler:r.permissionHandler,hooks:r.hooks,hookTypeExecutors:r.hookTypeExecutors,onTextDelta:r.onTextDelta,onToolExecution:r.onToolExecution}).run(e)}async function gi(e,t,n){let r=await Mr([t],{cwd:n,reason:`manual`});if(vr(r.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[yr(r.diagnostics)]}};let i=r.references[0];if(!i)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let a=ar(H([i])[0],`manual`,`active`),o=or(e,a);return{references:o.references,result:{reference:a,evicted:o.evicted,diagnostics:[]}}}function _i(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=ar(e,n.loadType,n.status,r);i=or(i,t).references}return i}function W(e){let t=C(e,`.robota`);return{settings:C(t,`settings.json`),settingsLocal:C(t,`settings.local.json`),logs:C(t,`logs`),sessions:C(t,`sessions`),memory:C(t,`memory`),checkpoints:C(t,`checkpoints`)}}function vi(){let e=C(E(),`.robota`);return{settings:C(e,`settings.json`),sessions:C(e,`sessions`),onboarded:C(e,`onboarded`)}}function yi(e){let t=e.fs??new B,n=e.manifests.filter(t=>t.sequence>e.target.sequence),r=e.manifests.filter(t=>t.sequence>=e.target.sequence);return{target:bi(e.target),capturedFiles:e.target.files.map(n=>{let r=n.snapshotFile?C(e.checkpointDir(e.sessionId,e.target.id),n.snapshotFile):void 0,i=r?Si(r,t):void 0;return{originalPath:n.originalPath,relativePath:w(e.cwd,n.originalPath),existed:n.existed,restoreAction:n.existed?`restore-preimage`:`delete-created-file`,snapshotAvailable:n.existed?i!==void 0:!1,...i?{snapshotSizeBytes:i.size}:{}}}),restoreToCheckpoint:xi(n),rollbackThroughCheckpoint:xi(r)}}function bi(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function xi(e){return{checkpointIds:e.map(e=>e.id),fileCount:e.reduce((e,t)=>e+t.fileCount,0)}}function Si(e,t){try{return t.statSync(e)}catch{return}}const Ci=`manifest.json`,wi=`files`;var Ti=class{fs;fsAsync;cwd;rootDir;now;activeTurn=null;constructor(e,t=new B,n=new V){this.fs=t,this.fsAsync=n,this.cwd=T(e.cwd),this.rootDir=W(this.cwd).checkpoints,this.now=e.now??(()=>new Date)}async beginTurn(e){this.activeTurn&&await this.finalizeTurn();let t=this.nextSequence(e.sessionId),n=`turn-${String(t).padStart(4,`0`)}`,r=C(this.sessionDir(e.sessionId),n);await this.fsAsync.mkdir(C(r,wi),{recursive:!0});let i={version:1,id:n,sessionId:e.sessionId,sequence:t,prompt:e.prompt,createdAt:this.now().toISOString(),fileCount:0,files:[]};return this.activeTurn={manifest:i,dir:r,capturedPaths:new Set},Ei(i)}async captureFile(e){if(!this.activeTurn)return;let t=T(this.cwd,e);if(this.activeTurn.capturedPaths.has(t)||Oi(this.rootDir,t))return;let n=await this.createFileRecord(t,this.activeTurn);this.activeTurn.manifest.files.push(n),this.activeTurn.manifest.fileCount=this.activeTurn.manifest.files.length,this.activeTurn.capturedPaths.add(t)}async finalizeTurn(){if(!this.activeTurn)return;let e=this.activeTurn;return this.activeTurn=null,await this.writeManifest(e.dir,e.manifest),Ei(e.manifest)}list(e){return this.loadManifests(e).map(Ei)}inspect(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);return yi({cwd:this.cwd,sessionId:e,target:r,manifests:n,checkpointDir:(e,t)=>this.checkpointDir(e,t)})}async restoreToCheckpoint(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);let i=n.filter(e=>e.sequence>r.sequence).sort((e,t)=>t.sequence-e.sequence),a=0;for(let t of i)for(let n of t.files)await this.restoreFile(e,t.id,n),a+=1;for(let t of i)await this.fsAsync.rm(this.checkpointDir(e,t.id),{recursive:!0,force:!0});return{target:Ei(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async rollbackThroughCheckpoint(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);let i=n.filter(e=>e.sequence>=r.sequence).sort((e,t)=>t.sequence-e.sequence),a=0;for(let t of i)for(let n of t.files)await this.restoreFile(e,t.id,n),a+=1;for(let t of i)await this.fsAsync.rm(this.checkpointDir(e,t.id),{recursive:!0,force:!0});return{target:Ei(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async createFileRecord(e,t){if(!await ki(this.fsAsync,this.fs,e))return{originalPath:e,existed:!1};let n=C(wi,`${String(t.manifest.files.length+1).padStart(6,`0`)}.content`);return await this.fsAsync.copyFile(e,C(t.dir,n)),{originalPath:e,existed:!0,snapshotFile:n}}async restoreFile(e,t,n){if(!n.existed){await this.fsAsync.rm(n.originalPath,{force:!0});return}if(!n.snapshotFile)throw Error(`Checkpoint file record is missing a snapshot: ${n.originalPath}`);await this.fsAsync.mkdir(S(n.originalPath),{recursive:!0}),await this.fsAsync.copyFile(C(this.checkpointDir(e,t),n.snapshotFile),n.originalPath)}loadManifests(e){let t=this.sessionDir(e);return Ai(this.fs,t).map(e=>C(t,e,Ci)).map(e=>ji(this.fs,e)).filter(e=>e!==void 0).sort((e,t)=>e.sequence-t.sequence)}nextSequence(e){return(this.list(e).at(-1)?.sequence??0)+1}async writeManifest(e,t){await this.fsAsync.mkdir(e,{recursive:!0});let n=C(e,Ci),r=`${n}.tmp`;await this.fsAsync.writeFile(r,JSON.stringify(t,null,2),`utf8`),await this.fsAsync.rename(r,n)}sessionDir(e){return C(this.rootDir,Di(e))}checkpointDir(e,t){return C(this.sessionDir(e),Di(t))}};function Ei(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function Di(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function Oi(e,t){let n=w(e,t);return n.length===0||!n.startsWith(`..`)&&!n.startsWith(`/`)}async function ki(e,t,n){try{return await e.access(n,t.constants.F_OK),!0}catch{return!1}}function Ai(e,t){try{return e.readdirSync(t)}catch{return[]}}function ji(e,t){try{let n=e.readFileSync(t,`utf8`);return JSON.parse(n)}catch{return}}function Mi(e){return e.source===`plugin`?`plugin`:`skill`}function Ni(e){return e.context===`fork`?`fork`:`inject`}function Pi(e){return{type:`skill-activation`,skillName:e.skill.name,source:Mi(e.skill),invocation:e.invocation,mode:Ni(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function Fi(e){let t=e.source===`plugin`?`plugin skill`:`skill`;return e.status===`failed`?`Skill failed: ${e.skillName}${e.error?` (${e.error})`:``}`:e.status===`completed`?`Skill completed: ${e.skillName}`:`Invoking ${t}: ${e.skillName}`}var Ii=class{cwd;getSessionId;getExecuting;persistSession;emitSkillActivation;history=[];editCheckpointStore=null;memoryEvents=[];usedMemoryReferences=[];contextReferences=[];skillActivationEvents=[];constructor(e,t,n,r,i,a=null){this.cwd=e,this.getSessionId=t,this.getExecuting=n,this.persistSession=r,this.emitSkillActivation=i,this.editCheckpointStore=a}restoreState(e){this.history=e.history,this.memoryEvents=e.memoryEvents,this.usedMemoryReferences=e.usedMemoryReferences,this.contextReferences=e.contextReferences,this.skillActivationEvents=e.skillActivationEvents}getState(){return{history:this.history,memoryEvents:this.memoryEvents,usedMemoryReferences:this.usedMemoryReferences,contextReferences:this.contextReferences,skillActivationEvents:this.skillActivationEvents}}append(e){this.history.push(e)}getHistory(){return this.history}clearHistory(){this.history=[],this.memoryEvents=[],this.usedMemoryReferences=[]}resetUsedMemoryReferences(){this.usedMemoryReferences=[]}recordContextReferenceUsage(e){this.contextReferences=_i(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=_i(this.contextReferences,e,{loadType:`prompt-reference`,status:`observed`}),this.persistSession()}listEditCheckpoints(){let e=this.getSessionId();return this.getCheckpointStore().list(e)}inspectEditCheckpoint(e){let t=this.getSessionId();return this.getCheckpointStore().inspect(t,e)}async restoreEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot restore edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push(h(o(`Restored edit checkpoint: ${e}`))),this.persistSession(),t}async rollbackEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot rollback edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().rollbackThroughCheckpoint(this.getSessionId(),e);return this.history.push(h(o(`Rolled back edit checkpoint: ${e}`))),this.persistSession(),t}async beginEditCheckpointTurn(e){this.editCheckpointStore&&await this.editCheckpointStore.beginTurn({sessionId:this.getSessionId(),prompt:e})}async finalizeEditCheckpointTurn(){if(this.editCheckpointStore)try{await this.editCheckpointStore.finalizeTurn()}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.history.push(h(o(`Checkpoint error: ${t.message}`))),t}}setEditCheckpointStore(e){this.editCheckpointStore=e}getUsedMemoryReferences(){return[...this.usedMemoryReferences]}recordMemoryEvent(e){this.memoryEvents.push(e),this.persistSession()}listContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await gi(this.contextReferences,e,this.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=sr(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=cr(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,t){this.skillActivationEvents.push(e),t&&this.history.push({id:v(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:Fi(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){return this.editCheckpointStore||=new Ti({cwd:this.cwd}),this.editCheckpointStore}};function Li(e){if(D(e))try{return JSON.parse(O(e,`utf-8`))}catch{return}}function Ri(e){if(D(k(e,`pnpm-workspace.yaml`))||D(k(e,`pnpm-lock.yaml`)))return`pnpm`;if(D(k(e,`yarn.lock`)))return`yarn`;if(D(k(e,`bun.lockb`)))return`bun`;if(D(k(e,`package-lock.json`)))return`npm`}async function zi(e){let t=k(e,`package.json`),n=k(e,`tsconfig.json`),r=k(e,`pyproject.toml`),i=k(e,`Cargo.toml`),a=k(e,`go.mod`);if(D(t)){let r=Li(t),i=D(n)?`typescript`:`javascript`,a=Ri(e);return{type:`node`,name:r?.name,packageManager:a,language:i}}return D(r)||D(k(e,`setup.py`))?{type:`python`,language:`python`}:D(i)?{type:`rust`,language:`rust`}:D(a)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}function Bi(e,t){let n=t.content,r=typeof n==`string`?n:n==null?``:JSON.stringify(n);t.role===`tool`?e.injectMessage(`tool`,r,{toolCallId:t.toolCallId,...t.name===void 0?{}:{name:t.name}}):e.injectMessage(t.role,r)}function Vi(e,t,n,r){let i=e.load(t);if(!i)return{history:[],sessionName:void 0,pendingRestoreMessages:null,backgroundTasks:[],backgroundTaskEvents:[],backgroundJobGroups:[],backgroundJobGroupEvents:[],skillActivationEvents:[],memoryEvents:[],usedMemoryReferences:[],contextReferences:[],sandboxSnapshotId:void 0};let a=i.history??[],o=i.backgroundTasks??[],s=i.backgroundTaskEvents??[],c=i.backgroundJobGroups??[],l=i.backgroundJobGroupEvents??[],u=i.skillActivationEvents??[],d=i.memoryEvents??[],f=i.usedMemoryReferences??[],p=i.contextReferences??[],m=i.sandboxSnapshotId,{backgroundTasks:h,backgroundTaskEvents:ee}=Hi(o,s),te=i.name,g=null;if(!n&&i.messages)if(r)for(let e of i.messages)Bi(r,e);else g=i.messages;return{history:a,sessionName:te,pendingRestoreMessages:g,backgroundTasks:h,backgroundTaskEvents:ee,backgroundJobGroups:c,backgroundJobGroupEvents:l,skillActivationEvents:u,memoryEvents:d,usedMemoryReferences:f,contextReferences:p,sandboxSnapshotId:m}}function Hi(e,t){let n=new Date().toISOString(),r=[];return{backgroundTasks:e.map(e=>{if(Ui(e.status))return e;let t={...e,status:`failed`,timeoutReason:`stale_worker`,error:{category:`timeout`,message:`Restored background task is stale; worker cannot be reattached`,recoverable:!0},unread:!0,completedAt:n,updatedAt:n};return r.push({type:`background_task_failed`,task:t}),t}),backgroundTaskEvents:[...t,...r]}}function Ui(e){return e===`completed`||e===`failed`||e===`cancelled`}function Wi(e){if(e.type===`background_task_started`&&e.task.kind===`agent`)return`SubagentStart`;if((e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)&&e.task.kind===`agent`)return`SubagentStop`}function Gi(e,t,n,r){let i=Wi(e);!i||!(`task`in e)||te(n,i,{session_id:e.task.parentSessionId,cwd:t,hook_event_name:i,agent_id:e.task.id,agent_type:e.task.agentType??e.task.label,...e.task.transcriptPath?{agent_transcript_path:e.task.transcriptPath,transcript_path:e.task.transcriptPath}:{},...e.task.error?.message||e.task.timeoutReason?{reason:e.task.error?.message??e.task.timeoutReason}:{},...i===`SubagentStop`?{stop_hook_active:!1,...e.task.result?.output?{last_assistant_message:e.task.result.output}:{}}:{},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e.task.parentSessionId,ROBOTA_AGENT_ID:e.task.id,ROBOTA_AGENT_TYPE:e.task.agentType??e.task.label}},r).catch(()=>void 0)}const Ki=[`Bash — execute shell commands`,`Read — read file contents with line numbers`,`Write — write content to a file`,`Edit — replace a string in a file`,`Glob — find files matching a pattern`,`Grep — search file contents with regex`,`WebFetch — fetch URL content as text`,`WebSearch — search the internet through the configured local tool`];function qi(e={}){return[ce(e),ue(e),de(e),le(e),pe,me,he,ge]}const Ji=new Set([`tools`,`disallowedTools`]),Yi=new Set([`maxTurns`]);function Xi(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Zi(e){let t=e.split(`
67
- `);if(t[0]?.trim()!==`---`)return{frontmatter:null,body:e};let n=-1;for(let e=1;e<t.length;e++)if(t[e]?.trim()===`---`){n=e;break}if(n===-1)return{frontmatter:null,body:e};let r={};for(let e=1;e<n;e++){let n=t[e].match(/^([a-zA-Z][a-zA-Z0-9]*(?:[A-Z][a-z]*)*):\s*(.+)/);if(!n)continue;let i=n[1],a=n[2].trim();Ji.has(i)?r[i]=Xi(a):Yi.has(i)?r[i]=parseInt(a,10):r[i]=a}let i=t.slice(n+1).join(`
68
- `).trim();return{frontmatter:Object.keys(r).length>0?r:null,body:i}}function Qi(e,t){if(!t.existsSync(e))return[];let n=[],r;try{r=t.readdirSync(e,{withFileTypes:!0})}catch{return[]}for(let i of r){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let r=C(e,i.name),{frontmatter:a,body:o}=Zi(t.readFileSync(r,`utf-8`)),s=Ge(i.name,`.md`),c={name:a?.name??s,description:a?.description??``,systemPrompt:o};a?.model!==void 0&&(c.model=a.model),a?.maxTurns!==void 0&&(c.maxTurns=a.maxTurns),a?.tools!==void 0&&(c.tools=a.tools),a?.disallowedTools!==void 0&&(c.disallowedTools=a.disallowedTools),n.push(c)}return n}var $i=class{cwd;home;fs;constructor(e,t,n=new B){this.cwd=e,this.home=t??E(),this.fs=n}loadAll(){let e=[Qi(C(this.cwd,`.robota`,`agents`),this.fs),Qi(C(this.cwd,`.agents`,`agents`),this.fs),Qi(C(this.cwd,`.claude`,`agents`),this.fs),Qi(C(this.home,`.robota`,`agents`),this.fs),Qi(C(this.home,`.claude`,`agents`),this.fs)],t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.name)||(t.add(e.name),n.push(e));let r=[...n];for(let e of nn)t.has(e.name)||r.push(e);return r}getAgent(e){return this.loadAll().find(t=>t.name===e)}};function ea(e){let t=e.content.trim();return e.title?[`## ${e.title}`,t].join(`
69
- `):t}function ta(e){return[...e].filter(e=>e.content.trim().length>0).sort((e,t)=>e.priority-t.priority||e.id.localeCompare(t.id)).map(e=>ea(e)).join(`
70
-
71
- `)}const na={safe:`safe`,moderate:`moderate`,full:`full`};function G(e,t,n,r,i){return{id:e,title:t,priority:n,content:r,source:i}}function ra(e){if(e)return G(`runtime-cwd`,`Working Directory`,30,`\`${e}\``,`runtime`)}function ia(e){let t=[];return e.name!==void 0&&t.push(`- **Name:** ${e.name}`),e.type!==`unknown`&&t.push(`- **Type:** ${e.type}`),e.language!==`unknown`&&t.push(`- **Language:** ${e.language}`),e.packageManager!==void 0&&t.push(`- **Package manager:** ${e.packageManager}`),G(`runtime-project`,`Current Project`,40,t.join(`
72
- `),`runtime`)}function aa(e){return G(`permission-mode`,`Permission Mode`,50,`- **Trust level:** ${na[e]}`,`permissions`)}function oa(e){if(!(e===void 0||e.trim().length===0))return G(`runtime-response-language`,`Response Language`,45,e,`runtime`)}function sa(e){if(e.trim().length!==0)return G(`project-agents-md`,`Agent Instructions`,10,e,`project-instructions`)}function ca(e){if(e.trim().length!==0)return G(`project-claude-md`,`Project Notes`,20,e,`project-instructions`)}function la(e){if(!(e===void 0||e.trim().length===0))return G(`project-memory`,`Project Memory`,25,e,`project-instructions`)}function ua(e){if(!(e===void 0||e.trim().length===0))return G(`active-task-context`,`Active Task Context`,27,e,`project-instructions`)}function da(e){if(e.length!==0)return G(`tool-descriptions`,`Available Tools`,60,e.map(e=>`- ${e}`).join(`
73
- `),`tool`)}function fa(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}`}function pa(e,t,n,r,i){let a=i.filter(t=>t.modelInvocable&&t.kind===e).map(fa);if(a.length!==0)return G(`capability-${e}`,t,n,a.join(`
74
- `),r)}function ma(e){let t=[],n=pa(`builtin-command`,`Built-in Commands`,70,`command`,e),r=pa(`skill`,`Skills`,80,`skill`,e),i=pa(`agent`,`Agents`,90,`agent`,e),a=pa(`tool`,`Tools`,100,`tool`,e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),a&&t.push(a),t}function K(e,t){t!==void 0&&e.push(t)}function ha(e){return e.map(e=>({name:e.name,kind:`skill`,description:e.description,userInvocable:!0,modelInvocable:e.disableModelInvocation!==!0}))}function ga(e){return e.map(e=>({name:e.name,kind:`agent`,description:e.description,userInvocable:!1,modelInvocable:!0,safety:`background-agent`}))}function _a(e){return[...e.commandDescriptors??[],...e.skills?ha(e.skills):[],...e.agents?ga(e.agents):[]]}function va(e){let t=[];return K(t,sa(e.agentsMd)),K(t,ca(e.claudeMd)),K(t,la(e.memoryMd)),K(t,ua(e.taskContext)),K(t,ra(e.cwd)),t.push(ia(e.projectInfo)),K(t,oa(e.language)),t.push(aa(e.trustLevel)),K(t,da(e.toolDescriptions)),t.push(...ma(_a(e))),ta(t)}function ya(e){return e}const ba=_.object({command:_.string().describe(`The shell command to start in the background`),timeout:_.number().optional().describe(`Optional timeout in milliseconds. Default is 120000.`),workingDirectory:_.string().optional().describe(`Working directory for the command. Defaults to the current project directory.`),stdin:_.string().optional().describe(`Optional stdin to write after the process starts.`),outputLimitBytes:_.number().optional().describe(`Maximum captured output bytes kept in the task result.`)});function xa(e,t,n){return JSON.stringify({success:!0,background:!0,output:``,taskId:e,status:t,command:n})}function Sa(e){return JSON.stringify({success:!1,background:!0,output:``,error:`Background process error: ${e}`})}async function Ca(e,t){try{let n=await t.backgroundTaskManager.spawn({kind:`process`,label:e.command,mode:`background`,parentSessionId:t.parentSessionId??`unknown-session`,depth:0,cwd:e.workingDirectory??t.cwd??process.cwd(),command:e.command,stdin:e.stdin,timeoutMs:e.timeout??12e4,outputLimitBytes:e.outputLimitBytes,metadata:t.metadata});return xa(n.id,n.status,e.command)}catch(e){return Sa(e instanceof Error?e.message:String(e))}}function wa(e){return fe(`BackgroundProcess`,`Start a shell command as a managed background task. Use this for long-running commands that should not block the current conversation. Use /background list, /background read <taskId>, /background cancel <taskId>, or /background close <taskId> to inspect or control it.`,ya(ba),async t=>Ca(t,e))}function Ta(e,t,n,r,i,a){let o,s=[],c;if(e.enableAgentRuntime){let l=new $i(n);s=l.loadAll(),o={config:e.config,context:e.context,tools:i,terminal:e.terminal,provider:r,cwd:n,parentSessionId:t,permissionMode:e.permissionMode,permissionHandler:e.permissionHandler,hooks:e.config.hooks,hookTypeExecutors:a.length>0?a:void 0,onTextDelta:e.onTextDelta,onToolExecution:e.onToolExecution,customAgentRegistry:e=>l.getAgent(e),agentDefinitions:s};let u=new ne({runner:(e.subagentRunnerFactory??On)(o),backgroundTaskRunners:e.backgroundTaskRunners});o.subagentManager=u,c=u.getBackgroundTaskManager(),o.backgroundTaskManager=c}else c=new g({runners:e.backgroundTaskRunners??[]});let l=e.sessionLogger;return l&&c.subscribe(e=>ka(l,t,e)),c.subscribe(t=>Gi(t,n,e.config.hooks,a.length>0?a:void 0)),{agentToolDeps:o,agentDefinitions:s,backgroundTaskManager:c}}function Ea(e,t,n,r,i){if(!e.backgroundTaskRunners?.some(e=>e.kind===`process`))return{backgroundProcessToolDeps:void 0};let a={backgroundTaskManager:t,cwd:r,parentSessionId:n,metadata:P({kind:`tool_call`,sessionId:n,label:`BackgroundProcess`})};return i.push(wa(a)),{backgroundProcessToolDeps:a}}function Da(e,t,n,r,i,a,o){let s=e.systemPromptBuilder??va,c=[...Ki,...r?r.commandTools.map(pn):[]],l=e.toolDescriptions??(i?[...c,`BackgroundProcess — start long-running shell commands as managed background tasks`]:c),u={agentsMd:e.context.agentsMd,claudeMd:e.context.claudeMd,memoryMd:e.context.memoryMd,taskContext:e.context.taskContext,toolDescriptions:l,trustLevel:e.config.defaultTrustLevel,projectInfo:e.projectInfo??{type:`unknown`,language:`unknown`},cwd:t,language:e.config.language,skills:a.map(e=>({name:e.name,description:e.description,disableModelInvocation:e.disableModelInvocation})),...o.length>0?{agents:o.map(e=>({name:e.name,description:e.description}))}:{},commandDescriptors:e.commandDescriptors??[]},d=s(u);return{finalSystemMessage:e.appendSystemPrompt?`${d}\n\n${e.appendSystemPrompt}`:d,rebuildSystemMessage:(t,n)=>{let r=s({...u,agentsMd:t,claudeMd:n});return e.appendSystemPrompt?`${r}\n\n${e.appendSystemPrompt}`:r}}}function Oa(e,t,n,r){t&&(t.parentSessionId=e.getSessionId()),n&&(n.parentSessionId=e.getSessionId()),zt(e,r),t&&Nn(e,t)}function ka(e,t,n){let r={};if(n.type===`background_task_created`){r.taskId=n.task.id;let e=n.task.metadata?.executionOriginToolCallId;typeof e==`string`&&(r.originToolCallId=e)}e.log(t,`background_task_event`,{backgroundEventType:n.type,backgroundEvent:n,...r})}const Aa=new Set([`Write`,`Edit`]);function ja(e,t){return e.map(e=>Aa.has(e.getName())?new Ma(e,t):e)}var Ma=class{delegate;recorder;schema;constructor(e,t){this.delegate=e,this.recorder=t,this.schema=e.schema}setEventService(e){this.delegate.setEventService(e)}async execute(e,t){let n=Na(e);return n&&await this.recorder.captureFile(n),this.delegate.execute(e,t)}validate(e){return this.delegate.validate(e)}validateParameters(e){return this.delegate.validateParameters(e)}getDescription(){return this.delegate.getDescription()}getName(){return this.delegate.getName()}};function Na(e){if(!e||typeof e!=`object`)return;let t=e.filePath;return typeof t==`string`&&t.length>0?t:void 0}const Pa=new Set([`disable-model-invocation`,`user-invocable`]),Fa=new Set([`allowed-tools`]);function Ia(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function La(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Ra(e){let t=e.split(`
75
- `);if(t[0]?.trim()!==`---`)return null;let n={};for(let e=1;e<t.length;e++){let r=t[e];if(r.trim()===`---`)break;let i=r.match(/^([a-z][a-z0-9-]*):\s*(.+)/);if(!i)continue;let a=i[1],o=i[2].trim(),s=Ia(a);Pa.has(a)?n[s]=o===`true`:Fa.has(a)?n[s]=La(o):n[s]=o}return Object.keys(n).length>0?n:null}function za(e,t,n){let r={name:e?.name??n,description:e?.description??`Skill: ${n}`,source:`skill`,skillContent:t};return e?.argumentHint!==void 0&&(r.argumentHint=e.argumentHint),e?.disableModelInvocation!==void 0&&(r.disableModelInvocation=e.disableModelInvocation),e?.userInvocable!==void 0&&(r.userInvocable=e.userInvocable),e?.allowedTools!==void 0&&(r.allowedTools=e.allowedTools),e?.model!==void 0&&(r.model=e.model),e?.effort!==void 0&&(r.effort=e.effort),e?.context!==void 0&&(r.context=e.context),e?.agent!==void 0&&(r.agent=e.agent),r}function Ba(e,t){if(!t.existsSync(e))return[];let n=[],r=t.readdirSync(e,{withFileTypes:!0});for(let i of r){if(!i.isDirectory())continue;let r=C(e,i.name,`SKILL.md`);if(!t.existsSync(r))continue;let a=t.readFileSync(r,`utf-8`),o=Ra(a);n.push(za(o,a,i.name))}return n}function Va(e,t){if(!t.existsSync(e))return[];let n=[],r=t.readdirSync(e,{withFileTypes:!0});for(let i of r){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let r=C(e,i.name),a=t.readFileSync(r,`utf-8`),o=Ra(a),s=Ge(i.name,`.md`);n.push(za(o,a,s))}return n}var Ha=class{name=`skill`;cwd;home;fs;cachedCommands=null;constructor(e,t,n=new B){this.cwd=e,this.home=t??E(),this.fs=n}getCommands(){if(this.cachedCommands)return this.cachedCommands;let e=[Ba(C(this.cwd,`.claude`,`skills`),this.fs),Va(C(this.cwd,`.claude`,`commands`),this.fs),Ba(C(this.home,`.robota`,`skills`),this.fs),Ba(C(this.cwd,`.agents`,`skills`),this.fs)],t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.name)||(t.add(e.name),n.push(e));return this.cachedCommands=n,this.cachedCommands}getModelInvocableSkills(){return this.getCommands().filter(e=>e.disableModelInvocation!==!0)}getUserInvocableSkills(){return this.getCommands().filter(e=>e.userInvocable!==!1)}};function Ua(){return C(process.env.HOME??process.env.USERPROFILE??`/`,`.robota`,`settings.json`)}function Wa(e,t){return t===void 0||t===`user`?Ua():C(e,`.robota`,`settings.local.json`)}function q(e){if(!y(e))return{};let t=b(e,`utf8`);try{return JSON.parse(t)}catch{return process.stderr.write(`Warning: corrupt settings file at ${e}, resetting to defaults\n`),{}}}function J(e,t){Oe(S(e),{recursive:!0}),Pe(e,JSON.stringify(t,null,2)+`
76
- `,`utf8`)}function Ga(e,t){let n=q(e),r=n.currentProvider,i=n.providers;if(typeof r==`string`&&Ka(i)){let e=i;e[r]={...Ka(e[r])?e[r]:{},model:t},n.providers=e}else n.provider={...Ka(n.provider)?n.provider:{},model:t};J(e,n)}function Ka(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function qa(e){return y(e)?(Ne(e),!0):!1}function Ja(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var Ya=class{type=`agent`;sessionFactory;constructor(e){this.sessionFactory=e.sessionFactory}async execute(e,t){let n=e,r=n.maxTurns??50,i=n.timeout??60;try{let e=this.sessionFactory({maxTurns:r,timeout:i}),n=`Hook input:\n${JSON.stringify(t)}\n\nRespond with JSON: { "ok": boolean, "reason"?: string }`,a=await e.run(n),o=Ja(a),s;try{s=JSON.parse(o)}catch{return{exitCode:1,stdout:``,stderr:`Failed to parse agent response as JSON: ${a}`}}return s.ok?{exitCode:0,stdout:JSON.stringify(s),stderr:``}:{exitCode:2,stdout:``,stderr:s.reason??`Blocked by agent hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};function Xa(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var Za=class{type=`prompt`;providerFactory;defaultModel;constructor(e){this.providerFactory=e.providerFactory,this.defaultModel=e.defaultModel}async execute(e,t){let n=e,r=n.model??this.defaultModel;try{let e=this.providerFactory(r),i=`${n.prompt}\n\nContext:\n${JSON.stringify(t)}\n\nRespond with JSON: { "ok": boolean, "reason"?: string }`,a=await e.complete(i),o=Xa(a),s;try{s=JSON.parse(o)}catch{return{exitCode:1,stdout:``,stderr:`Failed to parse AI response as JSON: ${a}`}}return s.ok?{exitCode:0,stdout:JSON.stringify(s),stderr:``}:{exitCode:2,stdout:``,stderr:s.reason??`Blocked by prompt hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};const Qa=new Set([`Write`,`Edit`]),$a=new Set([`Bash`,`BackgroundProcess`]),eo=new Set([`Read`,`Glob`,`Grep`,`WebFetch`,`WebSearch`]);function to(e){let t=e.toolName;return eo.has(t)?{toolName:t,reversible:!0,sideEffect:`none`,rollbackLayer:`none`,status:`read-only`,message:`${t} does not mutate the local workspace.`}:Qa.has(t)?e.context.isolation===`worktree`||e.context.isolation===`provider-sandbox`?io(t,`file-mutation`,e.context):e.context.checkpointAvailable?{toolName:t,reversible:!0,sideEffect:`file-mutation`,rollbackLayer:`edit-checkpoint`,status:`reversible`,message:`${t} is reversible through the active edit checkpoint.`}:{toolName:t,reversible:!1,sideEffect:`file-mutation`,rollbackLayer:`none`,status:`requires-checkpoint`,message:`${t} requires an edit checkpoint before file mutation.`}:$a.has(t)?io(t,`shell-process`,e.context):t===`Agent`?ao(e.toolArgs,e.context):{toolName:t,reversible:!1,sideEffect:`unknown`,rollbackLayer:`none`,status:`unknown`,message:`${t} has no reversible execution contract.`}}function no(e,t){let n={checkpointAvailable:t.checkpointAvailable,isolation:t.isolation??`none`},r=t.enforceUntrackedSideEffects??!0;return e.map(e=>new ro(e,{safetyContext:n,enforceUntrackedSideEffects:r}))}var ro=class{delegate;options;schema;constructor(e,t){this.delegate=e,this.options=t,this.schema=e.schema}setEventService(e){this.delegate.setEventService(e)}async execute(e,t){let n=to({toolName:this.getName(),toolArgs:lo(e),context:this.options.safetyContext});return!n.reversible&&this.options.enforceUntrackedSideEffects?uo(n):this.delegate.execute(e,t)}validate(e){return this.delegate.validate(e)}validateParameters(e){return this.delegate.validateParameters(e)}getDescription(){return this.delegate.getDescription()}getName(){return this.delegate.getName()}};function io(e,t,n){return n.isolation===`worktree`?{toolName:e,reversible:!0,sideEffect:t,rollbackLayer:`worktree`,status:`reversible`,message:`${e} side effects are contained in an isolated Git worktree.`}:n.isolation===`provider-sandbox`?{toolName:e,reversible:!0,sideEffect:t,rollbackLayer:`provider-sandbox`,status:`reversible`,message:`${e} side effects are contained in a provider sandbox snapshot.`}:{toolName:e,reversible:!1,sideEffect:t,rollbackLayer:`none`,status:`requires-isolation`,message:`${e} can create host shell side effects that edit checkpoints cannot restore; use worktree or provider sandbox isolation.`}}function ao(e,t){return t.isolation===`worktree`||t.isolation===`provider-sandbox`?io(`Agent`,`subagent`,t):oo(e)?{toolName:`Agent`,reversible:!0,sideEffect:`subagent`,rollbackLayer:`worktree`,status:`reversible`,message:`Agent jobs request worktree isolation, so shell side effects stay outside the parent workspace.`}:{toolName:`Agent`,reversible:!1,sideEffect:`subagent`,rollbackLayer:`none`,status:`requires-isolation`,message:`Agent jobs must request worktree isolation to be reversible in local-first mode.`}}function oo(e){if(!e)return!1;let t=e.jobs;return Array.isArray(t)?t.length>0&&t.every(e=>co(e)?so(e)===`worktree`:!1):so(e)===`worktree`}function so(e){let t=e.isolation;return typeof t==`string`?t:void 0}function co(e){return e!==void 0&&typeof e==`object`&&!Array.isArray(e)}function lo(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e}function uo(e){return{success:!0,data:{success:!1,output:``,error:e.message,reversibleSafety:{toolName:e.toolName,sideEffect:e.sideEffect,rollbackLayer:e.rollbackLayer,status:e.status}},metadata:{reversibleSafetyStatus:e.status,rollbackLayer:e.rollbackLayer}}}function fo(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function po(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function mo(e,t){return e.some(e=>po(e.name)===t)}function ho(e){if(!e.provider)throw Error(`provider is required. SDK is provider-neutral — consumer must create and pass a provider instance.`);let t=e.provider,n=e.cwd??process.cwd(),r=e.sessionId??go(),i=new Ha(n),a=fo(e.commandDescriptors),o=a.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,s=o?fn(a):void 0,c=mo(a,`skills`)?i.getModelInvocableSkills():[],l=qi({sandboxClient:e.sandboxClient,cwd:n}),u=e.editCheckpointRecorder!==void 0&&e.sandboxClient===void 0,d=[...u&&e.editCheckpointRecorder?ja(l,e.editCheckpointRecorder):l,...e.additionalTools??[]],f=e.reversibleExecution?{...e.reversibleExecution,isolation:e.reversibleExecution.isolation??(e.sandboxClient?`provider-sandbox`:void 0)}:void 0,p=f?no(d,{...f,checkpointAvailable:u}):d;o&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&p.push(...hn({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:a}));let m=[];e.providerFactory&&m.push(new Za({providerFactory:e.providerFactory,defaultModel:e.config.provider.model})),e.sessionFactory&&m.push(new Ya({sessionFactory:e.sessionFactory})),e.additionalHookExecutors&&m.push(...e.additionalHookExecutors);let{agentToolDeps:h,agentDefinitions:ee,backgroundTaskManager:te}=Ta(e,r,n,t,p,m),{backgroundProcessToolDeps:g}=Ea(e,te,r,n,p),{finalSystemMessage:ne,rebuildSystemMessage:re}=Da(e,n,a,s,g,c,ee),ie=[`Read(.agents/**)`,`Read(.claude/**)`,`Read(.robota/**)`,`Glob(.agents/**)`,`Glob(.claude/**)`,`Glob(.robota/**)`],ae=s?s.commandTools.filter(e=>!e.requiresPermission).map(e=>e.toolName):[],oe=(e.allowedTools??[]).map(e=>`${e}(*)`),se=(e.deniedTools??[]).map(e=>`${e}(*)`),ce={allow:[...ie,...ae,...e.config.permissions.allow??[],...oe],deny:[...e.config.permissions.deny??[],...se]},le=C(n,`.robota`,`settings.local.json`);function ue(e){let t=`${e}(*)`,n=q(le),r=Array.isArray(n.permissions)?[]:n.permissions?.allow??[];r.includes(t)||J(le,{...n,permissions:{...n.permissions??{},allow:[...r,t]}})}let de=new ye({tools:p,provider:t,systemMessage:ne,terminal:e.terminal,permissions:ce,hooks:e.config.hooks,permissionMode:e.permissionMode,defaultTrustLevel:e.config.defaultTrustLevel,model:e.model??e.config.provider.model,providerTimeout:e.config.provider.timeout??12e4,maxTurns:e.maxTurns,sessionStore:e.sessionStore,sessionId:r,permissionHandler:e.permissionHandler,onProjectAllowTool:ue,onTextDelta:e.onTextDelta,onContextUpdate:e.onContextUpdate,onToolExecution:e.onToolExecution,promptForApproval:e.promptForApproval,onCompact:e.onCompact,onCompactEvent:e.onCompactEvent,compactInstructions:e.compactInstructions??e.context.compactInstructions,autoCompactThreshold:e.autoCompactThreshold??e.config.autoCompactThreshold,sessionLogger:e.sessionLogger,hookTypeExecutors:m.length>0?m:void 0,agentName:e.agentName,...e.responseFormat?{responseFormat:e.responseFormat}:{}});return Oa(de,h,g,te),{session:de,rebuildSystemMessage:re}}function go(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function _o(e,t,n,r=new B){let i=C(n,e,`subagents`);return r.mkdirSync(i,{recursive:!0}),new ve(i)}function vo(e,t){return C(t,e,`subagents`)}const Y=_.lazy(()=>_.union([_.string(),_.number(),_.boolean(),_.null(),_.undefined(),_.date(),_.array(Y),_.record(Y)])),yo=_.object({name:_.string().optional(),model:_.string().optional(),apiKey:_.string().optional(),baseURL:_.string().optional(),timeout:_.number().optional(),options:_.record(Y).optional()}),bo=_.object({type:_.string().optional(),model:_.string().optional(),apiKey:_.string().optional(),baseURL:_.string().optional(),timeout:_.number().optional(),options:_.record(Y).optional()}),xo=_.object({allow:_.array(_.string()).optional(),deny:_.array(_.string()).optional()}),So=_.record(_.string()).optional(),Co=_.object({type:_.literal(`command`),command:_.string(),timeout:_.number().optional()}),wo=_.object({type:_.literal(`http`),url:_.string(),headers:_.record(_.string()).optional(),timeout:_.number().optional()}),To=_.object({type:_.literal(`prompt`),prompt:_.string(),model:_.string().optional()}),Eo=_.object({type:_.literal(`agent`),agent:_.string(),maxTurns:_.number().optional(),timeout:_.number().optional()}),Do=_.discriminatedUnion(`type`,[Co,wo,To,Eo]),X=_.object({matcher:_.string(),hooks:_.array(Do)}),Oo=_.object({PreToolUse:_.array(X).optional(),PostToolUse:_.array(X).optional(),SessionStart:_.array(X).optional(),SessionEnd:_.array(X).optional(),Stop:_.array(X).optional(),StopFailure:_.array(X).optional(),PreCompact:_.array(X).optional(),PostCompact:_.array(X).optional(),UserPromptSubmit:_.array(X).optional(),SubagentStart:_.array(X).optional(),SubagentStop:_.array(X).optional(),WorktreeCreate:_.array(X).optional(),WorktreeRemove:_.array(X).optional()}).optional(),ko=_.record(_.boolean()).optional(),Ao=_.object({source:_.object({type:_.enum([`github`,`git`,`local`,`url`]),repo:_.string().optional(),url:_.string().optional(),path:_.string().optional(),ref:_.string().optional()})}),jo=_.record(Ao).optional().catch(void 0),Mo=_.union([_.number().gt(0).lte(1),_.literal(!1)]).optional(),No=_.object({enabled:_.boolean().optional(),options:_.record(Y).optional()}),Po=_.object({defaultTrustLevel:_.enum([`safe`,`moderate`,`full`]).optional(),language:_.string().optional(),currentProvider:_.string().optional(),providers:_.record(bo).optional(),provider:yo.optional(),permissions:xo.optional(),env:So,hooks:Oo,enabledPlugins:ko,extraKnownMarketplaces:jo,autoCompactThreshold:Mo,transports:_.record(No).optional()});function Fo(){return process.env.HOME??process.env.USERPROFILE??`/`}const Z={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[]},env:{}};function Io(e){if(!D(e))return;let t=O(e,`utf-8`).trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function Lo(e){if(e.startsWith(`$ENV:`)){let t=e.slice(5);return process.env[t]??e}return e}function Ro(e){let t=e.provider?.apiKey===void 0?e.provider:zo(e.provider);if(e.providers!==void 0){let n=Object.fromEntries(Object.entries(e.providers).map(([e,t])=>[e,zo(t)]));return{...e,provider:t,providers:n}}return{...e,provider:t}}function zo(e){return{...e,...e.apiKey!==void 0&&{apiKey:Lo(e.apiKey)}}}function Bo(e){return e.reduce((e,t)=>({...e,...t,provider:e.provider!==void 0||t.provider!==void 0?{...e.provider,...t.provider}:void 0,permissions:e.permissions!==void 0||t.permissions!==void 0?{allow:t.permissions?.allow??e.permissions?.allow,deny:t.permissions?.deny??e.permissions?.deny}:void 0,env:{...e.env??{},...t.env??{}},providers:e.providers!==void 0||t.providers!==void 0?Vo(e.providers,t.providers):void 0,enabledPlugins:e.enabledPlugins!==void 0||t.enabledPlugins!==void 0?{...e.enabledPlugins??{},...t.enabledPlugins??{}}:void 0,extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold}),{})}function Vo(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function Ho(e){if(e.currentProvider!==void 0)return Uo(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...Z.provider}}function Uo(e){let t=e.currentProvider;if(t===void 0)throw Error(`currentProvider is required`);let n=e.providers?.[t];if(n===void 0)throw Error(`currentProvider "${t}" was not found in providers`);if(n.type===void 0)throw Error(`Provider profile "${t}" is missing type`);return{name:n.type,model:n.model??Z.provider.model,apiKey:n.apiKey??Z.provider.apiKey,...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function Wo(e){return{defaultTrustLevel:e.defaultTrustLevel??Z.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:Ho(e),permissions:{allow:e.permissions?.allow??Z.permissions.allow,deny:e.permissions?.deny??Z.permissions.deny},env:e.env??Z.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold}}function Go(e){let t=Fo();return[k(t,`.robota`,`settings.json`),k(t,`.claude`,`settings.json`),k(e,`.robota`,`settings.json`),k(e,`.robota`,`settings.local.json`),k(e,`.claude`,`settings.json`),k(e,`.claude`,`settings.local.json`)]}async function Ko(e){let t=Go(e),n=[];for(let e of t){let t=Io(e);t!==void 0&&n.push({raw:t,path:e})}return Wo(Bo(n.map(({raw:e,path:t})=>{let n=Po.safeParse(e);if(!n.success)throw Error(`Invalid settings in ${t}: ${n.error.message}`);return Ro(n.data)})))}const qo=C(`.agents`,`tasks`),Jo={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function Yo(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function Xo(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||Ge(t,`.md`)}function Zo(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function Qo(e,t){let n=e.split(/\r?\n/),r=RegExp(`^(#{2,6})\\s+${t}\\b`,`i`),i=n.findIndex(e=>r.test(e));if(i<0)return;let a=[];for(let e of n.slice(i+1)){if(/^##\s+/.test(e))break;a.push(e)}let o=a.join(`
77
- `).trim();return o.length>0?o:void 0}function $o(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(.+)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function es(e,t){return t&&e.branch===t?0:Jo[e.status]}function ts(e){let t=[`### ${e.title}`,`- **Path:** \`${e.relativePath}\``];return t.push(`- **Status:** ${e.status}`),e.branch&&t.push(`- **Branch:** ${e.branch}`),e.scope&&t.push(`- **Scope:** ${e.scope}`),e.objective&&t.push(`- **Objective:** ${e.objective}`),e.openItems.length>0&&(t.push(`- **Open items:**`),t.push(...e.openItems.map(e=>` - ${e}`))),t.join(`
78
- `)}function ns(e){return e.toISOString().slice(0,10)}function rs(e,t){let n=e.split(/\r?\n/),r=`- **Status**: ${t}`,i=n.findIndex(e=>/^- \*\*Status\*\*:\s*/.test(e));return i>=0?(n[i]=r,n.join(`
65
+ `).length;return[{type:`hunk`,text:`@@ -${d},${s.length+f+l.length} +${d},${s.length+p+l.length} @@`,lineNumber:d},...s,...a,...l]}function si(e){if(e.activeTools.length===0)return;let t=e.activeTools.map(e=>`${e.isRunning?`⟳`:e.result===`success`?`✓`:e.result===`error`?`✗`:`⊘`} ${e.toolName}${e.firstArg?`(${e.firstArg})`:``}`).join(`
66
+ `);e.history.push({id:_(),timestamp:new Date,category:`event`,type:`tool-summary`,data:{tools:e.activeTools.map(e=>({toolName:e.toolName,firstArg:e.firstArg,isRunning:e.isRunning,result:e.result,diffFile:e.diffFile,diffLines:e.diffLines,toolResultData:e.toolResultData})),summary:t}})}function ci(e){let t=e.filter(e=>!e.isRunning);if(t.length<=50)return e;let n=t.length-50,r=0;return e.filter(e=>!e.isRunning&&r<n?(r++,!1):!0)}function li(e,t){let n=ti(t.toolArgs),r={toolName:t.toolName,firstArg:n,isRunning:!0,...t.executionId?{executionId:t.executionId}:{}};return e.activeTools.push(r),e.history.push({id:_(),timestamp:new Date,category:`event`,type:`tool-start`,data:{toolName:t.toolName,firstArg:n,isRunning:!0}}),r}function ui(e,t){let n=t.denied?`denied`:t.success===!1?`error`:`success`,r=e.activeTools.findIndex(e=>e.toolName===t.toolName&&e.isRunning);if(r===-1)return null;let i={...e.activeTools[r],...ii(t),isRunning:!1,result:n,toolResultData:t.toolResultData};return e.activeTools[r]=i,e.activeTools=ci(e.activeTools),e.history.push({id:_(),timestamp:new Date,category:`event`,type:`tool-end`,data:{toolName:i.toolName,firstArg:i.firstArg,isRunning:!1,result:n,toolResultData:t.toolResultData}}),i}const di=[{pattern:/\b401\b|invalid.*api.?key|authentication.*fail|unauthorized/i,message:"Invalid API key. Run `/provider` to reconfigure, or check your settings file (~/.robota/settings.json)."},{pattern:/\b403\b|permission.*denied|forbidden/i,message:"Access denied. Your API key may lack permission for this model. Check your provider plan or run `/provider` to switch accounts."},{pattern:/\b429\b|rate.?limit|too many requests|quota.*exceeded/i,message:"Rate limit reached. Wait a moment and try again. Consider switching to a different model with `/model`."},{pattern:/\b500\b|internal server error/i,message:`The AI provider returned an internal error. This is usually temporary — try again.`},{pattern:/\b503\b|service.*unavailable|overloaded/i,message:`The AI provider is temporarily unavailable or overloaded. Try again in a few seconds.`},{pattern:/\b502\b|bad gateway/i,message:`The AI provider gateway is unreachable. Check your network or try again shortly.`},{pattern:/\btimeout\b|timed.?out|ETIMEDOUT/i,message:`The request timed out. Check your internet connection, or try a shorter prompt to reduce response time.`},{pattern:/ENOTFOUND|ECONNREFUSED|ECONNRESET|network.*error|fetch.*fail/i,message:`Network connection failed. Check your internet connection and verify your provider URL in settings.`}];function fi(i){if(i instanceof e)return"Invalid API key. Run `/provider` to reconfigure, or check your settings file (~/.robota/settings.json).";if(i instanceof r)return`Rate limit reached${i.retryAfter?` (retry after ${i.retryAfter}s)`:``}. Wait a moment and try again. Consider switching to a different model with \`/model\`.`;if(i instanceof t)return`Network connection failed. Check your internet connection and verify your provider URL in settings.`;if(i instanceof n&&i.originalError)return fi(i.originalError);let a=i.message;for(let{pattern:e,message:t}of di)if(e.test(a))return t;return a}async function pi(e,t,n,r){let i=r.getHistory();i.push(h(s(t??e))),r.onWorkspaceUpdated();let c=r.getSession().getHistory().length;r.resetUsedMemoryReferences();try{let o=await Zr(e,r.getCwd(),n,r.getContextReferences());o.promptFileReferenceEntry&&i.push(o.promptFileReferenceEntry),r.recordContextReferenceUsage(o.activeContextReferenceRecords),r.recordPromptContextReferences(o.promptFileReferenceRecords),await r.beginEditCheckpointTurn(t??e);let s=await r.getSession().run(o.modelInput,o.hookInput);r.flushStreaming(),si({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let l=Jr(s||`(empty response)`,r.getSession().getHistory(),i,c,r.getSession().getContextState(),o.promptFileReferenceRecords);i.push(h(a(l.response))),l.usage&&i.push(Xr(l.usage)),r.onComplete(l),r.onContextUpdate()}catch(e){if(r.flushStreaming(),Kr(e)){let e=Yr(r.getSession().getHistory(),i,c,r.getSession().getContextState());si({activeTools:r.getActiveTools(),history:i}),r.clearStreaming(),e.response&&i.push(h(a(e.response))),e.usage&&i.push(Xr(e.usage)),i.push(h(o(`Interrupted by user.`))),r.onInterrupted(e)}else{si({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let t=e instanceof Error?e:Error(String(e)),n=fi(t);i.push(h(o(`Error: ${n}`))),r.onError(t)}}}var mi=class{histTracker;skillRouter;callbacks;executing=!1;streamingText=``;flushTimer=null;activeTools=[];pendingPrompt=null;pendingDisplayInput;pendingRawInput;shuttingDown=!1;constructor(e,t,n){this.histTracker=e,this.skillRouter=t,this.callbacks=n}clearPendingQueue(){this.pendingPrompt=null,this.pendingDisplayInput=void 0,this.pendingRawInput=void 0}clearStreaming(){this.streamingText=``,this.activeTools=[],this.flushTimer&&=(clearTimeout(this.flushTimer),null)}flushStreaming(){this.flushTimer&&=(clearTimeout(this.flushTimer),null)}handleTextDelta(e){this.streamingText+=e,this.callbacks.emit(`text_delta`,e),this.flushTimer||=setTimeout(()=>{this.flushTimer=null},16)}handleCompactEvent(e){e.trigger===`auto`&&this.histTracker.append(h(o(`Auto compacted context: ${Math.round(e.before.usedPercentage)}% -> ${Math.round(e.after.usedPercentage)}%`))),this.callbacks.emit(`compact`,e),this.callbacks.emit(`context_update`,e.after)}handleToolExecution(e){let t={activeTools:this.activeTools,history:this.histTracker.getHistory()};if(e.type===`start`){let n=li(t,e);this.activeTools=t.activeTools,this.callbacks.emit(`tool_start`,n)}else{let n=ui(t,e);this.activeTools=t.activeTools,n&&this.callbacks.emit(`tool_end`,n)}}emitExecutionWorkspaceUpdated(e,t){this.callbacks.getSession()&&this.callbacks.emit(`execution_workspace_event`,{type:`execution_workspace_updated`,cause:e,...t?{entryId:t}:{},snapshot:this.callbacks.getExecutionWorkspaceSnapshot()})}drainPendingQueue(e){if(!this.shuttingDown&&this.pendingPrompt){let t=this.pendingPrompt,n=this.pendingDisplayInput,r=this.pendingRawInput;this.clearPendingQueue(),setTimeout(()=>void e(t,n,r),0)}}async executePrompt(e,t,n,r,i,a,o,s){await ar(r,i,a,o,()=>this.callbacks.getSessionOrThrow(),(e,t)=>this.callbacks.emit(e,t)),this.executing=!0,this.clearStreaming(),this.callbacks.emit(`user_message`,t??e),this.callbacks.emit(`thinking`,!0);try{await pi(e,t,n,{getSession:()=>this.callbacks.getSessionOrThrow(),getCwd:()=>this.callbacks.getCwd(),getHistory:()=>this.histTracker.getHistory(),getContextReferences:()=>this.histTracker.listInjectionContextReferences(),getActiveTools:()=>this.activeTools,resetUsedMemoryReferences:()=>this.histTracker.resetUsedMemoryReferences(),recordContextReferenceUsage:e=>this.histTracker.recordContextReferenceUsage(e),recordPromptContextReferences:e=>this.histTracker.recordPromptContextReferences(e),beginEditCheckpointTurn:e=>this.histTracker.beginEditCheckpointTurn(e),flushStreaming:()=>this.flushStreaming(),clearStreaming:()=>this.clearStreaming(),onWorkspaceUpdated:()=>this.emitExecutionWorkspaceUpdated(`main_thread`),onComplete:e=>{this.callbacks.emit(`complete`,e)},onInterrupted:e=>{this.callbacks.emit(`interrupted`,e)},onError:e=>{this.callbacks.emit(`error`,e)},onContextUpdate:()=>{this.callbacks.emit(`context_update`,this.callbacks.getContextState())}})}finally{try{await this.histTracker.finalizeEditCheckpointTurn()}catch(e){this.callbacks.emit(`error`,e instanceof Error?e:Error(String(e)))}this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(s)}}async executeForkSkillCommand(e,t,n,r,i,a){if(this.executing)throw Error(`Cannot execute fork skill while another prompt is running.`);this.executing=!0,this.clearStreaming(),this.callbacks.emit(`thinking`,!0),this.histTracker.append(h(s(n??`/${e.name}`))),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let n=await this.skillRouter.executeSkillWithActivation(e,t,i,r);return await this.applyForkSkillResult(n.result??`(empty response)`),n}catch(e){let t=e instanceof Error?e:Error(String(e));return this.histTracker.append(h(o(`Error: ${fi(t)}`))),this.callbacks.emit(`error`,t),{mode:`fork`,result:``}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(a)}}async executeForegroundCommand(e,t){this.executing=!0,this.clearStreaming(),this.callbacks.emit(`thinking`,!0),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let t=await e();return this.callbacks.emit(`context_update`,this.callbacks.getContextState()),t}catch(e){return{success:!1,message:`Error: ${e instanceof Error?e.message:String(e)}`}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(t)}}async applyForkSkillResult(e){this.flushStreaming(),si({activeTools:this.activeTools,history:this.histTracker.getHistory()}),this.clearStreaming();let t={response:e,history:this.histTracker.getHistory(),toolSummaries:[],contextState:this.callbacks.getContextState()};this.histTracker.append(h(a(e))),this.callbacks.emit(`complete`,t),this.callbacks.emit(`context_update`,this.callbacks.getContextState())}};function hi(e,t,n){let r=L(n)?.customAgentRegistry?.(e)??an(e);if(!r)throw Error(`Unknown agent type: ${e}`);return t.allowedTools?{...r,tools:t.allowedTools}:r}async function gi(e,t,n){let r=L(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);return Cn({agentDefinition:hi(t.agent??`general-purpose`,t,n),parentConfig:r.config,parentContext:r.context,parentTools:r.tools,provider:r.provider,terminal:r.terminal,isForkWorker:!0,permissionMode:r.permissionMode,permissionHandler:r.permissionHandler,hooks:r.hooks,hookTypeExecutors:r.hookTypeExecutors,onTextDelta:r.onTextDelta,onToolExecution:r.onToolExecution}).run(e)}async function _i(e,t,n){let r=await Nr([t],{cwd:n,reason:`manual`});if(yr(r.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[br(r.diagnostics)]}};let i=r.references[0];if(!i)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let a=or(V([i])[0],`manual`,`active`),o=sr(e,a);return{references:o.references,result:{reference:a,evicted:o.evicted,diagnostics:[]}}}function vi(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=or(e,n.loadType,n.status,r);i=sr(i,t).references}return i}function yi(e,t){let n=new Date().toISOString();return e.map(e=>{let r=C(t,e.filePath);return{id:`system:${r}`,sourcePath:e.filePath,relativePath:r,originalReference:r,loadType:`system`,status:`active`,byteLength:Buffer.byteLength(e.content,`utf-8`),loadedAt:n,lastUsedAt:n}})}function U(e){let t=S(e,`.robota`);return{settings:S(t,`settings.json`),settingsLocal:S(t,`settings.local.json`),logs:S(t,`logs`),sessions:S(t,`sessions`),memory:S(t,`memory`),checkpoints:S(t,`checkpoints`)}}function bi(){let e=S(T(),`.robota`);return{settings:S(e,`settings.json`),sessions:S(e,`sessions`),onboarded:S(e,`onboarded`)}}function xi(e){let t=e.fs??new z,n=e.manifests.filter(t=>t.sequence>e.target.sequence),r=e.manifests.filter(t=>t.sequence>=e.target.sequence);return{target:Si(e.target),capturedFiles:e.target.files.map(n=>{let r=n.snapshotFile?S(e.checkpointDir(e.sessionId,e.target.id),n.snapshotFile):void 0,i=r?wi(r,t):void 0;return{originalPath:n.originalPath,relativePath:C(e.cwd,n.originalPath),existed:n.existed,restoreAction:n.existed?`restore-preimage`:`delete-created-file`,snapshotAvailable:n.existed?i!==void 0:!1,...i?{snapshotSizeBytes:i.size}:{}}}),restoreToCheckpoint:Ci(n),rollbackThroughCheckpoint:Ci(r)}}function Si(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function Ci(e){return{checkpointIds:e.map(e=>e.id),fileCount:e.reduce((e,t)=>e+t.fileCount,0)}}function wi(e,t){try{return t.statSync(e)}catch{return}}const Ti=`manifest.json`,Ei=`files`;var Di=class{fs;fsAsync;cwd;rootDir;now;activeTurn=null;constructor(e,t=new z,n=new B){this.fs=t,this.fsAsync=n,this.cwd=w(e.cwd),this.rootDir=U(this.cwd).checkpoints,this.now=e.now??(()=>new Date)}async beginTurn(e){this.activeTurn&&await this.finalizeTurn();let t=this.nextSequence(e.sessionId),n=`turn-${String(t).padStart(4,`0`)}`,r=S(this.sessionDir(e.sessionId),n);await this.fsAsync.mkdir(S(r,Ei),{recursive:!0});let i={version:1,id:n,sessionId:e.sessionId,sequence:t,prompt:e.prompt,createdAt:this.now().toISOString(),fileCount:0,files:[]};return this.activeTurn={manifest:i,dir:r,capturedPaths:new Set},W(i)}async captureFile(e){if(!this.activeTurn)return;let t=w(this.cwd,e);if(this.activeTurn.capturedPaths.has(t)||ki(this.rootDir,t))return;let n=await this.createFileRecord(t,this.activeTurn);this.activeTurn.manifest.files.push(n),this.activeTurn.manifest.fileCount=this.activeTurn.manifest.files.length,this.activeTurn.capturedPaths.add(t)}async finalizeTurn(){if(!this.activeTurn)return;let e=this.activeTurn;return this.activeTurn=null,await this.writeManifest(e.dir,e.manifest),W(e.manifest)}list(e){return this.loadManifests(e).map(W)}inspect(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);return xi({cwd:this.cwd,sessionId:e,target:r,manifests:n,checkpointDir:(e,t)=>this.checkpointDir(e,t)})}async restoreToCheckpoint(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);let i=n.filter(e=>e.sequence>r.sequence).sort((e,t)=>t.sequence-e.sequence),a=0;for(let t of i)for(let n of t.files)await this.restoreFile(e,t.id,n),a+=1;for(let t of i)await this.fsAsync.rm(this.checkpointDir(e,t.id),{recursive:!0,force:!0});return{target:W(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async rollbackThroughCheckpoint(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);let i=n.filter(e=>e.sequence>=r.sequence).sort((e,t)=>t.sequence-e.sequence),a=0;for(let t of i)for(let n of t.files)await this.restoreFile(e,t.id,n),a+=1;for(let t of i)await this.fsAsync.rm(this.checkpointDir(e,t.id),{recursive:!0,force:!0});return{target:W(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async createFileRecord(e,t){if(!await Ai(this.fsAsync,this.fs,e))return{originalPath:e,existed:!1};let n=S(Ei,`${String(t.manifest.files.length+1).padStart(6,`0`)}.content`);return await this.fsAsync.copyFile(e,S(t.dir,n)),{originalPath:e,existed:!0,snapshotFile:n}}async restoreFile(e,t,n){if(!n.existed){await this.fsAsync.rm(n.originalPath,{force:!0});return}if(!n.snapshotFile)throw Error(`Checkpoint file record is missing a snapshot: ${n.originalPath}`);await this.fsAsync.mkdir(x(n.originalPath),{recursive:!0}),await this.fsAsync.copyFile(S(this.checkpointDir(e,t),n.snapshotFile),n.originalPath)}loadManifests(e){let t=this.sessionDir(e);return ji(this.fs,t).map(e=>S(t,e,Ti)).map(e=>Mi(this.fs,e)).filter(e=>e!==void 0).sort((e,t)=>e.sequence-t.sequence)}nextSequence(e){return(this.list(e).at(-1)?.sequence??0)+1}async writeManifest(e,t){await this.fsAsync.mkdir(e,{recursive:!0});let n=S(e,Ti),r=`${n}.tmp`;await this.fsAsync.writeFile(r,JSON.stringify(t,null,2),`utf8`),await this.fsAsync.rename(r,n)}sessionDir(e){return S(this.rootDir,Oi(e))}checkpointDir(e,t){return S(this.sessionDir(e),Oi(t))}};function W(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function Oi(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function ki(e,t){let n=C(e,t);return n.length===0||!n.startsWith(`..`)&&!n.startsWith(`/`)}async function Ai(e,t,n){try{return await e.access(n,t.constants.F_OK),!0}catch{return!1}}function ji(e,t){try{return e.readdirSync(t)}catch{return[]}}function Mi(e,t){try{let n=e.readFileSync(t,`utf8`);return JSON.parse(n)}catch{return}}function Ni(e){return e.source===`plugin`?`plugin`:`skill`}function Pi(e){return e.context===`fork`?`fork`:`inject`}function Fi(e){return{type:`skill-activation`,skillName:e.skill.name,source:Ni(e.skill),invocation:e.invocation,mode:Pi(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function Ii(e){let t=e.source===`plugin`?`plugin skill`:`skill`;return e.status===`failed`?`Skill failed: ${e.skillName}${e.error?` (${e.error})`:``}`:e.status===`completed`?`Skill completed: ${e.skillName}`:`Invoking ${t}: ${e.skillName}`}var Li=class{cwd;getSessionId;getExecuting;persistSession;emitSkillActivation;history=[];editCheckpointStore=null;memoryEvents=[];usedMemoryReferences=[];contextReferences=[];systemContextReferences=[];skillActivationEvents=[];constructor(e,t,n,r,i,a=null){this.cwd=e,this.getSessionId=t,this.getExecuting=n,this.persistSession=r,this.emitSkillActivation=i,this.editCheckpointStore=a}restoreState(e){this.history=e.history,this.memoryEvents=e.memoryEvents,this.usedMemoryReferences=e.usedMemoryReferences,this.contextReferences=e.contextReferences,this.skillActivationEvents=e.skillActivationEvents}getState(){return{history:this.history,memoryEvents:this.memoryEvents,usedMemoryReferences:this.usedMemoryReferences,contextReferences:this.contextReferences,skillActivationEvents:this.skillActivationEvents}}append(e){this.history.push(e)}getHistory(){return this.history}clearHistory(){this.history=[],this.memoryEvents=[],this.usedMemoryReferences=[]}resetUsedMemoryReferences(){this.usedMemoryReferences=[]}recordContextReferenceUsage(e){this.contextReferences=vi(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=vi(this.contextReferences,e,{loadType:`prompt-reference`,status:`observed`}),this.persistSession()}listEditCheckpoints(){let e=this.getSessionId();return this.getCheckpointStore().list(e)}inspectEditCheckpoint(e){let t=this.getSessionId();return this.getCheckpointStore().inspect(t,e)}async restoreEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot restore edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push(h(o(`Restored edit checkpoint: ${e}`))),this.persistSession(),t}async rollbackEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot rollback edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().rollbackThroughCheckpoint(this.getSessionId(),e);return this.history.push(h(o(`Rolled back edit checkpoint: ${e}`))),this.persistSession(),t}async beginEditCheckpointTurn(e){this.editCheckpointStore&&await this.editCheckpointStore.beginTurn({sessionId:this.getSessionId(),prompt:e})}async finalizeEditCheckpointTurn(){if(this.editCheckpointStore)try{await this.editCheckpointStore.finalizeTurn()}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.history.push(h(o(`Checkpoint error: ${t.message}`))),t}}setEditCheckpointStore(e){this.editCheckpointStore=e}getUsedMemoryReferences(){return[...this.usedMemoryReferences]}recordMemoryEvent(e){this.memoryEvents.push(e),this.persistSession()}recordSystemContextFiles(e){this.systemContextReferences=yi(e,this.cwd)}listContextReferences(){return[...this.systemContextReferences,...this.contextReferences]}listInjectionContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await _i(this.contextReferences,e,this.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=cr(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=lr(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,t){this.skillActivationEvents.push(e),t&&this.history.push({id:_(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:Ii(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){return this.editCheckpointStore||=new Di({cwd:this.cwd}),this.editCheckpointStore}};function Ri(e){if(E(e))try{return JSON.parse(D(e,`utf-8`))}catch{return}}function zi(e){if(E(O(e,`pnpm-workspace.yaml`))||E(O(e,`pnpm-lock.yaml`)))return`pnpm`;if(E(O(e,`yarn.lock`)))return`yarn`;if(E(O(e,`bun.lockb`)))return`bun`;if(E(O(e,`package-lock.json`)))return`npm`}async function Bi(e){let t=O(e,`package.json`),n=O(e,`tsconfig.json`),r=O(e,`pyproject.toml`),i=O(e,`Cargo.toml`),a=O(e,`go.mod`);if(E(t)){let r=Ri(t),i=E(n)?`typescript`:`javascript`,a=zi(e);return{type:`node`,name:r?.name,packageManager:a,language:i}}return E(r)||E(O(e,`setup.py`))?{type:`python`,language:`python`}:E(i)?{type:`rust`,language:`rust`}:E(a)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}function Vi(e,t){let n=t.content,r=typeof n==`string`?n:n==null?``:JSON.stringify(n);t.role===`tool`?e.injectMessage(`tool`,r,{toolCallId:t.toolCallId,...t.name===void 0?{}:{name:t.name}}):e.injectMessage(t.role,r)}function Hi(e,t,n,r){let i=e.load(t);if(!i)return{history:[],sessionName:void 0,pendingRestoreMessages:null,backgroundTasks:[],backgroundTaskEvents:[],backgroundJobGroups:[],backgroundJobGroupEvents:[],skillActivationEvents:[],memoryEvents:[],usedMemoryReferences:[],contextReferences:[],sandboxSnapshotId:void 0};let a=i.history??[],o=i.backgroundTasks??[],s=i.backgroundTaskEvents??[],c=i.backgroundJobGroups??[],l=i.backgroundJobGroupEvents??[],u=i.skillActivationEvents??[],d=i.memoryEvents??[],f=i.usedMemoryReferences??[],p=i.contextReferences??[],m=i.sandboxSnapshotId,{backgroundTasks:h,backgroundTaskEvents:ee}=Ui(o,s),te=i.name,ne=null;if(!n&&i.messages)if(r)for(let e of i.messages)Vi(r,e);else ne=i.messages;return{history:a,sessionName:te,pendingRestoreMessages:ne,backgroundTasks:h,backgroundTaskEvents:ee,backgroundJobGroups:c,backgroundJobGroupEvents:l,skillActivationEvents:u,memoryEvents:d,usedMemoryReferences:f,contextReferences:p,sandboxSnapshotId:m}}function Ui(e,t){let n=new Date().toISOString(),r=[];return{backgroundTasks:e.map(e=>{if(Wi(e.status))return e;let t={...e,status:`failed`,timeoutReason:`stale_worker`,error:{category:`timeout`,message:`Restored background task is stale; worker cannot be reattached`,recoverable:!0},unread:!0,completedAt:n,updatedAt:n};return r.push({type:`background_task_failed`,task:t}),t}),backgroundTaskEvents:[...t,...r]}}function Wi(e){return e===`completed`||e===`failed`||e===`cancelled`}function Gi(e){if(e.type===`background_task_started`&&e.task.kind===`agent`)return`SubagentStart`;if((e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)&&e.task.kind===`agent`)return`SubagentStop`}function Ki(e,t,n,r){let i=Gi(e);!i||!(`task`in e)||te(n,i,{session_id:e.task.parentSessionId,cwd:t,hook_event_name:i,agent_id:e.task.id,agent_type:e.task.agentType??e.task.label,...e.task.transcriptPath?{agent_transcript_path:e.task.transcriptPath,transcript_path:e.task.transcriptPath}:{},...e.task.error?.message||e.task.timeoutReason?{reason:e.task.error?.message??e.task.timeoutReason}:{},...i===`SubagentStop`?{stop_hook_active:!1,...e.task.result?.output?{last_assistant_message:e.task.result.output}:{}}:{},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e.task.parentSessionId,ROBOTA_AGENT_ID:e.task.id,ROBOTA_AGENT_TYPE:e.task.agentType??e.task.label}},r).catch(()=>void 0)}const qi=[`Bash — execute shell commands`,`Read — read file contents with line numbers`,`Write — write content to a file`,`Edit — replace a string in a file`,`Glob — find files matching a pattern`,`Grep — search file contents with regex`,`WebFetch — fetch URL content as text`,`WebSearch — search the internet through the configured local tool`];function Ji(e={}){return[le(e),de(e),fe(e),ue(e),me,he,ge,_e]}const Yi=new Set([`tools`,`disallowedTools`]),Xi=new Set([`maxTurns`]);function Zi(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Qi(e){let t=e.split(`
67
+ `);if(t[0]?.trim()!==`---`)return{frontmatter:null,body:e};let n=-1;for(let e=1;e<t.length;e++)if(t[e]?.trim()===`---`){n=e;break}if(n===-1)return{frontmatter:null,body:e};let r={};for(let e=1;e<n;e++){let n=t[e].match(/^([a-zA-Z][a-zA-Z0-9]*(?:[A-Z][a-z]*)*):\s*(.+)/);if(!n)continue;let i=n[1],a=n[2].trim();Yi.has(i)?r[i]=Zi(a):Xi.has(i)?r[i]=parseInt(a,10):r[i]=a}let i=t.slice(n+1).join(`
68
+ `).trim();return{frontmatter:Object.keys(r).length>0?r:null,body:i}}function $i(e,t){if(!t.existsSync(e))return[];let n=[],r;try{r=t.readdirSync(e,{withFileTypes:!0})}catch{return[]}for(let i of r){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let r=S(e,i.name),{frontmatter:a,body:o}=Qi(t.readFileSync(r,`utf-8`)),s=Ke(i.name,`.md`),c={name:a?.name??s,description:a?.description??``,systemPrompt:o};a?.model!==void 0&&(c.model=a.model),a?.maxTurns!==void 0&&(c.maxTurns=a.maxTurns),a?.tools!==void 0&&(c.tools=a.tools),a?.disallowedTools!==void 0&&(c.disallowedTools=a.disallowedTools),n.push(c)}return n}var ea=class{cwd;home;fs;constructor(e,t,n=new z){this.cwd=e,this.home=t??T(),this.fs=n}loadAll(){let e=[$i(S(this.cwd,`.robota`,`agents`),this.fs),$i(S(this.cwd,`.agents`,`agents`),this.fs),$i(S(this.cwd,`.claude`,`agents`),this.fs),$i(S(this.home,`.robota`,`agents`),this.fs),$i(S(this.home,`.claude`,`agents`),this.fs)],t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.name)||(t.add(e.name),n.push(e));let r=[...n];for(let e of rn)t.has(e.name)||r.push(e);return r}getAgent(e){return this.loadAll().find(t=>t.name===e)}};function ta(e){let t=e.content.trim();return e.title?[`## ${e.title}`,t].join(`
69
+ `):t}function na(e){return[...e].filter(e=>e.content.trim().length>0).sort((e,t)=>e.priority-t.priority||e.id.localeCompare(t.id)).map(e=>ta(e)).join(`
70
+
71
+ `)}const ra={safe:`safe`,moderate:`moderate`,full:`full`};function G(e,t,n,r,i){return{id:e,title:t,priority:n,content:r,source:i}}function ia(e){if(e)return G(`runtime-cwd`,`Working Directory`,30,`\`${e}\``,`runtime`)}function aa(e){let t=[];return e.name!==void 0&&t.push(`- **Name:** ${e.name}`),e.type!==`unknown`&&t.push(`- **Type:** ${e.type}`),e.language!==`unknown`&&t.push(`- **Language:** ${e.language}`),e.packageManager!==void 0&&t.push(`- **Package manager:** ${e.packageManager}`),G(`runtime-project`,`Current Project`,40,t.join(`
72
+ `),`runtime`)}function oa(e){return G(`permission-mode`,`Permission Mode`,50,`- **Trust level:** ${ra[e]}`,`permissions`)}function sa(e){if(!(e===void 0||e.trim().length===0))return G(`runtime-response-language`,`Response Language`,45,e,`runtime`)}function ca(e){if(e.trim().length!==0)return G(`project-agents-md`,`Agent Instructions`,10,e,`project-instructions`)}function la(e){if(e.trim().length!==0)return G(`project-claude-md`,`Project Notes`,20,e,`project-instructions`)}function ua(e){if(!(e===void 0||e.trim().length===0))return G(`project-memory`,`Project Memory`,25,e,`project-instructions`)}function da(e){if(!(e===void 0||e.trim().length===0))return G(`active-task-context`,`Active Task Context`,27,e,`project-instructions`)}function fa(e){if(e.length!==0)return G(`tool-descriptions`,`Available Tools`,60,e.map(e=>`- ${e}`).join(`
73
+ `),`tool`)}function pa(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}`}function ma(e,t,n,r,i){let a=i.filter(t=>t.modelInvocable&&t.kind===e).map(pa);if(a.length!==0)return G(`capability-${e}`,t,n,a.join(`
74
+ `),r)}function ha(e){let t=[],n=ma(`builtin-command`,`Built-in Commands`,70,`command`,e),r=ma(`skill`,`Skills`,80,`skill`,e),i=ma(`agent`,`Agents`,90,`agent`,e),a=ma(`tool`,`Tools`,100,`tool`,e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),a&&t.push(a),t}function K(e,t){t!==void 0&&e.push(t)}function ga(e){return e.map(e=>({name:e.name,kind:`skill`,description:e.description,userInvocable:!0,modelInvocable:e.disableModelInvocation!==!0}))}function _a(e){return e.map(e=>({name:e.name,kind:`agent`,description:e.description,userInvocable:!1,modelInvocable:!0,safety:`background-agent`}))}function va(e){return[...e.commandDescriptors??[],...e.skills?ga(e.skills):[],...e.agents?_a(e.agents):[]]}function ya(e){let t=[];return K(t,ca(e.agentsMd)),K(t,la(e.claudeMd)),K(t,ua(e.memoryMd)),K(t,da(e.taskContext)),K(t,ia(e.cwd)),t.push(aa(e.projectInfo)),K(t,sa(e.language)),t.push(oa(e.trustLevel)),K(t,fa(e.toolDescriptions)),t.push(...ha(va(e))),na(t)}function ba(e){return e}const xa=g.object({command:g.string().describe(`The shell command to start in the background`),timeout:g.number().optional().describe(`Optional timeout in milliseconds. Default is 120000.`),workingDirectory:g.string().optional().describe(`Working directory for the command. Defaults to the current project directory.`),stdin:g.string().optional().describe(`Optional stdin to write after the process starts.`),outputLimitBytes:g.number().optional().describe(`Maximum captured output bytes kept in the task result.`)});function Sa(e,t,n){return JSON.stringify({success:!0,background:!0,output:``,taskId:e,status:t,command:n})}function Ca(e){return JSON.stringify({success:!1,background:!0,output:``,error:`Background process error: ${e}`})}async function wa(e,t){try{let n=await t.backgroundTaskManager.spawn({kind:`process`,label:e.command,mode:`background`,parentSessionId:t.parentSessionId??`unknown-session`,depth:0,cwd:e.workingDirectory??t.cwd??process.cwd(),command:e.command,stdin:e.stdin,timeoutMs:e.timeout??12e4,outputLimitBytes:e.outputLimitBytes,metadata:t.metadata});return Sa(n.id,n.status,e.command)}catch(e){return Ca(e instanceof Error?e.message:String(e))}}function Ta(e){return pe(`BackgroundProcess`,`Start a shell command as a managed background task. Use this for long-running commands that should not block the current conversation. Use /background list, /background read <taskId>, /background cancel <taskId>, or /background close <taskId> to inspect or control it.`,ba(xa),async t=>wa(t,e))}function Ea(e,t,n,r,i,a){let o,s=[],c;if(e.enableAgentRuntime){let l=new ea(n);s=l.loadAll(),o={config:e.config,context:e.context,tools:i,terminal:e.terminal,provider:r,cwd:n,parentSessionId:t,permissionMode:e.permissionMode,permissionHandler:e.permissionHandler,hooks:e.config.hooks,hookTypeExecutors:a.length>0?a:void 0,onTextDelta:e.onTextDelta,onToolExecution:e.onToolExecution,customAgentRegistry:e=>l.getAgent(e),agentDefinitions:s};let u=new re({runner:(e.subagentRunnerFactory??kn)(o),backgroundTaskRunners:e.backgroundTaskRunners});o.subagentManager=u,c=u.getBackgroundTaskManager(),o.backgroundTaskManager=c}else c=new ne({runners:e.backgroundTaskRunners??[]});let l=e.sessionLogger;return l&&c.subscribe(e=>Aa(l,t,e)),c.subscribe(t=>Ki(t,n,e.config.hooks,a.length>0?a:void 0)),{agentToolDeps:o,agentDefinitions:s,backgroundTaskManager:c}}function Da(e,t,n,r,i){if(!e.backgroundTaskRunners?.some(e=>e.kind===`process`))return{backgroundProcessToolDeps:void 0};let a={backgroundTaskManager:t,cwd:r,parentSessionId:n,metadata:N({kind:`tool_call`,sessionId:n,label:`BackgroundProcess`})};return i.push(Ta(a)),{backgroundProcessToolDeps:a}}function Oa(e,t,n,r,i,a,o){let s=e.systemPromptBuilder??ya,c=[...qi,...r?r.commandTools.map(mn):[]],l=e.toolDescriptions??(i?[...c,`BackgroundProcess — start long-running shell commands as managed background tasks`]:c),u={agentsMd:e.context.agentsMd,claudeMd:e.context.claudeMd,memoryMd:e.context.memoryMd,taskContext:e.context.taskContext,toolDescriptions:l,trustLevel:e.config.defaultTrustLevel,projectInfo:e.projectInfo??{type:`unknown`,language:`unknown`},cwd:t,language:e.config.language,skills:a.map(e=>({name:e.name,description:e.description,disableModelInvocation:e.disableModelInvocation})),...o.length>0?{agents:o.map(e=>({name:e.name,description:e.description}))}:{},commandDescriptors:e.commandDescriptors??[]},d=s(u);return{finalSystemMessage:e.appendSystemPrompt?`${d}\n\n${e.appendSystemPrompt}`:d,rebuildSystemMessage:(t,n)=>{let r=s({...u,agentsMd:t,claudeMd:n});return e.appendSystemPrompt?`${r}\n\n${e.appendSystemPrompt}`:r}}}function ka(e,t,n,r){t&&(t.parentSessionId=e.getSessionId()),n&&(n.parentSessionId=e.getSessionId()),Bt(e,r),t&&Pn(e,t)}function Aa(e,t,n){let r={};if(n.type===`background_task_created`){r.taskId=n.task.id;let e=n.task.metadata?.executionOriginToolCallId;typeof e==`string`&&(r.originToolCallId=e)}e.log(t,`background_task_event`,{backgroundEventType:n.type,backgroundEvent:n,...r})}const ja=new Set([`Write`,`Edit`]);function Ma(e,t){return e.map(e=>ja.has(e.getName())?new Na(e,t):e)}var Na=class{delegate;recorder;schema;constructor(e,t){this.delegate=e,this.recorder=t,this.schema=e.schema}setEventService(e){this.delegate.setEventService(e)}async execute(e,t){let n=Pa(e);return n&&await this.recorder.captureFile(n),this.delegate.execute(e,t)}validate(e){return this.delegate.validate(e)}validateParameters(e){return this.delegate.validateParameters(e)}getDescription(){return this.delegate.getDescription()}getName(){return this.delegate.getName()}};function Pa(e){if(!e||typeof e!=`object`)return;let t=e.filePath;return typeof t==`string`&&t.length>0?t:void 0}const Fa=new Set([`disable-model-invocation`,`user-invocable`]),Ia=new Set([`allowed-tools`]);function La(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Ra(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function za(e){let t=e.split(`
75
+ `);if(t[0]?.trim()!==`---`)return null;let n={};for(let e=1;e<t.length;e++){let r=t[e];if(r.trim()===`---`)break;let i=r.match(/^([a-z][a-z0-9-]*):\s*(.+)/);if(!i)continue;let a=i[1],o=i[2].trim(),s=La(a);Fa.has(a)?n[s]=o===`true`:Ia.has(a)?n[s]=Ra(o):n[s]=o}return Object.keys(n).length>0?n:null}function Ba(e,t,n){let r={name:e?.name??n,description:e?.description??`Skill: ${n}`,source:`skill`,skillContent:t};return e?.argumentHint!==void 0&&(r.argumentHint=e.argumentHint),e?.disableModelInvocation!==void 0&&(r.disableModelInvocation=e.disableModelInvocation),e?.userInvocable!==void 0&&(r.userInvocable=e.userInvocable),e?.allowedTools!==void 0&&(r.allowedTools=e.allowedTools),e?.model!==void 0&&(r.model=e.model),e?.effort!==void 0&&(r.effort=e.effort),e?.context!==void 0&&(r.context=e.context),e?.agent!==void 0&&(r.agent=e.agent),r}function Va(e,t){if(!t.existsSync(e))return[];let n=[],r=t.readdirSync(e,{withFileTypes:!0});for(let i of r){if(!i.isDirectory())continue;let r=S(e,i.name,`SKILL.md`);if(!t.existsSync(r))continue;let a=t.readFileSync(r,`utf-8`),o=za(a);n.push(Ba(o,a,i.name))}return n}function Ha(e,t){if(!t.existsSync(e))return[];let n=[],r=t.readdirSync(e,{withFileTypes:!0});for(let i of r){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let r=S(e,i.name),a=t.readFileSync(r,`utf-8`),o=za(a),s=Ke(i.name,`.md`);n.push(Ba(o,a,s))}return n}var Ua=class{name=`skill`;cwd;home;fs;cachedCommands=null;constructor(e,t,n=new z){this.cwd=e,this.home=t??T(),this.fs=n}getCommands(){if(this.cachedCommands)return this.cachedCommands;let e=[Va(S(this.cwd,`.claude`,`skills`),this.fs),Ha(S(this.cwd,`.claude`,`commands`),this.fs),Va(S(this.home,`.robota`,`skills`),this.fs),Va(S(this.cwd,`.agents`,`skills`),this.fs)],t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.name)||(t.add(e.name),n.push(e));return this.cachedCommands=n,this.cachedCommands}getModelInvocableSkills(){return this.getCommands().filter(e=>e.disableModelInvocation!==!0)}getUserInvocableSkills(){return this.getCommands().filter(e=>e.userInvocable!==!1)}};function Wa(){return S(process.env.HOME??process.env.USERPROFILE??`/`,`.robota`,`settings.json`)}function Ga(e,t){return t===void 0||t===`user`?Wa():S(e,`.robota`,`settings.local.json`)}function q(e){if(!v(e))return{};let t=y(e,`utf8`);try{return JSON.parse(t)}catch{return process.stderr.write(`Warning: corrupt settings file at ${e}, resetting to defaults\n`),{}}}function J(e,t){ke(x(e),{recursive:!0}),Fe(e,JSON.stringify(t,null,2)+`
76
+ `,`utf8`)}function Ka(e,t){let n=q(e),r=n.currentProvider,i=n.providers;if(typeof r==`string`&&qa(i)){let e=i;e[r]={...qa(e[r])?e[r]:{},model:t},n.providers=e}else n.provider={...qa(n.provider)?n.provider:{},model:t};J(e,n)}function qa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Ja(e){return v(e)?(Pe(e),!0):!1}function Ya(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var Xa=class{type=`agent`;sessionFactory;constructor(e){this.sessionFactory=e.sessionFactory}async execute(e,t){let n=e,r=n.maxTurns??50,i=n.timeout??60;try{let e=this.sessionFactory({maxTurns:r,timeout:i}),n=`Hook input:\n${JSON.stringify(t)}\n\nRespond with JSON: { "ok": boolean, "reason"?: string }`,a=await e.run(n),o=Ya(a),s;try{s=JSON.parse(o)}catch{return{exitCode:1,stdout:``,stderr:`Failed to parse agent response as JSON: ${a}`}}return s.ok?{exitCode:0,stdout:JSON.stringify(s),stderr:``}:{exitCode:2,stdout:``,stderr:s.reason??`Blocked by agent hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};function Za(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var Qa=class{type=`prompt`;providerFactory;defaultModel;constructor(e){this.providerFactory=e.providerFactory,this.defaultModel=e.defaultModel}async execute(e,t){let n=e,r=n.model??this.defaultModel;try{let e=this.providerFactory(r),i=`${n.prompt}\n\nContext:\n${JSON.stringify(t)}\n\nRespond with JSON: { "ok": boolean, "reason"?: string }`,a=await e.complete(i),o=Za(a),s;try{s=JSON.parse(o)}catch{return{exitCode:1,stdout:``,stderr:`Failed to parse AI response as JSON: ${a}`}}return s.ok?{exitCode:0,stdout:JSON.stringify(s),stderr:``}:{exitCode:2,stdout:``,stderr:s.reason??`Blocked by prompt hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};const $a=new Set([`Write`,`Edit`]),eo=new Set([`Bash`,`BackgroundProcess`]),to=new Set([`Read`,`Glob`,`Grep`,`WebFetch`,`WebSearch`]);function no(e){let t=e.toolName;return to.has(t)?{toolName:t,reversible:!0,sideEffect:`none`,rollbackLayer:`none`,status:`read-only`,message:`${t} does not mutate the local workspace.`}:$a.has(t)?e.context.isolation===`worktree`||e.context.isolation===`provider-sandbox`?ao(t,`file-mutation`,e.context):e.context.checkpointAvailable?{toolName:t,reversible:!0,sideEffect:`file-mutation`,rollbackLayer:`edit-checkpoint`,status:`reversible`,message:`${t} is reversible through the active edit checkpoint.`}:{toolName:t,reversible:!1,sideEffect:`file-mutation`,rollbackLayer:`none`,status:`requires-checkpoint`,message:`${t} requires an edit checkpoint before file mutation.`}:eo.has(t)?ao(t,`shell-process`,e.context):t===`Agent`?oo(e.toolArgs,e.context):{toolName:t,reversible:!1,sideEffect:`unknown`,rollbackLayer:`none`,status:`unknown`,message:`${t} has no reversible execution contract.`}}function ro(e,t){let n={checkpointAvailable:t.checkpointAvailable,isolation:t.isolation??`none`},r=t.enforceUntrackedSideEffects??!0;return e.map(e=>new io(e,{safetyContext:n,enforceUntrackedSideEffects:r}))}var io=class{delegate;options;schema;constructor(e,t){this.delegate=e,this.options=t,this.schema=e.schema}setEventService(e){this.delegate.setEventService(e)}async execute(e,t){let n=no({toolName:this.getName(),toolArgs:uo(e),context:this.options.safetyContext});return!n.reversible&&this.options.enforceUntrackedSideEffects?fo(n):this.delegate.execute(e,t)}validate(e){return this.delegate.validate(e)}validateParameters(e){return this.delegate.validateParameters(e)}getDescription(){return this.delegate.getDescription()}getName(){return this.delegate.getName()}};function ao(e,t,n){return n.isolation===`worktree`?{toolName:e,reversible:!0,sideEffect:t,rollbackLayer:`worktree`,status:`reversible`,message:`${e} side effects are contained in an isolated Git worktree.`}:n.isolation===`provider-sandbox`?{toolName:e,reversible:!0,sideEffect:t,rollbackLayer:`provider-sandbox`,status:`reversible`,message:`${e} side effects are contained in a provider sandbox snapshot.`}:{toolName:e,reversible:!1,sideEffect:t,rollbackLayer:`none`,status:`requires-isolation`,message:`${e} can create host shell side effects that edit checkpoints cannot restore; use worktree or provider sandbox isolation.`}}function oo(e,t){return t.isolation===`worktree`||t.isolation===`provider-sandbox`?ao(`Agent`,`subagent`,t):so(e)?{toolName:`Agent`,reversible:!0,sideEffect:`subagent`,rollbackLayer:`worktree`,status:`reversible`,message:`Agent jobs request worktree isolation, so shell side effects stay outside the parent workspace.`}:{toolName:`Agent`,reversible:!1,sideEffect:`subagent`,rollbackLayer:`none`,status:`requires-isolation`,message:`Agent jobs must request worktree isolation to be reversible in local-first mode.`}}function so(e){if(!e)return!1;let t=e.jobs;return Array.isArray(t)?t.length>0&&t.every(e=>lo(e)?co(e)===`worktree`:!1):co(e)===`worktree`}function co(e){let t=e.isolation;return typeof t==`string`?t:void 0}function lo(e){return e!==void 0&&typeof e==`object`&&!Array.isArray(e)}function uo(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e}function fo(e){return{success:!0,data:{success:!1,output:``,error:e.message,reversibleSafety:{toolName:e.toolName,sideEffect:e.sideEffect,rollbackLayer:e.rollbackLayer,status:e.status}},metadata:{reversibleSafetyStatus:e.status,rollbackLayer:e.rollbackLayer}}}function po(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function mo(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function ho(e,t){return e.some(e=>mo(e.name)===t)}function go(e){if(!e.provider)throw Error(`provider is required. SDK is provider-neutral — consumer must create and pass a provider instance.`);let t=e.provider,n=e.cwd??process.cwd(),r=e.sessionId??_o(),i=new Ua(n),a=po(e.commandDescriptors),o=a.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,s=o?pn(a):void 0,c=ho(a,`skills`)?i.getModelInvocableSkills():[],l=Ji({sandboxClient:e.sandboxClient,cwd:n}),u=e.editCheckpointRecorder!==void 0&&e.sandboxClient===void 0,d=[...u&&e.editCheckpointRecorder?Ma(l,e.editCheckpointRecorder):l,...e.additionalTools??[]],f=e.reversibleExecution?{...e.reversibleExecution,isolation:e.reversibleExecution.isolation??(e.sandboxClient?`provider-sandbox`:void 0)}:void 0,p=f?ro(d,{...f,checkpointAvailable:u}):d;o&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&p.push(...gn({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:a}));let m=[];e.providerFactory&&m.push(new Qa({providerFactory:e.providerFactory,defaultModel:e.config.provider.model})),e.sessionFactory&&m.push(new Xa({sessionFactory:e.sessionFactory})),e.additionalHookExecutors&&m.push(...e.additionalHookExecutors);let{agentToolDeps:h,agentDefinitions:ee,backgroundTaskManager:te}=Ea(e,r,n,t,p,m),{backgroundProcessToolDeps:ne}=Da(e,te,r,n,p),{finalSystemMessage:re,rebuildSystemMessage:ie}=Oa(e,n,a,s,ne,c,ee),ae=[`Read(.agents/**)`,`Read(.claude/**)`,`Read(.robota/**)`,`Glob(.agents/**)`,`Glob(.claude/**)`,`Glob(.robota/**)`],oe=s?s.commandTools.filter(e=>!e.requiresPermission).map(e=>e.toolName):[],se=(e.allowedTools??[]).map(e=>`${e}(*)`),ce=(e.deniedTools??[]).map(e=>`${e}(*)`),le={allow:[...ae,...oe,...e.config.permissions.allow??[],...se],deny:[...e.config.permissions.deny??[],...ce]},ue=S(n,`.robota`,`settings.local.json`);function de(e){let t=`${e}(*)`,n=q(ue),r=Array.isArray(n.permissions)?[]:n.permissions?.allow??[];r.includes(t)||J(ue,{...n,permissions:{...n.permissions??{},allow:[...r,t]}})}let fe=new be({tools:p,provider:t,systemMessage:re,terminal:e.terminal,permissions:le,hooks:e.config.hooks,permissionMode:e.permissionMode,defaultTrustLevel:e.config.defaultTrustLevel,model:e.model??e.config.provider.model,providerTimeout:e.config.provider.timeout??12e4,maxTurns:e.maxTurns,sessionStore:e.sessionStore,sessionId:r,permissionHandler:e.permissionHandler,onProjectAllowTool:de,onTextDelta:e.onTextDelta,onContextUpdate:e.onContextUpdate,onToolExecution:e.onToolExecution,promptForApproval:e.promptForApproval,onCompact:e.onCompact,onCompactEvent:e.onCompactEvent,compactInstructions:e.compactInstructions??e.context.compactInstructions,autoCompactThreshold:e.autoCompactThreshold??e.config.autoCompactThreshold,sessionLogger:e.sessionLogger,hookTypeExecutors:m.length>0?m:void 0,agentName:e.agentName,...e.responseFormat?{responseFormat:e.responseFormat}:{}});return ka(fe,h,ne,te),{session:fe,rebuildSystemMessage:ie}}function _o(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function vo(e,t,n,r=new z){let i=S(n,e,`subagents`);return r.mkdirSync(i,{recursive:!0}),new ye(i)}function yo(e,t){return S(t,e,`subagents`)}const Y=g.lazy(()=>g.union([g.string(),g.number(),g.boolean(),g.null(),g.undefined(),g.date(),g.array(Y),g.record(Y)])),bo=g.object({name:g.string().optional(),model:g.string().optional(),apiKey:g.string().optional(),baseURL:g.string().optional(),timeout:g.number().optional(),options:g.record(Y).optional()}),xo=g.object({type:g.string().optional(),model:g.string().optional(),apiKey:g.string().optional(),baseURL:g.string().optional(),timeout:g.number().optional(),options:g.record(Y).optional()}),So=g.object({allow:g.array(g.string()).optional(),deny:g.array(g.string()).optional()}),Co=g.record(g.string()).optional(),wo=g.object({type:g.literal(`command`),command:g.string(),timeout:g.number().optional()}),To=g.object({type:g.literal(`http`),url:g.string(),headers:g.record(g.string()).optional(),timeout:g.number().optional()}),Eo=g.object({type:g.literal(`prompt`),prompt:g.string(),model:g.string().optional()}),Do=g.object({type:g.literal(`agent`),agent:g.string(),maxTurns:g.number().optional(),timeout:g.number().optional()}),Oo=g.discriminatedUnion(`type`,[wo,To,Eo,Do]),X=g.object({matcher:g.string(),hooks:g.array(Oo)}),ko=g.object({PreToolUse:g.array(X).optional(),PostToolUse:g.array(X).optional(),SessionStart:g.array(X).optional(),SessionEnd:g.array(X).optional(),Stop:g.array(X).optional(),StopFailure:g.array(X).optional(),PreCompact:g.array(X).optional(),PostCompact:g.array(X).optional(),UserPromptSubmit:g.array(X).optional(),SubagentStart:g.array(X).optional(),SubagentStop:g.array(X).optional(),WorktreeCreate:g.array(X).optional(),WorktreeRemove:g.array(X).optional()}).optional(),Ao=g.record(g.boolean()).optional(),jo=g.object({source:g.object({type:g.enum([`github`,`git`,`local`,`url`]),repo:g.string().optional(),url:g.string().optional(),path:g.string().optional(),ref:g.string().optional()})}),Mo=g.record(jo).optional().catch(void 0),No=g.union([g.number().gt(0).lte(1),g.literal(!1)]).optional(),Po=g.object({enabled:g.boolean().optional(),options:g.record(Y).optional()}),Fo=g.object({defaultTrustLevel:g.enum([`safe`,`moderate`,`full`]).optional(),language:g.string().optional(),currentProvider:g.string().optional(),providers:g.record(xo).optional(),provider:bo.optional(),permissions:So.optional(),env:Co,hooks:ko,enabledPlugins:Ao,extraKnownMarketplaces:Mo,autoCompactThreshold:No,transports:g.record(Po).optional()});function Io(){return process.env.HOME??process.env.USERPROFILE??`/`}const Z={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[]},env:{}};function Lo(e){if(!E(e))return;let t=D(e,`utf-8`).trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function Ro(e){if(e.startsWith(`$ENV:`)){let t=e.slice(5);return process.env[t]??e}return e}function zo(e){let t=e.provider?.apiKey===void 0?e.provider:Bo(e.provider);if(e.providers!==void 0){let n=Object.fromEntries(Object.entries(e.providers).map(([e,t])=>[e,Bo(t)]));return{...e,provider:t,providers:n}}return{...e,provider:t}}function Bo(e){return{...e,...e.apiKey!==void 0&&{apiKey:Ro(e.apiKey)}}}function Vo(e){return e.reduce((e,t)=>({...e,...t,provider:e.provider!==void 0||t.provider!==void 0?{...e.provider,...t.provider}:void 0,permissions:e.permissions!==void 0||t.permissions!==void 0?{allow:t.permissions?.allow??e.permissions?.allow,deny:t.permissions?.deny??e.permissions?.deny}:void 0,env:{...e.env??{},...t.env??{}},providers:e.providers!==void 0||t.providers!==void 0?Ho(e.providers,t.providers):void 0,enabledPlugins:e.enabledPlugins!==void 0||t.enabledPlugins!==void 0?{...e.enabledPlugins??{},...t.enabledPlugins??{}}:void 0,extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold}),{})}function Ho(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function Uo(e){if(e.currentProvider!==void 0)return Wo(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...Z.provider}}function Wo(e){let t=e.currentProvider;if(t===void 0)throw Error(`currentProvider is required`);let n=e.providers?.[t];if(n===void 0)throw Error(`currentProvider "${t}" was not found in providers`);if(n.type===void 0)throw Error(`Provider profile "${t}" is missing type`);return{name:n.type,model:n.model??Z.provider.model,apiKey:n.apiKey??Z.provider.apiKey,...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function Go(e){return{defaultTrustLevel:e.defaultTrustLevel??Z.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:Uo(e),permissions:{allow:e.permissions?.allow??Z.permissions.allow,deny:e.permissions?.deny??Z.permissions.deny},env:e.env??Z.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold}}function Ko(e){let t=Io();return[O(t,`.robota`,`settings.json`),O(t,`.claude`,`settings.json`),O(e,`.robota`,`settings.json`),O(e,`.robota`,`settings.local.json`),O(e,`.claude`,`settings.json`),O(e,`.claude`,`settings.local.json`)]}async function qo(e){let t=Ko(e),n=[];for(let e of t){let t=Lo(e);t!==void 0&&n.push({raw:t,path:e})}return Go(Vo(n.map(({raw:e,path:t})=>{let n=Fo.safeParse(e);if(!n.success)throw Error(`Invalid settings in ${t}: ${n.error.message}`);return zo(n.data)})))}const Jo=S(`.agents`,`tasks`),Yo={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function Xo(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function Zo(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||Ke(t,`.md`)}function Qo(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function $o(e,t){let n=e.split(/\r?\n/),r=RegExp(`^(#{2,6})\\s+${t}\\b`,`i`),i=n.findIndex(e=>r.test(e));if(i<0)return;let a=[];for(let e of n.slice(i+1)){if(/^##\s+/.test(e))break;a.push(e)}let o=a.join(`
77
+ `).trim();return o.length>0?o:void 0}function es(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(.+)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function ts(e,t){return t&&e.branch===t?0:Yo[e.status]}function ns(e){let t=[`### ${e.title}`,`- **Path:** \`${e.relativePath}\``];return t.push(`- **Status:** ${e.status}`),e.branch&&t.push(`- **Branch:** ${e.branch}`),e.scope&&t.push(`- **Scope:** ${e.scope}`),e.objective&&t.push(`- **Objective:** ${e.objective}`),e.openItems.length>0&&(t.push(`- **Open items:**`),t.push(...e.openItems.map(e=>` - ${e}`))),t.join(`
78
+ `)}function rs(e){return e.toISOString().slice(0,10)}function is(e,t){let n=e.split(/\r?\n/),r=`- **Status**: ${t}`,i=n.findIndex(e=>/^- \*\*Status\*\*:\s*/.test(e));return i>=0?(n[i]=r,n.join(`
79
79
  `)):(n.length>0&&/^#\s+/.test(n[0])?n.splice(1,0,``,r):n.unshift(r,``),n.join(`
80
- `))}function is(e,t,n){let r=[`### ${ns(t)}`,`- ${n.trim()}`],i=e.replace(/\s+$/u,``).split(/\r?\n/),a=i.findIndex(e=>/^## Progress\s*$/.test(e));if(a<0)return[...i,``,`## Progress`,``,...r,``].join(`
80
+ `))}function as(e,t,n){let r=[`### ${rs(t)}`,`- ${n.trim()}`],i=e.replace(/\s+$/u,``).split(/\r?\n/),a=i.findIndex(e=>/^## Progress\s*$/.test(e));if(a<0)return[...i,``,`## Progress`,``,...r,``].join(`
81
81
  `);let o=i.findIndex((e,t)=>t>a&&/^##\s+/.test(e));return o<0?[...i,``,...r,``].join(`
82
82
  `):(i.splice(o,0,``,...r,``),i.join(`
83
- `))}function as(e,t){let n=T(e),r=!1;for(;!r;){let e=C(n,`.git`);if(t.existsSync(e)){if(t.statSync(e).isDirectory())return e;let r=t.readFileSync(e,`utf8`).trim().match(/^gitdir:\s*(.+)$/)?.[1];if(r)return Ke(r)?r:T(n,r)}let i=S(n);r=i===n,n=i}}function os(e,t=new B){let n=as(e,t);if(!n)return;let r=C(n,`HEAD`);if(t.existsSync(r))return(t.readFileSync(r,`utf8`).trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1])?.trim()}function ss(e,t=new B){let n=C(e,qo);return t.existsSync(n)?t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isFile()).map(e=>e.name).filter(e=>e!==`README.md`&&e.endsWith(`.md`)).sort((e,t)=>e.localeCompare(t)).map(e=>C(n,e)):[]}function cs(e,t,n=new B){let r=n.readFileSync(e,`utf8`);return{path:e,relativePath:w(t,e),title:Xo(r,e),status:Yo(Zo(r,`Status`)),branch:Zo(r,`Branch`),scope:Zo(r,`Scope`),objective:Qo(r,`Objective`),openItems:$o(r)}}function ls(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>es(e,t.currentBranch)-es(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function us(e){return e.map(ts).join(`
83
+ `))}function os(e,t){let n=w(e),r=!1;for(;!r;){let e=S(n,`.git`);if(t.existsSync(e)){if(t.statSync(e).isDirectory())return e;let r=t.readFileSync(e,`utf8`).trim().match(/^gitdir:\s*(.+)$/)?.[1];if(r)return qe(r)?r:w(n,r)}let i=x(n);r=i===n,n=i}}function ss(e,t=new z){let n=os(e,t);if(!n)return;let r=S(n,`HEAD`);if(t.existsSync(r))return(t.readFileSync(r,`utf8`).trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1])?.trim()}function cs(e,t=new z){let n=S(e,Jo);return t.existsSync(n)?t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isFile()).map(e=>e.name).filter(e=>e!==`README.md`&&e.endsWith(`.md`)).sort((e,t)=>e.localeCompare(t)).map(e=>S(n,e)):[]}function ls(e,t,n=new z){let r=n.readFileSync(e,`utf8`);return{path:e,relativePath:C(t,e),title:Zo(r,e),status:Xo(Qo(r,`Status`)),branch:Qo(r,`Branch`),scope:Qo(r,`Scope`),objective:$o(r,`Objective`),openItems:es(r)}}function us(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>ts(e,t.currentBranch)-ts(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function ds(e){return e.map(ns).join(`
84
84
 
85
- `)}function ds(e,t={},n=new B){let r=t.currentBranch??os(e,n);return us(ls(ss(e,n).map(t=>cs(t,e,n)),{...t,currentBranch:r}))}function fs(e,t,n={},r=new B){let i=rs(r.readFileSync(e,`utf8`),t),a=n.progressMessage?is(i,n.now??new Date,n.progressMessage):i;r.writeFileSync(e,a,`utf8`)}const ps=200,ms=25600,hs=[`user`,`feedback`,`project`,`reference`];function gs(e){return hs.includes(e)}function _s(e){return k(e,`.robota`,`memory`)}function vs(e,t){let n=Buffer.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function ys(e,t){let n=e.split(/\r?\n/);return{content:n.slice(0,t).join(`
86
- `).trimEnd(),truncated:n.length>t}}function bs(e){return e.trim().toLowerCase().replace(/[^a-z0-9가-힣_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`general`}function xs(e,t,n){let r=e.toISOString().slice(0,10),i=t.text.trim().replace(/\s+/g,` `);return`[${r}] (${t.type}/${n}) ${i}`}function Ss(e){return e.trim().replace(/\s+/g,` `)}var Cs=class{cwd;now;constructor(e,t=()=>new Date){this.cwd=e,this.now=t}getIndexPath(){return k(_s(this.cwd),`MEMORY.md`)}getTopicsPath(){return k(_s(this.cwd),`topics`)}loadStartupMemory(){let e=this.getIndexPath();if(!D(e))return{content:``,path:e,lineCount:0,truncated:!1};let t=O(e,`utf8`),n=vs(t,ms),r=Buffer.byteLength(t,`utf8`)>ms,i=ys(n,200);return{content:i.content,path:e,lineCount:i.content.length===0?0:i.content.split(/\r?\n/).length,truncated:r||i.truncated}}list(){let e=this.getTopicsPath(),t=D(e)?Xe(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(t=>({name:Qe(t.name,`.md`),path:k(e,t.name)})).sort((e,t)=>e.name.localeCompare(t.name)):[];return{indexPath:this.getIndexPath(),topicsPath:e,topics:t}}readTopic(e){let t=bs(e),n=k(this.getTopicsPath(),`${t}.md`);return D(n)?O(n,`utf8`).trimEnd():``}append(e){let t=bs(e.topic),n=_s(this.cwd),r=this.getTopicsPath();Ye(r,{recursive:!0});let i=this.getIndexPath(),a=k(r,`${t}.md`),o=xs(this.now(),e,t),s=D(a)?``:`# ${t}\n\n`,c=Ss(e.text);return D(a)&&O(a,`utf8`).includes(`) ${c}`)?{indexPath:i,topicPath:a,topic:t,deduplicated:!0}:(D(i)||(Ye(n,{recursive:!0}),Ze(i,`# Project Memory
85
+ `)}function fs(e,t={},n=new z){let r=t.currentBranch??ss(e,n);return ds(us(cs(e,n).map(t=>ls(t,e,n)),{...t,currentBranch:r}))}function ps(e,t,n={},r=new z){let i=is(r.readFileSync(e,`utf8`),t),a=n.progressMessage?as(i,n.now??new Date,n.progressMessage):i;r.writeFileSync(e,a,`utf8`)}const ms=200,hs=25600,gs=[`user`,`feedback`,`project`,`reference`];function _s(e){return gs.includes(e)}function vs(e){return O(e,`.robota`,`memory`)}function ys(e,t){let n=Buffer.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function bs(e,t){let n=e.split(/\r?\n/);return{content:n.slice(0,t).join(`
86
+ `).trimEnd(),truncated:n.length>t}}function xs(e){return e.trim().toLowerCase().replace(/[^a-z0-9가-힣_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`general`}function Ss(e,t,n){let r=e.toISOString().slice(0,10),i=t.text.trim().replace(/\s+/g,` `);return`[${r}] (${t.type}/${n}) ${i}`}function Cs(e){return e.trim().replace(/\s+/g,` `)}var ws=class{cwd;now;constructor(e,t=()=>new Date){this.cwd=e,this.now=t}getIndexPath(){return O(vs(this.cwd),`MEMORY.md`)}getTopicsPath(){return O(vs(this.cwd),`topics`)}loadStartupMemory(){let e=this.getIndexPath();if(!E(e))return{content:``,path:e,lineCount:0,truncated:!1};let t=D(e,`utf8`),n=ys(t,hs),r=Buffer.byteLength(t,`utf8`)>hs,i=bs(n,200);return{content:i.content,path:e,lineCount:i.content.length===0?0:i.content.split(/\r?\n/).length,truncated:r||i.truncated}}list(){let e=this.getTopicsPath(),t=E(e)?Ze(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(t=>({name:$e(t.name,`.md`),path:O(e,t.name)})).sort((e,t)=>e.name.localeCompare(t.name)):[];return{indexPath:this.getIndexPath(),topicsPath:e,topics:t}}readTopic(e){let t=xs(e),n=O(this.getTopicsPath(),`${t}.md`);return E(n)?D(n,`utf8`).trimEnd():``}append(e){let t=xs(e.topic),n=vs(this.cwd),r=this.getTopicsPath();Xe(r,{recursive:!0});let i=this.getIndexPath(),a=O(r,`${t}.md`),o=Ss(this.now(),e,t),s=E(a)?``:`# ${t}\n\n`,c=Cs(e.text);return E(a)&&D(a,`utf8`).includes(`) ${c}`)?{indexPath:i,topicPath:a,topic:t,deduplicated:!0}:(E(i)||(Xe(n,{recursive:!0}),Qe(i,`# Project Memory
87
87
 
88
- `,`utf8`)),Je(i,`- ${o}\n`,`utf8`),Je(a,`${s}- ${o}\n`,`utf8`),{indexPath:i,topicPath:a,topic:t,deduplicated:!1})}};function ws(e,t){let n=[],r=et(e),i=!1;for(;!i;){let e=k(r,t);D(e)&&n.push(e);let a=$e(r);i=a===r,i||(r=a)}return n.reverse()}function Ts(e){let t=e.split(`
88
+ `,`utf8`)),Ye(i,`- ${o}\n`,`utf8`),Ye(a,`${s}- ${o}\n`,`utf8`),{indexPath:i,topicPath:a,topic:t,deduplicated:!1})}};function Ts(e,t){let n=[],r=tt(e),i=!1;for(;!i;){let e=O(r,t);E(e)&&n.push(e);let a=et(r);i=a===r,i||(r=a)}return n.reverse()}function Es(e){let t=e.split(`
89
89
  `),n=!1,r=0,i=[];for(let e of t){let t=/^(#{1,6})\s+/.exec(e);if(t){if(n&&t[1].length<=r)break;if(/compact\s+instructions/i.test(e)){n=!0,r=t[1].length;continue}}n&&i.push(e)}return i.join(`
90
- `).trim()||void 0}async function Es(e){let t=ws(e,`AGENTS.md`),n=ws(e,`CLAUDE.md`),r=t.map(e=>tr(e)),i=n.map(e=>tr(e)),a=r.map(e=>e.content).join(`
90
+ `).trim()||void 0}async function Ds(e){let t=Ts(e,`AGENTS.md`),n=Ts(e,`CLAUDE.md`),r=t.map(e=>nr(e)),i=n.map(e=>nr(e)),a=r.map(e=>e.content).join(`
91
91
 
92
92
  `),o=i.map(e=>e.content).join(`
93
93
 
94
- `),s=Ts(o),c=new Cs(e).loadStartupMemory().content||void 0,l=ds(e);return{agentsMd:a,claudeMd:o,memoryMd:c,taskContext:l.trim().length>0?l:void 0,compactInstructions:s,agentsFileEntries:r,claudeFileEntries:i}}var Ds=class{settingsPath;fs;constructor(e,t=new B){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=S(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 Os(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(`
95
- `)){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 ks(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 As(e,t=new B){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}var js=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new B){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){return this.discoverAndLoad()}async loadAll(){return this.discoverAndLoad()}discoverAndLoad(){let e=C(this.pluginsDir,`cache`);if(!this.fs.existsSync(e))return[];let t=[],n=As(e,this.fs);for(let r of n){let n=C(e,r),i=As(n,this.fs);for(let e of i){let i=C(n,e),a=As(i,this.fs);if(a.length===0)continue;let o=a[a.length-1],s=C(i,o),c=C(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 ks(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=C(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=C(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let{metadata:r,content:a}=Os(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=C(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}=Os(this.fs.readFileSync(C(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=C(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=C(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=C(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$/,``)):[]}},Ms=class{pluginsDir;cacheDir;registryPath;settingsStore;marketplaceClient;exec;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.cacheDir=C(this.pluginsDir,`cache`),this.registryPath=C(this.pluginsDir,`installed_plugins.json`),this.settingsStore=e.settingsStore,this.marketplaceClient=e.marketplaceClient,this.exec=e.exec,this.fs=e.fs??new B}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=C(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=C(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=S(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 B){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 Ns(e,t,n=new B){let r=S(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(e,JSON.stringify(t,null,2),`utf-8`)}function Ps(e,t,n=new B){let r=C(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=S(r);n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.writeFileSync(r,JSON.stringify(i,null,2),`utf-8`)}}const Fs=6e4;var Is=class{pluginsDir;exec;marketplacesDir;registryPath;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.exec=e.exec,this.marketplacesDir=C(this.pluginsDir,`marketplaces`),this.registryPath=C(this.pluginsDir,`known_marketplaces.json`),this.fs=e.fs??new B}addMarketplace(e){let t=`temp-`+Date.now().toString(36),n=C(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:Fs,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone marketplace: ${t}`)}}let r=C(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=C(this.marketplacesDir,i);return this.fs.renameSync(n,o),a[i]={source:e,installLocation:o,lastUpdated:new Date().toISOString()},Ns(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`);Ps(this.pluginsDir,e,this.fs),this.fs.existsSync(n.installLocation)&&this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),delete t[e],Ns(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:Fs,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(),Ns(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=C(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:Fs,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 Ls(e){let t=C(S(S(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function Rs(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 zs(e){let t={};for(let n of e){let e=n.hooks;if(!e)continue;let r=Ls(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=Rs(e,n.pluginDir);return t.env=r,t});t[e].push(...i)}}return t}function Bs(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 Vs(e){let t=e.cwd,[n,r,i]=await Promise.all([e.config?Promise.resolve(e.config):Ko(t),e.bare?Promise.resolve({agentsMd:``,claudeMd:``,agentsFileEntries:[],claudeFileEntries:[]}):Es(t),e.bare?Promise.resolve({type:`unknown`,language:`unknown`}):zi(t)]),a=e.language?{...n,language:e.language}:n,o=new js(C(E(),`.robota`,`plugins`));if(!e.bare)try{let e=o.loadPluginsSync();if(e.length>0){let t=zs(e);a={...a,hooks:Bs(a.hooks,t)}}}catch{}let s=W(t);await Us(e)||await Hs(e,t);let c=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,{session:l,rebuildSystemMessage:u}=ho({config:a,cwd:t,context:r,projectInfo:i,permissionMode:e.permissionMode,maxTurns:e.maxTurns,terminal:$r,sessionLogger:new ve(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,deniedTools:e.deniedTools,model:e.model,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,...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{}});return{session:l,agentsFileEntries:r.agentsFileEntries??[],claudeFileEntries:r.claudeFileEntries??[],rebuildSystemMessage:u}}async function Hs(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await se(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function Us(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 Ws(e,t){let n=e.config??await Ko(e.cwd),r=n.autoCompactThreshold===void 0?`default`:`settings`,i=new Ti({cwd:e.cwd});t.setEditCheckpointStore(i);let a=await Vs({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,deniedTools:e.deniedTools,model:e.model,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}:{},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},commandDescriptors:t.commandDescriptors,...t.commandDescriptors.length>0?{modelCommandExecutor:t.executeModelCommand,isModelCommandInvocable:t.isModelCommandInvocable}:{}});if(t.pendingRestoreMessages)for(let e of t.pendingRestoreMessages)Bi(a.session,e);return{session:a.session,agentsFileEntries:a.agentsFileEntries,claudeFileEntries:a.claudeFileEntries,rebuildSystemMessage:a.rebuildSystemMessage,autoCompactThresholdSource:r}}function Gs(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(Ks({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 Ks(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},...qs(e.backgroundState),...Js(e.memoryState),...Ys(e.skillActivationState),...Xs(e.contextReferenceState)}}function qs(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function Js(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function Ys(e){return e?{skillActivationEvents:[...e.events]}:{}}function Xs(e){return e?{contextReferences:[...e.references]}:{}}function Zs(e){return e.source===`skill`||e.source===`plugin`&&e.skillContent?`skill`:`builtin-command`}function Qs(e){let t=e.source===`skill`||e.source===`plugin`&&!!e.skillContent;return{name:e.name,kind:Zs(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 $s=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=>Qs(e))}},ec=class{commands;constructor(e){this.commands=new Map;for(let t of e??tc())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}:{},requiresPermission:this.resolveRequiresPermission(e)}))}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 tc(){return[]}function nc(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 rc=class{name=`builtin`;commands;constructor(e=tc()){this.commands=e.map(nc)}getCommands(){return this.commands}};function ic(){let e=tc();return{name:`sdk-builtin`,commandSources:[new rc(e)],systemCommands:e}}function ac(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function oc(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function sc(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 cc(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=c(n.providerDefinitions??[],t.type),i=d(r);if(i!==void 0&&!pc(t,r?.defaults,i))throw Error(`Provider profile "${e}" is missing ${hc(i)}`)}function lc(e,t={}){let n=uc(e,t);return cc(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function uc(e,t={}){let n=fc(e.type,t.providerDefinitions??[]);e.apiKey!==void 0&&e.apiKeyEnv===void 0&&console.warn(`API key stored as plain text in settings. Use --api-key-env for better security.`);let r=e.apiKeyEnv===void 0?e.apiKey??n.apiKey:u(e.apiKeyEnv),i=e.baseURL??n.baseURL;return{type:e.type,model:e.model??n.model,...gc(r)&&{apiKey:r},...i!==void 0&&{baseURL:i},...e.timeout!==void 0&&{timeout:e.timeout}}}function dc(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=ac(e,n,r);return t.currentProvider?oc(i,t.currentProvider):i}function fc(e,t){return c(t,e)?.defaults??{}}function pc(e,t,n){return n.anyOf.some(n=>p(mc(n,e,t)))}function mc(e,t,n){return t[e]??n?.[e]}function hc(e){return e.anyOf.join(` or `)}function gc(e){return e!==void 0&&e.length>0}async function _c(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{cc(i,a,{providerDefinitions:r.providerDefinitions})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let o=await((a.type?c(r.providerDefinitions,a.type):void 0)?.probeProfile??vc)(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 vc(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function yc(e,t=[]){return bc(e,t)?`valid`:`incomplete`}function bc(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return xc(n?.type,n,t)}return!!(e.provider&&xc(e.provider.name,e.provider,t))}function xc(e,t,n){if(!t)return!1;if(!e)return p(t.apiKey);let r=c(n,e);if(r===void 0)return!1;let i=d(r);return i===void 0?!0:Sc(t,r,i)}function Sc(e,t,n){return n.anyOf.some(n=>p(Cc(n,e,t)))}function Cc(e,t,n){return t[e]??n.defaults?.[e]}function wc(e,t=[]){if(!y(e))return`missing`;try{let n=b(e,`utf8`).trim();return n.length===0?`incomplete`:yc(JSON.parse(n),t)}catch{return`corrupt`}}function Tc(e,t=new B){return e.reduce((e,n)=>{let r=Ec(n,t);return r===void 0?e:Dc(e,r)},{})}function Ec(e,t){if(t.existsSync(e))try{let n=t.readFileSync(e,`utf8`);return JSON.parse(n)}catch{return}}function Dc(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?Oc(e.providers,t.providers):void 0}}function Oc(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function kc(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 oe({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 oe({name:i.name,model:i.model,apiKey:i.apiKey,baseURL:i.baseURL,timeout:i.timeout,options:i.options},n)}function Ac(){return process.env.HOME??process.env.USERPROFILE??`/`}function jc(e){let t=Ac();return[C(t,`.robota`,`settings.json`),C(t,`.claude`,`settings.json`),C(e,`.robota`,`settings.json`),C(e,`.robota`,`settings.local.json`),C(e,`.claude`,`settings.json`),C(e,`.claude`,`settings.local.json`)]}function Mc(e,t={}){let n=t.settingsPaths??jc(e),r=zc(n)??n[0];if(r===void 0)throw Error(`No settings path available for provider update`);return r}function Nc(e){return q(e)}function Pc(e,t,n={}){let r=dc(Nc(e),lc(t,n));return J(e,r),r}function Fc(e,t,n={}){let r=Nc(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:oc(r,t);return J(e,o),o}function Ic(e,t,n={}){let r=n.settingsPaths??jc(e),i=Tc(r),a=n.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Lc(r,a,t)}function Lc(e,t,n){let r=Rc(e,t)??e[0];if(r===void 0)throw Error(`No settings path available for model update`);let i=Nc(r),a=i.providers??{},o=a[t]??{},s={...i,providers:{...a,[t]:{...o,model:n}}};return J(r,s),{settingsPath:r,settings:s,profileName:t}}function Rc(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&Nc(r).providers?.[t]!==void 0)return r}}function zc(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&Nc(n).currentProvider!==void 0)return n}}function Bc(e){return Tc(jc(e))}function Vc(e,t={}){let n=kc(Bc(e),t.providerOverride,t.providerDefinitions??[]);if(n!==void 0)return n;throw Error("No provider configuration found. Run `robota` to set up.")}function Hc(e,t,n={}){let r=n.providerDefinitions??[],i=Vc(e,{...n,providerDefinitions:r}),a=t??i.model;return ie({...i,model:a},r)}var Uc=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 Wc=_e,Gc=`autoCompactThreshold`;function Kc(e){return e.getContextState()}function qc(e){return e.getAutoCompactThreshold()}function Jc(e){return e.getAutoCompactThresholdSource?.()??`session`}function Yc(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 Xc(e,t){let n=rl(e);return n?(n.write({...n.read(),[Gc]:t}),!0):!1}function Zc(e){let t=rl(e);if(!t)return!1;let n={...t.read()};return delete n[Gc],t.write(n),!0}async function Qc(e,t){let n=Kc(e),r=e.getSession().getMessageCount();return await e.compactContext(t),{before:n,after:Kc(e),beforeMessageCount:r,afterMessageCount:e.getSession().getMessageCount()}}function $c(e){return e.listContextReferences?.()??[]}async function el(e,t){return e.addContextReference?e.addContextReference(t):{evicted:[],diagnostics:[`Command host does not support context reference additions.`]}}function tl(e,t){return e.removeContextReference?.(t)??{}}function nl(e){return e.clearContextReferences?.()??{removed:[]}}function rl(e){return e.getCommandHostAdapters?.().settings}function il(e,t={}){let n=al(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 al(e){let t=e?.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t!==void 0&&t.length>0?t:void 0}const ol=`Show available commands`;function sl(e){return e.listCommands?.()??[]}function cl(e){return[`Available commands:`,...sl(e).flatMap(e=>{let t=e.displayName??e.name,n=`/${e.name}`,r=` ${(e.displayName?`${t} (${n})`:n).padEnd(32)} — ${e.description}`;return e.example?[r,` Example: ${e.example}`]:[r]})].join(`
96
- `)}const ll=`List and control background tasks`,ul=`Usage: background list | background read <task-id> [offset] | background cancel <task-id> | background close <task-id>`;function dl(){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 fl(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=hl(e),s=t?` — ${t}`:``;return`${e.id} [${e.status}${n}${i}${a}${o}] ${e.kind}:${e.label}${r}${s}`}function pl(e){return e.length===0?`No background tasks.`:[`Background tasks:`,...e.map(e=>` ${fl(e)}`)].join(`
97
- `)}function ml(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isNaN(t)?void 0:{offset:t}}function hl(e){let t=[];return e.worktreePath&&t.push(`worktree=${e.worktreePath}`),e.branchName&&t.push(`branch=${e.branchName}`),e.worktreeStatus&&t.push(`worktreeStatus="${gl(e.worktreeStatus)}"`),e.worktreeNextAction&&t.push(`next="${gl(e.worktreeNextAction)}"`),t.length===0?``:` ${t.join(` `)}`}function gl(e){let t=e.trim().replace(/\s+/g,` `);return t.length>160?`${t.slice(0,160)}...`:t}function _l(e,t){return e.listBackgroundTasks(t)}function vl(e,t,n){return e.readBackgroundTaskLog(t,n)}function yl(e,t,n){return e.cancelBackgroundTask(t,n)}function bl(e,t){return e.closeBackgroundTask(t)}const xl=`Set response language`,Sl=`<code>`,Cl=[{code:`ko`,description:`Korean`},{code:`en`,description:`English`},{code:`ja`,description:`Japanese`},{code:`zh`,description:`Chinese`}];function wl(e=`language`){return Cl.map(t=>({name:t.code,description:t.description,source:e}))}function Tl(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function El(e=`language`){return`Usage: ${e} <code> (e.g., ko, en, ja, zh)`}const Dl=`Show/change permission mode`,Ol=`plan | default | acceptEdits | bypassPermissions`,kl=`Show/change permission mode and permission rules`,Al=[`plan`,`default`,`acceptEdits`,`bypassPermissions`];function jl(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 Ml(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Nl(e){return Al.includes(e)}function Pl(){return`Invalid mode. Valid: ${Al.join(` | `)}`}function Fl(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 Il(e){return Fl(e).getPermissionMode()}function Ll(e,t){Fl(e).setPermissionMode(t)}function Rl(e){return Fl(e).listSessionAllowedTools()}function zl(e){return{mode:Il(e),sessionAllowed:Rl(e)}}function Bl(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
- `)}const Vl=`Configure TUI status-line visibility and fields such as model, context, tokens, session, and git branch.`,Hl=`on | off | reset | git on | git off`,Ul={enabled:!0,gitBranch:!0};function Wl(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 Gl(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function Kl(e){let t=e.statusline;return Jl(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:Ul.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:Ul.gitBranch}:{...Ul}}function ql(e,t){let n=q(e),r={...Kl(n),...t};return n.statusline=r,J(e,n),r}function Jl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}const Yl=`Manage plugins`,Xl=`manage | install <name@marketplace> | uninstall <name@marketplace> | enable <name@marketplace> | disable <name@marketplace> | marketplace <action>`,Zl=`Reload all plugin resources`;function Ql(){return{type:`plugin-tui-requested`}}function $l(){return{type:`plugin-registry-reload-requested`}}function eu(e){return e.getCommandHostAdapters?.().plugin}function tu(){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 nu=`Clear conversation history`,ru=`Rename the current session`,iu=`Usage: rename <name>`,au=`Resume a previous session`,ou=`Show session token usage and estimated cost. /cost budget <amount> sets a monthly budget.`,su=`Validate current session replay log`,cu=`Exit CLI`;function lu(e){if(e.clearConversationHistory!==void 0){e.clearConversationHistory();return}e.getSession().clearHistory()}function uu(e){let t=e.trim();return t.length>0?t:void 0}function du(e){return{type:`session-renamed`,name:e}}function fu(){return{type:`session-picker-requested`}}function pu(){return{type:`session-exit-requested`}}function mu(e){let t=e.getSession();return{sessionId:t.getSessionId(),messageCount:t.getMessageCount()}}function hu(e){let t=e.validateCurrentSessionReplayLog?.();if(t!==void 0)return t;let n=e.getSession().getSessionId(),r=C(W(e.getCwd()).logs,`${n}.jsonl`),i=xe(r);return{logFile:r,entryCount:i.length,validation:Ce(i)}}function gu(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
- `);let r=e.validation.issues.map((e,t)=>{let n=_u(e);return`${t+1}. ${e.code}${n}: ${e.message}`});return[t,...n,``,...r].join(`
100
- `)}function _u(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 vu=`List, inspect, restore, or rollback edit checkpoints.`,yu=`list | inspect CHECKPOINT_ID | restore CHECKPOINT_ID | code CHECKPOINT_ID | rollback CHECKPOINT_ID`;function bu(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 xu(e){return e.listEditCheckpoints()}function Su(e,t){if(!e.inspectEditCheckpoint)throw Error(`Checkpoint inspection is not available in this command host.`);return e.inspectEditCheckpoint(t)}function Cu(e,t){return e.restoreEditCheckpoint(t)}function wu(e,t){return e.rollbackEditCheckpoint(t)}const Tu=[/\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 Eu(e){return Tu.some(t=>t.test(e))}function Du(e){return C(e,`.robota`,`memory`)}function Ou(){return{version:1,records:[]}}var ku=class{fs;path;now;constructor(e,t=()=>new Date,n=new B){this.fs=n,this.path=C(Du(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 Ou();try{return{version:1,records:JSON.parse(this.fs.readFileSync(this.path,`utf8`)).records??[]}}catch{return Ou()}}write(e){this.fs.mkdirSync(S(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,JSON.stringify(e,null,2),`utf8`)}};const Au=`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.`,ju=`list | show [topic] | add <user|feedback|project|reference> <topic> <text> | pending | approve <id> | reject <id> | used`,Mu=`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 Nu(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 Pu(e,t){return new Cs(e,t)}function Fu(e,t){return new ku(e,t)}function Iu(e,t){let n=e.getCwd();return{project:Pu(n,t),pending:Fu(n,t)}}function Lu(e){return gs(e)}function Ru(e){return Eu(e)}function zu(e){return e.getUsedMemoryReferences()}function Bu(e,t,n=()=>new Date){e.recordMemoryEvent({...t,at:n().toISOString()})}function Vu(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 Hu(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 Uu(e,t,n,r){return e.skillContent?Vu(await Hu(e.skillContent,n.shellExec),t,r):null}async function Wu(e,t,n,r){let i=await Uu(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 Gu(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 Uu(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 Wu(e,t,n,r)}}function Ku(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function qu(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Ju(e,t){let n=t.trim();return n.length>0?`${e} ${n}`:e}function Yu(e){if(!e?.startsWith(`/`))return;let t=e.slice(1).trim().split(/\s+/)[0];return t&&t.length>0?t:void 0}var Xu=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 ec(e.flatMap(e=>e.systemCommands??[])),this.skillCommandSource=new Ha(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=Ku(e);return this.skillCommandSource.getCommands().find(e=>e.name.toLowerCase()===t.toLowerCase())}async executeCommand(e,t){let n=qu(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,Ju(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=Yu(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 Gu(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=Pi({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 Zu(){let e=C(E(),`.robota`,`org-policy.json`);if(!y(e))return null;try{let t=b(e,`utf8`);return JSON.parse(t)}catch{return null}}function Qu(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function $u(e){return e?!e.startsWith(`$ENV:`):!1}var ed=class extends $n{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 Ti({cwd:t})),this.bgTracker=new zn(()=>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 Ii(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 Xu(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)=>hi(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 pi(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=Vi(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 Ws(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.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 Bt(this.session)??R(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();Gs(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=Vc(n,{providerOverride:e,providerDefinitions:this.providerDefinitions}),i=Hc(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:Qu(`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:Qu(`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 td(e,t=new B){let n=W(e);return new ad(n.sessions,n.logs,t)}function nd(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:od(e.messages)}))}function rd(e,t){return nd(e,t)[0]?.id}function id(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var ad=class{store;logsDir;fs;constructor(e,t,n=new B){this.store=new be(e),this.logsDir=t,this.fs=n}save(e){this.store.save(sd(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):cd(t)}list(){let e=this.store.list().map(cd),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=Se(xe(C(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:ld(n),backgroundTaskEvents:n,backgroundJobGroups:dd(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 od(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 sd(e){return{...e}}function cd(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 ld(e){let t=new Map;for(let n of e){let e=ud(n);e&&t.set(e.id,e)}return[...t.values()]}function ud(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 dd(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function fd(e){let t=new ed({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 pd=[`preferences`,`view-state`,`memory-projections`,`task-associations`,`workflow-metadata`,`inspection-index`],md=[{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 hd(e){return e.toISOString()}function gd(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!x.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function _d(){return process.env.HOME??E()}function vd(e,t){let n=x.relative(e,t);return n===``||!n.startsWith(`..`)&&!x.isAbsolute(n)}async function yd(e,t){let n=e;for(;x.dirname(n)!==n;)try{let r=await t.realpath(n),i=x.relative(n,e);return x.resolve(r,i)}catch{n=x.dirname(n)}try{return await t.realpath(n)}catch{return x.resolve(e)}}async function bd(e){let t=e.fsAsync??new V,n=x.resolve(e.activeRepositoryRoot);gd(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?x.join(e.homeDir??_d(),`.robota`):e.storageRoot;gd(`userLocalStorageRoot`,r);let i=x.resolve(r),a=await yd(i,t);if(vd(await yd(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function xd(e,t){return x.join(e,t)}async function Sd(e,t,n){let r=xd(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=x.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:hd(new Date(o.birthtimeMs)),lastUsedAt:hd(new Date(o.mtimeMs)),enabled:!0,deleteAvailable:!0,disableAvailable:!1}}))).sort((e,t)=>e.key.localeCompare(t.key))}async function Cd(e){let t=e.fsAsync??new V,n=await bd(e),r=x.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all(md.map(async e=>{let r=xd(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await Sd(n,e.category,t);return{category:e.category,purpose:e.purpose,mayExecuteCommands:e.mayExecuteCommands,storageLocation:r,itemCount:a.length,items:a}})),generatedAt:hd((e.now??(()=>new Date))())}}const wd=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],Td=`.json`,Ed=/^[a-z0-9][a-z0-9._-]*$/u,Dd={"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 Od(e){return e.toISOString()}function kd(e){return wd.includes(e)}function Ad(e){if(!kd(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function jd(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!Ed.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function Md(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 Nd(e){return Md(`value`,e,240)}function Pd(e,t){return`${e}__${t}${Td}`}async function Fd(e){let t=await bd(e);return{root:t,memoryRoot:x.join(t,`memory-projections`)}}function Id(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:Ad(r),key:$(n,`key`),value:$(n,`value`),summary:$(n,`summary`),source:$(n,`source`),scope:$(n,`scope`),createdAt:$(n,`createdAt`),lastUsedAt:$(n,`lastUsedAt`),enabled:Ld(n,`enabled`)}}function $(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function Ld(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function Rd(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:Nd(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:Dd[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function zd(e,t,n){return Rd(e,t,Id(await n.readFile(t,`utf8`),t))}async function Bd(e){let t=Ad(e.category),n=jd(`key`,e.key),{root:r,memoryRoot:i}=await Fd(e);return{root:r,storageLocation:x.join(i,Pd(t,n))}}async function Vd(e){let t=e.fsAsync??new V,n=Ad(e.category),r=jd(`key`,e.key),i=Md(`summary`,e.summary,240),a=Md(`source`,e.source,80),o=Md(`scope`,e.scope??`user`,120),s=Nd(e.value),c=Od((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await Fd(e),d=x.join(u,Pd(n,r)),f=c;try{f=Id(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`),Rd(l,d,p)}async function Hd(e){let t=e.fsAsync??new V,{root:n,memoryRoot:r}=await Fd(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(Td)).map(e=>zd(n,x.join(r,e.name),t)));return{root:n,activeRepositoryRoot:x.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function Ud(e){let t=e.fsAsync??new V,{root:n,storageLocation:r}=await Bd(e);return zd(n,r,t)}async function Wd(e){let t=e.fsAsync??new V,{root:n,storageLocation:r}=await Bd(e),i={...Id(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:Od((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),Rd(n,r,i)}async function Gd(e){let t=e.fsAsync??new V,{storageLocation:n}=await Bd(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}async function Kd(e){let t=await Ud(e);return t.enabled?t:null}const qd=[`test`,`typecheck`,`build`],Jd={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 Yd(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))):[]}function Xd(e){return e.flatMap(e=>qd.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 Zd(){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 Qd(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 $d(){return{id:`rollback-on-failure`,phase:`recover`,description:`Use the existing edit checkpoint restore path if verification fails.`,required:!0}}function ef(e){if(e.changedFiles.length===0)throw Error(`Self-hosting verification requires at least one changed file.`);let t=e.baseRef??`origin/develop`,n=Yd(e.packageScopes),r=[...Zd(),...Xd(n),Qd(t),$d()];return{changedFiles:[...e.changedFiles],packageScopes:n,baseRef:t,steps:r}}function tf(e,t){let n=Jd[e][t];if(!n)throw Error(`Invalid self-hosting loop transition: ${e} -> ${t}`);return n}function nf(e){return e}function rf(e){if(!e||e.length===0)return;let[t,...n]=e;if(t!==void 0)return[t,...n]}function af(e){let t=rf(e),n=t===void 0?_.string().describe(`Registered model-invocable command name to execute`):_.enum(t).describe(`Registered model-invocable command name to execute`);return _.object({command:n,args:_.string().optional().describe(`Arguments to pass to the command`)})}function of(e){if(e.commandNames!==void 0)return e.commandNames;if(e.commandDescriptors!==void 0)return e.commandDescriptors.map(e=>L(e.name))}function sf(e){return`- ${L(e.name)}${e.argumentHint?` ${e.argumentHint}`:``}: ${e.description}`}function cf(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(sf)].join(`
101
- `)}function lf(e){let t=af(of(e));return fe(`ExecuteCommand`,cf(e.commandDescriptors),nf(t),async n=>{let r=t.parse(n),i=L(r.command);return e.isModelInvocable(i)?mn(i,await e.execute(i,r.args??``)):JSON.stringify({success:!1,command:i,error:`Command is not model-invocable: ${i}`})})}const uf=[`Allow once`,`Allow for this session`,`Deny`];function df(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 ff(e,t,n){e.writeLine(``),e.writeError(`[Permission Required] Tool: ${t}`),e.writeLine(` ${df(n)}`),e.writeLine(``);let r=await e.select(uf,0);return r===1?`allow-session`:r===0}const pf={usedTokens:0,maxTokens:2e5,usedPercentage:0,remainingPercentage:100},mf={sessionId:`test-session-id`,updatedAt:new Date().toISOString(),entries:[]},hf={id:``,parentSessionId:`test-session-id`,waitPolicy:`wait_all`,taskIds:[],status:`completed`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),results:[]};function gf(e){return{submit:()=>Promise.resolve(),abort:()=>{},cancelQueue:()=>{},shutdown:()=>Promise.resolve(),isExecuting:()=>!1,getPendingPrompt:()=>null,getMessages:()=>[],getContextState:()=>({...pf}),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:()=>({...hf}),waitBackgroundJobGroup:()=>Promise.resolve({...hf}),getExecutionWorkspaceSnapshot:()=>({...mf}),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 _f(){let e=Ua();return{deleted:qa(e),path:e}}function vf(e){try{let t=yf(e);if(!t)return;let n=b(C(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 yf(e){let t=T(e),n=S(t);for(;n!==t;){let e=bf(C(t,`.git`),t);if(e)return e;t=n,n=S(t)}return bf(C(t,`.git`),t)}function bf(e,t){if(!y(e))return;let n=De(e);if(n.isDirectory())return e;if(!n.isFile())return;let r=b(e,`utf8`).trim();if(!r.startsWith(`gitdir:`))return;let i=r.slice(7).trim();return Ke(i)?i:T(t,i)}function xf(e,t){let n=Cf(e),r=Cf(t);if(n===void 0||r===void 0)return Math.sign(e.localeCompare(t));let i=Tf(n.major,r.major)||Tf(n.minor,r.minor)||Tf(n.patch,r.patch);return i===0?Ef(n.prerelease,r.prerelease):i}function Sf(e,t){return xf(e,t)>0}function Cf(e){let[t,n]=(e.trim().replace(/^v/,``).split(`+`)[0]??``).split(`-`,2),[r,i,a]=t.split(`.`),o=wf(r),s=wf(i),c=wf(a);if(!(o===void 0||s===void 0||c===void 0))return{major:o,minor:s,patch:c,prerelease:n?n.split(`.`):[]}}function wf(e){if(!(e===void 0||!/^\d+$/.test(e)))return Number(e)}function Tf(e,t){return Math.sign(e-t)}function Ef(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=Df(n,i);if(a!==0)return a}return 0}function Df(e,t){let n=wf(e),r=wf(t);return n!==void 0&&r!==void 0?Tf(n,r):n===void 0?r===void 0?Math.sign(e.localeCompare(t)):1:-1}function Of(e){let t=S(tt(e)),n=[C(t,`..`,`..`,`package.json`),C(t,`..`,`package.json`)];for(let e of n)try{let t=b(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 kf=`@robota-sdk/agent-cli`,Af=`https://registry.npmjs.org`,jf=1440*60*1e3,Mf=1500;function Nf(e=process.env.HOME??process.env.USERPROFILE??`/`){return C(e,`.robota`,`update-check.json`)}function Pf(e){if(y(e))try{return Yf(JSON.parse(b(e,`utf8`)))}catch{return}}function Ff(e,t){Oe(S(e),{recursive:!0}),Pe(e,JSON.stringify(t,null,2)+`
102
- `,`utf8`)}async function If(e){if(e.disabled===!0)return{status:`skipped`,reason:`disabled`};let t=e.packageName??`@robota-sdk/agent-cli`,n=e.cachePath??Nf(),r=e.now??new Date,i=e.ttlMs??864e5;if(e.force!==!0){let a=Pf(n);if(a!==void 0&&Gf(a,r,i,t))return Uf(a,e.currentVersion)}let a=await Lf(e,t,n,r);return typeof a==`string`?Wf(e.currentVersion,a):a}async function Lf(e,t,n,r){let i=await Kf({fetchImpl:e.fetchImpl??fetch,packageName:t,registryUrl:e.registryUrl??`https://registry.npmjs.org`,timeoutMs:e.timeoutMs??1500});return i.ok?(Rf(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,latestVersion:i.version}),i.version):(Rf(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,errorMessage:i.errorMessage}),{status:`error`,errorMessage:i.errorMessage})}function Rf(e,t){try{Ff(e,t)}catch{}}async function zf(e){let t=await If(e);return t.status===`update_available`?t.notice:void 0}function Bf(e){return e.printMode===!1&&e.disableUpdateCheck===!1}function Vf(e){return[`Robota update available: ${e.currentVersion} -> ${e.latestVersion}.`,`Run ${e.installCommand}`].join(` `)}function Hf(e){return e.status===`update_available`?Vf(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 Uf(e,t){return e.errorMessage===void 0?e.latestVersion===void 0?{status:`error`,errorMessage:`Cached update check has no latest version`}:Wf(t,e.latestVersion):{status:`error`,errorMessage:e.errorMessage}}function Wf(e,t){return Sf(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 Gf(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 Kf(e){try{return{ok:!0,version:await qf(e)}}catch(e){return{ok:!1,errorMessage:e instanceof Error?e.message:String(e)}}}async function qf(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=Jf(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 Jf(e,t){return`${e.replace(/\/+$/,``)}/${encodeURIComponent(t)}`}function Yf(e){if(!Xf(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 Xf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zf(e){let t=Ua(),n={settings:{read:()=>q(t),write:e=>J(t,e)}},r=e.backgroundTaskRunners??re(),i=e.commandModules??[],a=e.commandHostAdapters??n,o=`sessionStore`in e?e.sessionStore:td(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 ed({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 Qf(e){let t=Zf({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{Gc as AUTO_COMPACT_THRESHOLD_SETTINGS_KEY,Ya as AgentExecutor,ll as BACKGROUND_COMMAND_DESCRIPTION,ul as BACKGROUND_COMMAND_USAGE,nn as BUILT_IN_AGENTS,rt as BackgroundJobOrchestrator,rc as BuiltinCommandSource,Ms as BundlePluginInstaller,js as BundlePluginLoader,nu as CLEAR_COMMAND_DESCRIPTION,jf as CLI_UPDATE_CACHE_TTL_MS,kf as CLI_UPDATE_PACKAGE_NAME,Af as CLI_UPDATE_REGISTRY_URL,Mf as CLI_UPDATE_TIMEOUT_MS,ou as COST_COMMAND_DESCRIPTION,$s as CommandRegistry,Wc as DEFAULT_AUTO_COMPACT_THRESHOLD,Ul as DEFAULT_STATUS_LINE_COMMAND_SETTINGS,j as EXECUTION_ORIGIN_METADATA_KEYS,cu as EXIT_COMMAND_DESCRIPTION,Ti as EditCheckpointStore,ol as HELP_COMMAND_DESCRIPTION,ed as InteractiveSession,Sl as LANGUAGE_COMMAND_ARGUMENT_HINT,xl as LANGUAGE_COMMAND_DESCRIPTION,ju as MEMORY_COMMAND_ARGUMENT_HINT,Au as MEMORY_COMMAND_DESCRIPTION,Mu as MEMORY_COMMAND_USAGE,ms as MEMORY_INDEX_MAX_BYTES,ps as MEMORY_INDEX_MAX_LINES,cn as MODEL_COMMAND_TOOL_PREFIX,Is as MarketplaceClient,kl as PERMISSIONS_COMMAND_DESCRIPTION,Ol as PERMISSION_MODE_ARGUMENT_HINT,Dl as PERMISSION_MODE_COMMAND_DESCRIPTION,Xl as PLUGIN_COMMAND_ARGUMENT_HINT,Yl as PLUGIN_COMMAND_DESCRIPTION,ln as PROVIDER_SAFE_TOOL_NAME_PATTERN,Uc as PluginCommandSource,Ds as PluginSettingsStore,Cs as ProjectMemoryStore,Za as PromptExecutor,Cl as RECOMMENDED_RESPONSE_LANGUAGES,Zl as RELOAD_PLUGINS_COMMAND_DESCRIPTION,ru as RENAME_COMMAND_DESCRIPTION,iu as RENAME_COMMAND_USAGE,au as RESUME_COMMAND_DESCRIPTION,yu as REWIND_COMMAND_ARGUMENT_HINT,vu as REWIND_COMMAND_DESCRIPTION,Hl as STATUSLINE_COMMAND_ARGUMENT_HINT,Vl as STATUSLINE_COMMAND_DESCRIPTION,Ha as SkillCommandSource,ec as SystemCommandExecutor,wd as USER_LOCAL_MEMORY_CATEGORIES,pd as USER_LOCAL_STORAGE_CATEGORIES,md as USER_LOCAL_STORAGE_CATEGORY_DEFINITIONS,su as VALIDATE_SESSION_COMMAND_DESCRIPTION,Al as VALID_PERMISSION_MODES,el as addCommandContextReference,Ic as applyActiveModelChange,Pc as applyProviderConfiguration,Fc as applyProviderSwitch,ql as applyStatusLineSettings,sn as assembleSubagentPrompt,dl as buildBackgroundCommandSubcommands,wl as buildLanguageCommandSubcommands,Nu as buildMemoryCommandSubcommands,jl as buildPermissionModeSubcommands,tu as buildPluginCommandSubcommands,_r as buildPromptWithFileReferences,uc as buildProviderProfile,lc as buildProviderSetupPatch,bu as buildRewindCommandSubcommands,Wl as buildStatusLineCommandSubcommands,yl as cancelCommandBackgroundTask,If as checkForCliUpdate,yc as checkSettingsDocument,wc as checkSettingsFile,nl as clearCommandContextReferences,cr as clearContextReferences,lu as clearConversationHistory,bl as closeCommandBackgroundTask,Qc as compactCommandContext,xf as compareSemverVersions,Zf as createAgentRuntime,Rn as createAgentTool,ft as createBackgroundGroupExecutionEntryId,wa as createBackgroundProcessTool,N as createBackgroundTaskExecutionEntryId,ic as createBuiltinCommandModule,lf as createCommandExecutionTool,Iu as createCommandMemoryStores,Fu as createCommandPendingMemoryStore,Pu as createCommandProjectMemoryStore,ar as createContextReferenceItem,qi as createDefaultTools,P as createExecutionOriginMetadata,mt as createExecutionWorkspaceSnapshot,Ft as createExecutionWorkspaceTaskSpawner,On as createInProcessSubagentRunner,Mt as createLineDetailPage,jt as createMainThreadDetailPage,M as createMainThreadExecutionEntryId,fn as createModelCommandToolProjection,$l as createPluginRegistryReloadRequestedEffect,Ql as createPluginTuiRequestedEffect,td as createProjectSessionStore,hn as createProjectedCommandExecutionTools,br as createPromptFileReferenceHistoryEntry,Hc as createProviderFromSettings,dn as createProviderSafeModelCommandToolName,fd as createQuery,pu as createSessionExitRequestedEffect,fu as createSessionPickerRequestedEffect,du as createSessionRenamedEffect,Qf as createStatelessRuntime,_o as createSubagentLogger,Sn as createSubagentSession,tc as createSystemCommands,gf as createTestInteractiveSession,sc as deleteProviderProfile,qa as deleteSettings,Gd as deleteUserLocalMemoryItem,Wd as disableUserLocalMemoryItem,ss as discoverTaskFiles,to as evaluateReversibleToolSafety,Gu as executeSkill,Hf as formatCliUpdateCheckMessage,Vf as formatCliUpdateNotice,fl as formatCommandBackgroundTask,pl as formatCommandBackgroundTaskList,cl as formatCommandHelpMessage,Bl as formatCommandPermissionsMessage,gu as formatCommandSessionReplayValidationReport,l as formatEnvReference,Pl as formatInvalidPermissionModeMessage,El as formatLanguageUsageMessage,Qu as formatOrgPolicyViolationMessage,pn as formatProjectedModelCommandToolPromptDescription,yr as formatPromptFileReferenceDiagnostics,us as formatTaskContext,rn as getBuiltInAgent,on as getForkWorkerSuffix,jc as getProviderSettingsPaths,zf as getStartupCliUpdateNotice,an as getSubagentSuffix,Ua as getUserSettingsPath,Nf as getUserUpdateCheckCachePath,vr as hasBlockingPromptFileReferenceDiagnostics,Ru as hasSensitiveCommandMemoryContent,f as hasUsableSecretReference,Su as inspectCommandEditCheckpoint,Ud as inspectUserLocalMemoryItem,Cd as inspectUserLocalStorage,$u as isApiKeyPlaintext,Lu as isCommandMemoryType,m as isEnvReference,gs as isMemoryType,Sf as isNewerSemverVersion,Nl as isPermissionMode,Gl as isStatusLineCommandSettingsPatch,lr as listActiveContextReferences,_l as listCommandBackgroundTasks,$c as listCommandContextReferences,xu as listCommandEditCheckpoints,Rl as listCommandSessionAllowedTools,zu as listCommandUsedMemoryReferences,nd as listResumableSessionSummaries,Hd as listUserLocalMemoryItems,Zu as loadOrgPolicy,ds as loadTaskContext,dc as mergeProviderPatch,Oc as mergeProviders,Dc as mergeSettings,L as normalizeModelCommandName,ml as parseCommandBackgroundLogCursor,pt as parseExecutionWorkspaceEntryId,Ra as parseFrontmatter,Tl as parseLanguageArgument,Ml as parsePermissionModeArgument,wr as parsePromptFileReferences,uu as parseSessionNameArgument,cs as parseTaskFile,ef as planSelfHostingVerification,Hu as preprocessShellCommands,vc as probeProviderProfile,W as projectPaths,ff as promptForApproval,qc as readAutoCompactThreshold,Jc as readAutoCompactThresholdSource,vl as readCommandBackgroundTaskLog,Kc as readCommandContextState,Il as readCommandPermissionMode,zl as readCommandPermissionsState,mu as readCommandSessionInfo,os as readCurrentGitBranch,Kd as readEnabledUserLocalMemoryItem,Bc as readMergedProviderSettings,Tc as readMergedProviderSettingsFromPaths,Of as readPackageVersion,Vc as readProviderSettings,q as readSettings,Kl as readStatusLineSettings,Pf as readUpdateCheckCache,Bu as recordCommandMemoryEvent,tl as removeCommandContextReference,sr as removeContextReference,Zc as resetAutoCompactThresholdSetting,_f as resetUserConfig,kc as resolveActiveProvider,ee as resolveEnvReference,vf as resolveGitBranch,rd as resolveLatestSessionId,Fl as resolvePermissionModeAdapter,eu as resolvePluginCommandAdapter,Mr as resolvePromptFileReferencePaths,jr as resolvePromptFileReferences,Mc as resolveProviderSettingsWriteTargetPath,id as resolveSessionIdByIdOrName,Wa as resolveSettingsPathForScope,vo as resolveSubagentLogDir,bd as resolveUserLocalStorageRoot,Cu as restoreCommandEditCheckpoint,R as retrieveAgentToolDeps,wu as rollbackCommandEditCheckpoint,al as sanitizeProviderProfileName,ls as selectRelevantTasks,Yc as setCommandAutoCompactThreshold,oc as setCurrentProvider,Vd as setUserLocalMemoryItem,Bf as shouldRunStartupCliUpdateCheck,Nn as storeAgentToolDeps,Vu as substituteVariables,il as suggestProviderProfileName,ct as summarizeBackgroundJobGroup,_c as testProviderProfileCommand,ur as toContextReferenceRecords,H as toPromptFileReferenceRecords,tf as transitionSelfHostingLoop,Ga as updateModelInSettings,fs as updateTaskFileStatus,or as upsertContextReference,ac as upsertProviderProfile,vi as userPaths,hu as validateCommandSessionReplayLog,cc as validateProviderProfile,ja as wrapEditCheckpointTools,no as wrapReversibleExecutionTools,Xc as writeAutoCompactThresholdSetting,Ll as writeCommandPermissionMode,J as writeSettings,Ff as writeUpdateCheckCache};
94
+ `),s=Es(o),c=new ws(e).loadStartupMemory().content||void 0,l=fs(e);return{agentsMd:a,claudeMd:o,memoryMd:c,taskContext:l.trim().length>0?l:void 0,compactInstructions:s,agentsFileEntries:r,claudeFileEntries:i}}var Os=class{settingsPath;fs;constructor(e,t=new z){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=x(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 ks(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(`
95
+ `)){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 As(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 js(e,t=new z){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}var Ms=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new z){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){return this.discoverAndLoad()}async loadAll(){return this.discoverAndLoad()}discoverAndLoad(){let e=S(this.pluginsDir,`cache`);if(!this.fs.existsSync(e))return[];let t=[],n=js(e,this.fs);for(let r of n){let n=S(e,r),i=js(n,this.fs);for(let e of i){let i=S(n,e),a=js(i,this.fs);if(a.length===0)continue;let o=a[a.length-1],s=S(i,o),c=S(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 As(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=S(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=S(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let{metadata:r,content:a}=ks(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=S(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}=ks(this.fs.readFileSync(S(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=S(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=S(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=S(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$/,``)):[]}},Ns=class{pluginsDir;cacheDir;registryPath;settingsStore;marketplaceClient;exec;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.cacheDir=S(this.pluginsDir,`cache`),this.registryPath=S(this.pluginsDir,`installed_plugins.json`),this.settingsStore=e.settingsStore,this.marketplaceClient=e.marketplaceClient,this.exec=e.exec,this.fs=e.fs??new z}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=S(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=S(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=x(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 z){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 Ps(e,t,n=new z){let r=x(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(e,JSON.stringify(t,null,2),`utf-8`)}function Fs(e,t,n=new z){let r=S(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=x(r);n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.writeFileSync(r,JSON.stringify(i,null,2),`utf-8`)}}const Is=6e4;var Ls=class{pluginsDir;exec;marketplacesDir;registryPath;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.exec=e.exec,this.marketplacesDir=S(this.pluginsDir,`marketplaces`),this.registryPath=S(this.pluginsDir,`known_marketplaces.json`),this.fs=e.fs??new z}addMarketplace(e){let t=`temp-`+Date.now().toString(36),n=S(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:Is,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone marketplace: ${t}`)}}let r=S(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=S(this.marketplacesDir,i);return this.fs.renameSync(n,o),a[i]={source:e,installLocation:o,lastUpdated:new Date().toISOString()},Ps(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`);Fs(this.pluginsDir,e,this.fs),this.fs.existsSync(n.installLocation)&&this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),delete t[e],Ps(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:Is,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(),Ps(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=S(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:Is,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 Rs(e){let t=S(x(x(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function zs(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 Bs(e){let t={};for(let n of e){let e=n.hooks;if(!e)continue;let r=Rs(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=zs(e,n.pluginDir);return t.env=r,t});t[e].push(...i)}}return t}function Vs(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 Hs(e){let t=e.cwd,[n,r,i]=await Promise.all([e.config?Promise.resolve(e.config):qo(t),e.bare?Promise.resolve({agentsMd:``,claudeMd:``,agentsFileEntries:[],claudeFileEntries:[]}):Ds(t),e.bare?Promise.resolve({type:`unknown`,language:`unknown`}):Bi(t)]),a=e.language?{...n,language:e.language}:n,o=new Ms(S(T(),`.robota`,`plugins`));if(!e.bare)try{let e=o.loadPluginsSync();if(e.length>0){let t=Bs(e);a={...a,hooks:Vs(a.hooks,t)}}}catch{}let s=U(t);await Ws(e)||await Us(e,t);let c=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,{session:l,rebuildSystemMessage:u}=go({config:a,cwd:t,context:r,projectInfo:i,permissionMode:e.permissionMode,maxTurns:e.maxTurns,terminal:ei,sessionLogger:new ye(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,deniedTools:e.deniedTools,model:e.model,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,...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{}});return{session:l,agentsFileEntries:r.agentsFileEntries??[],claudeFileEntries:r.claudeFileEntries??[],rebuildSystemMessage:u}}async function Us(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await ce(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function Ws(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 Gs(e,t){let n=e.config??await qo(e.cwd),r=n.autoCompactThreshold===void 0?`default`:`settings`,i=new Di({cwd:e.cwd});t.setEditCheckpointStore(i);let a=await Hs({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,deniedTools:e.deniedTools,model:e.model,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}:{},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},commandDescriptors:t.commandDescriptors,...t.commandDescriptors.length>0?{modelCommandExecutor:t.executeModelCommand,isModelCommandInvocable:t.isModelCommandInvocable}:{}});if(t.pendingRestoreMessages)for(let e of t.pendingRestoreMessages)Vi(a.session,e);return{session:a.session,agentsFileEntries:a.agentsFileEntries,claudeFileEntries:a.claudeFileEntries,rebuildSystemMessage:a.rebuildSystemMessage,autoCompactThresholdSource:r}}function Ks(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(qs({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 qs(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},...Js(e.backgroundState),...Ys(e.memoryState),...Xs(e.skillActivationState),...Zs(e.contextReferenceState)}}function Js(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function Ys(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function Xs(e){return e?{skillActivationEvents:[...e.events]}:{}}function Zs(e){return e?{contextReferences:[...e.references]}:{}}function Qs(e){return e.source===`skill`||e.source===`plugin`&&e.skillContent?`skill`:`builtin-command`}function $s(e){let t=e.source===`skill`||e.source===`plugin`&&!!e.skillContent;return{name:e.name,kind:Qs(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 ec=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=>$s(e))}},tc=class{commands;constructor(e){this.commands=new Map;for(let t of e??nc())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}:{},requiresPermission:this.resolveRequiresPermission(e)}))}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 nc(){return[]}function rc(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 ic=class{name=`builtin`;commands;constructor(e=nc()){this.commands=e.map(rc)}getCommands(){return this.commands}};function ac(){let e=nc();return{name:`sdk-builtin`,commandSources:[new ic(e)],systemCommands:e}}function oc(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function sc(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function cc(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 lc(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=c(n.providerDefinitions??[],t.type),i=d(r);if(i!==void 0&&!mc(t,r?.defaults,i))throw Error(`Provider profile "${e}" is missing ${gc(i)}`)}function uc(e,t={}){let n=dc(e,t);return lc(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function dc(e,t={}){let n=pc(e.type,t.providerDefinitions??[]);e.apiKey!==void 0&&e.apiKeyEnv===void 0&&console.warn(`API key stored as plain text in settings. Use --api-key-env for better security.`);let r=e.apiKeyEnv===void 0?e.apiKey??n.apiKey:u(e.apiKeyEnv),i=e.baseURL??n.baseURL;return{type:e.type,model:e.model??n.model,..._c(r)&&{apiKey:r},...i!==void 0&&{baseURL:i},...e.timeout!==void 0&&{timeout:e.timeout}}}function fc(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=oc(e,n,r);return t.currentProvider?sc(i,t.currentProvider):i}function pc(e,t){return c(t,e)?.defaults??{}}function mc(e,t,n){return n.anyOf.some(n=>p(hc(n,e,t)))}function hc(e,t,n){return t[e]??n?.[e]}function gc(e){return e.anyOf.join(` or `)}function _c(e){return e!==void 0&&e.length>0}async function vc(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{lc(i,a,{providerDefinitions:r.providerDefinitions})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let o=await((a.type?c(r.providerDefinitions,a.type):void 0)?.probeProfile??yc)(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 yc(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function bc(e,t=[]){return xc(e,t)?`valid`:`incomplete`}function xc(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return Sc(n?.type,n,t)}return!!(e.provider&&Sc(e.provider.name,e.provider,t))}function Sc(e,t,n){if(!t)return!1;if(!e)return p(t.apiKey);let r=c(n,e);if(r===void 0)return!1;let i=d(r);return i===void 0?!0:Cc(t,r,i)}function Cc(e,t,n){return n.anyOf.some(n=>p(wc(n,e,t)))}function wc(e,t,n){return t[e]??n.defaults?.[e]}function Tc(e,t=[]){if(!v(e))return`missing`;try{let n=y(e,`utf8`).trim();return n.length===0?`incomplete`:bc(JSON.parse(n),t)}catch{return`corrupt`}}function Ec(e,t=new z){return e.reduce((e,n)=>{let r=Dc(n,t);return r===void 0?e:Oc(e,r)},{})}function Dc(e,t){if(t.existsSync(e))try{let n=t.readFileSync(e,`utf8`);return JSON.parse(n)}catch{return}}function Oc(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?kc(e.providers,t.providers):void 0}}function kc(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function Ac(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 se({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 se({name:i.name,model:i.model,apiKey:i.apiKey,baseURL:i.baseURL,timeout:i.timeout,options:i.options},n)}function jc(){return process.env.HOME??process.env.USERPROFILE??`/`}function Mc(e){let t=jc();return[S(t,`.robota`,`settings.json`),S(t,`.claude`,`settings.json`),S(e,`.robota`,`settings.json`),S(e,`.robota`,`settings.local.json`),S(e,`.claude`,`settings.json`),S(e,`.claude`,`settings.local.json`)]}function Nc(e,t={}){let n=t.settingsPaths??Mc(e),r=Bc(n)??n[0];if(r===void 0)throw Error(`No settings path available for provider update`);return r}function Pc(e){return q(e)}function Fc(e,t,n={}){let r=fc(Pc(e),uc(t,n));return J(e,r),r}function Ic(e,t,n={}){let r=Pc(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:sc(r,t);return J(e,o),o}function Lc(e,t,n={}){let r=n.settingsPaths??Mc(e),i=Ec(r),a=n.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Rc(r,a,t)}function Rc(e,t,n){let r=zc(e,t)??e[0];if(r===void 0)throw Error(`No settings path available for model update`);let i=Pc(r),a=i.providers??{},o=a[t]??{},s={...i,providers:{...a,[t]:{...o,model:n}}};return J(r,s),{settingsPath:r,settings:s,profileName:t}}function zc(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&Pc(r).providers?.[t]!==void 0)return r}}function Bc(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&Pc(n).currentProvider!==void 0)return n}}function Vc(e){return Ec(Mc(e))}function Hc(e,t={}){let n=Ac(Vc(e),t.providerOverride,t.providerDefinitions??[]);if(n!==void 0)return n;throw Error("No provider configuration found. Run `robota` to set up.")}function Uc(e,t,n={}){let r=n.providerDefinitions??[],i=Hc(e,{...n,providerDefinitions:r}),a=t??i.model;return ae({...i,model:a},r)}var Wc=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 Gc=ve,Kc=`autoCompactThreshold`;function qc(e){return e.getContextState()}function Jc(e){return e.getAutoCompactThreshold()}function Yc(e){return e.getAutoCompactThresholdSource?.()??`session`}function Xc(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 Zc(e,t){let n=il(e);return n?(n.write({...n.read(),[Kc]:t}),!0):!1}function Qc(e){let t=il(e);if(!t)return!1;let n={...t.read()};return delete n[Kc],t.write(n),!0}async function $c(e,t){let n=qc(e),r=e.getSession().getMessageCount();return await e.compactContext(t),{before:n,after:qc(e),beforeMessageCount:r,afterMessageCount:e.getSession().getMessageCount()}}function el(e){return e.listContextReferences?.()??[]}async function tl(e,t){return e.addContextReference?e.addContextReference(t):{evicted:[],diagnostics:[`Command host does not support context reference additions.`]}}function nl(e,t){return e.removeContextReference?.(t)??{}}function rl(e){return e.clearContextReferences?.()??{removed:[]}}function il(e){return e.getCommandHostAdapters?.().settings}function al(e,t={}){let n=ol(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 ol(e){let t=e?.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t!==void 0&&t.length>0?t:void 0}const sl=`Show available commands`;function cl(e){return e.listCommands?.()??[]}function ll(e){return[`Available commands:`,...cl(e).flatMap(e=>{let t=e.displayName??e.name,n=`/${e.name}`,r=` ${(e.displayName?`${t} (${n})`:n).padEnd(32)} — ${e.description}`;return e.example?[r,` Example: ${e.example}`]:[r]})].join(`
96
+ `)}const ul=`List and control background tasks`,dl=`Usage: background list | background read <task-id> [offset] | background cancel <task-id> | background close <task-id>`;function fl(){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 pl(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=gl(e),s=t?` — ${t}`:``;return`${e.id} [${e.status}${n}${i}${a}${o}] ${e.kind}:${e.label}${r}${s}`}function ml(e){return e.length===0?`No background tasks.`:[`Background tasks:`,...e.map(e=>` ${pl(e)}`)].join(`
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
+ `)}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
+ `);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}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(`
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}`})})}const df=[`Allow once`,`Allow for this session`,`Deny`];function ff(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 pf(e,t,n){e.writeLine(``),e.writeError(`[Permission Required] Tool: ${t}`),e.writeLine(` ${ff(n)}`),e.writeLine(``);let r=await e.select(df,0);return r===1?`allow-session`:r===0}const mf={usedTokens:0,maxTokens:2e5,usedPercentage:0,remainingPercentage:100},hf={sessionId:`test-session-id`,updatedAt:new Date().toISOString(),entries:[]},gf={id:``,parentSessionId:`test-session-id`,waitPolicy:`wait_all`,taskIds:[],status:`completed`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),results:[]};function _f(e){return{submit:()=>Promise.resolve(),abort:()=>{},cancelQueue:()=>{},shutdown:()=>Promise.resolve(),isExecuting:()=>!1,getPendingPrompt:()=>null,getMessages:()=>[],getContextState:()=>({...mf}),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:()=>({...gf}),waitBackgroundJobGroup:()=>Promise.resolve({...gf}),getExecutionWorkspaceSnapshot:()=>({...hf}),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 vf(){let e=Wa();return{deleted:Ja(e),path:e}}function yf(e){try{let t=bf(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 bf(e){let t=w(e),n=x(t);for(;n!==t;){let e=xf(S(t,`.git`),t);if(e)return e;t=n,n=x(t)}return xf(S(t,`.git`),t)}function xf(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 Sf(e,t){let n=wf(e),r=wf(t);if(n===void 0||r===void 0)return Math.sign(e.localeCompare(t));let i=Ef(n.major,r.major)||Ef(n.minor,r.minor)||Ef(n.patch,r.patch);return i===0?Df(n.prerelease,r.prerelease):i}function Cf(e,t){return Sf(e,t)>0}function wf(e){let[t,n]=(e.trim().replace(/^v/,``).split(`+`)[0]??``).split(`-`,2),[r,i,a]=t.split(`.`),o=Tf(r),s=Tf(i),c=Tf(a);if(!(o===void 0||s===void 0||c===void 0))return{major:o,minor:s,patch:c,prerelease:n?n.split(`.`):[]}}function Tf(e){if(!(e===void 0||!/^\d+$/.test(e)))return Number(e)}function Ef(e,t){return Math.sign(e-t)}function Df(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=Of(n,i);if(a!==0)return a}return 0}function Of(e,t){let n=Tf(e),r=Tf(t);return n!==void 0&&r!==void 0?Ef(n,r):n===void 0?r===void 0?Math.sign(e.localeCompare(t)):1:-1}function kf(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 Af=`@robota-sdk/agent-cli`,jf=`https://registry.npmjs.org`,Mf=1440*60*1e3,Nf=1500;function Pf(e=process.env.HOME??process.env.USERPROFILE??`/`){return S(e,`.robota`,`update-check.json`)}function Ff(e){if(v(e))try{return Xf(JSON.parse(y(e,`utf8`)))}catch{return}}function If(e,t){ke(x(e),{recursive:!0}),Fe(e,JSON.stringify(t,null,2)+`
102
+ `,`utf8`)}async function Lf(e){if(e.disabled===!0)return{status:`skipped`,reason:`disabled`};let t=e.packageName??`@robota-sdk/agent-cli`,n=e.cachePath??Pf(),r=e.now??new Date,i=e.ttlMs??864e5;if(e.force!==!0){let a=Ff(n);if(a!==void 0&&Kf(a,r,i,t))return Wf(a,e.currentVersion)}let a=await Rf(e,t,n,r);return typeof a==`string`?Gf(e.currentVersion,a):a}async function Rf(e,t,n,r){let i=await qf({fetchImpl:e.fetchImpl??fetch,packageName:t,registryUrl:e.registryUrl??`https://registry.npmjs.org`,timeoutMs:e.timeoutMs??1500});return i.ok?(zf(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,latestVersion:i.version}),i.version):(zf(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,errorMessage:i.errorMessage}),{status:`error`,errorMessage:i.errorMessage})}function zf(e,t){try{If(e,t)}catch{}}async function Bf(e){let t=await Lf(e);return t.status===`update_available`?t.notice:void 0}function Vf(e){return e.printMode===!1&&e.disableUpdateCheck===!1}function Hf(e){return[`Robota update available: ${e.currentVersion} -> ${e.latestVersion}.`,`Run ${e.installCommand}`].join(` `)}function Uf(e){return e.status===`update_available`?Hf(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 Wf(e,t){return e.errorMessage===void 0?e.latestVersion===void 0?{status:`error`,errorMessage:`Cached update check has no latest version`}:Gf(t,e.latestVersion):{status:`error`,errorMessage:e.errorMessage}}function Gf(e,t){return Cf(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 Kf(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 qf(e){try{return{ok:!0,version:await Jf(e)}}catch(e){return{ok:!1,errorMessage:e instanceof Error?e.message:String(e)}}}async function Jf(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=Yf(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 Yf(e,t){return`${e.replace(/\/+$/,``)}/${encodeURIComponent(t)}`}function Xf(e){if(!Zf(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 Zf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qf(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 $f(e){let t=Qf({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,Mf as CLI_UPDATE_CACHE_TTL_MS,Af as CLI_UPDATE_PACKAGE_NAME,jf as CLI_UPDATE_REGISTRY_URL,Nf 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,Lf as checkForCliUpdate,bc as checkSettingsDocument,Tc as checkSettingsFile,rl as clearCommandContextReferences,lr as clearContextReferences,uu as clearConversationHistory,xl as closeCommandBackgroundTask,$c as compactCommandContext,Sf as compareSemverVersions,Qf 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,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,$f as createStatelessRuntime,vo as createSubagentLogger,Cn as createSubagentSession,nc as createSystemCommands,_f as createTestInteractiveSession,cc as deleteProviderProfile,Ja as deleteSettings,Kd as deleteUserLocalMemoryItem,Gd as disableUserLocalMemoryItem,cs as discoverTaskFiles,no as evaluateReversibleToolSafety,Ku as executeSkill,Uf as formatCliUpdateCheckMessage,Hf 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,Bf as getStartupCliUpdateNotice,on as getSubagentSuffix,Wa as getUserSettingsPath,Pf 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,Cf as isNewerSemverVersion,Pl as isPermissionMode,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,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,pf 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,kf as readPackageVersion,Hc as readProviderSettings,q as readSettings,ql as readStatusLineSettings,Ff as readUpdateCheckCache,Vu as recordCommandMemoryEvent,nl as removeCommandContextReference,cr as removeContextReference,Qc as resetAutoCompactThresholdSetting,vf as resetUserConfig,Ac as resolveActiveProvider,ee as resolveEnvReference,yf 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,Vf as shouldRunStartupCliUpdateCheck,Pn as storeAgentToolDeps,Hu as substituteVariables,al as suggestProviderProfileName,lt as summarizeBackgroundJobGroup,vc as testProviderProfileCommand,dr as toContextReferenceRecords,V as toPromptFileReferenceRecords,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,If as writeUpdateCheckCache};
103
103
  //# sourceMappingURL=index.js.map