@robota-sdk/agent-framework 3.0.0-beta.76 → 3.0.0-beta.78

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,111 +1,4 @@
1
- import{AuthenticationError as e,ENV_REFERENCE_PREFIX as t,NetworkError as n,ProviderError as r,RateLimitError as i,TRUST_TO_MODE as a,collectAssistantUsageMetadata as o,createAssistantMessage as s,createSystemMessage as c,createUserMessage as l,findProviderDefinition as u,formatEnvReference as d,formatEnvReference as f,formatSupportedProviderTypes as p,getProviderCredentialRequirement as m,hasUsableSecretReference as ee,hasUsableSecretReference as h,isEnvReference as g,isEnvReference as te,messageToHistoryEntry as _,resolveEnvReference as ne,runHooks as re}from"@robota-sdk/agent-core";import{BackgroundTaskManager as ie,SubagentManager as ae,createDefaultBackgroundTaskRunners as oe,createProviderFromConfig as se,isTerminalBackgroundTaskStatus as ce,normalizeProviderConfig as le}from"@robota-sdk/agent-executor";import{applyWorkspaceManifest as ue,createBashTool as de,createEditTool as fe,createReadTool as pe,createWriteTool as me,createZodFunctionTool as he,globTool as ge,grepTool as _e,webFetchTool as ve,webSearchTool as ye}from"@robota-sdk/agent-tools";import{z as v}from"zod";import{AUTO_COMPACT_THRESHOLD as be,FileSessionLogger as xe,Session as Se,SessionStore as Ce,loadSessionLogEntries as we,replaySessionLogEntries as Te,validateSessionReplayLogEntries as Ee}from"@robota-sdk/agent-session";import{createHash as De,randomUUID as y}from"node:crypto";import{constants as Oe,cpSync as ke,existsSync as b,lstatSync as Ae,mkdirSync as je,readFileSync as x,readdirSync as Me,renameSync as Ne,rmSync as Pe,statSync as Fe,unlinkSync as Ie,writeFileSync as Le}from"node:fs";import{access as Re,copyFile as ze,mkdir as Be,readFile as Ve,readdir as He,realpath as Ue,rename as We,rm as Ge,stat as Ke,writeFile as qe}from"node:fs/promises";import S,{basename as Je,dirname as C,isAbsolute as Ye,join as w,relative as T,resolve as E,sep as Xe}from"node:path";import{homedir as D}from"node:os";import{appendFileSync as Ze,existsSync as O,mkdirSync as Qe,readFileSync as $e,readdirSync as et,writeFileSync as tt}from"fs";import{basename as nt,dirname as rt,join as k,resolve as it}from"path";import{fileURLToPath as at}from"node:url";const ot=1e3;var st=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&&ce(n.status)&&this.captureTask(e,n)}}handleTaskEvent(e){let t=ct(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,ut(t)],e.state.updatedAt=this.now(),!0)}evaluateCompletion(e){if(e.state.status===`completed`)return;if(!lt(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 ct(e){if(e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)return e.task}function lt(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 ut(e){return{taskId:e.id,label:e.label,status:e.status,...e.result?.output?{summary:dt(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 dt(e){let t=e.trim();return t.length<=ot?t:`${t.slice(0,ot)}...`}function ft(e){let t=pt(e,`completed`),n=pt(e,`failed`),r=pt(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=>mt(e))}}function pt(e,t){return e.results.filter(e=>e.status===t).length}function mt(e){let t=ht(e),n=e.outputRef&&e.summary?` (output: ${e.outputRef})`:``;return`[${e.status}] ${e.label} ${e.taskId}: ${t}${n}`}function ht(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 gt(e){return[`main`,e].join(`:`)}function _t(e){return[`task`,e].join(`:`)}function vt(e){return[`group`,e].join(`:`)}function yt(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 M(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 bt(e){let t=Tt(e.groups),n=[xt(e.mainThread),...It(e.groups).map(e=>Ct(e)),...Ft(e.tasks).map(e=>St(e,t.get(e.id)))].filter(t=>Pt(t,e.filter));return{sessionId:e.sessionId,selectedEntryId:e.selectedEntryId??n.find(e=>e.kind===`main_thread`)?.id??gt(e.sessionId),updatedAt:n[0]?.updatedAt??e.mainThread.updatedAt,entries:n}}function xt(e){return{id:gt(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:N(e.preview),unread:!1,attention:`none`,visibility:`default`,updatedAt:e.updatedAt,controls:[`select`]}}function St(e,t){return{id:_t(e.id),sourceId:e.id,kind:`background_task`,parentId:e.parentTaskId?_t(e.parentTaskId):gt(e.parentSessionId),...t?{groupId:vt(t)}:{},origin:wt(e.metadata,{kind:`system`,sessionId:e.parentSessionId}),taskKind:e.kind,status:e.status,title:e.label,subtitle:Dt(e),preview:At(e),currentAction:e.currentAction,unread:e.unread,attention:jt(e),visibility:Mt(e),updatedAt:e.lastActivityAt??e.updatedAt,controls:Et(e)}}function Ct(e){let t=N(e.results.map(e=>e.summary??e.error?.message).join(` `));return{id:vt(e.id),sourceId:e.id,kind:`background_group`,parentId:gt(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:Nt(e),visibility:e.status===`completed`?`collapsed`:`default`,updatedAt:e.updatedAt,controls:e.status===`running`?[`select`,`wait`]:[`select`]}}function wt(e,t){let n=Lt(e?.[j.kind]),r=P(e?.[j.sessionId]);return{kind:n??t.kind,sessionId:r??t.sessionId,turnId:P(e?.[j.turnId])??t.turnId,commandName:P(e?.[j.commandName])??t.commandName,toolCallId:P(e?.[j.toolCallId])??t.toolCallId,skillId:P(e?.[j.skillId])??t.skillId,label:P(e?.[j.label])??t.label}}function Tt(e){return new Map(e.flatMap(e=>e.taskIds.map(t=>[t,e.id])))}function Et(e){let t=[`select`];return ce(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 Dt(e){if(e.kind===`agent`)return e.agentType??e.cwd;let t=e.schedule?.agentInstruction;if(e.status===`sleeping`&&e.nextFireAt!==void 0){let n=`next: ${kt(e.nextFireAt)}`;return t===void 0?n:`↻ wake "${Ot(t)}" · ${n}`}return e.cwd}function Ot(e){let t=e.trim();return t.length>32?`${t.slice(0,32)}…`:t}function kt(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 At(e){return e.status===`failed`?N(e.error?.message):e.status===`completed`?N(e.result?.output):N(e.promptPreview??e.commandPreview)}function jt(e){return e.status===`failed`?`failed`:e.status===`waiting_permission`?`permission`:e.unread?`unread`:e.status===`completed`?`completed`:`none`}function Mt(e){return e.status===`completed`&&!e.unread&&!e.error&&(e.result?.exitCode??0)===0&&!e.result?.signalCode&&!e.worktreePath&&!e.branchName?`collapsed`:`default`}function Nt(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`none`}function Pt(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 Ft(e){return[...e].sort((e,t)=>(t.lastActivityAt??t.updatedAt).localeCompare(e.lastActivityAt??e.updatedAt))}function It(e){return[...e].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}function N(e){let t=e?.trim().replace(/\s+/g,` `);if(t)return t.length>120?`${t.slice(0,120)}...`:t}function P(e){return typeof e==`string`?e:void 0}function Lt(e){if(e===`user_prompt`||e===`slash_command`||e===`model_command`||e===`tool_call`||e===`skill`||e===`transport`||e===`system`)return e}function Rt(e){let t=Bt(e.cursor?.offset),n=e.history.slice(t,t+80),r=n.map(e=>({id:e.id,kind:e.category===`chat`?`message`:`progress`,text:Vt(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 zt(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 Bt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function Vt(e){return typeof e.data==`string`?e.data:e.type}function Ht(e){return{spawnAgent:t=>e.manager.spawn(Ut(e,t)),spawnProcess:t=>e.manager.spawn(Wt(e,t)),createGroup:t=>e.groupOrchestrator.createGroup({parentSessionId:e.sessionId,waitPolicy:t.waitPolicy,taskIds:[...t.taskIds],label:t.label})}}function Ut(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:M(e.origin)}}function Wt(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:M(e.origin)}}const Gt=new WeakMap;function Kt(e,t){Gt.set(e,t)}function qt(e){return Gt.get(e)}function Jt(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
-
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 Yt(){return`agent_group_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function Xt(e,t){let n=e?.trim();return n&&n.length>0?n:t}function Zt(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:Xt(e.label,i?.name??r)}}function Qt(e){return e.agentDef!==void 0}function $t(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 en(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 tn(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 nn(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 rn(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 an(e,t,n){if(e.agentId===void 0)return tn(e,t);try{let r=await n.wait(e.agentId);return nn({...e,agentId:e.agentId},t,r)}catch(n){let r=n instanceof Error?n.message:String(n);return rn({...e,agentId:e.agentId},t,r)}}async function on(e){let t=Yt(),n=e.jobs.map((t,n)=>Zt(t,n,e)),r=n.filter(e=>!Qt(e)).map(e=>$t(e,t)),i=await Promise.all(n.filter(Qt).map(t=>en(t,e))),a=await Promise.all(i.map(n=>an(n,t,e.manager))),o=[...r,...a].sort((e,t)=>e.index-t.index);return Jt({groupId:t,requestedJobCount:e.jobs.length,jobs:o})}function sn(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 cn(){return JSON.stringify({success:!1,mode:`single`,requestedJobCount:0,startedJobCount:0,failedJobCount:0,output:``,error:`Parallel subagents are disabled for the active preset.`,provenance:{source:`agent-tool-single`,requestedJobCount:0,startedJobCount:0,failedJobCount:0}})}function ln(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 un(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 dn=[{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
-
5
- Your role is to complete the assigned task thoroughly and accurately. Follow these guidelines:
6
-
7
- - Execute the task as described in the prompt. Do not expand scope beyond what is requested.
8
- - Use the most appropriate tools for each step. Prefer precise tools (Read, Grep, Glob) over broad ones (Bash) when possible.
9
- - Report your findings clearly and concisely when the task is complete.
10
- - If a task cannot be completed, explain why and what information is missing.
11
- - Maintain the same code quality standards as the parent session (strict types, no fallbacks, proper error handling).`},{name:`Explore`,description:`Read-only codebase exploration and analysis agent.`,systemPrompt:`You are a codebase exploration and analysis agent. Your purpose is to search, read, and understand code without making any modifications.
12
-
13
- You operate in read-only mode. You must NEVER attempt to write or edit files. Your tools are restricted to read-only operations: reading files, searching with grep and glob, and running non-destructive bash commands.
14
-
15
- Your role is to answer questions about the codebase by:
16
-
17
- - Searching for relevant files, symbols, and patterns using Glob and Grep.
18
- - Reading source files, configuration, and documentation to understand structure and behavior.
19
- - Tracing code paths across modules to understand how components interact.
20
- - Summarizing findings in a clear, structured format with file paths and line references.
21
- - Identifying architectural patterns, dependencies, and potential issues.
22
-
23
- When exploring, prefer targeted searches over broad scans. Start with the most likely locations and narrow down. Always include absolute file paths in your responses so the caller can navigate directly to relevant code.`,disallowedTools:[`Write`,`Edit`]},{name:`Plan`,description:`Read-only planning, research, and architecture agent.`,systemPrompt:`You are a planning, research, and architecture agent. Your purpose is to analyze requirements, research approaches, and produce structured plans without making any code modifications.
24
-
25
- You operate in read-only mode. You must NEVER attempt to write or edit files. Your tools are restricted to read-only operations.
26
-
27
- Your role is to:
28
-
29
- - Analyze the current codebase state relevant to the task by reading specs, source code, and tests.
30
- - Research implementation approaches by examining existing patterns and architectural conventions in the repository.
31
- - Identify affected files, modules, and interfaces that a proposed change would touch.
32
- - Assess risks, dependencies, and potential breaking changes.
33
- - Produce a structured implementation plan with clear steps, file lists, and ordering.
34
- - Consider edge cases, error handling, and test coverage requirements.
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 fn(e){return dn.find(t=>t.name===e)}function pn(){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
-
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
-
40
- Do not use emojis.`}function mn(){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
- - Scope: What was requested
42
- - Result: What was done
43
- - Key files: Relevant file paths (absolute)
44
- - Files changed: List of modifications
45
- - Issues: Any problems encountered`}function hn(e){let t=[e.agentBody];e.claudeMd&&t.push(e.claudeMd),e.agentsMd&&t.push(e.agentsMd);let n=e.isForkWorker?mn():pn();return t.push(n),t.join(`
46
-
47
- `)}const gn=`robota_command_`,_n=/^[A-Za-z0-9_-]{1,64}$/;function vn(e){return e}function F(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function yn(e){let t=F(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=`${gn}${n}`;if(_n.test(r))return r;let i=De(`sha256`).update(t).digest(`hex`).slice(0,8),a=`${gn}${n.slice(0,40).replace(/[_-]+$/g,``)||`command`}_${i}`;if(!_n.test(a))throw Error(`Projected model command tool name is not provider-safe: ${a}`);return a}function bn(e){let t=new Set,n=new Map,r=new Map,i=[];for(let a of e){let e=F(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=yn(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:Tn(e,a),descriptor:a,requiresPermission:a.requiresPermission!==!1})}return{commandTools:i,toolNameToCommandName:n,commandNameToToolName:r}}function xn(e){return`${e.toolName} — ${e.descriptor.description}`}function Sn(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 Cn(e){return bn(e.commandDescriptors).commandTools.map(t=>{let n=wn(t.descriptor);return he(t.toolName,t.description,vn(n),async r=>{let i=n.parse(r);return e.isModelInvocable(t.commandName)?Sn(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 wn(e){let t=e.argumentHint?`Arguments for the command. Expected grammar: ${e.argumentHint}`:`Arguments for the command as a single string.`;return v.object({args:v.string().optional().describe(t)})}function Tn(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
-
49
- `)}const En={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`,opus:`claude-opus-4-6`},Dn=yn(`agent`);function On(e,t){return En[e]??e}function kn(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()!==Dn),n}function An(e){let{agentDefinition:t,parentConfig:n,parentContext:r,parentTools:i,terminal:a}=e,o=kn(i,t),s=t.model?On(t.model,n.provider.model):n.provider.model,c=hn({agentBody:t.systemPrompt,claudeMd:r.claudeMd,agentsMd:r.agentsMd,isForkWorker:e.isForkWorker??!1}),l=e.provider;return new Se({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 jn(e,t){let n=t?.(e)??fn(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Mn(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 Nn(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function Pn(e){if(e.request.isolation===`worktree`)throw Error(`Worktree isolation requires a runtime shell subagent runner`)}function Fn(e,t){if(t.type===`start`){e.emit?.({type:`background_task_tool_start`,toolName:t.toolName,firstArg:Nn(t.toolArgs)});return}e.emit?.({type:`background_task_tool_end`,toolName:t.toolName,success:t.success??!0})}function In(e){return{start(t){Pn(t);let n=An({agentDefinition:Mn(jn(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=>{Fn(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 Ln=[`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 Rn(e){return e}const zn=v.object({prompt:v.string().optional().describe(`The task for a single subagent to perform. Required when jobs is omitted.`),subagent_type:v.string().optional().describe(`Agent type: "general-purpose", "Explore", "Plan", or a custom agent name`),model:v.string().optional().describe(`Optional model override`),isolation:v.enum([`none`,`worktree`]).optional().describe(`Optional runtime isolation mode. "worktree" runs in a Git worktree.`),jobs:v.array(v.object({label:v.string().optional().describe(`Stable role label for this batch job`),prompt:v.string().describe(`The task for this subagent to perform`),subagent_type:v.string().optional().describe(`Agent type for this job`),model:v.string().optional().describe(`Optional model override for this job`),isolation:v.enum([`none`,`worktree`]).optional().describe(`Isolation for this job`)}).passthrough()).optional().describe(`Batch of subagent jobs to start in one Agent tool call`)}).passthrough(),Bn=new WeakMap;function Vn(e,t){Bn.set(e,t)}function I(e){return Bn.get(e)}function Hn(e,t){if(t){let n=t(e);if(n)return n}let n=fn(e);if(n)return n}function Un(e){return e.subagentManager??new ae({runner:In(e)})}function Wn(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:M({kind:`tool_call`,sessionId:r.parentSessionId??`unknown-session`,label:i,...a?{toolCallId:a}:{}})}}async function Gn(e,t,n,r){if(typeof e.prompt!=`string`||e.prompt.length===0)return un(`prompt is required when jobs is omitted`);let i={...e,prompt:e.prompt},a=e.subagent_type??`general-purpose`,o=Hn(a,t.customAgentRegistry);if(!o)return sn(a);let s;try{let e=await n.spawn(Wn(i,a,o,t,void 0,r));return s=e.id,ln(await n.wait(e.id))}catch(e){return un(e instanceof Error?e.message:String(e),s)}}function Kn(e){let t=Un(e);return he(`Agent`,Ln,Rn(zn),async(n,r)=>{let i=n,a=r?.executionId;return e.isParallelSubagentsEnabled!==void 0&&!e.isParallelSubagentsEnabled()?cn():Array.isArray(i.jobs)&&i.jobs.length>0?on({jobs:i.jobs,deps:e,manager:t,resolveAgentDefinition:Hn,createSpawnRequest:Wn,toolCallId:a}):Gn({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 qn=class{getManager;onChanged;emitTaskEvent;emitGroupEvent;persistSession;onWake;appendSystemNote;backgroundTasks=[];backgroundTaskEvents=[];backgroundJobGroups=[];backgroundJobGroupEvents=[];backgroundTaskUnsubscribe=null;backgroundJobUnsubscribe=null;backgroundJobOrchestrator=null;constructor(e,t,n,r,i,a,o){this.getManager=e,this.onChanged=t,this.emitTaskEvent=n,this.emitGroupEvent=r,this.persistSession=i,this.onWake=a,this.appendSystemNote=o}subscribe(e){if(this.backgroundTaskUnsubscribe)return;let t=qt(e)??I(e)?.backgroundTaskManager;t&&(this.backgroundTaskUnsubscribe=t.subscribe(e=>{this.recordTaskEvent(e),this.emitTaskEvent(e),e.type===`background_task_waking`&&e.instruction!==void 0&&this.onWake?.(e.instruction,e.taskId)}),this.reArmRestoredSchedules(t))}reArmRestoredSchedules(e){let t=Date.now();for(let n of this.backgroundTasks)n.kind!==`scheduled`||n.status!==`sleeping`||!n.schedule||(n.nextFireAt!==void 0&&new Date(n.nextFireAt).getTime()<t&&this.appendSystemNote?.(`Missed scheduled wake "${n.label}" (was due ${n.nextFireAt} while the session was closed); re-arming.`),e.spawn({kind:`scheduled`,cronExpression:n.schedule.cronExpression,label:n.label,mode:n.mode,parentSessionId:n.parentSessionId,depth:n.depth,cwd:n.cwd,...n.schedule.agentInstruction===void 0?{}:{agentInstruction:n.schedule.agentInstruction},...n.schedule.command===void 0?{}:{command:n.schedule.command},...n.schedule.shell===void 0?{}:{shell:n.schedule.shell},...n.schedule.env===void 0?{}:{env:{...n.schedule.env}}}))}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 st({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 zt({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 zt({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 zt({entryId:e,lines:ft(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`,Jn(e))}recordGroupEvent(e,t){this.backgroundJobGroups=this.getGroupSnapshots(),this.backgroundJobGroupEvents.push(e),this.persistSession(),this.onChanged(`background_group`,vt(e.group.id))}};function Jn(e){if(`task`in e)return _t(e.task.id);if(`taskId`in e)return _t(e.taskId)}function Yn(e){let t=I(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 L(e){let t=Yn(e);if(!t.subagentManager)throw Error(`Subagent manager is not available for this session.`);return t.subagentManager}function Xn(e,t){let n=t.customAgentRegistry?.(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Zn(e){return(I(e)?.agentDefinitions??[]).map(e=>({name:e.name,description:e.description}))}async function Qn(e,t,n,r){let i=Yn(e),a=Xn(t.agentType,i),o=e.getSessionId();return L(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:M({kind:r===`model`?`model_command`:`slash_command`,sessionId:o,commandName:`agent`,label:t.label})})}async function $n(e,t){return L(e).wait(t)}async function er(e,t,n){await L(e).send(t,n)}async function tr(e,t,n){await L(e).cancel(t,n)}async function nr(e,t){await L(e).close(t)}function rr(e){return L(e).list()}function ir(e,t={}){let{sessionId:n,execCtrl:r,histTracker:i,bgTracker:a}=e,o=i.getHistory();return bt({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 ar(e,t,n,r,i){let a=yt(e);if(!a)throw Error(`Unknown execution workspace entry: ${e}`);return a.kind===`main_thread`?Rt({entryId:e,history:t(),cursor:i}):a.kind===`background_group`?n.readGroupDetail(e,a.sourceId,r):n.readTaskDetail(e,a.sourceId,i)}function or(e,t,n,r){return Ht({manager:e.getManagerOrThrow(),groupOrchestrator:e.getOrchestratorOrThrow(t),sessionId:t,cwd:n,origin:{...r,sessionId:r.sessionId||t}})}var sr=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 ir({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(),ar(e,()=>this.histTracker.getHistory(),this.bgTracker,this.getSessionOrThrow().getSessionId(),t)}createExecutionWorkspaceTaskSpawner(e){return or(this.bgTracker,this.getSessionOrThrow().getSessionId(),this.getCwd(),e)}listAgentDefinitions(){return Zn(this.getSessionOrThrow())}listAgentJobs(){return rr(this.getSessionOrThrow())}async spawnAgentJob(e){return await this.ensureInitialized(),Qn(this.getSessionOrThrow(),e,this.getCwd(),this.skillRouter.getCommandInvocationSource())}async waitAgentJob(e){return await this.ensureInitialized(),$n(this.getSessionOrThrow(),e)}async sendAgentJob(e,t){await this.ensureInitialized(),await er(this.getSessionOrThrow(),e,t)}async cancelAgentJob(e,t){await this.ensureInitialized(),await tr(this.getSessionOrThrow(),e,t)}async closeAgentJob(e){await this.ensureInitialized(),await nr(this.getSessionOrThrow(),e)}async spawnScheduledWake(e){return await this.ensureInitialized(),this.bgTracker.getManagerOrThrow().spawn({kind:`scheduled`,label:e.label,mode:`background`,parentSessionId:this.getSessionOrThrow().getSessionId(),depth:0,cwd:this.getCwd(),cronExpression:e.cronExpression,agentInstruction:e.agentInstruction})}async spawnMonitorWake(e){return await this.ensureInitialized(),this.bgTracker.getManagerOrThrow().spawn({kind:`process`,label:e.label,mode:`background`,parentSessionId:this.getSessionOrThrow().getSessionId(),depth:0,cwd:this.getCwd(),command:e.command,matchPattern:e.matchPattern,agentInstruction:e.agentInstruction})}},R=class{existsSync(e){return b(e)}readFileSync(e,t){return x(e,t)}writeFileSync(e,t,n){Le(e,t,n??`utf8`)}mkdirSync(e,t){je(e,t)}readdirSync(e,t){return t?.withFileTypes?Me(e,{withFileTypes:!0}):Me(e)}statSync(e){return Fe(e)}rmSync(e,t){Pe(e,t)}cpSync(e,t,n){ke(e,t,n)}renameSync(e,t){Ne(e,t)}get constants(){return Oe}},z=class{async access(e,t){await Re(e,t)}async copyFile(e,t,n){await ze(e,t,n)}async mkdir(e,t){await Be(e,t)}async readFile(e,t){return Ve(e,t)}async readdir(e,t){return t?.withFileTypes?await He(e,{withFileTypes:!0}):He(e)}async realpath(e){return Ue(e)}async rename(e,t){await We(e,t)}async rm(e,t){await Ge(e,t)}async stat(e){return Ke(e)}async writeFile(e,t,n){await qe(e,t,n??`utf8`)}};function cr(e){return De(`sha256`).update(e,`utf-8`).digest(`hex`)}function lr(e,t=new R){let n=t.readFileSync(e,`utf-8`);return{filePath:e,content:n,contentHash:cr(n)}}async function ur(e,t=new R){let n=[],r=[];for(let i of e){if(!t.existsSync(i.filePath)){r.push(i);continue}cr(t.readFileSync(i.filePath,`utf-8`))===i.contentHash?r.push(i):n.push(i)}return{stale:n,fresh:r}}async function dr(e,t=new R){let{stale:n}=await ur(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:cr(n)}}),refreshed:i}}async function fr(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 dr(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
-
51
- `),d.map(e=>e.content).join(`
52
-
53
- `));i().updateSystemMessage(f);for(let e of l)a(`context_file_refreshed`,{filePath:e})}function pr(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 mr(e,t,n){let r=e.find(e=>e.sourcePath===t.sourcePath),i=e.filter(e=>e.sourcePath!==t.sourcePath),a=r?yr(r,t):t;return br([...i,a],n)}function hr(e,t){let n=Cr(t),r=e.find(e=>wr(e,n));return r?{references:e.filter(e=>e.sourcePath!==r.sourcePath),result:{removed:r}}:{references:[...e],result:{}}}function gr(e){return{removed:[...e]}}function _r(e){return e.filter(e=>e.status===`active`)}function vr(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 yr(e,t){return t.status===`active`?{...t,loadedAt:e.loadedAt}:{...e,byteLength:t.byteLength,originalReference:t.originalReference,lastUsedAt:t.lastUsedAt}}function br(e,t){let n=t?.maxActiveReferences??8,r=t?.maxActiveBytes??262144,i=t?.maxObservedReferences??32,a=[],o=[...e];for(;xr(o)>n||Sr(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 xr(e){return e.filter(e=>e.status===`active`).length}function Sr(e){return e.reduce((e,t)=>e+(t.status===`active`?t.byteLength:0),0)}function Cr(e){return e.startsWith(`@`)?e.slice(1):e}function wr(e,t){return e.relativePath===t||e.sourcePath===t||e.originalReference===t||e.originalReference===`@${t}`}function Tr(e,t){return t.length===0?e:[e,`<robota_file_references>`,...t.map(e=>{let t=e.content.replaceAll(`</file>`,`<\\/file>`);return[`<file path="${kr(e.relativePath)}" bytes="${e.byteLength}" reason="${e.reason}">`,t,`</file>`].join(`
54
- `)}),`</robota_file_references>`].join(`
55
-
56
- `)}function Er(e){return e.some(e=>e.severity===`error`)}function Dr(e){return e.length===0?``:[`File reference error:`,...e.map(e=>`- ${e.reference}: ${e.message}`)].join(`
57
- `)}function B(e){return e.map(({content:e,...t})=>t)}function Or(e){let t=B(e);return{id:`prompt_file_reference_${y()}`,timestamp:new Date,category:`event`,type:`prompt-file-reference`,data:{message:Ar(t),references:t}}}function kr(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function Ar(e){return`Loaded file references: ${e.map(e=>`${e.relativePath} (${e.byteLength} B)`).join(`, `)}`}const jr=/(^|[\s([{])@([^\s)\]}>,;"'`]+)/g;function Mr(e){let t=[];for(let n of e.matchAll(jr)){let e=Nr(n[2]??``);Pr(e)&&t.push({original:`@${e}`,path:e,index:n.index??0})}return t}function Nr(e){let t=e.length;for(;t>0&&/[.,:;!?]/.test(e[t-1]??``);)--t;return e.slice(0,t)}function Pr(e){return e.length===0||e.includes(`://`)?!1:e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)||e.startsWith(`~/`)||e.startsWith(`.`)||e.includes(`.`)}function Fr(e,t){return e.startsWith(`~/`)?E(D(),e.slice(2)):Ye(e)?E(e):E(t,e)}function Ir(e,t){let n=T(t,e);return n===``||!n.startsWith(`..`)&&!Ye(n)}function Lr(e,t){return T(e,t).split(Xe).join(`/`)}async function Rr(e,t){let n=await Br(t);for(let t of Mr(e))await Wr(t,0,[],n);return Vr(n)}async function zr(e,t){let n=await Br(t);for(let t of e)await Wr({original:`@${t}`,path:t,index:0},0,[],n);return Vr(n)}async function Br(e){let t=e.fsAsync??new z;return{rootPath:await Ur(e.cwd,t),limits:Hr(e.limits),reason:e.reason??`prompt-reference`,references:[],diagnostics:[],loadedPaths:new Set,totalBytes:0,fsAsync:t}}function Vr(e){return{references:e.references,diagnostics:e.diagnostics}}function Hr(e){return{maxDepth:e?.maxDepth??2,maxReferences:e?.maxReferences??8,maxFileBytes:e?.maxFileBytes??65536,maxTotalBytes:e?.maxTotalBytes??262144}}async function Ur(e,t){try{return await t.realpath(e)}catch{return E(e)}}async function Wr(e,t,n,r){if(!Gr(e,t,r))return;let i=await Kr(e,r);if(i===void 0||!qr(e,i,n,r))return;let a=await Jr(e,i,r);if(a===void 0)return;let o=await Yr(e,i,r);o!==void 0&&(r.loadedPaths.add(i),r.totalBytes+=a.byteLength,r.references.push(Xr(e,a,t,o,r)),await Zr(o,t,[...n,i],r))}function Gr(e,t,n){return n.references.length>=n.limits.maxReferences?(V(n,`too-many-references`,e,`Too many file references.`),!1):t>n.limits.maxDepth?(V(n,`max-depth`,e,`File reference nesting is too deep.`),!1):!0}async function Kr(e,t){let n=Fr(e.path,t.rootPath);if(!Ir(n,t.rootPath)){V(t,`outside-root`,e,`Referenced path is outside the workspace.`);return}try{let r=await t.fsAsync.realpath(n);if(Ir(r,t.rootPath))return r;V(t,`outside-root`,e,`Referenced path resolves outside the workspace.`)}catch{V(t,`not-found`,e,`Referenced file was not found.`)}}function qr(e,t,n,r){return n.includes(t)?(V(r,`circular-reference`,e,`Circular file reference detected.`),!1):!r.loadedPaths.has(t)}async function Jr(e,t,n){try{let r=await n.fsAsync.stat(t);if(r.isDirectory()){V(n,`directory-not-supported`,e,`Directory references are not supported.`);return}if(r.size>n.limits.maxFileBytes){V(n,`file-too-large`,e,`Referenced file exceeds the per-file size limit.`);return}if(n.totalBytes+r.size>n.limits.maxTotalBytes){V(n,`total-too-large`,e,`Referenced files exceed the total size limit.`);return}return{sourcePath:t,byteLength:r.size}}catch{V(n,`unreadable`,e,`Referenced file could not be inspected.`);return}}async function Yr(e,t,n){try{return await n.fsAsync.readFile(t,`utf8`)}catch{V(n,`unreadable`,e,`Referenced file could not be read.`);return}}function Xr(e,t,n,r,i){return{originalReference:e.original,sourcePath:t.sourcePath,relativePath:Lr(i.rootPath,t.sourcePath),reason:i.reason,depth:n,byteLength:t.byteLength,content:r}}async function Zr(e,t,n,r){for(let i of Mr(e))await Wr(i,t+1,n,r)}function V(e,t,n,r){e.diagnostics.push({code:t,severity:`error`,reference:n.original,message:r,path:n.path})}function Qr(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&(e.message.includes(`aborted`)||e.message.includes(`abort`))}function $r(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 ei(e,t,n,r,i,a){let o=$r(t,r),s=ai(t,r,i);return{response:e,history:n,toolSummaries:o,contextState:i,...s&&{usage:s},...a&&a.length>0?{promptFileReferences:[...a]}:{}}}function ti(e,t,n,r){let i=$r(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=ai(e,n,r);return{response:a.join(`
58
-
59
- `),history:t,toolSummaries:i,contextState:r,...o&&{usage:o}}}function ni(e){return{id:`usage_${y()}`,timestamp:new Date,category:`event`,type:`usage-summary`,data:e}}async function ri(e,t,n,r=[]){let i=await zr(_r(r).map(e=>e.sourcePath),{cwd:t,reason:`manual`}),a=await Rr(e,{cwd:t}),o=[...i.diagnostics,...a.diagnostics];if(Er(o))throw Error(Dr(o));let s=Tr(e,ii([...i.references,...a.references])),c=n??(s===e?void 0:e),l=B(i.references),u=B(a.references),d=a.references.length>0?Or(a.references):void 0;return{modelInput:s,...c===void 0?{}:{hookInput:c},activeContextReferenceRecords:l,promptFileReferenceRecords:u,...d===void 0?{}:{promptFileReferenceEntry:d}}}function ii(e){return[...new Map(e.map(e=>[e.sourcePath,e])).values()]}function ai(e,t,n){let r=e.slice(t),i=0,a=0,s=!1;for(let e of r){if(e.role!==`assistant`)continue;let t=o(e);t&&(s=!0,i+=t.inputTokens,a+=t.outputTokens)}if(s)return{kind:`exact`,scope:`turn`,promptTokens:i,completionTokens:a,totalTokens:i+a,contextUsedTokens:n.usedTokens,contextMaxTokens:n.maxTokens,contextUsedPercentage:n.usedPercentage,costStatus:`unknown`}}const oi={write:()=>{},writeLine:()=>{},writeMarkdown:()=>{},writeError:()=>{},prompt:()=>Promise.resolve(``),select:()=>Promise.resolve(0),spinner:()=>({stop:()=>{},update:()=>{}})};function si(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 ci(e,t,n){let r=e?.[t]??e?.[n];return typeof r==`string`?r:null}function li(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 ui(e){if(e.toolName!==`Edit`)return{};let t=ci(e.toolArgs,`file_path`,`filePath`),n=ci(e.toolArgs,`old_string`,`oldString`),r=ci(e.toolArgs,`new_string`,`newString`);return!t||n===null||r===null||n===r?{}:{diffFile:t,diffLines:fi(n,r,li(e.toolResultData),t)}}function di(e,t,n){return[...e.split(`
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 fi(e,t,n,r,i=new R){let a=di(e,t,n),o;try{o=i.readFileSync(r,`utf8`).split(`
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
- `).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
- `).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 pi(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:y(),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 mi(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 hi(e,t){let n=si(t.toolArgs),r={toolName:t.toolName,firstArg:n,isRunning:!0,...t.executionId?{executionId:t.executionId}:{}};return e.activeTools.push(r),e.history.push({id:y(),timestamp:new Date,category:`event`,type:`tool-start`,data:{toolName:t.toolName,firstArg:n,isRunning:!0}}),r}function gi(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],...ui(t),isRunning:!1,result:n,toolResultData:t.toolResultData};return e.activeTools[r]=i,e.activeTools=mi(e.activeTools),e.history.push({id:y(),timestamp:new Date,category:`event`,type:`tool-end`,data:{toolName:i.toolName,firstArg:i.firstArg,isRunning:!1,result:n,toolResultData:t.toolResultData}}),i}const _i=[{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 vi(t){if(t instanceof e)return"Invalid API key. Run `/provider` to reconfigure, or check your settings file (~/.robota/settings.json).";if(t instanceof i)return`Rate limit reached${t.retryAfter?` (retry after ${t.retryAfter}s)`:``}. Wait a moment and try again. Consider switching to a different model with \`/model\`.`;if(t instanceof n)return`Network connection failed. Check your internet connection and verify your provider URL in settings.`;if(t instanceof r&&t.originalError)return vi(t.originalError);let a=t.message;for(let{pattern:e,message:t}of _i)if(e.test(a))return t;return a}async function yi(e,t,n,r){let i=r.getHistory();i.push(_(l(t??e))),r.onWorkspaceUpdated();let a=r.getSession().getHistory().length;r.resetUsedMemoryReferences();try{let o=await ri(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 c=await r.getSession().run(o.modelInput,o.hookInput);r.flushStreaming(),pi({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let l=ei(c||`(empty response)`,r.getSession().getHistory(),i,a,r.getSession().getContextState(),o.promptFileReferenceRecords);i.push(_(s(l.response))),l.usage&&i.push(ni(l.usage)),r.onComplete(l),r.onContextUpdate()}catch(e){if(r.flushStreaming(),Qr(e)){let e=ti(r.getSession().getHistory(),i,a,r.getSession().getContextState());pi({activeTools:r.getActiveTools(),history:i}),r.clearStreaming(),e.response&&i.push(_(s(e.response))),e.usage&&i.push(ni(e.usage)),i.push(_(c(`Interrupted by user.`))),r.onInterrupted(e)}else{pi({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let t=e instanceof Error?e:Error(String(e)),n=vi(t);i.push(_(c(`Error: ${n}`))),r.onError(t)}}}var bi=class{histTracker;skillRouter;callbacks;executing=!1;streamingText=``;flushTimer=null;activeTools=[];pendingPrompt=null;pendingDisplayInput;pendingRawInput;pendingTurnOptions={};shuttingDown=!1;wakeTaskIds=new Set;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,this.pendingTurnOptions={}}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(_(c(`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=hi(t,e);this.activeTools=t.activeTools,this.callbacks.emit(`tool_start`,n)}else{let n=gi(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,i=this.pendingTurnOptions;this.clearPendingQueue(),setTimeout(()=>void e(t,n,r,i),0)}}async executePrompt(e,t,n,r,i,a,o,s,c={}){await fr(r,i,a,o,()=>this.callbacks.getSessionOrThrow(),(e,t)=>this.callbacks.emit(e,t)),this.executing=!0,this.clearStreaming(),this.callbacks.emit(`turn_source`,c.turnSource??`user`),this.callbacks.emit(`user_message`,t??e),this.callbacks.emit(`thinking`,!0);try{await yi(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),c.wakeTaskId!==void 0&&this.wakeTaskIds.delete(c.wakeTaskId),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(_(l(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(_(c(`Error: ${vi(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(),pi({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(_(s(e))),this.callbacks.emit(`complete`,t),this.callbacks.emit(`context_update`,this.callbacks.getContextState())}};function xi(e,t,n){let r=I(n)?.customAgentRegistry?.(e)??fn(e);if(!r)throw Error(`Unknown agent type: ${e}`);return t.allowedTools?{...r,tools:t.allowedTools}:r}async function Si(e,t,n){let r=I(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);return An({agentDefinition:xi(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 Ci(e,t,n){let r=await zr([t],{cwd:n,reason:`manual`});if(Er(r.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[Dr(r.diagnostics)]}};let i=r.references[0];if(!i)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let a=pr(B([i])[0],`manual`,`active`),o=mr(e,a);return{references:o.references,result:{reference:a,evicted:o.evicted,diagnostics:[]}}}function wi(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=pr(e,n.loadType,n.status,r);i=mr(i,t).references}return i}function Ti(e,t){let n=new Date().toISOString();return e.map(e=>{let r=T(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 H(e){let t=w(e,`.robota`);return{settings:w(t,`settings.json`),settingsLocal:w(t,`settings.local.json`),logs:w(t,`logs`),sessions:w(t,`sessions`),memory:w(t,`memory`),checkpoints:w(t,`checkpoints`)}}function Ei(){let e=w(D(),`.robota`);return{settings:w(e,`settings.json`),sessions:w(e,`sessions`),onboarded:w(e,`onboarded`)}}function Di(e){let t=e.fs??new R,n=e.manifests.filter(t=>t.sequence>e.target.sequence),r=e.manifests.filter(t=>t.sequence>=e.target.sequence);return{target:Oi(e.target),capturedFiles:e.target.files.map(n=>{let r=n.snapshotFile?w(e.checkpointDir(e.sessionId,e.target.id),n.snapshotFile):void 0,i=r?Ai(r,t):void 0;return{originalPath:n.originalPath,relativePath:T(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:ki(n),rollbackThroughCheckpoint:ki(r)}}function Oi(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function ki(e){return{checkpointIds:e.map(e=>e.id),fileCount:e.reduce((e,t)=>e+t.fileCount,0)}}function Ai(e,t){try{return t.statSync(e)}catch{return}}const ji=`manifest.json`,Mi=`files`;var Ni=class{fs;fsAsync;cwd;rootDir;now;activeTurn=null;constructor(e,t=new R,n=new z){this.fs=t,this.fsAsync=n,this.cwd=E(e.cwd),this.rootDir=H(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=w(this.sessionDir(e.sessionId),n);await this.fsAsync.mkdir(w(r,Mi),{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},U(i)}async captureFile(e){if(!this.activeTurn)return;let t=E(this.cwd,e);if(this.activeTurn.capturedPaths.has(t)||Fi(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),U(e.manifest)}list(e){return this.loadManifests(e).map(U)}inspect(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);return Di({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:U(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:U(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async createFileRecord(e,t){if(!await Ii(this.fsAsync,this.fs,e))return{originalPath:e,existed:!1};let n=w(Mi,`${String(t.manifest.files.length+1).padStart(6,`0`)}.content`);return await this.fsAsync.copyFile(e,w(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(C(n.originalPath),{recursive:!0}),await this.fsAsync.copyFile(w(this.checkpointDir(e,t),n.snapshotFile),n.originalPath)}loadManifests(e){let t=this.sessionDir(e);return Li(this.fs,t).map(e=>w(t,e,ji)).map(e=>Ri(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=w(e,ji),r=`${n}.tmp`;await this.fsAsync.writeFile(r,JSON.stringify(t,null,2),`utf8`),await this.fsAsync.rename(r,n)}sessionDir(e){return w(this.rootDir,Pi(e))}checkpointDir(e,t){return w(this.sessionDir(e),Pi(t))}};function U(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function Pi(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function Fi(e,t){let n=T(e,t);return n.length===0||!n.startsWith(`..`)&&!n.startsWith(`/`)}async function Ii(e,t,n){try{return await e.access(n,t.constants.F_OK),!0}catch{return!1}}function Li(e,t){try{return e.readdirSync(t)}catch{return[]}}function Ri(e,t){try{let n=e.readFileSync(t,`utf8`);return JSON.parse(n)}catch{return}}function zi(e){return e.source===`plugin`?`plugin`:`skill`}function Bi(e){return e.context===`fork`?`fork`:`inject`}function Vi(e){return{type:`skill-activation`,skillName:e.skill.name,source:zi(e.skill),invocation:e.invocation,mode:Bi(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function Hi(e){let t=e.source===`plugin`?`plugin skill`:`skill`;return e.status===`failed`?`Skill failed: ${e.skillName}${e.error?` (${e.error})`:``}`:e.status===`completed`?`Skill completed: ${e.skillName}`:`Invoking ${t}: ${e.skillName}`}const Ui=new Set([`memory_candidate_saved`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`]);function Wi(e){let t=e.topic?`: ${e.topic}`:``;switch(e.type){case`memory_candidate_saved`:return`Memory saved${t}`;case`memory_candidate_approved`:return`Memory approved${t}`;case`memory_candidate_rejected`:return`Memory rejected${t}${e.reason?` (${e.reason})`:``}`;case`memory_retrieved`:return`Memory recalled${t}`;case`memory_candidate_extracted`:return`Memory candidate extracted${t}`;case`memory_candidate_queued`:return`Memory candidate queued${t}`;case`memory_candidate_skipped`:return`Memory candidate skipped${t}${e.reason?` (${e.reason})`:``}`}}var Gi=class{cwd;getSessionId;getExecuting;persistSession;emitSkillActivation;emitMemoryEvent;history=[];editCheckpointStore=null;memoryEvents=[];usedMemoryReferences=[];contextReferences=[];systemContextReferences=[];skillActivationEvents=[];constructor(e,t,n,r,i,a,o=null){this.cwd=e,this.getSessionId=t,this.getExecuting=n,this.persistSession=r,this.emitSkillActivation=i,this.emitMemoryEvent=a,this.editCheckpointStore=o}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=wi(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=wi(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(_(c(`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(_(c(`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(_(c(`Checkpoint error: ${t.message}`))),t}}setEditCheckpointStore(e){this.editCheckpointStore=e}getUsedMemoryReferences(){return[...this.usedMemoryReferences]}recordMemoryEvent(e){this.memoryEvents.push(e),Ui.has(e.type)&&this.history.push({id:y(),timestamp:new Date(e.at),category:`event`,type:`memory-event`,data:{...e,message:Wi(e)}}),this.emitMemoryEvent(e),this.persistSession()}recordSystemContextFiles(e){this.systemContextReferences=Ti(e,this.cwd)}listContextReferences(){return[...this.systemContextReferences,...this.contextReferences]}listInjectionContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await Ci(this.contextReferences,e,this.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=hr(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=gr(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,t){this.skillActivationEvents.push(e),t&&this.history.push({id:y(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:Hi(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){return this.editCheckpointStore||=new Ni({cwd:this.cwd}),this.editCheckpointStore}};function Ki(e){if(O(e))try{return JSON.parse($e(e,`utf-8`))}catch{return}}function qi(e){if(O(k(e,`pnpm-workspace.yaml`))||O(k(e,`pnpm-lock.yaml`)))return`pnpm`;if(O(k(e,`yarn.lock`)))return`yarn`;if(O(k(e,`bun.lockb`)))return`bun`;if(O(k(e,`package-lock.json`)))return`npm`}async function Ji(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(O(t)){let r=Ki(t),i=O(n)?`typescript`:`javascript`,a=qi(e);return{type:`node`,name:r?.name,packageManager:a,language:i}}return O(r)||O(k(e,`setup.py`))?{type:`python`,language:`python`}:O(i)?{type:`rust`,language:`rust`}:O(a)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}function Yi(e,t){e.injectRawMessage(t)}function Xi(e,t,n){let r=e.load(t);if(!r)return{history:[],sessionName:void 0,pendingRestoreMessages:null,backgroundTasks:[],backgroundTaskEvents:[],backgroundJobGroups:[],backgroundJobGroupEvents:[],skillActivationEvents:[],memoryEvents:[],usedMemoryReferences:[],contextReferences:[],sandboxSnapshotId:void 0};let i=r.history??[],a=r.backgroundTasks??[],o=r.backgroundTaskEvents??[],s=r.backgroundJobGroups??[],c=r.backgroundJobGroupEvents??[],l=r.skillActivationEvents??[],u=r.memoryEvents??[],d=r.usedMemoryReferences??[],f=r.contextReferences??[],p=r.sandboxSnapshotId,{backgroundTasks:m,backgroundTaskEvents:ee}=Zi(a,o),h=r.name,g=null;if(r.messages)if(n)for(let e of r.messages)Yi(n,e);else g=r.messages;return{history:i,sessionName:h,pendingRestoreMessages:g,backgroundTasks:m,backgroundTaskEvents:ee,backgroundJobGroups:s,backgroundJobGroupEvents:c,skillActivationEvents:l,memoryEvents:u,usedMemoryReferences:d,contextReferences:f,sandboxSnapshotId:p}}function Zi(e,t){let n=new Date().toISOString(),r=[];return{backgroundTasks:e.map(e=>{if(Qi(e.status)||$i(e))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 Qi(e){return e===`completed`||e===`failed`||e===`cancelled`}function $i(e){return e.kind===`scheduled`&&e.status===`sleeping`&&e.schedule!==void 0}function ea(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 ta(e,t,n,r){let i=ea(e);!i||!(`task`in e)||re(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 na=[`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 ra(e={}){return[de(e),pe(e),me(e),fe(e),ge,_e,ve,ye]}const ia=new Set([`tools`,`disallowedTools`]),aa=new Set([`maxTurns`]);function oa(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function sa(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();ia.has(i)?r[i]=oa(a):aa.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 W(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=w(e,i.name),{frontmatter:a,body:o}=sa(t.readFileSync(r,`utf-8`)),s=Je(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 ca=class{cwd;home;fs;constructor(e,t,n=new R){this.cwd=e,this.home=t??D(),this.fs=n}loadAll(){let e=[W(w(this.cwd,`.robota`,`agents`),this.fs),W(w(this.cwd,`.agents`,`agents`),this.fs),W(w(this.cwd,`.claude`,`agents`),this.fs),W(w(this.home,`.robota`,`agents`),this.fs),W(w(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 dn)t.has(e.name)||r.push(e);return r}getAgent(e){return this.loadAll().find(t=>t.name===e)}};function la(e){let t=e.content.trim();return e.title?[`## ${e.title}`,t].join(`
69
- `):t}function ua(e){return[...e].filter(e=>e.content.trim().length>0).sort((e,t)=>e.priority-t.priority||e.id.localeCompare(t.id)).map(e=>la(e)).join(`
70
-
71
- `)}function G(e,t,n,r,i){return{id:e,title:t,priority:n,content:r,source:i}}function da(e){return G(`preset-persona`,void 0,5,e,`persona`)}function fa(){return G(`preset-self-verification`,void 0,6,`Before you report a task complete, verify your work against this session's tool results — re-run the relevant checks and confirm the outcome matches what was asked. If something is not yet verified, say so plainly rather than implying it is done.`,`self-verification`)}function pa(e){if(e)return G(`runtime-cwd`,`Working Directory`,30,`\`${e}\``,`runtime`)}function ma(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 ha(e){return G(`permission-mode`,`Permission Mode`,50,`- **Permission mode:** ${e}`,`permissions`)}function ga(e){if(!(e===void 0||e.trim().length===0))return G(`runtime-response-language`,`Response Language`,45,e,`runtime`)}function _a(e){if(e.trim().length!==0)return G(`project-agents-md`,`Agent Instructions`,10,e,`project-instructions`)}function va(e){if(e.trim().length!==0)return G(`project-claude-md`,`Project Notes`,20,e,`project-instructions`)}function ya(e){if(!(e===void 0||e.trim().length===0))return G(`project-memory`,`Project Memory`,25,e,`project-instructions`)}function ba(e){if(!(e===void 0||e.trim().length===0))return G(`active-task-context`,`Active Task Context`,27,e,`project-instructions`)}function xa(e){if(e.length!==0)return G(`tool-descriptions`,`Available Tools`,60,e.map(e=>`- ${e}`).join(`
73
- `),`tool`)}function Sa(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}`}function Ca(e,t,n,r,i){let a=i.filter(t=>t.modelInvocable&&t.kind===e).map(Sa);if(a.length!==0)return G(`capability-${e}`,t,n,a.join(`
74
- `),r)}function wa(e){let t=[],n=Ca(`builtin-command`,`Built-in Commands`,70,`command`,e),r=Ca(`skill`,`Skills`,80,`skill`,e),i=Ca(`agent`,`Agents`,90,`agent`,e),a=Ca(`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 Ta(e){return e.map(e=>({name:e.name,kind:`skill`,description:e.description,userInvocable:!0,modelInvocable:e.disableModelInvocation!==!0}))}function Ea(e){return e.map(e=>({name:e.name,kind:`agent`,description:e.description,userInvocable:!1,modelInvocable:!0,safety:`background-agent`}))}function Da(e){return[...e.commandDescriptors??[],...e.skills?Ta(e.skills):[],...e.agents?Ea(e.agents):[]]}function Oa(e){let t=[];return K(t,e.persona!==void 0&&e.persona.trim().length>0?da(e.persona):void 0),K(t,e.selfVerification===!0?fa():void 0),K(t,_a(e.agentsMd)),K(t,va(e.claudeMd)),K(t,ya(e.memoryMd)),K(t,ba(e.taskContext)),K(t,pa(e.cwd)),t.push(ma(e.projectInfo)),K(t,ga(e.language)),t.push(ha(e.permissionMode)),K(t,xa(e.toolDescriptions)),t.push(...wa(Da(e))),ua(t)}function ka(e){return e}const Aa=v.object({command:v.string().describe(`The shell command to start in the background`),timeout:v.number().optional().describe(`Optional timeout in milliseconds. Default is 120000.`),workingDirectory:v.string().optional().describe(`Working directory for the command. Defaults to the current project directory.`),stdin:v.string().optional().describe(`Optional stdin to write after the process starts.`),outputLimitBytes:v.number().optional().describe(`Maximum captured output bytes kept in the task result.`)});function ja(e,t,n){return JSON.stringify({success:!0,background:!0,output:``,taskId:e,status:t,command:n})}function Ma(e){return JSON.stringify({success:!1,background:!0,output:``,error:`Background process error: ${e}`})}async function Na(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 ja(n.id,n.status,e.command)}catch(e){return Ma(e instanceof Error?e.message:String(e))}}function Pa(e){return he(`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.`,ka(Aa),async t=>Na(t,e))}function Fa(e,t,n,r,i,a){let o,s=[],c;if(e.enableAgentRuntime||e.enableParallelSubagents){let l=new ca(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 ae({runner:(e.subagentRunnerFactory??In)(o),backgroundTaskRunners:e.backgroundTaskRunners});o.subagentManager=u,c=u.getBackgroundTaskManager(),o.backgroundTaskManager=c}else c=new ie({runners:e.backgroundTaskRunners??[]});let l=e.sessionLogger;return l&&c.subscribe(e=>Ba(l,t,e)),c.subscribe(t=>ta(t,n,e.config.hooks,a.length>0?a:void 0)),{agentToolDeps:o,agentDefinitions:s,backgroundTaskManager:c}}function Ia(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:M({kind:`tool_call`,sessionId:n,label:`BackgroundProcess`})};return i.push(Pa(a)),{backgroundProcessToolDeps:a}}function La(e,t,n,r,i){return{agentsMd:e.context.agentsMd,claudeMd:e.context.claudeMd,memoryMd:e.context.memoryMd,taskContext:e.context.taskContext,toolDescriptions:n,permissionMode:e.permissionMode??a[e.config.defaultTrustLevel]??`default`,projectInfo:e.projectInfo??{type:`unknown`,language:`unknown`},cwd:t,language:e.config.language,skills:r.map(e=>({name:e.name,description:e.description,disableModelInvocation:e.disableModelInvocation})),...i.length>0?{agents:i.map(e=>({name:e.name,description:e.description}))}:{},commandDescriptors:e.commandDescriptors??[]}}function Ra(e,t,n,r,i,a,o){let s=e.systemPromptBuilder??Oa,c=[...na,...r?r.commandTools.map(xn):[]],l=e.toolDescriptions??(i?[...c,`BackgroundProcess — start long-running shell commands as managed background tasks`]:c),u=e.persona,d=e.selfVerification,f=La(e,t,l,a,o),p=s({...f,...u===void 0?{}:{persona:u},...d===void 0?{}:{selfVerification:d}});return{finalSystemMessage:e.appendSystemPrompt?`${p}\n\n${e.appendSystemPrompt}`:p,rebuildSystemMessage:(t,n,r)=>{r?.persona!==void 0&&(u=r.persona),r?.selfVerification!==void 0&&(d=r.selfVerification);let i=s({...f,...u===void 0?{}:{persona:u},...d===void 0?{}:{selfVerification:d},agentsMd:t,claudeMd:n});return e.appendSystemPrompt?`${i}\n\n${e.appendSystemPrompt}`:i}}}function za(e,t,n,r){t&&(t.parentSessionId=e.getSessionId()),t&&(t.isParallelSubagentsEnabled=()=>e.getParallelSubagentsEnabled()),n&&(n.parentSessionId=e.getSessionId()),Kt(e,r),t&&Vn(e,t)}function Ba(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 Va=new Set([`Write`,`Edit`]);function Ha(e,t){return e.map(e=>Va.has(e.getName())?new Ua(e,t):e)}var Ua=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=Wa(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 Wa(e){if(!e||typeof e!=`object`)return;let t=e.filePath;return typeof t==`string`&&t.length>0?t:void 0}const Ga=new Set([`disable-model-invocation`,`user-invocable`]),Ka=new Set([`allowed-tools`]);function qa(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Ja(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Ya(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=qa(a);Ga.has(a)?n[s]=o===`true`:Ka.has(a)?n[s]=Ja(o):n[s]=o}return Object.keys(n).length>0?n:null}function Xa(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 Za(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=w(e,i.name,`SKILL.md`);if(!t.existsSync(r))continue;let a=t.readFileSync(r,`utf-8`),o=Ya(a);n.push(Xa(o,a,i.name))}return n}function Qa(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=w(e,i.name),a=t.readFileSync(r,`utf-8`),o=Ya(a),s=Je(i.name,`.md`);n.push(Xa(o,a,s))}return n}var $a=class{name=`skill`;cwd;home;fs;cachedCommands=null;constructor(e,t,n=new R){this.cwd=e,this.home=t??D(),this.fs=n}getCommands(){if(this.cachedCommands)return this.cachedCommands;let e=[Za(w(this.cwd,`.claude`,`skills`),this.fs),Qa(w(this.cwd,`.claude`,`commands`),this.fs),Za(w(this.home,`.robota`,`skills`),this.fs),Za(w(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)}},eo=class extends Error{filePath;constructor(e,t){super(`Settings file ${e} contains invalid JSON: ${t}. Fix or delete the file, or run robota diagnose.`),this.name=`SettingsParseError`,this.filePath=e}};function to(){return w(process.env.HOME??process.env.USERPROFILE??`/`,`.robota`,`settings.json`)}function no(e,t){return t===void 0||t===`user`?to():w(e,`.robota`,`settings.local.json`)}function q(e){if(!b(e))return{};let t=x(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new eo(e,t instanceof Error?t.message:String(t))}}function J(e,t){je(C(e),{recursive:!0}),Le(e,JSON.stringify(t,null,2)+`
76
- `,`utf8`)}function ro(e,t){let n=q(e),r=n.currentProvider,i=n.providers;if(typeof r==`string`&&io(i)){let e=i;e[r]={...io(e[r])?e[r]:{},model:t},n.providers=e}else n.provider={...io(n.provider)?n.provider:{},model:t};J(e,n)}function io(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function ao(e){return b(e)?(Ie(e),!0):!1}function oo(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var so=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=oo(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 co(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var lo=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=co(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 uo=new Set([`Write`,`Edit`]),fo=new Set([`Bash`,`BackgroundProcess`]),po=new Set([`Read`,`Glob`,`Grep`,`WebFetch`,`WebSearch`]);function mo(e){let t=e.toolName;return po.has(t)?{toolName:t,reversible:!0,sideEffect:`none`,rollbackLayer:`none`,status:`read-only`,message:`${t} does not mutate the local workspace.`}:uo.has(t)?e.context.isolation===`worktree`||e.context.isolation===`provider-sandbox`?_o(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.`}:fo.has(t)?_o(t,`shell-process`,e.context):t===`Agent`?vo(e.toolArgs,e.context):{toolName:t,reversible:!1,sideEffect:`unknown`,rollbackLayer:`none`,status:`unknown`,message:`${t} has no reversible execution contract.`}}function ho(e,t){let n={checkpointAvailable:t.checkpointAvailable,isolation:t.isolation??`none`},r=t.enforceUntrackedSideEffects??!0;return e.map(e=>new go(e,{safetyContext:n,enforceUntrackedSideEffects:r}))}var go=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=mo({toolName:this.getName(),toolArgs:So(e),context:this.options.safetyContext});return!n.reversible&&this.options.enforceUntrackedSideEffects?Co(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 _o(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 vo(e,t){return t.isolation===`worktree`||t.isolation===`provider-sandbox`?_o(`Agent`,`subagent`,t):yo(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 yo(e){if(!e)return!1;let t=e.jobs;return Array.isArray(t)?t.length>0&&t.every(e=>xo(e)?bo(e)===`worktree`:!1):bo(e)===`worktree`}function bo(e){let t=e.isolation;return typeof t==`string`?t:void 0}function xo(e){return e!==void 0&&typeof e==`object`&&!Array.isArray(e)}function So(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e}function Co(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 wo(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function To(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Eo(e,t){return e.some(e=>To(e.name)===t)}function Do(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??Oo(),i=new $a(n),a=wo(e.commandDescriptors),o=a.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,s=o?bn(a):void 0,c=Eo(a,`skills`)?i.getModelInvocableSkills():[],l=ra({sandboxClient:e.sandboxClient,cwd:n}),u=e.editCheckpointRecorder!==void 0&&e.sandboxClient===void 0,d=[...u&&e.editCheckpointRecorder?Ha(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?ho(d,{...f,checkpointAvailable:u}):d;o&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&p.push(...Cn({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:a}));let m=[];e.providerFactory&&m.push(new lo({providerFactory:e.providerFactory,defaultModel:e.config.provider.model})),e.sessionFactory&&m.push(new so({sessionFactory:e.sessionFactory})),e.additionalHookExecutors&&m.push(...e.additionalHookExecutors);let{agentToolDeps:ee,agentDefinitions:h,backgroundTaskManager:g}=Fa(e,r,n,t,p,m),{backgroundProcessToolDeps:te}=Ia(e,g,r,n,p),{finalSystemMessage:_,rebuildSystemMessage:ne}=Ra(e,n,a,s,te,c,h),re=[`Read(.agents/**)`,`Read(.claude/**)`,`Read(.robota/**)`,`Glob(.agents/**)`,`Glob(.claude/**)`,`Glob(.robota/**)`],ie=s?s.commandTools.filter(e=>!e.requiresPermission).map(e=>e.toolName):[],ae=(e.allowedTools??[]).map(e=>`${e}(*)`),oe=(e.deniedTools??[]).map(e=>`${e}(*)`),se={allow:[...re,...ie,...e.config.permissions.allow??[],...ae],deny:[...e.config.permissions.deny??[],...oe]},ce=w(n,`.robota`,`settings.local.json`);function le(e){let t=`${e}(*)`,n=q(ce),r=Array.isArray(n.permissions)?[]:n.permissions?.allow??[];r.includes(t)||J(ce,{...n,permissions:{...n.permissions??{},allow:[...r,t]}})}let ue=new Se({tools:p,provider:t,systemMessage:_,terminal:e.terminal,permissions:se,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:le,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.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.effort===void 0?{}:{effort:e.effort}});return za(ue,ee,te,g),{session:ue,rebuildSystemMessage:ne}}function Oo(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function ko(e,t,n,r=new R){let i=w(n,e,`subagents`);return r.mkdirSync(i,{recursive:!0}),new xe(i)}function Ao(e,t){return w(t,e,`subagents`)}const jo=v.lazy(()=>v.union([v.string(),v.number(),v.boolean(),v.null(),v.undefined(),v.date(),v.array(jo),v.record(jo)])),Mo=v.object({name:v.string().optional(),model:v.string().optional(),apiKey:v.string().optional(),baseURL:v.string().optional(),timeout:v.number().optional(),options:v.record(jo).optional()}),No=v.object({type:v.string().optional(),model:v.string().optional(),apiKey:v.string().optional(),baseURL:v.string().optional(),timeout:v.number().optional(),options:v.record(jo).optional()}),Po=v.object({allow:v.array(v.string()).optional(),deny:v.array(v.string()).optional()}),Fo=v.record(v.string()).optional(),Io=v.object({type:v.literal(`command`),command:v.string(),timeout:v.number().optional()}),Lo=v.object({type:v.literal(`http`),url:v.string(),headers:v.record(v.string()).optional(),timeout:v.number().optional()}),Ro=v.object({type:v.literal(`prompt`),prompt:v.string(),model:v.string().optional()}),zo=v.object({type:v.literal(`agent`),agent:v.string(),maxTurns:v.number().optional(),timeout:v.number().optional()}),Bo=v.discriminatedUnion(`type`,[Io,Lo,Ro,zo]),Y=v.object({matcher:v.string(),hooks:v.array(Bo)}),Vo=v.object({PreToolUse:v.array(Y).optional(),PostToolUse:v.array(Y).optional(),SessionStart:v.array(Y).optional(),SessionEnd:v.array(Y).optional(),Stop:v.array(Y).optional(),StopFailure:v.array(Y).optional(),PreCompact:v.array(Y).optional(),PostCompact:v.array(Y).optional(),UserPromptSubmit:v.array(Y).optional(),SubagentStart:v.array(Y).optional(),SubagentStop:v.array(Y).optional(),WorktreeCreate:v.array(Y).optional(),WorktreeRemove:v.array(Y).optional()}).optional(),Ho=v.record(v.boolean()).optional(),Uo=v.object({source:v.object({type:v.enum([`github`,`git`,`local`,`url`]),repo:v.string().optional(),url:v.string().optional(),path:v.string().optional(),ref:v.string().optional()})}),Wo=v.record(Uo).optional().catch(void 0),Go=v.union([v.number().gt(0).lte(1),v.literal(!1)]).optional(),Ko=v.object({enabled:v.boolean().optional(),options:v.record(jo).optional()}),qo=v.object({defaultTrustLevel:v.enum([`safe`,`moderate`,`full`]).optional(),language:v.string().optional(),preset:v.string().optional(),currentProvider:v.string().optional(),providers:v.record(No).optional(),provider:Mo.optional(),permissions:Po.optional(),env:Fo,hooks:Vo,enabledPlugins:Ho,extraKnownMarketplaces:Wo,autoCompactThreshold:Go,transports:v.record(Ko).optional()});function Jo(){return process.env.HOME??process.env.USERPROFILE??`/`}const X={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[]},env:{}};function Yo(e){if(!O(e))return;let t=$e(e,`utf-8`).trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function Xo(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:Qo(e.provider);if(e.providers!==void 0){let n=Object.fromEntries(Object.entries(e.providers).map(([e,t])=>[e,Qo(t)]));return{...e,provider:t,providers:n}}return{...e,provider:t}}function Qo(e){return{...e,...e.apiKey!==void 0&&{apiKey:Xo(e.apiKey)}}}function $o(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?es(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 es(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function ts(e){if(e.currentProvider!==void 0)return ns(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...X.provider}}function ns(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??X.provider.model,apiKey:n.apiKey??X.provider.apiKey,...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function rs(e){return{defaultTrustLevel:e.defaultTrustLevel??X.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:ts(e),permissions:{allow:e.permissions?.allow??X.permissions.allow,deny:e.permissions?.deny??X.permissions.deny},env:e.env??X.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold}}function is(e){let t=Jo();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 as(e){let t=is(e),n=[];for(let e of t){let t=Yo(e);t!==void 0&&n.push({raw:t,path:e})}return rs($o(n.map(({raw:e,path:t})=>{let n=qo.safeParse(e);if(!n.success)throw Error(`Invalid settings in ${t}: ${n.error.message}`);return Zo(n.data)})))}const os=w(`.agents`,`tasks`),ss={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function cs(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function ls(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||Je(t,`.md`)}function us(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function ds(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 fs(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(.+)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function ps(e,t){return t&&e.branch===t?0:ss[e.status]}function ms(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 hs(e){return e.toISOString().slice(0,10)}function gs(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
- `)):(n.length>0&&/^#\s+/.test(n[0])?n.splice(1,0,``,r):n.unshift(r,``),n.join(`
80
- `))}function _s(e,t,n){let r=[`### ${hs(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
- `);let o=i.findIndex((e,t)=>t>a&&/^##\s+/.test(e));return o<0?[...i,``,...r,``].join(`
82
- `):(i.splice(o,0,``,...r,``),i.join(`
83
- `))}function vs(e,t){let n=E(e),r=!1;for(;!r;){let e=w(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 Ye(r)?r:E(n,r)}let i=C(n);r=i===n,n=i}}function ys(e,t=new R){let n=vs(e,t);if(!n)return;let r=w(n,`HEAD`);if(t.existsSync(r))return(t.readFileSync(r,`utf8`).trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1])?.trim()}function bs(e,t=new R){let n=w(e,os);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=>w(n,e)):[]}function xs(e,t,n=new R){let r=n.readFileSync(e,`utf8`);return{path:e,relativePath:T(t,e),title:ls(r,e),status:cs(us(r,`Status`)),branch:us(r,`Branch`),scope:us(r,`Scope`),objective:ds(r,`Objective`),openItems:fs(r)}}function Ss(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>ps(e,t.currentBranch)-ps(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function Cs(e){return e.map(ms).join(`
84
-
85
- `)}function ws(e,t={},n=new R){let r=t.currentBranch??ys(e,n);return Cs(Ss(bs(e,n).map(t=>xs(t,e,n)),{...t,currentBranch:r}))}function Ts(e,t,n={},r=new R){let i=gs(r.readFileSync(e,`utf8`),t),a=n.progressMessage?_s(i,n.now??new Date,n.progressMessage):i;r.writeFileSync(e,a,`utf8`)}const Es=200,Ds=25600,Os=[`user`,`feedback`,`project`,`reference`];function ks(e){return Os.includes(e)}function As(e){return k(e,`.robota`,`memory`)}function js(e,t){let n=Buffer.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function Ms(e,t){let n=e.split(/\r?\n/);return{content:n.slice(0,t).join(`
86
- `).trimEnd(),truncated:n.length>t}}function Ns(e){return e.trim().toLowerCase().replace(/[^a-z0-9가-힣_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`general`}function Ps(e,t,n){let r=e.toISOString().slice(0,10),i=t.text.trim().replace(/\s+/g,` `);return`[${r}] (${t.type}/${n}) ${i}`}function Fs(e){return e.trim().replace(/\s+/g,` `)}var Is=class{cwd;now;constructor(e,t=()=>new Date){this.cwd=e,this.now=t}getIndexPath(){return k(As(this.cwd),`MEMORY.md`)}getTopicsPath(){return k(As(this.cwd),`topics`)}loadStartupMemory(){let e=this.getIndexPath();if(!O(e))return{content:``,path:e,lineCount:0,truncated:!1};let t=$e(e,`utf8`),n=js(t,Ds),r=Buffer.byteLength(t,`utf8`)>Ds,i=Ms(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=O(e)?et(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(t=>({name:nt(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=Ns(e),n=k(this.getTopicsPath(),`${t}.md`);return O(n)?$e(n,`utf8`).trimEnd():``}append(e){let t=Ns(e.topic),n=As(this.cwd),r=this.getTopicsPath();Qe(r,{recursive:!0});let i=this.getIndexPath(),a=k(r,`${t}.md`),o=Ps(this.now(),e,t),s=O(a)?``:`# ${t}\n\n`,c=Fs(e.text);return O(a)&&$e(a,`utf8`).includes(`) ${c}`)?{indexPath:i,topicPath:a,topic:t,deduplicated:!0}:(O(i)||(Qe(n,{recursive:!0}),tt(i,`# Project Memory
87
-
88
- `,`utf8`)),Ze(i,`- ${o}\n`,`utf8`),Ze(a,`${s}- ${o}\n`,`utf8`),{indexPath:i,topicPath:a,topic:t,deduplicated:!1})}};function Ls(e,t){let n=[],r=it(e),i=!1;for(;!i;){let e=k(r,t);O(e)&&n.push(e);let a=rt(r);i=a===r,i||(r=a)}return n.reverse()}function Rs(e){let t=e.split(`
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 zs(e){let t=Ls(e,`AGENTS.md`),n=Ls(e,`CLAUDE.md`),r=t.map(e=>lr(e)),i=n.map(e=>lr(e)),a=r.map(e=>e.content).join(`
91
-
92
- `),o=i.map(e=>e.content).join(`
93
-
94
- `),s=Rs(o),c=new Is(e).loadStartupMemory().content||void 0,l=ws(e);return{agentsMd:a,claudeMd:o,memoryMd:c,taskContext:l.trim().length>0?l:void 0,compactInstructions:s,agentsFileEntries:r,claudeFileEntries:i}}var Bs=class{settingsPath;fs;constructor(e,t=new R){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=C(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 Vs(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 Hs(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 Us(e,t=new R){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}var Ws=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new R){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){return this.discoverAndLoad()}async loadAll(){return this.discoverAndLoad()}discoverAndLoad(){let e=w(this.pluginsDir,`cache`);if(!this.fs.existsSync(e))return[];let t=[],n=Us(e,this.fs);for(let r of n){let n=w(e,r),i=Us(n,this.fs);for(let e of i){let i=w(n,e),a=Us(i,this.fs);if(a.length===0)continue;let o=a[a.length-1],s=w(i,o),c=w(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 Hs(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=w(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=w(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let{metadata:r,content:a}=Vs(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=w(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}=Vs(this.fs.readFileSync(w(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=w(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=w(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=w(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$/,``)):[]}},Gs=class{pluginsDir;cacheDir;registryPath;settingsStore;marketplaceClient;exec;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.cacheDir=w(this.pluginsDir,`cache`),this.registryPath=w(this.pluginsDir,`installed_plugins.json`),this.settingsStore=e.settingsStore,this.marketplaceClient=e.marketplaceClient,this.exec=e.exec,this.fs=e.fs??new R}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=w(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=w(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=C(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 Z(e,t=new R){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 Ks(e,t,n=new R){let r=C(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(e,JSON.stringify(t,null,2),`utf-8`)}function qs(e,t,n=new R){let r=w(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=C(r);n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.writeFileSync(r,JSON.stringify(i,null,2),`utf-8`)}}const Js=6e4;var Ys=class{pluginsDir;exec;marketplacesDir;registryPath;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.exec=e.exec,this.marketplacesDir=w(this.pluginsDir,`marketplaces`),this.registryPath=w(this.pluginsDir,`known_marketplaces.json`),this.fs=e.fs??new R}addMarketplace(e){let t=`temp-`+Date.now().toString(36),n=w(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:Js,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone marketplace: ${t}`)}}let r=w(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=Z(this.registryPath,this.fs);if(a[i])throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace "${i}" already exists`);let o=w(this.marketplacesDir,i);return this.fs.renameSync(n,o),a[i]={source:e,installLocation:o,lastUpdated:new Date().toISOString()},Ks(this.registryPath,a,this.fs),i}removeMarketplace(e){let t=Z(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);qs(this.pluginsDir,e,this.fs),this.fs.existsSync(n.installLocation)&&this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),delete t[e],Ks(this.registryPath,t,this.fs)}updateMarketplace(e){let t=Z(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:Js,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(),Ks(this.registryPath,t,this.fs)}listMarketplaces(){let e=Z(this.registryPath,this.fs);return Object.entries(e).map(([e,t])=>({name:e,source:t.source,lastUpdated:t.lastUpdated}))}fetchManifest(e){let t=Z(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);let n=w(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=Z(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:Js,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 Xs(e){let t=w(C(C(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 Qs(e){let t={};for(let n of e){let e=n.hooks;if(!e)continue;let r=Xs(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 $s(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 ec(e){let t=e.cwd,[n,r,i]=await Promise.all([e.config?Promise.resolve(e.config):as(t),e.bare?Promise.resolve({agentsMd:``,claudeMd:``,agentsFileEntries:[],claudeFileEntries:[]}):zs(t),e.bare?Promise.resolve({type:`unknown`,language:`unknown`}):Ji(t)]),a=e.language?{...n,language:e.language}:n,o=new Ws(w(D(),`.robota`,`plugins`));if(!e.bare)try{let e=o.loadPluginsSync();if(e.length>0){let t=Qs(e);a={...a,hooks:$s(a.hooks,t)}}}catch{}let s=H(t);await nc(e)||await tc(e,t);let c=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,{session:l,rebuildSystemMessage:u}=Do({config:a,cwd:t,context:r,projectInfo:i,permissionMode:e.permissionMode,maxTurns:e.maxTurns,terminal:oi,sessionLogger:new xe(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.persona===void 0?{}:{persona:e.persona},...e.systemPrompt?{systemPromptBuilder:()=>e.systemPrompt}:{},backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,...e.commandModules?.some(e=>e.sessionRequirements?.includes(`agent-runtime`))?{enableAgentRuntime:!0}:{},...e.enableParallelSubagents===void 0?{}:{enableParallelSubagents:e.enableParallelSubagents},...e.selfVerification===void 0?{}:{selfVerification:e.selfVerification},...e.commandModules||e.commandDescriptors?{commandDescriptors:[...e.commandDescriptors??[],...e.commandModules?.flatMap(e=>e.commandDescriptors??[])??[]]}:{},modelCommandExecutor:e.modelCommandExecutor,isModelCommandInvocable:e.isModelCommandInvocable,editCheckpointRecorder:e.editCheckpointRecorder,reversibleExecution:e.reversibleExecution,sandboxClient:e.sandboxClient,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{}});return{session:l,agentsFileEntries:r.agentsFileEntries??[],claudeFileEntries:r.claudeFileEntries??[],rebuildSystemMessage:u}}async function tc(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await ue(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function nc(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 rc(e,t){let n=e.config??await as(e.cwd),r=n.autoCompactThreshold===void 0?`default`:`settings`,i=new Ni({cwd:e.cwd});t.setEditCheckpointStore(i);let a=await ec({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.persona===void 0?{}:{persona:e.persona},...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.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.enableParallelSubagents===void 0?{}:{enableParallelSubagents:e.enableParallelSubagents},...e.selfVerification===void 0?{}:{selfVerification:e.selfVerification},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.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)Yi(a.session,e);a.session.syncContextFromHistory()}return{session:a.session,agentsFileEntries:a.agentsFileEntries,claudeFileEntries:a.claudeFileEntries,rebuildSystemMessage:a.rebuildSystemMessage,autoCompactThresholdSource:r}}function ic(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(ac({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 ac(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},...oc(e.backgroundState),...sc(e.memoryState),...cc(e.skillActivationState),...lc(e.contextReferenceState)}}function oc(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function sc(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function cc(e){return e?{skillActivationEvents:[...e.events]}:{}}function lc(e){return e?{contextReferences:[...e.references]}:{}}function uc(e){return e.source===`skill`||e.source===`plugin`&&e.skillContent?`skill`:`builtin-command`}function dc(e){let t=e.source===`skill`||e.source===`plugin`&&!!e.skillContent;return{name:e.name,kind:uc(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 fc=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=>dc(e))}},pc=class{commands;constructor(e){this.commands=new Map;for(let t of e??mc())this.commands.set(t.name,t)}register(e){this.commands.set(e.name,e)}replaceCommands(e){this.commands.clear();for(let t of e)this.commands.set(t.name,t)}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 mc(){return[]}function hc(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 gc=class{name=`builtin`;commands;constructor(e=mc()){this.commands=e.map(hc)}getCommands(){return this.commands}};function _c(){let e=mc();return{name:`sdk-builtin`,commandSources:[new gc(e)],systemCommands:e}}function vc(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function yc(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function bc(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 xc(e,t,n={}){if(!t.type)throw Error(`Provider profile "${e}" is missing type`);let r=n.providerDefinitions??[],i=u(r,t.type);if(i===void 0&&r.length>0)throw Error(`Unknown provider "${t.type}". Supported providers: ${p(r)}`);if(!t.model)throw Error(`Provider profile "${e}" is missing model`);let a=m(i);if(a!==void 0&&!Ec(t,i?.defaults,a))throw Error(`Provider profile "${e}" is missing ${Oc(a)}`)}function Sc(e,t={}){let n=Cc(e,t);return xc(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function Cc(e,t={}){let n=Tc(e.type,t.providerDefinitions??[]);if(e.apiKey!==void 0&&e.apiKeyEnv===void 0&&console.warn(`API key stored as plain text in settings. Use --api-key-env for better security.`),e.apiKeyEnv!==void 0){let n=(t.env??process.env)[e.apiKeyEnv];if(n===void 0||n.length===0)throw Error(`Environment variable ${e.apiKeyEnv} is not set — set it before configuring (the profile will reference $ENV:${e.apiKeyEnv})`)}let r=e.apiKeyEnv===void 0?e.apiKey??n.apiKey:f(e.apiKeyEnv),i=e.baseURL??n.baseURL;return{type:e.type,model:e.model??n.model,...kc(r)&&{apiKey:r},...i!==void 0&&{baseURL:i},...e.timeout!==void 0&&{timeout:e.timeout}}}function wc(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=vc(e,n,r);return t.currentProvider?yc(i,t.currentProvider):i}function Tc(e,t){return u(t,e)?.defaults??{}}function Ec(e,t,n){return n.anyOf.some(n=>h(Dc(n,e,t)))}function Dc(e,t,n){return t[e]??n?.[e]}function Oc(e){return e.anyOf.join(` or `)}function kc(e){return e!==void 0&&e.length>0}async function Ac(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{xc(i,a,{providerDefinitions:r.providerDefinitions})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let o=await((a.type?u(r.providerDefinitions,a.type):void 0)?.probeProfile??jc)(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 jc(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function Mc(e,t=[]){return Nc(e,t)?`valid`:`incomplete`}function Nc(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return Pc(n?.type,n,t)}return!!(e.provider&&Pc(e.provider.name,e.provider,t))}function Pc(e,t,n){if(!t)return!1;if(!e)return h(t.apiKey);let r=u(n,e);if(r===void 0)return!1;let i=m(r);return i===void 0?!0:Fc(t,r,i)}function Fc(e,t,n){return n.anyOf.some(n=>h(Ic(n,e,t)))}function Ic(e,t,n){return t[e]??n.defaults?.[e]}function Lc(e,t=[]){if(!b(e))return`missing`;try{let n=x(e,`utf8`).trim();return n.length===0?`incomplete`:Mc(JSON.parse(n),t)}catch{return`corrupt`}}function Rc(e,t=new R){return e.reduce((e,n)=>{let r=zc(n,t);return r===void 0?e:Bc(e,r)},{})}function zc(e,t){if(!t.existsSync(e))return;let n=t.readFileSync(e,`utf8`);try{return JSON.parse(n)}catch(t){throw new eo(e,t instanceof Error?t.message:String(t))}}function Bc(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?Vc(e.providers,t.providers):void 0}}function Vc(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function Hc(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 le({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 le({name:i.name,model:i.model,apiKey:i.apiKey,baseURL:i.baseURL,timeout:i.timeout,options:i.options},n)}function Uc(){return process.env.HOME??process.env.USERPROFILE??`/`}function Wc(e){let t=Uc();return[w(t,`.robota`,`settings.json`),w(t,`.claude`,`settings.json`),w(e,`.robota`,`settings.json`),w(e,`.robota`,`settings.local.json`),w(e,`.claude`,`settings.json`),w(e,`.claude`,`settings.local.json`)]}function Gc(e,t={}){let n=t.settingsPaths??Wc(e),r=Qc(n)??n[0];if(r===void 0)throw Error(`No settings path available for provider update`);return r}function Kc(e){return q(e)}function qc(e,t,n={}){let r=wc(Kc(e),Sc(t,n));return J(e,r),r}function Jc(e,t,n={}){let r=Kc(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:yc(r,t);return J(e,o),o}function Yc(e,t,n={}){let r=n.settingsPaths??Wc(e),i=Rc(r),a=n.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Xc(r,a,t)}function Xc(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=Kc(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&&Kc(r).providers?.[t]!==void 0)return r}}function Qc(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&Kc(n).currentProvider!==void 0)return n}}var $c=class extends Error{constructor(e){super(e),this.name=`ProviderConfigError`}};function el(e){return Rc(Wc(e))}function tl(e,n=process.env){for(let r of e){let e=r.defaults;if(e?.apiKey===void 0||e.model===void 0||!te(e.apiKey))continue;let i=e.apiKey.slice(t.length).trim();if(i.length===0)continue;let a=n[i];if(!(a===void 0||a.length===0))return{name:r.type,model:e.model,apiKey:a,...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},...e.options!==void 0&&{options:e.options},source:`env-default`,sourceEnvVar:i}}}function nl(e,t={}){let n=Hc(el(e),t.providerOverride,t.providerDefinitions??[]);if(n!==void 0)return n;let r=tl(t.providerDefinitions??[],t.env);if(r!==void 0)return r;throw new $c("No provider configuration found. Run `robota` to set up.")}function rl(e,t,n={}){let r=n.providerDefinitions??[],i=nl(e,{...n,providerDefinitions:r}),a=t??i.model;return se({...i,model:a},r)}var il=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}};function al(e,t,n){let r=e;if(t!==void 0){let e=new Set(t);r=r.filter(t=>e.has(t.name))}if(n!==void 0){let e=new Set(n);r=r.filter(t=>!e.has(t.name))}return r}const ol=be,sl=`autoCompactThreshold`;function cl(e){return e.getContextState()}function ll(e){return e.getAutoCompactThreshold()}function ul(e){return e.getAutoCompactThresholdSource?.()??`session`}function dl(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 fl(e,t){let n=yl(e);return n?(n.write({...n.read(),[sl]:t}),!0):!1}function pl(e){let t=yl(e);if(!t)return!1;let n={...t.read()};return delete n[sl],t.write(n),!0}async function ml(e,t){let n=cl(e),r=e.getSession().getMessageCount();return await e.compactContext(t),{before:n,after:cl(e),beforeMessageCount:r,afterMessageCount:e.getSession().getMessageCount()}}function hl(e){return e.listContextReferences?.()??[]}async function gl(e,t){return e.addContextReference?e.addContextReference(t):{evicted:[],diagnostics:[`Command host does not support context reference additions.`]}}function _l(e,t){return e.removeContextReference?.(t)??{}}function vl(e){return e.clearContextReferences?.()??{removed:[]}}function yl(e){return e.getCommandHostAdapters?.().settings}function bl(e,t={}){let n=xl(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 xl(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 wl(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 Tl=`List and control background tasks`,El=`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 Ol(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=jl(e),s=t?` — ${t}`:``;return`${e.id} [${e.status}${n}${i}${a}${o}] ${e.kind}:${e.label}${r}${s}`}function kl(e){return e.length===0?`No background tasks.`:[`Background tasks:`,...e.map(e=>` ${Ol(e)}`)].join(`
97
- `)}function Al(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isNaN(t)?void 0:{offset:t}}function jl(e){let t=[];return e.worktreePath&&t.push(`worktree=${e.worktreePath}`),e.branchName&&t.push(`branch=${e.branchName}`),e.worktreeStatus&&t.push(`worktreeStatus="${Ml(e.worktreeStatus)}"`),e.worktreeNextAction&&t.push(`next="${Ml(e.worktreeNextAction)}"`),t.length===0?``:` ${t.join(` `)}`}function Ml(e){let t=e.trim().replace(/\s+/g,` `);return t.length>160?`${t.slice(0,160)}...`:t}function Nl(e,t){return e.listBackgroundTasks(t)}function Pl(e,t,n){return e.readBackgroundTaskLog(t,n)}function Fl(e,t,n){return e.cancelBackgroundTask(t,n)}function Il(e,t){return e.closeBackgroundTask(t)}const Ll=`Set response language`,Rl=`<code>`,zl=[{code:`ko`,description:`Korean`},{code:`en`,description:`English`},{code:`ja`,description:`Japanese`},{code:`zh`,description:`Chinese`}];function Bl(e=`language`){return zl.map(t=>({name:t.code,description:t.description,source:e}))}function Vl(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Hl(e=`language`){return`Usage: ${e} <code> (e.g., ko, en, ja, zh)`}const Ul=`Show/change permission mode`,Wl=`plan | default | acceptEdits | bypassPermissions`,Gl=`Show/change permission mode and permission rules`,Kl=[`plan`,`default`,`acceptEdits`,`bypassPermissions`];function ql(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 Jl(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Yl(e){return Kl.includes(e)}function Xl(){return`Invalid mode. Valid: ${Kl.join(` | `)}`}function Zl(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 Ql(e){return Zl(e).getPermissionMode()}function $l(e,t){Zl(e).setPermissionMode(t)}function eu(e){return Zl(e).listSessionAllowedTools()}function tu(e){return{mode:Ql(e),sessionAllowed:eu(e)}}function nu(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
- `)}async function ru(e,t,n){let r=[],i=[];e.getSession().setActivePresetId?.(t),n.permissionMode===void 0?i.push(`permissionMode`):($l(e,n.permissionMode),r.push(`permissionMode`));let a={...n.model!==void 0&&{model:n.model},...n.effort!==void 0&&{effort:n.effort},...n.temperature!==void 0&&{temperature:n.temperature},...n.maxOutputTokens!==void 0&&{maxOutputTokens:n.maxOutputTokens}};for(let e of[`model`,`effort`,`temperature`,`maxOutputTokens`])n[e]===void 0?i.push(e):r.push(e);return Object.keys(a).length>0&&await e.getSession().applyModelOptions?.(a),n.persona===void 0?i.push(`persona`):(e.applyPersona?.(n.persona),r.push(`persona`)),n.enabledCommandModules!==void 0||n.disabledCommandModules!==void 0?(e.applyCommandModuleSelection?.(n.enabledCommandModules,n.disabledCommandModules),r.push(`commandModules`)):i.push(`commandModules`),n.enableParallelSubagents===void 0?i.push(`enableParallelSubagents`):(e.getSession().setParallelSubagentsEnabled?.(n.enableParallelSubagents),r.push(`enableParallelSubagents`)),n.selfVerification===void 0?i.push(`selfVerification`):(e.applySelfVerification?.(n.selfVerification),r.push(`selfVerification`)),{applied:r,skipped:i}}const iu=`Configure TUI status-line visibility and fields such as model, context, tokens, session, and git branch.`,au=`on | off | reset | git on | git off`,ou={enabled:!0,gitBranch:!0};function su(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 cu(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function lu(e){let t=e.statusline;return du(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:ou.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:ou.gitBranch}:{...ou}}function uu(e,t){let n=q(e),r={...lu(n),...t};return n.statusline=r,J(e,n),r}function du(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}const fu=`Manage plugins`,pu=`manage | install <name@marketplace> | uninstall <name@marketplace> | enable <name@marketplace> | disable <name@marketplace> | marketplace <action>`,mu=`Reload all plugin resources`;function hu(){return{type:`plugin-tui-requested`}}function gu(){return{type:`plugin-registry-reload-requested`}}function _u(e){return e.getCommandHostAdapters?.().plugin}function vu(){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 yu=`Clear conversation history`,bu=`Rename the current session`,xu=`Usage: rename <name>`,Su=`Resume a previous session`,Cu=`Show session token usage and estimated cost. /cost budget <amount> sets a monthly budget.`,wu=`Validate current session replay log`,Tu=`Exit CLI`;function Eu(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 Ou(e){return{type:`session-renamed`,name:e}}function ku(){return{type:`session-picker-requested`}}function Au(){return{type:`session-exit-requested`}}function ju(e){let t=e.getSession();return{sessionId:t.getSessionId(),messageCount:t.getMessageCount()}}function Mu(e){let t=e.validateCurrentSessionReplayLog?.();if(t!==void 0)return t;let n=e.getSession().getSessionId(),r=w(H(e.getCwd()).logs,`${n}.jsonl`),i=we(r);return{logFile:r,entryCount:i.length,validation:Ee(i)}}function Nu(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=Pu(e);return`${t+1}. ${e.code}${n}: ${e.message}`});return[t,...n,``,...r].join(`
100
- `)}function Pu(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 Fu=`List, inspect, restore, or rollback edit checkpoints.`,Iu=`list | inspect CHECKPOINT_ID | restore CHECKPOINT_ID | code CHECKPOINT_ID | rollback CHECKPOINT_ID`;function Lu(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 Ru(e){return e.listEditCheckpoints()}function zu(e,t){if(!e.inspectEditCheckpoint)throw Error(`Checkpoint inspection is not available in this command host.`);return e.inspectEditCheckpoint(t)}function Bu(e,t){return e.restoreEditCheckpoint(t)}function Vu(e,t){return e.rollbackEditCheckpoint(t)}const Hu=[/\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 Uu(e){return Hu.some(t=>t.test(e))}function Wu(e){return w(e,`.robota`,`memory`)}function Gu(){return{version:1,records:[]}}var Ku=class{fs;path;now;constructor(e,t=()=>new Date,n=new R){this.fs=n,this.path=w(Wu(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 Gu();try{return{version:1,records:JSON.parse(this.fs.readFileSync(this.path,`utf8`)).records??[]}}catch{return Gu()}}write(e){this.fs.mkdirSync(C(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,JSON.stringify(e,null,2),`utf8`)}};const qu=`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`,Yu=`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 Xu(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 Zu(e,t){return new Is(e,t)}function Qu(e,t){return new Ku(e,t)}function $u(e,t){let n=e.getCwd();return{project:Zu(n,t),pending:Qu(n,t)}}function ed(e){return ks(e)}function td(e){return Uu(e)}function nd(e){return e.getUsedMemoryReferences()}function rd(e,t,n=()=>new Date){e.recordMemoryEvent({...t,at:n().toISOString()})}function id(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 ad(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 od(e,t,n,r){return e.skillContent?id(await ad(e.skillContent,n.shellExec),t,r):null}async function sd(e,t,n,r){let i=await od(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 cd(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 od(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 sd(e,t,n,r)}}function ld(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function ud(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function dd(e,t){let n=t.trim();return n.length>0?`${e} ${n}`:e}function fd(e){if(!e?.startsWith(`/`))return;let t=e.slice(1).trim().split(/\s+/)[0];return t&&t.length>0?t:void 0}var pd=class{getSession;getSessionId;onSubmit;onApplyResult;recordSkillActivation;runSkillInFork;onForkSkill;onBlockingCommand;shellExec;commandExecutor;allCommandModules;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.allCommandModules=e,this.commandExecutor=new pc(e.flatMap(e=>e.systemCommands??[])),this.skillCommandSource=new $a(t),this.commandHostAdapters=n}reapplyCommandModuleSelection(e,t){let n=al(this.allCommandModules,e,t);this.commandExecutor.replaceCommands(n.flatMap(e=>e.systemCommands??[]))}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=ld(e);return this.skillCommandSource.getCommands().find(e=>e.name.toLowerCase()===t.toLowerCase())}async executeCommand(e,t){let n=ud(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,dd(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=fd(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 cd(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=Vi({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 md(){let e=w(D(),`.robota`,`org-policy.json`);if(!b(e))return null;try{let t=x(e,`utf8`);return JSON.parse(t)}catch{return null}}function hd(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function gd(e){return e?!e.startsWith(`$ENV:`):!1}var _d=class extends sr{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 Ni({cwd:t})),this.bgTracker=new qn(()=>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(),(e,t)=>this.requestWakeup(e,t),e=>this.histTracker.append(_(c(e)))),this.histTracker=new Gi(t,()=>this.getSessionOrThrow().getSessionId(),()=>this.execCtrl.executing,()=>this.persistCurrentSession(),e=>this.emit(`skill_activation`,e),e=>this.emit(`memory_event`,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 pd(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)=>Si(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 bi(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=Xi(this.sessionStore,e.resumeSessionId,this.session);this.histTracker.restoreState({history:t.history,memoryEvents:t.memoryEvents,usedMemoryReferences:t.usedMemoryReferences,contextReferences:t.contextReferences,skillActivationEvents:t.skillActivationEvents}),t.sessionName&&(this.sessionName=t.sessionName),this.bgTracker.restoreState({tasks:t.backgroundTasks,taskEvents:t.backgroundTaskEvents,groups:t.backgroundJobGroups,groupEvents:t.backgroundJobGroupEvents}),this.pendingRestoreMessages=t.pendingRestoreMessages,this.sandboxSnapshotId=this.forkSession?void 0:t.sandboxSnapshotId,this.session&&t.pendingRestoreMessages===null&&(this.session.syncContextFromHistory(),this.emit(`context_update`,this.getContextState()))}startAsyncInitializationIfNeeded(e,t){if(t)return;let n=e;this.initPromise=this.initializeAsync(n)}async initializeAsync(e){let t=await rc(e,{sandboxSnapshotId:this.sandboxSnapshotId,resumeSessionId:this.resumeSessionId,pendingRestoreMessages:this.pendingRestoreMessages,onTextDelta:e=>this.execCtrl.handleTextDelta(e),onContextUpdate:e=>this.emit(`context_update`,e),onCompactEvent:e=>this.execCtrl.handleCompactEvent(e),onToolExecution:e=>this.execCtrl.handleToolExecution(e),executeModelCommand:(e,t)=>this.executeModelCommand(e,t),isModelCommandInvocable:e=>this.skillRouter.commandExecutor.isModelInvocable(e),commandDescriptors:this.skillRouter.commandExecutor.listModelInvocableCommands(),setEditCheckpointStore:e=>this.histTracker.setEditCheckpointStore(e)});this.session=t.session,this.agentsFileEntries=t.agentsFileEntries,this.claudeFileEntries=t.claudeFileEntries,this.rebuildSystemMessage=t.rebuildSystemMessage,this.autoCompactThresholdSource=t.autoCompactThresholdSource,this.histTracker.recordSystemContextFiles([...t.agentsFileEntries,...t.claudeFileEntries]),this.pendingRestoreMessages=null,this.initialized=!0,this.bgTracker.subscribe(this.session),this.persistCurrentSession(),this.emit(`context_update`,this.getContextState())}async ensureInitialized(){!this.initialized&&this.initPromise&&await this.initPromise}getSessionOrThrow(){if(!this.session)throw Error(`InteractiveSession not initialized. Call submit() or await initialization.`);return this.session}getCwd(){if(!this.cwd)throw Error(`cwd is not set — provide cwd in session options`);return this.cwd}get sessionId(){return this.session?.getSessionId()??``}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,...t){let n=this.listeners.get(e);if(n)for(let e of n)e(...t)}async submit(e,t,n,r={}){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,this.execCtrl.pendingTurnOptions=r;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,r)=>this.submit(e,t,n,r),r)}requestWakeup(e,t){this.execCtrl.shuttingDown||this.execCtrl.wakeTaskIds.has(t)||(this.execCtrl.wakeTaskIds.add(t),this.submit(e,void 0,void 0,{turnSource:`agent-wakeup`,wakeTaskId:t}))}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()}applyPersona(e){if(this.rebuildSystemMessage===null)return;let t=this.agentsFileEntries.map(e=>e.content).join(`
101
-
102
- `),n=this.claudeFileEntries.map(e=>e.content).join(`
103
-
104
- `),r=this.rebuildSystemMessage(t,n,{persona:e});this.getSessionOrThrow().updateSystemMessage(r)}applySelfVerification(e){if(this.rebuildSystemMessage===null)return;let t=this.agentsFileEntries.map(e=>e.content).join(`
105
-
106
- `),n=this.claudeFileEntries.map(e=>e.content).join(`
107
-
108
- `),r=this.rebuildSystemMessage(t,n,{selfVerification:e});this.getSessionOrThrow().updateSystemMessage(r)}applyCommandModuleSelection(e,t){this.skillRouter.reapplyCommandModuleSelection(e,t)}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 qt(this.session)??I(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(_(c(`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();ic(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=nl(n,{providerOverride:e,providerDefinitions:this.providerDefinitions}),i=rl(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:hd(`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:hd(`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 vd(e,t=new R){let n=H(e);return new Cd(n.sessions,n.logs,t)}function yd(e=new R){return new Cd(Ei().sessions,void 0,e)}function bd(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:wd(e.messages)}))}function xd(e,t){return bd(e,t)[0]?.id}function Sd(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var Cd=class{store;logsDir;fs;constructor(e,t,n=new R){this.store=new Ce(e),this.logsDir=t,this.fs=n}save(e){this.store.save(Td(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):Ed(t)}list(){let e=this.store.list().map(Ed),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=Te(we(w(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:Dd(n),backgroundTaskEvents:n,backgroundJobGroups:kd(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 wd(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 Td(e){return{...e}}function Ed(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 Dd(e){let t=new Map;for(let n of e){let e=Od(n);e&&t.set(e.id,e)}return[...t.values()]}function Od(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 kd(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function Ad(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,``).trim().replace(/\s+/g,`-`).replace(/-+/g,`-`).slice(0,60)}async function jd(e,t){let n=t.slice(0,200),r=await e.chat([c(`You generate short session titles. Respond with ONLY a 3-5 word lowercase-hyphenated title (e.g. refactor-auth-middleware). No explanation, no punctuation, no quotes.`),l(n)],{maxTokens:20}),i=Ad(typeof r.content==`string`?r.content:``);return!i||i.length<3?Ad(t):i}function Md(e){let t=new _d({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 Nd=[`preferences`,`view-state`,`memory-projections`,`task-associations`,`workflow-metadata`,`inspection-index`],Pd=[{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 Fd(e){return e.toISOString()}function Id(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!S.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function Ld(){return process.env.HOME??D()}function Rd(e,t){let n=S.relative(e,t);return n===``||!n.startsWith(`..`)&&!S.isAbsolute(n)}async function zd(e,t){let n=e;for(;S.dirname(n)!==n;)try{let r=await t.realpath(n),i=S.relative(n,e);return S.resolve(r,i)}catch{n=S.dirname(n)}try{return await t.realpath(n)}catch{return S.resolve(e)}}async function Bd(e){let t=e.fsAsync??new z,n=S.resolve(e.activeRepositoryRoot);Id(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?S.join(e.homeDir??Ld(),`.robota`):e.storageRoot;Id(`userLocalStorageRoot`,r);let i=S.resolve(r),a=await zd(i,t);if(Rd(await zd(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function Vd(e,t){return S.join(e,t)}async function Hd(e,t,n){let r=Vd(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=S.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:Fd(new Date(o.birthtimeMs)),lastUsedAt:Fd(new Date(o.mtimeMs)),enabled:!0,deleteAvailable:!0,disableAvailable:!1}}))).sort((e,t)=>e.key.localeCompare(t.key))}async function Ud(e){let t=e.fsAsync??new z,n=await Bd(e),r=S.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all(Pd.map(async e=>{let r=Vd(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await Hd(n,e.category,t);return{category:e.category,purpose:e.purpose,mayExecuteCommands:e.mayExecuteCommands,storageLocation:r,itemCount:a.length,items:a}})),generatedAt:Fd((e.now??(()=>new Date))())}}const Wd=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],Gd=`.json`,Kd=/^[a-z0-9][a-z0-9._-]*$/u,qd={"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 Jd(e){return e.toISOString()}function Yd(e){return Wd.includes(e)}function Xd(e){if(!Yd(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function Zd(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!Kd.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function Qd(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 $d(e){return Qd(`value`,e,240)}function ef(e,t){return`${e}__${t}${Gd}`}async function tf(e){let t=await Bd(e);return{root:t,memoryRoot:S.join(t,`memory-projections`)}}function nf(e,t){let n=JSON.parse(e),r=Q(n,`category`);if(n.schemaVersion!==1)throw Error(`Unsupported user-local memory schema at ${t}`);return{schemaVersion:1,category:Xd(r),key:Q(n,`key`),value:Q(n,`value`),summary:Q(n,`summary`),source:Q(n,`source`),scope:Q(n,`scope`),createdAt:Q(n,`createdAt`),lastUsedAt:Q(n,`lastUsedAt`),enabled:rf(n,`enabled`)}}function Q(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function rf(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function af(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:$d(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:qd[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function of(e,t,n){return af(e,t,nf(await n.readFile(t,`utf8`),t))}async function sf(e){let t=Xd(e.category),n=Zd(`key`,e.key),{root:r,memoryRoot:i}=await tf(e);return{root:r,storageLocation:S.join(i,ef(t,n))}}async function cf(e){let t=e.fsAsync??new z,n=Xd(e.category),r=Zd(`key`,e.key),i=Qd(`summary`,e.summary,240),a=Qd(`source`,e.source,80),o=Qd(`scope`,e.scope??`user`,120),s=$d(e.value),c=Jd((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await tf(e),d=S.join(u,ef(n,r)),f=c;try{f=nf(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`),af(l,d,p)}async function lf(e){let t=e.fsAsync??new z,{root:n,memoryRoot:r}=await tf(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(Gd)).map(e=>of(n,S.join(r,e.name),t)));return{root:n,activeRepositoryRoot:S.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function uf(e){let t=e.fsAsync??new z,{root:n,storageLocation:r}=await sf(e);return of(n,r,t)}async function df(e){let t=e.fsAsync??new z,{root:n,storageLocation:r}=await sf(e),i={...nf(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:Jd((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),af(n,r,i)}async function ff(e){let t=e.fsAsync??new z,{storageLocation:n}=await sf(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}async function pf(e){let t=await uf(e);return t.enabled?t:null}const mf=[`test`,`typecheck`,`build`],hf={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 gf(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))):[]}function _f(e){return e.flatMap(e=>mf.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 vf(){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 yf(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 bf(){return{id:`rollback-on-failure`,phase:`recover`,description:`Use the existing edit checkpoint restore path if verification fails.`,required:!0}}function xf(e){if(e.changedFiles.length===0)throw Error(`Self-hosting verification requires at least one changed file.`);let t=e.baseRef??`origin/develop`,n=gf(e.packageScopes),r=[...vf(),..._f(n),yf(t),bf()];return{changedFiles:[...e.changedFiles],packageScopes:n,baseRef:t,steps:r}}function Sf(e,t){let n=hf[e][t];if(!n)throw Error(`Invalid self-hosting loop transition: ${e} -> ${t}`);return n}function Cf(e){return e}function wf(e){if(!e||e.length===0)return;let[t,...n]=e;if(t!==void 0)return[t,...n]}function Tf(e){let t=wf(e),n=t===void 0?v.string().describe(`Registered model-invocable command name to execute`):v.enum(t).describe(`Registered model-invocable command name to execute`);return v.object({command:n,args:v.string().optional().describe(`Arguments to pass to the command`)})}function Ef(e){if(e.commandNames!==void 0)return e.commandNames;if(e.commandDescriptors!==void 0)return e.commandDescriptors.map(e=>F(e.name))}function Df(e){return`- ${F(e.name)}${e.argumentHint?` ${e.argumentHint}`:``}: ${e.description}`}function Of(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(Df)].join(`
109
- `)}function kf(e){let t=Tf(Ef(e));return he(`ExecuteCommand`,Of(e.commandDescriptors),Cf(t),async n=>{let r=t.parse(n),i=F(r.command);return e.isModelInvocable(i)?Sn(i,await e.execute(i,r.args??``)):JSON.stringify({success:!1,command:i,error:`Command is not model-invocable: ${i}`})})}function Af(e){return/^\/\S/.test(e)}function jf(e){let t=e.slice(1).trim().split(/\s+/);return{name:t[0]??``,args:t.slice(1).filter(e=>e.length>0)}}function Mf(e){if(!Af(e))return{type:`user-message`,text:e};let{name:t,args:n}=jf(e);return{type:`slash-command`,name:t,args:n}}function Nf(e,t){return t.type===`pick`?{type:`pick`,id:e,title:`/${e}`,items:t.getItems()}:{type:`confirm`,id:e,message:t.message}}function Pf(e,t){return t.type===`cancelled`?null:e.type===`pick`&&t.type===`pick`?[t.item.value]:e.type===`confirm`&&t.type===`confirm`?[]:null}function Ff(e){return e.map(e=>({name:e.name,description:e.description}))}function If(e,t){let n=``,r=e=>{n+=e,t.write({type:`assistant-chunk`,chunk:e})},i=()=>{t.write({type:`assistant-done`,fullText:n}),n=``,t.setBusy(!1)},a=e=>{t.write({type:`tool-call`,id:e.executionId??e.toolName,name:e.toolName,args:e.firstArg})},o=e=>{t.write({type:`tool-result`,id:e.executionId??e.toolName,name:e.toolName,result:e.toolResultData??e.result})},s=e=>{t.setBusy(!1),t.write({type:`error`,error:e})},c=()=>{t.setBusy(!1)};return e.on(`text_delta`,r),e.on(`complete`,i),e.on(`tool_start`,a),e.on(`tool_end`,o),e.on(`error`,s),e.on(`interrupted`,c),()=>{e.off(`text_delta`,r),e.off(`complete`,i),e.off(`tool_start`,a),e.off(`tool_end`,o),e.off(`error`,s),e.off(`interrupted`,c)}}function Lf(e){let{channel:t,commandModules:n,_testSession:r}=e,i=null,a=null,o={};for(let e of n)e.interactionHints&&Object.assign(o,e.interactionHints);async function s(e){if(!i)return;let n=Mf(e);if(n.type===`user-message`){t.write({type:`user-message`,text:e}),t.setBusy(!0),await i.submit(e);return}let{name:r,args:a}=n,s=o[r],c=a;if(s&&a.length===0){let e=Pf(s,await t.requestAction(Nf(r,s)));if(e===null)return;c=e}let l=await i.executeCommand(r,c.join(` `));l?t.write({type:`command-result`,name:r,output:l.message}):t.write({type:`error`,error:Error(`Unknown command "/${r}". Type /help for help.`)})}return{async start(){if(r)i=r;else{let{provider:t,cwd:r,sessionStore:a}=e;if(!t)throw Error(`createInteractiveRuntime: provider is required`);if(!r)throw Error(`createInteractiveRuntime: cwd is required`);i=new _d({provider:t,cwd:r,sessionStore:a,commandModules:n})}a=If(i,t);let o=i.listCommands();t.setAvailableCommands(Ff(o)),t.onSubmit(s),await t.start()},async stop(){a?.(),await t.stop(),await i?.shutdown(),i=null}}}const Rf=[`Allow once`,`Allow for this session`,`Deny`];function zf(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 Bf(e,t,n){e.writeLine(``),e.writeError(`[Permission Required] Tool: ${t}`),e.writeLine(` ${zf(n)}`),e.writeLine(``);let r=await e.select(Rf,0);return r===1?`allow-session`:r===0}const Vf={usedTokens:0,maxTokens:2e5,usedPercentage:0,remainingPercentage:100},Hf={sessionId:`test-session-id`,updatedAt:new Date().toISOString(),entries:[]},Uf={id:``,parentSessionId:`test-session-id`,waitPolicy:`wait_all`,taskIds:[],status:`completed`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),results:[]};function Wf(e){return{submit:()=>Promise.resolve(),abort:()=>{},cancelQueue:()=>{},shutdown:()=>Promise.resolve(),isExecuting:()=>!1,getPendingPrompt:()=>null,getMessages:()=>[],getContextState:()=>({...Vf}),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:()=>({...Uf}),waitBackgroundJobGroup:()=>Promise.resolve({...Uf}),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 Gf(){let e=to();return{deleted:ao(e),path:e}}function Kf(e){try{let t=qf(e);if(!t)return;let n=x(w(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 qf(e){let t=E(e),n=C(t);for(;n!==t;){let e=Jf(w(t,`.git`),t);if(e)return e;t=n,n=C(t)}return Jf(w(t,`.git`),t)}function Jf(e,t){if(!b(e))return;let n=Ae(e);if(n.isDirectory())return e;if(!n.isFile())return;let r=x(e,`utf8`).trim();if(!r.startsWith(`gitdir:`))return;let i=r.slice(7).trim();return Ye(i)?i:E(t,i)}function Yf(e,t){let n=Zf(e),r=Zf(t);if(n===void 0||r===void 0)return Math.sign(e.localeCompare(t));let i=Qf(n.major,r.major)||Qf(n.minor,r.minor)||Qf(n.patch,r.patch);return i===0?$f(n.prerelease,r.prerelease):i}function Xf(e,t){return Yf(e,t)>0}function Zf(e){let[t,n]=(e.trim().replace(/^v/,``).split(`+`)[0]??``).split(`-`,2),[r,i,a]=t.split(`.`),o=$(r),s=$(i),c=$(a);if(!(o===void 0||s===void 0||c===void 0))return{major:o,minor:s,patch:c,prerelease:n?n.split(`.`):[]}}function $(e){if(!(e===void 0||!/^\d+$/.test(e)))return Number(e)}function Qf(e,t){return Math.sign(e-t)}function $f(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=ep(n,i);if(a!==0)return a}return 0}function ep(e,t){let n=$(e),r=$(t);return n!==void 0&&r!==void 0?Qf(n,r):n===void 0?r===void 0?Math.sign(e.localeCompare(t)):1:-1}function tp(e){let t=C(at(e)),n=[w(t,`..`,`..`,`package.json`),w(t,`..`,`package.json`)];for(let e of n)try{let t=x(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 np=`@robota-sdk/agent-cli`,rp=`https://registry.npmjs.org`,ip=1440*60*1e3,ap=1500;function op(e=process.env.HOME??process.env.USERPROFILE??`/`){return w(e,`.robota`,`update-check.json`)}function sp(e){if(b(e))try{return Sp(JSON.parse(x(e,`utf8`)))}catch{return}}function cp(e,t){je(C(e),{recursive:!0}),Le(e,JSON.stringify(t,null,2)+`
110
- `,`utf8`)}async function lp(e){if(e.disabled===!0)return{status:`skipped`,reason:`disabled`};let t=e.packageName??`@robota-sdk/agent-cli`,n=e.cachePath??op(),r=e.now??new Date,i=e.ttlMs??864e5;if(e.force!==!0){let a=sp(n);if(a!==void 0&&vp(a,r,i,t))return gp(a,e.currentVersion)}let a=await up(e,t,n,r);return typeof a==`string`?_p(e.currentVersion,a):a}async function up(e,t,n,r){let i=await yp({fetchImpl:e.fetchImpl??fetch,packageName:t,registryUrl:e.registryUrl??`https://registry.npmjs.org`,timeoutMs:e.timeoutMs??1500});return i.ok?(dp(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,latestVersion:i.version}),i.version):(dp(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,errorMessage:i.errorMessage}),{status:`error`,errorMessage:i.errorMessage})}function dp(e,t){try{cp(e,t)}catch{}}async function fp(e){let t=await lp(e);return t.status===`update_available`?t.notice:void 0}function pp(e){return e.printMode===!1&&e.disableUpdateCheck===!1}function mp(e){return[`Robota update available: ${e.currentVersion} -> ${e.latestVersion}.`,`Run ${e.installCommand}`].join(` `)}function hp(e){return e.status===`update_available`?mp(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 gp(e,t){return e.errorMessage===void 0?e.latestVersion===void 0?{status:`error`,errorMessage:`Cached update check has no latest version`}:_p(t,e.latestVersion):{status:`error`,errorMessage:e.errorMessage}}function _p(e,t){return Xf(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 vp(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 yp(e){try{return{ok:!0,version:await bp(e)}}catch(e){return{ok:!1,errorMessage:e instanceof Error?e.message:String(e)}}}async function bp(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=xp(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 xp(e,t){return`${e.replace(/\/+$/,``)}/${encodeURIComponent(t)}`}function Sp(e){if(!Cp(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 Cp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wp(e){let t=to(),n={settings:{read:()=>q(t),write:e=>J(t,e)}},r=e.backgroundTaskRunners??oe(),i=e.commandModules??[],a=e.commandHostAdapters??n,o=`sessionStore`in e?e.sessionStore:vd(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 _d({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 Tp(e){let t=wp({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{sl as AUTO_COMPACT_THRESHOLD_SETTINGS_KEY,so as AgentExecutor,Tl as BACKGROUND_COMMAND_DESCRIPTION,El as BACKGROUND_COMMAND_USAGE,dn as BUILT_IN_AGENTS,st as BackgroundJobOrchestrator,gc as BuiltinCommandSource,Gs as BundlePluginInstaller,Ws as BundlePluginLoader,yu as CLEAR_COMMAND_DESCRIPTION,ip as CLI_UPDATE_CACHE_TTL_MS,np as CLI_UPDATE_PACKAGE_NAME,rp as CLI_UPDATE_REGISTRY_URL,ap as CLI_UPDATE_TIMEOUT_MS,Cu as COST_COMMAND_DESCRIPTION,fc as CommandRegistry,ol as DEFAULT_AUTO_COMPACT_THRESHOLD,ou as DEFAULT_STATUS_LINE_COMMAND_SETTINGS,j as EXECUTION_ORIGIN_METADATA_KEYS,Tu as EXIT_COMMAND_DESCRIPTION,Ni as EditCheckpointStore,Sl as HELP_COMMAND_DESCRIPTION,_d as InteractiveSession,Rl as LANGUAGE_COMMAND_ARGUMENT_HINT,Ll as LANGUAGE_COMMAND_DESCRIPTION,Ju as MEMORY_COMMAND_ARGUMENT_HINT,qu as MEMORY_COMMAND_DESCRIPTION,Yu as MEMORY_COMMAND_USAGE,Ds as MEMORY_INDEX_MAX_BYTES,Es as MEMORY_INDEX_MAX_LINES,gn as MODEL_COMMAND_TOOL_PREFIX,Ys as MarketplaceClient,Gl as PERMISSIONS_COMMAND_DESCRIPTION,Wl as PERMISSION_MODE_ARGUMENT_HINT,Ul as PERMISSION_MODE_COMMAND_DESCRIPTION,pu as PLUGIN_COMMAND_ARGUMENT_HINT,fu as PLUGIN_COMMAND_DESCRIPTION,_n as PROVIDER_SAFE_TOOL_NAME_PATTERN,il as PluginCommandSource,Bs as PluginSettingsStore,Is as ProjectMemoryStore,lo as PromptExecutor,$c as ProviderConfigError,zl as RECOMMENDED_RESPONSE_LANGUAGES,mu as RELOAD_PLUGINS_COMMAND_DESCRIPTION,bu as RENAME_COMMAND_DESCRIPTION,xu as RENAME_COMMAND_USAGE,Su as RESUME_COMMAND_DESCRIPTION,Iu as REWIND_COMMAND_ARGUMENT_HINT,Fu as REWIND_COMMAND_DESCRIPTION,au as STATUSLINE_COMMAND_ARGUMENT_HINT,iu as STATUSLINE_COMMAND_DESCRIPTION,eo as SettingsParseError,$a as SkillCommandSource,pc as SystemCommandExecutor,Wd as USER_LOCAL_MEMORY_CATEGORIES,Nd as USER_LOCAL_STORAGE_CATEGORIES,Pd as USER_LOCAL_STORAGE_CATEGORY_DEFINITIONS,wu as VALIDATE_SESSION_COMMAND_DESCRIPTION,Kl as VALID_PERMISSION_MODES,gl as addCommandContextReference,Yc as applyActiveModelChange,ru as applyPresetToSession,qc as applyProviderConfiguration,Jc as applyProviderSwitch,uu as applyStatusLineSettings,hn as assembleSubagentPrompt,Dl as buildBackgroundCommandSubcommands,Bl as buildLanguageCommandSubcommands,Xu as buildMemoryCommandSubcommands,ql as buildPermissionModeSubcommands,vu as buildPluginCommandSubcommands,Tr as buildPromptWithFileReferences,Cc as buildProviderProfile,Sc as buildProviderSetupPatch,Lu as buildRewindCommandSubcommands,su as buildStatusLineCommandSubcommands,Fl as cancelCommandBackgroundTask,lp as checkForCliUpdate,Mc as checkSettingsDocument,Lc as checkSettingsFile,vl as clearCommandContextReferences,gr as clearContextReferences,Eu as clearConversationHistory,Il as closeCommandBackgroundTask,ml as compactCommandContext,Yf as compareSemverVersions,wp as createAgentRuntime,Kn as createAgentTool,vt as createBackgroundGroupExecutionEntryId,Pa as createBackgroundProcessTool,_t as createBackgroundTaskExecutionEntryId,_c as createBuiltinCommandModule,kf as createCommandExecutionTool,$u as createCommandMemoryStores,Qu as createCommandPendingMemoryStore,Zu as createCommandProjectMemoryStore,pr as createContextReferenceItem,ra as createDefaultTools,M as createExecutionOriginMetadata,bt as createExecutionWorkspaceSnapshot,Ht as createExecutionWorkspaceTaskSpawner,In as createInProcessSubagentRunner,Lf as createInteractiveRuntime,zt as createLineDetailPage,Rt as createMainThreadDetailPage,gt as createMainThreadExecutionEntryId,bn as createModelCommandToolProjection,gu as createPluginRegistryReloadRequestedEffect,hu as createPluginTuiRequestedEffect,vd as createProjectSessionStore,Cn as createProjectedCommandExecutionTools,Or as createPromptFileReferenceHistoryEntry,rl as createProviderFromSettings,yn as createProviderSafeModelCommandToolName,Md as createQuery,Au as createSessionExitRequestedEffect,ku as createSessionPickerRequestedEffect,Ou as createSessionRenamedEffect,Tp as createStatelessRuntime,ko as createSubagentLogger,An as createSubagentSession,mc as createSystemCommands,Wf as createTestInteractiveSession,yd as createUserSessionStore,bc as deleteProviderProfile,ao as deleteSettings,ff as deleteUserLocalMemoryItem,df as disableUserLocalMemoryItem,bs as discoverTaskFiles,mo as evaluateReversibleToolSafety,cd as executeSkill,hp as formatCliUpdateCheckMessage,mp as formatCliUpdateNotice,Ol as formatCommandBackgroundTask,kl as formatCommandBackgroundTaskList,wl as formatCommandHelpMessage,nu as formatCommandPermissionsMessage,Nu as formatCommandSessionReplayValidationReport,d as formatEnvReference,Xl as formatInvalidPermissionModeMessage,Hl as formatLanguageUsageMessage,hd as formatOrgPolicyViolationMessage,xn as formatProjectedModelCommandToolPromptDescription,Dr as formatPromptFileReferenceDiagnostics,Cs as formatTaskContext,jd as generateSessionName,fn as getBuiltInAgent,mn as getForkWorkerSuffix,Wc as getProviderSettingsPaths,fp as getStartupCliUpdateNotice,pn as getSubagentSuffix,to as getUserSettingsPath,op as getUserUpdateCheckCachePath,Er as hasBlockingPromptFileReferenceDiagnostics,td as hasSensitiveCommandMemoryContent,ee as hasUsableSecretReference,zu as inspectCommandEditCheckpoint,uf as inspectUserLocalMemoryItem,Ud as inspectUserLocalStorage,gd as isApiKeyPlaintext,ed as isCommandMemoryType,g as isEnvReference,ks as isMemoryType,Xf as isNewerSemverVersion,Yl as isPermissionMode,Af as isSlashCommand,cu as isStatusLineCommandSettingsPatch,_r as listActiveContextReferences,Nl as listCommandBackgroundTasks,hl as listCommandContextReferences,Ru as listCommandEditCheckpoints,eu as listCommandSessionAllowedTools,nd as listCommandUsedMemoryReferences,bd as listResumableSessionSummaries,lf as listUserLocalMemoryItems,md as loadOrgPolicy,ws as loadTaskContext,wc as mergeProviderPatch,Vc as mergeProviders,Bc as mergeSettings,F as normalizeModelCommandName,Al as parseCommandBackgroundLogCursor,yt as parseExecutionWorkspaceEntryId,Ya as parseFrontmatter,Mf as parseInput,Vl as parseLanguageArgument,Jl as parsePermissionModeArgument,Mr as parsePromptFileReferences,Du as parseSessionNameArgument,xs as parseTaskFile,xf as planSelfHostingVerification,ad as preprocessShellCommands,jc as probeProviderProfile,H as projectPaths,Bf as promptForApproval,ll as readAutoCompactThreshold,ul as readAutoCompactThresholdSource,Pl as readCommandBackgroundTaskLog,cl as readCommandContextState,Ql as readCommandPermissionMode,tu as readCommandPermissionsState,ju as readCommandSessionInfo,ys as readCurrentGitBranch,pf as readEnabledUserLocalMemoryItem,el as readMergedProviderSettings,Rc as readMergedProviderSettingsFromPaths,tp as readPackageVersion,nl as readProviderSettings,q as readSettings,lu as readStatusLineSettings,sp as readUpdateCheckCache,rd as recordCommandMemoryEvent,_l as removeCommandContextReference,hr as removeContextReference,pl as resetAutoCompactThresholdSetting,Gf as resetUserConfig,Hc as resolveActiveProvider,tl as resolveEnvDefaultProvider,ne as resolveEnvReference,Kf as resolveGitBranch,xd as resolveLatestSessionId,Zl as resolvePermissionModeAdapter,_u as resolvePluginCommandAdapter,zr as resolvePromptFileReferencePaths,Rr as resolvePromptFileReferences,Gc as resolveProviderSettingsWriteTargetPath,Sd as resolveSessionIdByIdOrName,no as resolveSettingsPathForScope,Ao as resolveSubagentLogDir,Bd as resolveUserLocalStorageRoot,Bu as restoreCommandEditCheckpoint,I as retrieveAgentToolDeps,Vu as rollbackCommandEditCheckpoint,xl as sanitizeProviderProfileName,Ss as selectRelevantTasks,dl as setCommandAutoCompactThreshold,yc as setCurrentProvider,cf as setUserLocalMemoryItem,pp as shouldRunStartupCliUpdateCheck,Vn as storeAgentToolDeps,id as substituteVariables,bl as suggestProviderProfileName,ft as summarizeBackgroundJobGroup,Ac as testProviderProfileCommand,vr as toContextReferenceRecords,B as toPromptFileReferenceRecords,jf as tokeniseSlashCommand,Sf as transitionSelfHostingLoop,ro as updateModelInSettings,Ts as updateTaskFileStatus,mr as upsertContextReference,vc as upsertProviderProfile,Ei as userPaths,Mu as validateCommandSessionReplayLog,xc as validateProviderProfile,Ha as wrapEditCheckpointTools,ho as wrapReversibleExecutionTools,fl as writeAutoCompactThresholdSetting,$l as writeCommandPermissionMode,J as writeSettings,cp as writeUpdateCheckCache};
1
+ import{$ as e,$n as t,$r as n,$t as r,A as i,An as a,Ar as o,At as s,B as c,Bn as l,Br as u,Bt as d,C as f,Cn as p,Cr as ee,Ct as te,D as ne,Dn as re,Dr as ie,Dt as ae,E as oe,En as se,Er as ce,Et as le,F as ue,Fn as de,Fr as fe,Ft as pe,G as me,Gn as he,Gr as ge,Gt as _e,H as ve,Hn as ye,Hr as be,Ht as xe,I as Se,In as Ce,Ir as we,It as Te,J as Ee,Jn as De,Jr as Oe,Jt as ke,K as Ae,Kn as je,Kr as Me,Kt as Ne,L as Pe,Ln as Fe,Lr as Ie,Lt as Le,M as Re,Mn as ze,Mr as Be,Mt as Ve,N as He,Nn as Ue,Nr as We,Nt as Ge,O as Ke,On as qe,Or as Je,Ot as Ye,P as Xe,Pn as Ze,Pr as m,Pt as Qe,Q as $e,Qn as et,Qr as tt,Qt as nt,R as rt,Rn as it,Rr as at,Rt as ot,S as st,Sn as ct,Sr as lt,St as ut,T as dt,Tn as ft,Tr as pt,Tt as mt,U as ht,Un as gt,Ur as _t,Ut as vt,V as yt,Vn as bt,Vr as xt,Vt as St,W as Ct,Wn as wt,Wr as Tt,Wt as Et,X as Dt,Xn as Ot,Xr as kt,Xt as At,Y as jt,Yn as Mt,Yr as Nt,Yt as Pt,Z as Ft,Zn as It,Zr as Lt,Zt as Rt,_ as zt,_n as Bt,_r as Vt,_t as Ht,a as Ut,ai as Wt,an as Gt,ar as Kt,at as qt,b as Jt,bn as Yt,br as Xt,bt as Zt,c as Qt,ci as $t,cn as en,cr as h,ct as tn,d as nn,di as rn,dn as an,dr as on,dt as sn,ei as cn,en as ln,er as un,et as dn,f as fn,fi as pn,fn as mn,fr as hn,ft as gn,g as _n,gn as vn,gr as yn,gt as bn,h as xn,hn as Sn,hr as Cn,ht as wn,i as Tn,ii as En,in as Dn,ir as On,it as kn,j as An,jn,jr as Mn,jt as Nn,k as Pn,kn as Fn,kr as In,kt as Ln,l as Rn,li as zn,ln as Bn,lr as g,lt as Vn,m as Hn,mi as Un,mn as Wn,mr as Gn,mt as Kn,n as _,ni as v,nn as qn,nr as Jn,nt as Yn,o as Xn,oi as Zn,on as Qn,or as $n,ot as er,p as tr,pi as nr,pn as rr,pr as y,pt as ir,q as ar,qn as or,qr as sr,qt as cr,r as lr,ri as ur,rn as dr,rr as fr,rt as pr,s as b,si as mr,sn as hr,sr as gr,st as _r,t as vr,ti as x,tn as yr,tr as br,tt as xr,u as Sr,ui as Cr,un as wr,ur as S,ut as Tr,v as Er,vn as Dr,vr as Or,vt as kr,w as Ar,wn as jr,wr as Mr,wt as Nr,x as Pr,xn as Fr,xr as Ir,xt as Lr,y as Rr,yn as zr,yr as Br,yt as Vr,z as Hr,zn as Ur,zr as Wr,zt as Gr}from"./interactive-C93XBn4U.js";import C,{dirname as w,isAbsolute as Kr,join as T,resolve as E}from"node:path";import{homedir as qr}from"node:os";import{existsSync as Jr,lstatSync as Yr,mkdirSync as Xr,readFileSync as D,writeFileSync as Zr}from"node:fs";import{createDefaultBackgroundTaskRunners as Qr}from"@robota-sdk/agent-executor";import{createZodFunctionTool as $r}from"@robota-sdk/agent-tools";import{z as O}from"zod";import{fileURLToPath as ei}from"node:url";var ti=class{settingsPath;fs;constructor(e,t=new x){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=w(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:{}}},ni=class{pluginsDir;cacheDir;registryPath;settingsStore;marketplaceClient;exec;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.cacheDir=T(this.pluginsDir,`cache`),this.registryPath=T(this.pluginsDir,`installed_plugins.json`),this.settingsStore=e.settingsStore,this.marketplaceClient=e.marketplaceClient,this.exec=e.exec,this.fs=e.fs??new x}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=T(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=T(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=w(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 k(e,t=new x){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 A(e,t,n=new x){let r=w(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(e,JSON.stringify(t,null,2),`utf-8`)}function ri(e,t,n=new x){let r=T(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=w(r);n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.writeFileSync(r,JSON.stringify(i,null,2),`utf-8`)}}const j=6e4;var ii=class{pluginsDir;exec;marketplacesDir;registryPath;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.exec=e.exec,this.marketplacesDir=T(this.pluginsDir,`marketplaces`),this.registryPath=T(this.pluginsDir,`known_marketplaces.json`),this.fs=e.fs??new x}addMarketplace(e){let t=`temp-`+Date.now().toString(36),n=T(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:j,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone marketplace: ${t}`)}}let r=T(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=k(this.registryPath,this.fs);if(a[i])throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace "${i}" already exists`);let o=T(this.marketplacesDir,i);return this.fs.renameSync(n,o),a[i]={source:e,installLocation:o,lastUpdated:new Date().toISOString()},A(this.registryPath,a,this.fs),i}removeMarketplace(e){let t=k(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);ri(this.pluginsDir,e,this.fs),this.fs.existsSync(n.installLocation)&&this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),delete t[e],A(this.registryPath,t,this.fs)}updateMarketplace(e){let t=k(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:j,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(),A(this.registryPath,t,this.fs)}listMarketplaces(){let e=k(this.registryPath,this.fs);return Object.entries(e).map(([e,t])=>({name:e,source:t.source,lastUpdated:t.lastUpdated}))}fetchManifest(e){let t=k(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);let n=T(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=k(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:j,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 ai(e){let t=new b({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 oi=[`preferences`,`view-state`,`memory-projections`,`task-associations`,`workflow-metadata`,`inspection-index`],M=[{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 N(e){return e.toISOString()}function si(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!C.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function ci(){return process.env.HOME??qr()}function li(e,t){let n=C.relative(e,t);return n===``||!n.startsWith(`..`)&&!C.isAbsolute(n)}async function ui(e,t){let n=e;for(;C.dirname(n)!==n;)try{let r=await t.realpath(n),i=C.relative(n,e);return C.resolve(r,i)}catch{n=C.dirname(n)}try{return await t.realpath(n)}catch{return C.resolve(e)}}async function P(e){let t=e.fsAsync??new v,n=C.resolve(e.activeRepositoryRoot);si(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?C.join(e.homeDir??ci(),`.robota`):e.storageRoot;si(`userLocalStorageRoot`,r);let i=C.resolve(r),a=await ui(i,t);if(li(await ui(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function F(e,t){return C.join(e,t)}async function di(e,t,n){let r=F(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=C.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:N(new Date(o.birthtimeMs)),lastUsedAt:N(new Date(o.mtimeMs)),enabled:!0,deleteAvailable:!0,disableAvailable:!1}}))).sort((e,t)=>e.key.localeCompare(t.key))}async function fi(e){let t=e.fsAsync??new v,n=await P(e),r=C.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all(M.map(async e=>{let r=F(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await di(n,e.category,t);return{category:e.category,purpose:e.purpose,mayExecuteCommands:e.mayExecuteCommands,storageLocation:r,itemCount:a.length,items:a}})),generatedAt:N((e.now??(()=>new Date))())}}const I=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],L=`.json`,pi=/^[a-z0-9][a-z0-9._-]*$/u,mi={"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 R(e){return e.toISOString()}function hi(e){return I.includes(e)}function z(e){if(!hi(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function B(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!pi.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function V(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 H(e){return V(`value`,e,240)}function U(e,t){return`${e}__${t}${L}`}async function W(e){let t=await P(e);return{root:t,memoryRoot:C.join(t,`memory-projections`)}}function G(e,t){let n=JSON.parse(e),r=K(n,`category`);if(n.schemaVersion!==1)throw Error(`Unsupported user-local memory schema at ${t}`);return{schemaVersion:1,category:z(r),key:K(n,`key`),value:K(n,`value`),summary:K(n,`summary`),source:K(n,`source`),scope:K(n,`scope`),createdAt:K(n,`createdAt`),lastUsedAt:K(n,`lastUsedAt`),enabled:gi(n,`enabled`)}}function K(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function gi(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function q(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:H(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:mi[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function J(e,t,n){return q(e,t,G(await n.readFile(t,`utf8`),t))}async function Y(e){let t=z(e.category),n=B(`key`,e.key),{root:r,memoryRoot:i}=await W(e);return{root:r,storageLocation:C.join(i,U(t,n))}}async function _i(e){let t=e.fsAsync??new v,n=z(e.category),r=B(`key`,e.key),i=V(`summary`,e.summary,240),a=V(`source`,e.source,80),o=V(`scope`,e.scope??`user`,120),s=H(e.value),c=R((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await W(e),d=C.join(u,U(n,r)),f=c;try{f=G(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`),q(l,d,p)}async function vi(e){let t=e.fsAsync??new v,{root:n,memoryRoot:r}=await W(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(L)).map(e=>J(n,C.join(r,e.name),t)));return{root:n,activeRepositoryRoot:C.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function X(e){let t=e.fsAsync??new v,{root:n,storageLocation:r}=await Y(e);return J(n,r,t)}async function yi(e){let t=e.fsAsync??new v,{root:n,storageLocation:r}=await Y(e),i={...G(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:R((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),q(n,r,i)}async function bi(e){let t=e.fsAsync??new v,{storageLocation:n}=await Y(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}async function xi(e){let t=await X(e);return t.enabled?t:null}const Si=[`test`,`typecheck`,`build`],Ci={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 wi(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))):[]}function Ti(e){return e.flatMap(e=>Si.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 Ei(){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 Di(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 Oi(){return{id:`rollback-on-failure`,phase:`recover`,description:`Use the existing edit checkpoint restore path if verification fails.`,required:!0}}function ki(e){if(e.changedFiles.length===0)throw Error(`Self-hosting verification requires at least one changed file.`);let t=e.baseRef??`origin/develop`,n=wi(e.packageScopes),r=[...Ei(),...Ti(n),Di(t),Oi()];return{changedFiles:[...e.changedFiles],packageScopes:n,baseRef:t,steps:r}}function Ai(e,t){let n=Ci[e][t];if(!n)throw Error(`Invalid self-hosting loop transition: ${e} -> ${t}`);return n}function ji(e){if(!e||e.length===0)return;let[t,...n]=e;if(t!==void 0)return[t,...n]}function Mi(e){let t=ji(e),n=t===void 0?O.string().describe(`Registered model-invocable command name to execute`):O.enum(t).describe(`Registered model-invocable command name to execute`);return O.object({command:n,args:O.string().optional().describe(`Arguments to pass to the command`)})}function Ni(e){if(e.commandNames!==void 0)return e.commandNames;if(e.commandDescriptors!==void 0)return e.commandDescriptors.map(e=>m(e.name))}function Pi(e){return`- ${m(e.name)}${e.argumentHint?` ${e.argumentHint}`:``}: ${e.description}`}function Fi(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(Pi)].join(`
2
+ `)}function Ii(e){let t=Mi(Ni(e));return $r(`ExecuteCommand`,Fi(e.commandDescriptors),t,async n=>{let r=t.parse(n),i=m(r.command);return e.isModelInvocable(i)?fe(i,await e.execute(i,r.args??``)):JSON.stringify({success:!1,command:i,error:`Command is not model-invocable: ${i}`})})}function Li(e){return/^\/\S/.test(e)}function Ri(e){let t=e.slice(1).trim().split(/\s+/);return{name:t[0]??``,args:t.slice(1).filter(e=>e.length>0)}}function zi(e){if(!Li(e))return{type:`user-message`,text:e};let{name:t,args:n}=Ri(e);return{type:`slash-command`,name:t,args:n}}function Bi(e){return e.map(e=>({name:e.name,description:e.description}))}function Vi(e,t){let n=e=>{t.write({type:`assistant-chunk`,chunk:e})},r=e=>{t.write({type:`assistant-done`,fullText:e.response}),t.setBusy(!1)},i=e=>{t.write({type:`tool-call`,id:e.executionId??e.toolName,name:e.toolName,args:e.firstArg})},a=e=>{t.write({type:`tool-result`,id:e.executionId??e.toolName,name:e.toolName,result:e.toolResultData??e.result})},o=e=>{t.setBusy(!1),t.write({type:`error`,error:e})},s=()=>{t.setBusy(!1)};return e.on(`text_delta`,n),e.on(`complete`,r),e.on(`tool_start`,i),e.on(`tool_end`,a),e.on(`error`,o),e.on(`interrupted`,s),()=>{e.off(`text_delta`,n),e.off(`complete`,r),e.off(`tool_start`,i),e.off(`tool_end`,a),e.off(`error`,o),e.off(`interrupted`,s)}}function Hi(e){let{channel:t,commandModules:n,_testSession:r}=e,i=null,a=null;async function o(e){if(!i)return;let n=zi(e);if(n.type===`user-message`){t.write({type:`user-message`,text:e}),t.setBusy(!0),await i.submit(e);return}let{name:r,args:a}=n,o=await i.executeCommand(r,a.join(` `));o?t.write({type:`command-result`,name:r,output:o.message}):t.write({type:`error`,error:Error(`Unknown command "/${r}". Type /help for help.`)})}return{async start(){if(r)i=r;else{let{provider:r,cwd:a,sessionStore:o,permissionMode:s}=e;if(!r)throw Error(`createInteractiveRuntime: provider is required`);if(!a)throw Error(`createInteractiveRuntime: cwd is required`);i=new b({provider:r,cwd:a,sessionStore:o,commandModules:n,permissionMode:s,askHandler:e=>t.askUser(e)})}a=Vi(i,t);let s=i.listCommands();t.setAvailableCommands(Bi(s)),t.onSubmit(o),await t.start()},async stop(){try{a?.(),await t.stop()}catch{}await i?.shutdown(),i=null}}}const Ui=[`Allow once`,`Allow for this session`,`Deny`];function Wi(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 Gi(e,t,n){e.writeLine(``),e.writeError(`[Permission Required] Tool: ${t}`),e.writeLine(` ${Wi(n)}`),e.writeLine(``);let r=await e.select(Ui,0);return r===1?`allow-session`:r===0}function Ki(){let e=g();return{deleted:h(e),path:e}}function qi(e){try{let t=Ji(e);if(!t)return;let n=D(T(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 Ji(e){let t=E(e),n=w(t);for(;n!==t;){let e=Yi(T(t,`.git`),t);if(e)return e;t=n,n=w(t)}return Yi(T(t,`.git`),t)}function Yi(e,t){if(!Jr(e))return;let n=Yr(e);if(n.isDirectory())return e;if(!n.isFile())return;let r=D(e,`utf8`).trim();if(!r.startsWith(`gitdir:`))return;let i=r.slice(7).trim();return Kr(i)?i:E(t,i)}function Xi(e,t){let n=Z(e),r=Z(t);if(n===void 0||r===void 0)return Math.sign(e.localeCompare(t));let i=$(n.major,r.major)||$(n.minor,r.minor)||$(n.patch,r.patch);return i===0?Qi(n.prerelease,r.prerelease):i}function Zi(e,t){return Xi(e,t)>0}function Z(e){let[t,n]=(e.trim().replace(/^v/,``).split(`+`)[0]??``).split(`-`,2),[r,i,a]=t.split(`.`),o=Q(r),s=Q(i),c=Q(a);if(!(o===void 0||s===void 0||c===void 0))return{major:o,minor:s,patch:c,prerelease:n?n.split(`.`):[]}}function Q(e){if(!(e===void 0||!/^\d+$/.test(e)))return Number(e)}function $(e,t){return Math.sign(e-t)}function Qi(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=$i(n,i);if(a!==0)return a}return 0}function $i(e,t){let n=Q(e),r=Q(t);return n!==void 0&&r!==void 0?$(n,r):n===void 0?r===void 0?Math.sign(e.localeCompare(t)):1:-1}function ea(e){let t=w(ei(e)),n=[T(t,`..`,`..`,`package.json`),T(t,`..`,`package.json`)];for(let e of n)try{let t=D(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 ta=`@robota-sdk/agent-cli`,na=`https://registry.npmjs.org`,ra=1440*60*1e3,ia=1500;function aa(e=process.env.HOME??process.env.USERPROFILE??`/`){return T(e,`.robota`,`update-check.json`)}function oa(e){if(Jr(e))try{return xa(JSON.parse(D(e,`utf8`)))}catch{return}}function sa(e,t){Xr(w(e),{recursive:!0}),Zr(e,JSON.stringify(t,null,2)+`
3
+ `,`utf8`)}async function ca(e){if(e.disabled===!0)return{status:`skipped`,reason:`disabled`};let t=e.packageName??`@robota-sdk/agent-cli`,n=e.cachePath??aa(),r=e.now??new Date,i=e.ttlMs??864e5;if(e.force!==!0){let a=oa(n);if(a!==void 0&&_a(a,r,i,t))return ha(a,e.currentVersion)}let a=await la(e,t,n,r);return typeof a==`string`?ga(e.currentVersion,a):a}async function la(e,t,n,r){let i=await va({fetchImpl:e.fetchImpl??fetch,packageName:t,registryUrl:e.registryUrl??`https://registry.npmjs.org`,timeoutMs:e.timeoutMs??1500});return i.ok?(ua(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,latestVersion:i.version}),i.version):(ua(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,errorMessage:i.errorMessage}),{status:`error`,errorMessage:i.errorMessage})}function ua(e,t){try{sa(e,t)}catch{}}async function da(e){let t=await ca(e);return t.status===`update_available`?t.notice:void 0}function fa(e){return e.printMode===!1&&e.disableUpdateCheck===!1}function pa(e){return[`Robota update available: ${e.currentVersion} -> ${e.latestVersion}.`,`Run ${e.installCommand}`].join(` `)}function ma(e){return e.status===`update_available`?pa(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 ha(e,t){return e.errorMessage===void 0?e.latestVersion===void 0?{status:`error`,errorMessage:`Cached update check has no latest version`}:ga(t,e.latestVersion):{status:`error`,errorMessage:e.errorMessage}}function ga(e,t){return Zi(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 _a(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 va(e){try{return{ok:!0,version:await ya(e)}}catch(e){return{ok:!1,errorMessage:e instanceof Error?e.message:String(e)}}}async function ya(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=ba(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 ba(e,t){return`${e.replace(/\/+$/,``)}/${encodeURIComponent(t)}`}function xa(e){if(!Sa(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 Sa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ca(e){let t=g(),n={settings:{read:()=>S(t),write:e=>y(t,e)}},r=e.backgroundTaskRunners??Qr(),i=e.commandModules??[],a=e.commandHostAdapters??n,o=`sessionStore`in e?e.sessionStore:_(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 b({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 wa(e){let t=Ca({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{Ne as AUTO_COMPACT_THRESHOLD_SETTINGS_KEY,t as AgentExecutor,Ve as BACKGROUND_COMMAND_DESCRIPTION,Ge as BACKGROUND_COMMAND_USAGE,Wr as BUILT_IN_AGENTS,Lt as BackgroundJobOrchestrator,jn as BuiltinCommandSource,ni as BundlePluginInstaller,Ce as BundlePluginLoader,Se as CLEAR_COMMAND_DESCRIPTION,ra as CLI_UPDATE_CACHE_TTL_MS,ta as CLI_UPDATE_PACKAGE_NAME,na as CLI_UPDATE_REGISTRY_URL,ia as CLI_UPDATE_TIMEOUT_MS,Pe as COST_COMMAND_DESCRIPTION,de as CommandRegistry,cr as DEFAULT_AUTO_COMPACT_THRESHOLD,un as DEFAULT_GOAL_MAX_ITERATIONS,br as DEFAULT_GOAL_NO_PROGRESS_LIMIT,kn as DEFAULT_STATUS_LINE_COMMAND_SETTINGS,ge as EXECUTION_ORIGIN_METADATA_KEYS,rt as EXIT_COMMAND_DESCRIPTION,Xt as EditCheckpointStore,$n as GOAL_SIGNAL_TOOL_NAME,Jn as GoalController,xe as HELP_COMMAND_DESCRIPTION,b as InteractiveSession,le as LANGUAGE_COMMAND_ARGUMENT_HINT,ae as LANGUAGE_COMMAND_DESCRIPTION,Er as MEMORY_COMMAND_ARGUMENT_HINT,Rr as MEMORY_COMMAND_DESCRIPTION,Jt as MEMORY_COMMAND_USAGE,Fe as MEMORY_INDEX_MAX_BYTES,it as MEMORY_INDEX_MAX_LINES,Je as MODEL_COMMAND_TOOL_PREFIX,ii as MarketplaceClient,gn as PERMISSIONS_COMMAND_DESCRIPTION,ir as PERMISSION_MODE_ARGUMENT_HINT,Kn as PERMISSION_MODE_COMMAND_DESCRIPTION,Ft as PLUGIN_COMMAND_ARGUMENT_HINT,$e as PLUGIN_COMMAND_DESCRIPTION,In as PROVIDER_SAFE_TOOL_NAME_PATTERN,Gt as PluginCommandSource,ti as PluginSettingsStore,Ur as ProjectMemoryStore,et as PromptExecutor,Qn as ProviderConfigError,Ye as RECOMMENDED_RESPONSE_LANGUAGES,e as RELOAD_PLUGINS_COMMAND_DESCRIPTION,Hr as RENAME_COMMAND_DESCRIPTION,c as RENAME_COMMAND_USAGE,yt as RESUME_COMMAND_DESCRIPTION,Pn as REWIND_COMMAND_ARGUMENT_HINT,i as REWIND_COMMAND_DESCRIPTION,qt as STATUSLINE_COMMAND_ARGUMENT_HINT,er as STATUSLINE_COMMAND_DESCRIPTION,Gn as SettingsParseError,Cn as SkillCommandSource,Ze as SystemCommandExecutor,I as USER_LOCAL_MEMORY_CATEGORIES,oi as USER_LOCAL_STORAGE_CATEGORIES,M as USER_LOCAL_STORAGE_CATEGORY_DEFINITIONS,ve as VALIDATE_SESSION_COMMAND_DESCRIPTION,wn as VALID_PERMISSION_MODES,ke as addCommandContextReference,an as applyActiveModelChange,sn as applyPresetToSession,mn as applyProviderConfiguration,rr as applyProviderSwitch,_r as applyStatusLineSettings,we as assembleSubagentPrompt,Qe as buildBackgroundCommandSubcommands,On as buildGoalContinuationPrompt,Kt as buildGoalStartPrompt,Ln as buildLanguageCommandSubcommands,Pr as buildMemoryCommandSubcommands,bn as buildPermissionModeSubcommands,dn as buildPluginCommandSubcommands,En as buildPromptWithFileReferences,jr as buildProviderProfile,ft as buildProviderSetupPatch,An as buildRewindCommandSubcommands,tn as buildStatusLineCommandSubcommands,pe as cancelCommandBackgroundTask,ca as checkForCliUpdate,Yt as checkSettingsDocument,Fr as checkSettingsFile,Pt as clearCommandContextReferences,zn as clearContextReferences,ht as clearConversationHistory,Te as closeCommandBackgroundTask,At as compactCommandContext,Xi as compareSemverVersions,Ca as createAgentRuntime,ee as createAgentTool,Me as createBackgroundGroupExecutionEntryId,Or as createBackgroundProcessTool,sr as createBackgroundTaskExecutionEntryId,ze as createBuiltinCommandModule,Ii as createCommandExecutionTool,st as createCommandMemoryStores,f as createCommandPendingMemoryStore,Ar as createCommandProjectMemoryStore,Cr as createContextReferenceItem,Br as createDefaultTools,Oe as createExecutionOriginMetadata,Tt as createExecutionWorkspaceSnapshot,xt as createExecutionWorkspaceTaskSpawner,gr as createGoalStatusTool,ce as createInProcessSubagentRunner,Hi as createInteractiveRuntime,be as createLineDetailPage,_t as createMainThreadDetailPage,Nt as createMainThreadExecutionEntryId,o as createModelCommandToolProjection,xr as createPluginRegistryReloadRequestedEffect,Yn as createPluginTuiRequestedEffect,_ as createProjectSessionStore,Mn as createProjectedCommandExecutionTools,Wt as createPromptFileReferenceHistoryEntry,hr as createProviderFromSettings,Be as createProviderSafeModelCommandToolName,ai as createQuery,Ct as createSessionExitRequestedEffect,me as createSessionPickerRequestedEffect,Ae as createSessionRenamedEffect,wa as createStatelessRuntime,De as createSubagentLogger,ie as createSubagentSession,Ue as createSystemCommands,lr as createUserSessionStore,se as deleteProviderProfile,h as deleteSettings,bi as deleteUserLocalMemoryItem,yi as disableUserLocalMemoryItem,bt as discoverTaskFiles,Ot as evaluateReversibleToolSafety,xn as executeSkill,fr as extractGoalSignal,ma as formatCliUpdateCheckMessage,pa as formatCliUpdateNotice,Le as formatCommandBackgroundTask,ot as formatCommandBackgroundTaskList,vt as formatCommandHelpMessage,Ht as formatCommandPermissionsMessage,ar as formatCommandSessionReplayValidationReport,nn as formatEnvReference,kr as formatInvalidPermissionModeMessage,s as formatLanguageUsageMessage,Qt as formatOrgPolicyViolationMessage,We as formatProjectedModelCommandToolPromptDescription,Zn as formatPromptFileReferenceDiagnostics,ye as formatTaskContext,vr as generateSessionName,u as getBuiltInAgent,Ie as getForkWorkerSuffix,Sn as getProviderSettingsPaths,da as getStartupCliUpdateNotice,at as getSubagentSuffix,g as getUserSettingsPath,aa as getUserUpdateCheckCachePath,mr as hasBlockingPromptFileReferenceDiagnostics,dt as hasSensitiveCommandMemoryContent,fn as hasUsableSecretReference,Re as inspectCommandEditCheckpoint,X as inspectUserLocalMemoryItem,fi as inspectUserLocalStorage,Rn as isApiKeyPlaintext,oe as isCommandMemoryType,tr as isEnvReference,l as isMemoryType,Zi as isNewerSemverVersion,Vr as isPermissionMode,Li as isSlashCommand,Vn as isStatusLineCommandSettingsPatch,rn as listActiveContextReferences,Gr as listCommandBackgroundTasks,Rt as listCommandContextReferences,He as listCommandEditCheckpoints,Zt as listCommandSessionAllowedTools,ne as listCommandUsedMemoryReferences,Tn as listResumableSessionSummaries,vi as listUserLocalMemoryItems,Sr as loadOrgPolicy,gt as loadTaskContext,re as mergeProviderPatch,vn as mergeProviders,Bt as mergeSettings,m as normalizeModelCommandName,d as parseCommandBackgroundLogCursor,kt as parseExecutionWorkspaceEntryId,yn as parseFrontmatter,zi as parseInput,Nn as parseLanguageArgument,Lr as parsePermissionModeArgument,ur as parsePromptFileReferences,Ee as parseSessionNameArgument,wt as parseTaskFile,ki as planSelfHostingVerification,_n as preprocessShellCommands,ct as probeProviderProfile,Ir as projectPaths,Gi as promptForApproval,nt as readAutoCompactThreshold,r as readAutoCompactThresholdSource,St as readCommandBackgroundTaskLog,ln as readCommandContextState,ut as readCommandPermissionMode,te as readCommandPermissionsState,jt as readCommandSessionInfo,he as readCurrentGitBranch,xi as readEnabledUserLocalMemoryItem,en as readMergedProviderSettings,Dr as readMergedProviderSettingsFromPaths,ea as readPackageVersion,Bn as readProviderSettings,S as readSettings,Tr as readStatusLineSettings,oa as readUpdateCheckCache,Ke as recordCommandMemoryEvent,yr as removeCommandContextReference,pn as removeContextReference,qn as resetAutoCompactThresholdSetting,Ki as resetUserConfig,zr as resolveActiveProvider,wr as resolveEnvDefaultProvider,Hn as resolveEnvReference,qi as resolveGitBranch,Ut as resolveLatestSessionId,Nr as resolvePermissionModeAdapter,pr as resolvePluginCommandAdapter,n as resolvePromptFileReferencePaths,cn as resolvePromptFileReferences,Wn as resolveProviderSettingsWriteTargetPath,Xn as resolveSessionIdByIdOrName,on as resolveSettingsPathForScope,Mt as resolveSubagentLogDir,P as resolveUserLocalStorageRoot,Xe as restoreCommandEditCheckpoint,Mr as retrieveAgentToolDeps,ue as rollbackCommandEditCheckpoint,Et as sanitizeProviderProfileName,je as selectRelevantTasks,dr as setCommandAutoCompactThreshold,qe as setCurrentProvider,_i as setUserLocalMemoryItem,fa as shouldRunStartupCliUpdateCheck,pt as storeAgentToolDeps,zt as substituteVariables,_e as suggestProviderProfileName,tt as summarizeBackgroundJobGroup,p as testProviderProfileCommand,nr as toContextReferenceRecords,$t as toPromptFileReferenceRecords,Ri as tokeniseSlashCommand,Ai as transitionSelfHostingLoop,hn as updateModelInSettings,or as updateTaskFileStatus,Un as upsertContextReference,Fn as upsertProviderProfile,lt as userPaths,Dt as validateCommandSessionReplayLog,a as validateProviderProfile,Vt as wrapEditCheckpointTools,It as wrapReversibleExecutionTools,Dn as writeAutoCompactThresholdSetting,mt as writeCommandPermissionMode,y as writeSettings,sa as writeUpdateCheckCache};
111
4
  //# sourceMappingURL=index.js.map