@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.
@@ -0,0 +1,111 @@
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 h,hasUsableSecretReference as ee,isEnvReference as g,isEnvReference as te,messageToHistoryEntry as _,resolveEnvReference as ne,runHooks as re,sumHistoryUsage as ie}from"@robota-sdk/agent-core";import{createHash as ae,randomUUID as v}from"node:crypto";import{basename as oe,dirname as y,isAbsolute as se,join as b,relative as x,resolve as S,sep as ce}from"node:path";import{homedir as C}from"node:os";import{constants as le,cpSync as ue,existsSync as w,mkdirSync as de,readFileSync as fe,readdirSync as pe,renameSync as me,rmSync as he,statSync as ge,unlinkSync as _e,writeFileSync as ve}from"node:fs";import{access as ye,copyFile as be,mkdir as xe,readFile as Se,readdir as Ce,realpath as we,rename as Te,rm as Ee,stat as De,writeFile as Oe}from"node:fs/promises";import{BackgroundTaskManager as ke,SubagentManager as Ae,createProviderFromConfig as je,isTerminalBackgroundTaskStatus as Me,normalizeProviderConfig as Ne}from"@robota-sdk/agent-executor";import{applyWorkspaceManifest as Pe,createAskUserQuestionTool as Fe,createBashTool as Ie,createEditTool as Le,createReadTool as Re,createShellTool as ze,createWriteTool as Be,createZodFunctionTool as Ve,globTool as He,grepTool as Ue,webFetchTool as We,webSearchTool as Ge}from"@robota-sdk/agent-tools";import{z as T}from"zod";import{AUTO_COMPACT_THRESHOLD as Ke,FileSessionLogger as qe,Session as Je,SessionStore as Ye,loadSessionLogEntries as Xe,replaySessionLogEntries as Ze,validateSessionReplayLogEntries as Qe}from"@robota-sdk/agent-session";import{appendFileSync as $e,existsSync as E,mkdirSync as et,readFileSync as D,readdirSync as tt,writeFileSync as nt}from"fs";import{basename as rt,dirname as it,join as O,resolve as at}from"path";function ot(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 st(e,t,n){let r=e.find(e=>e.sourcePath===t.sourcePath),i=e.filter(e=>e.sourcePath!==t.sourcePath),a=r?ft(r,t):t;return pt([...i,a],n)}function ct(e,t){let n=gt(t),r=e.find(e=>_t(e,n));return r?{references:e.filter(e=>e.sourcePath!==r.sourcePath),result:{removed:r}}:{references:[...e],result:{}}}function lt(e){return{removed:[...e]}}function ut(e){return e.filter(e=>e.status===`active`)}function dt(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 ft(e,t){return t.status===`active`?{...t,loadedAt:e.loadedAt}:{...e,byteLength:t.byteLength,originalReference:t.originalReference,lastUsedAt:t.lastUsedAt}}function pt(e,t){let n=t?.maxActiveReferences??8,r=t?.maxActiveBytes??262144,i=t?.maxObservedReferences??32,a=[],o=[...e];for(;mt(o)>n||ht(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 mt(e){return e.filter(e=>e.status===`active`).length}function ht(e){return e.reduce((e,t)=>e+(t.status===`active`?t.byteLength:0),0)}function gt(e){return e.startsWith(`@`)?e.slice(1):e}function _t(e,t){return e.relativePath===t||e.sourcePath===t||e.originalReference===t||e.originalReference===`@${t}`}function vt(e,t){return t.length===0?e:[e,`<robota_file_references>`,...t.map(e=>{let t=e.content.replaceAll(`</file>`,`<\\/file>`);return[`<file path="${St(e.relativePath)}" bytes="${e.byteLength}" reason="${e.reason}">`,t,`</file>`].join(`
2
+ `)}),`</robota_file_references>`].join(`
3
+
4
+ `)}function yt(e){return e.some(e=>e.severity===`error`)}function bt(e){return e.length===0?``:[`File reference error:`,...e.map(e=>`- ${e.reference}: ${e.message}`)].join(`
5
+ `)}function k(e){return e.map(({content:e,...t})=>t)}function xt(e){let t=k(e);return{id:`prompt_file_reference_${v()}`,timestamp:new Date,category:`event`,type:`prompt-file-reference`,data:{message:Ct(t),references:t}}}function St(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function Ct(e){return`Loaded file references: ${e.map(e=>`${e.relativePath} (${e.byteLength} B)`).join(`, `)}`}const wt=/(^|[\s([{])@([^\s)\]}>,;"'`]+)/g;function Tt(e){let t=[];for(let n of e.matchAll(wt)){let e=Et(n[2]??``);Dt(e)&&t.push({original:`@${e}`,path:e,index:n.index??0})}return t}function Et(e){let t=e.length;for(;t>0&&/[.,:;!?]/.test(e[t-1]??``);)--t;return e.slice(0,t)}function Dt(e){return e.length===0||e.includes(`://`)?!1:e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)||e.startsWith(`~/`)||e.startsWith(`.`)||e.includes(`.`)}function Ot(e,t){return e.startsWith(`~/`)?S(C(),e.slice(2)):se(e)?S(e):S(t,e)}function kt(e,t){let n=x(t,e);return n===``||!n.startsWith(`..`)&&!se(n)}function At(e,t){return x(e,t).split(ce).join(`/`)}var A=class{existsSync(e){return w(e)}readFileSync(e,t){return fe(e,t)}writeFileSync(e,t,n){ve(e,t,n??`utf8`)}mkdirSync(e,t){de(e,t)}readdirSync(e,t){return t?.withFileTypes?pe(e,{withFileTypes:!0}):pe(e)}statSync(e){return ge(e)}rmSync(e,t){he(e,t)}cpSync(e,t,n){ue(e,t,n)}renameSync(e,t){me(e,t)}get constants(){return le}},jt=class{async access(e,t){await ye(e,t)}async copyFile(e,t,n){await be(e,t,n)}async mkdir(e,t){await xe(e,t)}async readFile(e,t){return Se(e,t)}async readdir(e,t){return t?.withFileTypes?await Ce(e,{withFileTypes:!0}):Ce(e)}async realpath(e){return we(e)}async rename(e,t){await Te(e,t)}async rm(e,t){await Ee(e,t)}async stat(e){return De(e)}async writeFile(e,t,n){await Oe(e,t,n??`utf8`)}};async function Mt(e,t){let n=await Pt(t);for(let t of Tt(e))await Rt(t,0,[],n);return Ft(n)}async function Nt(e,t){let n=await Pt(t);for(let t of e)await Rt({original:`@${t}`,path:t,index:0},0,[],n);return Ft(n)}async function Pt(e){let t=e.fsAsync??new jt;return{rootPath:await Lt(e.cwd,t),limits:It(e.limits),reason:e.reason??`prompt-reference`,references:[],diagnostics:[],loadedPaths:new Set,totalBytes:0,fsAsync:t}}function Ft(e){return{references:e.references,diagnostics:e.diagnostics}}function It(e){return{maxDepth:e?.maxDepth??2,maxReferences:e?.maxReferences??8,maxFileBytes:e?.maxFileBytes??65536,maxTotalBytes:e?.maxTotalBytes??262144}}async function Lt(e,t){try{return await t.realpath(e)}catch{return S(e)}}async function Rt(e,t,n,r){if(!zt(e,t,r))return;let i=await Bt(e,r);if(i===void 0||!Vt(e,i,n,r))return;let a=await Ht(e,i,r);if(a===void 0)return;let o=await Ut(e,i,r);o!==void 0&&(r.loadedPaths.add(i),r.totalBytes+=a.byteLength,r.references.push(Wt(e,a,t,o,r)),await Gt(o,t,[...n,i],r))}function zt(e,t,n){return n.references.length>=n.limits.maxReferences?(j(n,`too-many-references`,e,`Too many file references.`),!1):t>n.limits.maxDepth?(j(n,`max-depth`,e,`File reference nesting is too deep.`),!1):!0}async function Bt(e,t){let n=Ot(e.path,t.rootPath);if(!kt(n,t.rootPath)){j(t,`outside-root`,e,`Referenced path is outside the workspace.`);return}try{let r=await t.fsAsync.realpath(n);if(kt(r,t.rootPath))return r;j(t,`outside-root`,e,`Referenced path resolves outside the workspace.`)}catch{j(t,`not-found`,e,`Referenced file was not found.`)}}function Vt(e,t,n,r){return n.includes(t)?(j(r,`circular-reference`,e,`Circular file reference detected.`),!1):!r.loadedPaths.has(t)}async function Ht(e,t,n){try{let r=await n.fsAsync.stat(t);if(r.isDirectory()){j(n,`directory-not-supported`,e,`Directory references are not supported.`);return}if(r.size>n.limits.maxFileBytes){j(n,`file-too-large`,e,`Referenced file exceeds the per-file size limit.`);return}if(n.totalBytes+r.size>n.limits.maxTotalBytes){j(n,`total-too-large`,e,`Referenced files exceed the total size limit.`);return}return{sourcePath:t,byteLength:r.size}}catch{j(n,`unreadable`,e,`Referenced file could not be inspected.`);return}}async function Ut(e,t,n){try{return await n.fsAsync.readFile(t,`utf8`)}catch{j(n,`unreadable`,e,`Referenced file could not be read.`);return}}function Wt(e,t,n,r,i){return{originalReference:e.original,sourcePath:t.sourcePath,relativePath:At(i.rootPath,t.sourcePath),reason:i.reason,depth:n,byteLength:t.byteLength,content:r}}async function Gt(e,t,n,r){for(let i of Tt(e))await Rt(i,t+1,n,r)}function j(e,t,n,r){e.diagnostics.push({code:t,severity:`error`,reference:n.original,message:r,path:n.path})}function Kt(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&(e.message.includes(`aborted`)||e.message.includes(`abort`))}function qt(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 Jt(e,t,n,r,i,a){let o=qt(t,r),s=en(t,r,i);return{response:e,history:n,toolSummaries:o,contextState:i,...s&&{usage:s},...a&&a.length>0?{promptFileReferences:[...a]}:{}}}function Yt(e,t,n,r){let i=qt(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=en(e,n,r);return{response:a.join(`
6
+
7
+ `),history:t,toolSummaries:i,contextState:r,...o&&{usage:o}}}function Xt(e){return{id:`usage_${v()}`,timestamp:new Date,category:`event`,type:`usage-summary`,data:e}}function Zt(e,t){return Xt({kind:`exact`,scope:`turn`,totalTokens:e.totalTokens,promptTokens:e.promptTokens,completionTokens:e.completionTokens,contextUsedTokens:0,contextMaxTokens:0,contextUsedPercentage:0,costStatus:`exact`,source:t})}async function Qt(e,t,n,r=[]){let i=await Nt(ut(r).map(e=>e.sourcePath),{cwd:t,reason:`manual`}),a=await Mt(e,{cwd:t}),o=[...i.diagnostics,...a.diagnostics];if(yt(o))throw Error(bt(o));let s=vt(e,$t([...i.references,...a.references])),c=n??(s===e?void 0:e),l=k(i.references),u=k(a.references),d=a.references.length>0?xt(a.references):void 0;return{modelInput:s,...c===void 0?{}:{hookInput:c},activeContextReferenceRecords:l,promptFileReferenceRecords:u,...d===void 0?{}:{promptFileReferenceEntry:d}}}function $t(e){return[...new Map(e.map(e=>[e.sourcePath,e])).values()]}function en(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 tn={write:()=>{},writeLine:()=>{},writeMarkdown:()=>{},writeError:()=>{},prompt:()=>Promise.resolve(``),select:()=>Promise.resolve(0),spinner:()=>({stop:()=>{},update:()=>{}})},nn=1e3;var rn=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:M(r.state)}),this.evaluateCompletion(r),M(r.state)}listGroups(){return[...this.groups.values()].map(e=>M(e.state))}getGroup(e){let t=this.groups.get(e);return t?M(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(M(e));this.groups.set(e.id,t),e.status===`completed`&&t.resolve(M(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&&Me(n.status)&&this.captureTask(e,n)}}handleTaskEvent(e){let t=an(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:M(e.state)}))}captureTask(e,t){return e.state.results.some(e=>e.taskId===t.id)?!1:(e.state.results=[...e.state.results,sn(t)],e.state.updatedAt=this.now(),!0)}evaluateCompletion(e){if(e.state.status===`completed`)return;if(!on(e.state)){this.emit({type:`background_job_group_updated`,group:M(e.state)});return}let t=this.now();e.state.status=`completed`,e.state.completedAt=t,e.state.updatedAt=t;let n=M(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 an(e){if(e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)return e.task}function on(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 sn(e){return{taskId:e.id,label:e.label,status:e.status,...e.result?.output?{summary:cn(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 cn(e){let t=e.trim();return t.length<=nn?t:`${t.slice(0,nn)}...`}function ln(e){let t=un(e,`completed`),n=un(e,`failed`),r=un(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=>dn(e))}}function un(e,t){return e.results.filter(e=>e.status===t).length}function dn(e){let t=fn(e),n=e.outputRef&&e.summary?` (output: ${e.outputRef})`:``;return`[${e.status}] ${e.label} ${e.taskId}: ${t}${n}`}function fn(e){let t=(e.error?.message??e.summary??``).replace(/\s+/g,` `).trim();return t.length>0?t:`(no summary)`}function M(e){return{...e,taskIds:[...e.taskIds],results:e.results.map(e=>({...e,...e.error?{error:{...e.error}}:{}}))}}const N={kind:`executionOriginKind`,sessionId:`executionOriginSessionId`,turnId:`executionOriginTurnId`,commandName:`executionOriginCommandName`,toolCallId:`executionOriginToolCallId`,skillId:`executionOriginSkillId`,label:`executionOriginLabel`};function P(e){return[`main`,e].join(`:`)}function F(e){return[`task`,e].join(`:`)}function I(e){return[`group`,e].join(`:`)}function pn(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 L(e){return{[N.kind]:e.kind,[N.sessionId]:e.sessionId,...e.turnId?{[N.turnId]:e.turnId}:{},...e.commandName?{[N.commandName]:e.commandName}:{},...e.toolCallId?{[N.toolCallId]:e.toolCallId}:{},...e.skillId?{[N.skillId]:e.skillId}:{},...e.label?{[N.label]:e.label}:{}}}function mn(e){let t=yn(e.groups),n=[hn(e.mainThread),...An(e.groups).map(e=>_n(e)),...kn(e.tasks).map(e=>gn(e,t.get(e.id)))].filter(t=>On(t,e.filter));return{sessionId:e.sessionId,selectedEntryId:e.selectedEntryId??n.find(e=>e.kind===`main_thread`)?.id??P(e.sessionId),updatedAt:n[0]?.updatedAt??e.mainThread.updatedAt,entries:n}}function hn(e){return{id:P(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:R(e.preview),unread:!1,attention:`none`,visibility:`default`,updatedAt:e.updatedAt,controls:[`select`]}}function gn(e,t){return{id:F(e.id),sourceId:e.id,kind:`background_task`,parentId:e.parentTaskId?F(e.parentTaskId):P(e.parentSessionId),...t?{groupId:I(t)}:{},origin:vn(e.metadata,{kind:`system`,sessionId:e.parentSessionId}),taskKind:e.kind,status:e.status,title:e.label,subtitle:xn(e),preview:wn(e),currentAction:e.currentAction,unread:e.unread,attention:Tn(e),visibility:En(e),updatedAt:e.lastActivityAt??e.updatedAt,controls:bn(e)}}function _n(e){let t=R(e.results.map(e=>e.summary??e.error?.message).join(` `));return{id:I(e.id),sourceId:e.id,kind:`background_group`,parentId:P(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:Dn(e),visibility:e.status===`completed`?`collapsed`:`default`,updatedAt:e.updatedAt,controls:e.status===`running`?[`select`,`wait`]:[`select`]}}function vn(e,t){let n=jn(e?.[N.kind]),r=z(e?.[N.sessionId]);return{kind:n??t.kind,sessionId:r??t.sessionId,turnId:z(e?.[N.turnId])??t.turnId,commandName:z(e?.[N.commandName])??t.commandName,toolCallId:z(e?.[N.toolCallId])??t.toolCallId,skillId:z(e?.[N.skillId])??t.skillId,label:z(e?.[N.label])??t.label}}function yn(e){return new Map(e.flatMap(e=>e.taskIds.map(t=>[t,e.id])))}function bn(e){let t=[`select`];return Me(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 xn(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: ${Cn(e.nextFireAt)}`;return t===void 0?n:`↻ wake "${Sn(t)}" · ${n}`}return e.cwd}function Sn(e){let t=e.trim();return t.length>32?`${t.slice(0,32)}…`:t}function Cn(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 wn(e){return e.status===`failed`?R(e.error?.message):e.status===`completed`?R(e.result?.output):R(e.promptPreview??e.commandPreview)}function Tn(e){return e.status===`failed`?`failed`:e.status===`waiting_permission`?`permission`:e.unread?`unread`:e.status===`completed`?`completed`:`none`}function En(e){return e.status===`completed`&&!e.unread&&!e.error&&(e.result?.exitCode??0)===0&&!e.result?.signalCode&&!e.worktreePath&&!e.branchName?`collapsed`:`default`}function Dn(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`none`}function On(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 kn(e){return[...e].sort((e,t)=>{let n=e.startedAt??e.updatedAt,r=t.startedAt??t.updatedAt,i=n.localeCompare(r);return i===0?e.id.localeCompare(t.id):i})}function An(e){return[...e].sort((e,t)=>e.id.localeCompare(t.id))}function R(e){let t=e?.trim().replace(/\s+/g,` `);if(t)return t.length>120?`${t.slice(0,120)}...`:t}function z(e){return typeof e==`string`?e:void 0}function jn(e){if(e===`user_prompt`||e===`slash_command`||e===`model_command`||e===`tool_call`||e===`skill`||e===`transport`||e===`system`)return e}function Mn(e){let t=Pn(e.cursor?.offset),n=e.history.slice(t,t+80),r=n.map(e=>({id:e.id,kind:e.category===`chat`?`message`:`progress`,text:Fn(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 Nn(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 Pn(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function Fn(e){return typeof e.data==`string`?e.data:e.type}function In(e){return{spawnAgent:t=>e.manager.spawn(Ln(e,t)),spawnProcess:t=>e.manager.spawn(Rn(e,t)),createGroup:t=>e.groupOrchestrator.createGroup({parentSessionId:e.sessionId,waitPolicy:t.waitPolicy,taskIds:[...t.taskIds],label:t.label})}}function Ln(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:L(e.origin)}}function Rn(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:L(e.origin)}}const zn=new WeakMap;function Bn(e,t){zn.set(e,t)}function Vn(e){return zn.get(e)}function Hn(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(`
8
+
9
+ `),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 Un(){return`agent_group_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function Wn(e,t){let n=e?.trim();return n&&n.length>0?n:t}function Gn(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:Wn(e.label,i?.name??r)}}function Kn(e){return e.agentDef!==void 0}function qn(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 Jn(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 Yn(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 Xn(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 Zn(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 Qn(e,t,n){if(e.agentId===void 0)return Yn(e,t);try{let r=await n.wait(e.agentId);return Xn({...e,agentId:e.agentId},t,r)}catch(n){let r=n instanceof Error?n.message:String(n);return Zn({...e,agentId:e.agentId},t,r)}}async function $n(e){let t=Un(),n=e.jobs.map((t,n)=>Gn(t,n,e)),r=n.filter(e=>!Kn(e)).map(e=>qn(e,t)),i=await Promise.all(n.filter(Kn).map(t=>Jn(t,e))),a=await Promise.all(i.map(n=>Qn(n,t,e.manager))),o=[...r,...a].sort((e,t)=>e.index-t.index);return Hn({groupId:t,requestedJobCount:e.jobs.length,jobs:o})}function er(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 tr(){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 nr(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 rr(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 ir=[{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.
10
+
11
+ Your role is to complete the assigned task thoroughly and accurately. Follow these guidelines:
12
+
13
+ - Execute the task as described in the prompt. Do not expand scope beyond what is requested.
14
+ - Use the most appropriate tools for each step. Prefer precise tools (Read, Grep, Glob) over broad ones (Bash) when possible.
15
+ - Report your findings clearly and concisely when the task is complete.
16
+ - If a task cannot be completed, explain why and what information is missing.
17
+ - 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.
18
+
19
+ 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.
20
+
21
+ Your role is to answer questions about the codebase by:
22
+
23
+ - Searching for relevant files, symbols, and patterns using Glob and Grep.
24
+ - Reading source files, configuration, and documentation to understand structure and behavior.
25
+ - Tracing code paths across modules to understand how components interact.
26
+ - Summarizing findings in a clear, structured format with file paths and line references.
27
+ - Identifying architectural patterns, dependencies, and potential issues.
28
+
29
+ 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.
30
+
31
+ You operate in read-only mode. You must NEVER attempt to write or edit files. Your tools are restricted to read-only operations.
32
+
33
+ Your role is to:
34
+
35
+ - Analyze the current codebase state relevant to the task by reading specs, source code, and tests.
36
+ - Research implementation approaches by examining existing patterns and architectural conventions in the repository.
37
+ - Identify affected files, modules, and interfaces that a proposed change would touch.
38
+ - Assess risks, dependencies, and potential breaking changes.
39
+ - Produce a structured implementation plan with clear steps, file lists, and ordering.
40
+ - Consider edge cases, error handling, and test coverage requirements.
41
+
42
+ 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 ar(e){return ir.find(t=>t.name===e)}function or(){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.
43
+
44
+ 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.
45
+
46
+ Do not use emojis.`}function sr(){return`You are a worker subagent executing a specific task. Do NOT spawn subagents; execute directly. Keep your report under 500 words. Use this structure:
47
+ - Scope: What was requested
48
+ - Result: What was done
49
+ - Key files: Relevant file paths (absolute)
50
+ - Files changed: List of modifications
51
+ - Issues: Any problems encountered`}function cr(e){let t=[e.agentBody];e.claudeMd&&t.push(e.claudeMd),e.agentsMd&&t.push(e.agentsMd);let n=e.isForkWorker?sr():or();return t.push(n),t.join(`
52
+
53
+ `)}const lr=`robota_command_`,ur=/^[A-Za-z0-9_-]{1,64}$/;function dr(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function fr(e){let t=dr(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=`${lr}${n}`;if(ur.test(r))return r;let i=ae(`sha256`).update(t).digest(`hex`).slice(0,8),a=`${lr}${n.slice(0,40).replace(/[_-]+$/g,``)||`command`}_${i}`;if(!ur.test(a))throw Error(`Projected model command tool name is not provider-safe: ${a}`);return a}function pr(e){let t=new Set,n=new Map,r=new Map,i=[];for(let a of e){let e=dr(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=fr(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:vr(e,a),descriptor:a,requiresPermission:a.requiresPermission!==!1})}return{commandTools:i,toolNameToCommandName:n,commandNameToToolName:r}}function mr(e){return`${e.toolName} — ${e.descriptor.description}`}function hr(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 gr(e){return pr(e.commandDescriptors).commandTools.map(t=>{let n=_r(t.descriptor);return Ve(t.toolName,t.description,n,async r=>{let i=n.parse(r);return e.isModelInvocable(t.commandName)?hr(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 _r(e){let t=e.argumentHint?`Arguments for the command. Expected grammar: ${e.argumentHint}`:`Arguments for the command as a single string.`;return T.object({args:T.string().optional().describe(t)})}function vr(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(`
54
+
55
+ `)}const yr={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`,opus:`claude-opus-4-6`},br=fr(`agent`);function xr(e,t){return yr[e]??e}function Sr(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()!==br),n}function Cr(e){let{agentDefinition:t,parentConfig:n,parentContext:r,parentTools:i,terminal:a}=e,o=Sr(i,t),s=t.model?xr(t.model,n.provider.model):n.provider.model,c=cr({agentBody:t.systemPrompt,claudeMd:r.claudeMd,agentsMd:r.agentsMd,isForkWorker:e.isForkWorker??!1}),l=e.provider;return new Je({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 wr(e,t){let n=t?.(e)??ar(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Tr(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 Er(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function Dr(e){if(e.request.isolation===`worktree`)throw Error(`Worktree isolation requires a runtime shell subagent runner`)}function Or(e,t){if(t.type===`start`){e.emit?.({type:`background_task_tool_start`,toolName:t.toolName,firstArg:Er(t.toolArgs)});return}e.emit?.({type:`background_task_tool_end`,toolName:t.toolName,success:t.success??!0})}function kr(e){try{return ie(e.getFullHistory())}catch{return}}function Ar(e){return{start(t){Dr(t);let n=Cr({agentDefinition:Tr(wr(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=>{Or(t,n),e.onToolExecution?.(n)}});return{jobId:t.jobId,result:n.run(t.request.prompt).then(e=>{let r=kr(n);return{jobId:t.jobId,output:e,...r?{usage:r}:{}}}),cancel:()=>(n.abort(),Promise.resolve())}}}}const jr=[`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(` `),Mr=T.object({prompt:T.string().optional().describe(`The task for a single subagent to perform. Required when jobs is omitted.`),subagent_type:T.string().optional().describe(`Agent type: "general-purpose", "Explore", "Plan", or a custom agent name`),model:T.string().optional().describe(`Optional model override`),isolation:T.enum([`none`,`worktree`]).optional().describe(`Optional runtime isolation mode. "worktree" runs in a Git worktree.`),jobs:T.array(T.object({label:T.string().optional().describe(`Stable role label for this batch job`),prompt:T.string().describe(`The task for this subagent to perform`),subagent_type:T.string().optional().describe(`Agent type for this job`),model:T.string().optional().describe(`Optional model override for this job`),isolation:T.enum([`none`,`worktree`]).optional().describe(`Isolation for this job`)}).passthrough()).optional().describe(`Batch of subagent jobs to start in one Agent tool call`)}).passthrough(),Nr=new WeakMap;function Pr(e,t){Nr.set(e,t)}function B(e){return Nr.get(e)}function Fr(e,t){if(t){let n=t(e);if(n)return n}let n=ar(e);if(n)return n}function Ir(e){return e.subagentManager??new Ae({runner:Ar(e)})}function Lr(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:L({kind:`tool_call`,sessionId:r.parentSessionId??`unknown-session`,label:i,...a?{toolCallId:a}:{}})}}async function Rr(e,t,n,r){if(typeof e.prompt!=`string`||e.prompt.length===0)return rr(`prompt is required when jobs is omitted`);let i={...e,prompt:e.prompt},a=e.subagent_type??`general-purpose`,o=Fr(a,t.customAgentRegistry);if(!o)return er(a);let s;try{let e=await n.spawn(Lr(i,a,o,t,void 0,r));return s=e.id,nr(await n.wait(e.id))}catch(e){return rr(e instanceof Error?e.message:String(e),s)}}function zr(e){let t=Ir(e);return Ve(`Agent`,jr,Mr,async(n,r)=>{let i=n,a=r?.executionId;return e.isParallelSubagentsEnabled!==void 0&&!e.isParallelSubagentsEnabled()?tr():Array.isArray(i.jobs)&&i.jobs.length>0?$n({jobs:i.jobs,deps:e,manager:t,resolveAgentDefinition:Fr,createSpawnRequest:Lr,toolCallId:a}):Rr({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 Br=class{getManager;onChanged;emitTaskEvent;emitGroupEvent;persistSession;onWake;appendSystemNote;appendHistoryEntry;backgroundTasks=[];backgroundTaskEvents=[];backgroundJobGroups=[];backgroundJobGroupEvents=[];backgroundTaskUnsubscribe=null;backgroundJobUnsubscribe=null;backgroundJobOrchestrator=null;constructor(e,t,n,r,i,a,o,s){this.getManager=e,this.onChanged=t,this.emitTaskEvent=n,this.emitGroupEvent=r,this.persistSession=i,this.onWake=a,this.appendSystemNote=o,this.appendHistoryEntry=s}subscribe(e){if(this.backgroundTaskUnsubscribe)return;let t=Vn(e)??B(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 rn({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 Nn({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 Nn({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 Nn({entryId:e,lines:ln(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.recordCompletedTaskUsage(e),this.persistSession(),this.onChanged(`background_task`,Vr(e))}recordCompletedTaskUsage(e){if(e.type!==`background_task_completed`)return;let t=e.task.result?.usage;!t||t.totalTokens<=0||this.appendHistoryEntry?.(Zt(t,{scope:`background`,id:e.task.id,label:e.task.agentType??e.task.label}))}recordGroupEvent(e,t){this.backgroundJobGroups=this.getGroupSnapshots(),this.backgroundJobGroupEvents.push(e),this.persistSession(),this.onChanged(`background_group`,I(e.group.id))}};function Vr(e){if(`task`in e)return F(e.task.id);if(`taskId`in e)return F(e.taskId)}function Hr(e){let t=B(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 V(e){let t=Hr(e);if(!t.subagentManager)throw Error(`Subagent manager is not available for this session.`);return t.subagentManager}function Ur(e,t){let n=t.customAgentRegistry?.(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Wr(e){return(B(e)?.agentDefinitions??[]).map(e=>({name:e.name,description:e.description}))}async function Gr(e,t,n,r){let i=Hr(e),a=Ur(t.agentType,i),o=e.getSessionId();return V(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:L({kind:r===`model`?`model_command`:`slash_command`,sessionId:o,commandName:`agent`,label:t.label})})}async function Kr(e,t){return V(e).wait(t)}async function qr(e,t,n){await V(e).send(t,n)}async function Jr(e,t,n){await V(e).cancel(t,n)}async function Yr(e,t){await V(e).close(t)}function Xr(e){return V(e).list()}function Zr(e,t={}){let{sessionId:n,execCtrl:r,histTracker:i,bgTracker:a}=e,o=i.getHistory();return mn({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 Qr(e,t,n,r,i){let a=pn(e);if(!a)throw Error(`Unknown execution workspace entry: ${e}`);return a.kind===`main_thread`?Mn({entryId:e,history:t(),cursor:i}):a.kind===`background_group`?n.readGroupDetail(e,a.sourceId,r):n.readTaskDetail(e,a.sourceId,i)}function $r(e,t,n,r){return In({manager:e.getManagerOrThrow(),groupOrchestrator:e.getOrchestratorOrThrow(t),sessionId:t,cwd:n,origin:{...r,sessionId:r.sessionId||t}})}var ei=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 Zr({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(),Qr(e,()=>this.histTracker.getHistory(),this.bgTracker,this.getSessionOrThrow().getSessionId(),t)}createExecutionWorkspaceTaskSpawner(e){return $r(this.bgTracker,this.getSessionOrThrow().getSessionId(),this.getCwd(),e)}listAgentDefinitions(){return Wr(this.getSessionOrThrow())}listAgentJobs(){return Xr(this.getSessionOrThrow())}async spawnAgentJob(e){return await this.ensureInitialized(),Gr(this.getSessionOrThrow(),e,this.getCwd(),this.skillRouter.getCommandInvocationSource())}async waitAgentJob(e){return await this.ensureInitialized(),Kr(this.getSessionOrThrow(),e)}async sendAgentJob(e,t){await this.ensureInitialized(),await qr(this.getSessionOrThrow(),e,t)}async cancelAgentJob(e,t){await this.ensureInitialized(),await Jr(this.getSessionOrThrow(),e,t)}async closeAgentJob(e){await this.ensureInitialized(),await Yr(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})}};function ti(e){return ae(`sha256`).update(e,`utf-8`).digest(`hex`)}function ni(e,t=new A){let n=t.readFileSync(e,`utf-8`);return{filePath:e,content:n,contentHash:ti(n)}}async function ri(e,t=new A){let n=[],r=[];for(let i of e){if(!t.existsSync(i.filePath)){r.push(i);continue}ti(t.readFileSync(i.filePath,`utf-8`))===i.contentHash?r.push(i):n.push(i)}return{stale:n,fresh:r}}async function ii(e,t=new A){let{stale:n}=await ri(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:ti(n)}}),refreshed:i}}async function ai(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 ii(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(`
56
+
57
+ `),d.map(e=>e.content).join(`
58
+
59
+ `));i().updateSystemMessage(f);for(let e of l)a(`context_file_refreshed`,{filePath:e})}function oi(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 si(e,t,n){let r=e?.[t]??e?.[n];return typeof r==`string`?r:null}function ci(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 li(e){if(e.toolName!==`Edit`)return{};let t=si(e.toolArgs,`file_path`,`filePath`),n=si(e.toolArgs,`old_string`,`oldString`),r=si(e.toolArgs,`new_string`,`newString`);return!t||n===null||r===null||n===r?{}:{diffFile:t,diffLines:di(n,r,ci(e.toolResultData),t)}}function ui(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 di(e,t,n,r,i=new A){let a=ui(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 fi(e){if(e.activeTools.length===0)return;let t=e.activeTools.map(e=>`${e.isRunning?`⟳`:e.result===`success`?`✓`:e.result===`error`?`✗`:`⊘`} ${e.toolName}${e.firstArg?`(${e.firstArg})`:``}`).join(`
66
+ `);e.history.push({id:v(),timestamp:new Date,category:`event`,type:`tool-summary`,data:{tools:e.activeTools.map(e=>({toolName:e.toolName,firstArg:e.firstArg,isRunning:e.isRunning,result:e.result,diffFile:e.diffFile,diffLines:e.diffLines,toolResultData:e.toolResultData})),summary:t}})}function pi(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 mi(e,t){let n=oi(t.toolArgs),r={toolName:t.toolName,firstArg:n,isRunning:!0,...t.executionId?{executionId:t.executionId}:{}};return e.activeTools.push(r),e.history.push({id:v(),timestamp:new Date,category:`event`,type:`tool-start`,data:{toolName:t.toolName,firstArg:n,isRunning:!0}}),r}function hi(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],...li(t),isRunning:!1,result:n,toolResultData:t.toolResultData};return e.activeTools[r]=i,e.activeTools=pi(e.activeTools),e.history.push({id:v(),timestamp:new Date,category:`event`,type:`tool-end`,data:{toolName:i.toolName,firstArg:i.firstArg,isRunning:!1,result:n,toolResultData:t.toolResultData}}),i}const gi=[{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 _i(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 _i(t.originalError);let a=t.message;for(let{pattern:e,message:t}of gi)if(e.test(a))return t;return a}async function vi(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 Qt(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(),fi({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let l=Jt(c||`(empty response)`,r.getSession().getHistory(),i,a,r.getSession().getContextState(),o.promptFileReferenceRecords);i.push(_(s(l.response))),l.usage&&i.push(Xt(l.usage)),r.onComplete(l),r.onContextUpdate()}catch(e){if(r.flushStreaming(),Kt(e)){let e=Yt(r.getSession().getHistory(),i,a,r.getSession().getContextState());fi({activeTools:r.getActiveTools(),history:i}),r.clearStreaming(),e.response&&i.push(_(s(e.response))),e.usage&&i.push(Xt(e.usage)),i.push(_(c(`Interrupted by user.`))),r.onInterrupted(e)}else{fi({activeTools:r.getActiveTools(),history:i});let t=r.getStreamingText();if(r.clearStreaming(),t.trim().length>0){let e=s(t);e.state=`interrupted`,i.push(_(e))}let n=e instanceof Error?e:Error(String(e)),a=_i(n);i.push(_(c(`Error: ${a}`,{metadata:{kind:`error`}}))),r.onError(n)}}}var yi=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.pendingTurnOptions.wakeTaskId!==void 0&&this.wakeTaskIds.delete(this.pendingTurnOptions.wakeTaskId),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=mi(t,e);this.activeTools=t.activeTools,this.callbacks.emit(`tool_start`,n)}else{let n=hi(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 ai(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 vi(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(),getStreamingText:()=>this.streamingText,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: ${_i(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(),fi({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 bi(e,t,n){let r=B(n)?.customAgentRegistry?.(e)??ar(e);if(!r)throw Error(`Unknown agent type: ${e}`);return t.allowedTools?{...r,tools:t.allowedTools}:r}async function xi(e,t,n){let r=B(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);return Cr({agentDefinition:bi(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 Si(e,t,n){let r=await Nt([t],{cwd:n,reason:`manual`});if(yt(r.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[bt(r.diagnostics)]}};let i=r.references[0];if(!i)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let a=ot(k([i])[0],`manual`,`active`),o=st(e,a);return{references:o.references,result:{reference:a,evicted:o.evicted,diagnostics:[]}}}function Ci(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=ot(e,n.loadType,n.status,r);i=st(i,t).references}return i}function wi(e,t){let n=new Date().toISOString();return e.map(e=>{let r=x(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=b(e,`.robota`);return{settings:b(t,`settings.json`),settingsLocal:b(t,`settings.local.json`),logs:b(t,`logs`),sessions:b(t,`sessions`),memory:b(t,`memory`),checkpoints:b(t,`checkpoints`)}}function Ti(){let e=b(C(),`.robota`);return{settings:b(e,`settings.json`),sessions:b(e,`sessions`),onboarded:b(e,`onboarded`)}}function Ei(e){let t=e.fs??new A,n=e.manifests.filter(t=>t.sequence>e.target.sequence),r=e.manifests.filter(t=>t.sequence>=e.target.sequence);return{target:Di(e.target),capturedFiles:e.target.files.map(n=>{let r=n.snapshotFile?b(e.checkpointDir(e.sessionId,e.target.id),n.snapshotFile):void 0,i=r?ki(r,t):void 0;return{originalPath:n.originalPath,relativePath:x(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:Oi(n),rollbackThroughCheckpoint:Oi(r)}}function Di(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function Oi(e){return{checkpointIds:e.map(e=>e.id),fileCount:e.reduce((e,t)=>e+t.fileCount,0)}}function ki(e,t){try{return t.statSync(e)}catch{return}}const Ai=`manifest.json`,ji=`files`;var Mi=class{fs;fsAsync;cwd;rootDir;now;activeTurn=null;constructor(e,t=new A,n=new jt){this.fs=t,this.fsAsync=n,this.cwd=S(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=b(this.sessionDir(e.sessionId),n);await this.fsAsync.mkdir(b(r,ji),{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=S(this.cwd,e);if(this.activeTurn.capturedPaths.has(t)||Pi(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 Ei({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 Fi(this.fsAsync,this.fs,e))return{originalPath:e,existed:!1};let n=b(ji,`${String(t.manifest.files.length+1).padStart(6,`0`)}.content`);return await this.fsAsync.copyFile(e,b(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(y(n.originalPath),{recursive:!0}),await this.fsAsync.copyFile(b(this.checkpointDir(e,t),n.snapshotFile),n.originalPath)}loadManifests(e){let t=this.sessionDir(e);return Ii(this.fs,t).map(e=>b(t,e,Ai)).map(e=>Li(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=b(e,Ai),r=`${n}.tmp`;await this.fsAsync.writeFile(r,JSON.stringify(t,null,2),`utf8`),await this.fsAsync.rename(r,n)}sessionDir(e){return b(this.rootDir,Ni(e))}checkpointDir(e,t){return b(this.sessionDir(e),Ni(t))}};function U(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function Ni(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function Pi(e,t){let n=x(e,t);return n.length===0||!n.startsWith(`..`)&&!n.startsWith(`/`)}async function Fi(e,t,n){try{return await e.access(n,t.constants.F_OK),!0}catch{return!1}}function Ii(e,t){try{return e.readdirSync(t)}catch{return[]}}function Li(e,t){try{let n=e.readFileSync(t,`utf8`);return JSON.parse(n)}catch{return}}function Ri(e){return e.source===`plugin`?`plugin`:`skill`}function zi(e){return e.context===`fork`?`fork`:`inject`}function Bi(e){return{type:`skill-activation`,skillName:e.skill.name,source:Ri(e.skill),invocation:e.invocation,mode:zi(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function Vi(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 Hi=new Set([`memory_candidate_saved`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`]);function Ui(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 Wi=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=Ci(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=Ci(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),Hi.has(e.type)&&this.history.push({id:v(),timestamp:new Date(e.at),category:`event`,type:`memory-event`,data:{...e,message:Ui(e)}}),this.emitMemoryEvent(e),this.persistSession()}recordSystemContextFiles(e){this.systemContextReferences=wi(e,this.cwd)}listContextReferences(){return[...this.systemContextReferences,...this.contextReferences]}listInjectionContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await Si(this.contextReferences,e,this.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=ct(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=lt(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,t){this.skillActivationEvents.push(e),t&&this.history.push({id:v(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:Vi(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){return this.editCheckpointStore||=new Mi({cwd:this.cwd}),this.editCheckpointStore}};function Gi(e){if(E(e))try{return JSON.parse(D(e,`utf-8`))}catch{return}}function Ki(e){if(E(O(e,`pnpm-workspace.yaml`))||E(O(e,`pnpm-lock.yaml`)))return`pnpm`;if(E(O(e,`yarn.lock`)))return`yarn`;if(E(O(e,`bun.lockb`)))return`bun`;if(E(O(e,`package-lock.json`)))return`npm`}async function qi(e){let t=O(e,`package.json`),n=O(e,`tsconfig.json`),r=O(e,`pyproject.toml`),i=O(e,`Cargo.toml`),a=O(e,`go.mod`);if(E(t)){let r=Gi(t),i=E(n)?`typescript`:`javascript`,a=Ki(e);return{type:`node`,name:r?.name,packageManager:a,language:i}}return E(r)||E(O(e,`setup.py`))?{type:`python`,language:`python`}:E(i)?{type:`rust`,language:`rust`}:E(a)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}function Ji(e,t){e.injectRawMessage(t)}function Yi(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,goal: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:h}=Xi(a,o),ee=r.name,g=null;if(r.messages)if(n)for(let e of r.messages)Ji(n,e);else g=r.messages;return{history:i,sessionName:ee,pendingRestoreMessages:g,backgroundTasks:m,backgroundTaskEvents:h,backgroundJobGroups:s,backgroundJobGroupEvents:c,skillActivationEvents:l,memoryEvents:u,usedMemoryReferences:d,contextReferences:f,sandboxSnapshotId:p,goal:r.goal}}function Xi(e,t){let n=new Date().toISOString(),r=[];return{backgroundTasks:e.map(e=>{if(Zi(e.status)||Qi(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 Zi(e){return e===`completed`||e===`failed`||e===`cancelled`}function Qi(e){return e.kind===`scheduled`&&e.status===`sleeping`&&e.schedule!==void 0}function $i(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 ea(e,t,n,r){let i=$i(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 ta=[`Shell — execute host shell commands (OS-aware: bash/PowerShell)`,`Bash — alias of Shell (model-familiar name)`,`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`,`AskUserQuestion — ask the user structured questions (options/multi-select/free text) mid-task`];function na(e={}){return[ze(e),Ie(e),Re(e),Be(e),Le(e),He,Ue,We,Ge,Fe()]}const ra=new Set([`tools`,`disallowedTools`]),ia=new Set([`maxTurns`]);function aa(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function oa(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();ra.has(i)?r[i]=aa(a):ia.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=b(e,i.name),{frontmatter:a,body:o}=oa(t.readFileSync(r,`utf-8`)),s=oe(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 sa=class{cwd;home;fs;constructor(e,t,n=new A){this.cwd=e,this.home=t??C(),this.fs=n}loadAll(){let e=[W(b(this.cwd,`.robota`,`agents`),this.fs),W(b(this.cwd,`.agents`,`agents`),this.fs),W(b(this.cwd,`.claude`,`agents`),this.fs),W(b(this.home,`.robota`,`agents`),this.fs),W(b(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 ir)t.has(e.name)||r.push(e);return r}getAgent(e){return this.loadAll().find(t=>t.name===e)}};function ca(e){let t=e.content.trim();return e.title?[`## ${e.title}`,t].join(`
69
+ `):t}function la(e){return[...e].filter(e=>e.content.trim().length>0).sort((e,t)=>e.priority-t.priority||e.id.localeCompare(t.id)).map(e=>ca(e)).join(`
70
+
71
+ `)}function G(e,t,n,r,i){return{id:e,title:t,priority:n,content:r,source:i}}function ua(e){return G(`preset-persona`,void 0,5,e,`persona`)}function da(){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 fa(e){if(e)return G(`runtime-cwd`,`Working Directory`,30,`\`${e}\``,`runtime`)}function pa(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 ma(e){return G(`permission-mode`,`Permission Mode`,50,`- **Permission mode:** ${e}`,`permissions`)}function ha(e){if(!(e===void 0||e.trim().length===0))return G(`runtime-response-language`,`Response Language`,45,e,`runtime`)}function ga(e){if(e.trim().length!==0)return G(`project-agents-md`,`Agent Instructions`,10,e,`project-instructions`)}function _a(e){if(e.trim().length!==0)return G(`project-claude-md`,`Project Notes`,20,e,`project-instructions`)}function va(e){if(!(e===void 0||e.trim().length===0))return G(`project-memory`,`Project Memory`,25,e,`project-instructions`)}function ya(e){if(!(e===void 0||e.trim().length===0))return G(`active-task-context`,`Active Task Context`,27,e,`project-instructions`)}function ba(e){if(e.length!==0)return G(`tool-descriptions`,`Available Tools`,60,e.map(e=>`- ${e}`).join(`
73
+ `),`tool`)}function xa(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}`}function Sa(e,t,n,r,i){let a=i.filter(t=>t.modelInvocable&&t.kind===e).map(xa);if(a.length!==0)return G(`capability-${e}`,t,n,a.join(`
74
+ `),r)}function Ca(e){let t=[],n=Sa(`builtin-command`,`Built-in Commands`,70,`command`,e),r=Sa(`skill`,`Skills`,80,`skill`,e),i=Sa(`agent`,`Agents`,90,`agent`,e),a=Sa(`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 wa(e){return e.map(e=>({name:e.name,kind:`skill`,description:e.description,userInvocable:!0,modelInvocable:e.disableModelInvocation!==!0}))}function Ta(e){return e.map(e=>({name:e.name,kind:`agent`,description:e.description,userInvocable:!1,modelInvocable:!0,safety:`background-agent`}))}function Ea(e){return[...e.commandDescriptors??[],...e.skills?wa(e.skills):[],...e.agents?Ta(e.agents):[]]}function Da(e){let t=[];return K(t,e.persona!==void 0&&e.persona.trim().length>0?ua(e.persona):void 0),K(t,e.selfVerification===!0?da():void 0),K(t,ga(e.agentsMd)),K(t,_a(e.claudeMd)),K(t,va(e.memoryMd)),K(t,ya(e.taskContext)),K(t,fa(e.cwd)),t.push(pa(e.projectInfo)),K(t,ha(e.language)),t.push(ma(e.permissionMode)),K(t,ba(e.toolDescriptions)),t.push(...Ca(Ea(e))),la(t)}const Oa=T.object({command:T.string().describe(`The shell command to start in the background`),timeout:T.number().optional().describe(`Optional timeout in milliseconds. Default is 120000.`),workingDirectory:T.string().optional().describe(`Working directory for the command. Defaults to the current project directory.`),stdin:T.string().optional().describe(`Optional stdin to write after the process starts.`),outputLimitBytes:T.number().optional().describe(`Maximum captured output bytes kept in the task result.`)});function ka(e,t,n){return JSON.stringify({success:!0,background:!0,output:``,taskId:e,status:t,command:n})}function Aa(e){return JSON.stringify({success:!1,background:!0,output:``,error:`Background process error: ${e}`})}async function ja(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 ka(n.id,n.status,e.command)}catch(e){return Aa(e instanceof Error?e.message:String(e))}}function Ma(e){return Ve(`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.`,Oa,async t=>ja(t,e))}function Na(e,t,n,r,i,a){let o,s=[],c;if(e.enableAgentRuntime||e.enableParallelSubagents){let l=new sa(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??Ar)(o),backgroundTaskRunners:e.backgroundTaskRunners});o.subagentManager=u,c=u.getBackgroundTaskManager(),o.backgroundTaskManager=c}else c=new ke({runners:e.backgroundTaskRunners??[]});let l=e.sessionLogger;return l&&c.subscribe(e=>Ra(l,t,e)),c.subscribe(t=>ea(t,n,e.config.hooks,a.length>0?a:void 0)),{agentToolDeps:o,agentDefinitions:s,backgroundTaskManager:c}}function Pa(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:L({kind:`tool_call`,sessionId:n,label:`BackgroundProcess`})};return i.push(Ma(a)),{backgroundProcessToolDeps:a}}function Fa(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 Ia(e,t,n,r,i,a,o){let s=e.systemPromptBuilder??Da,c=[...ta,...r?r.commandTools.map(mr):[]],l=e.toolDescriptions??(i?[...c,`BackgroundProcess — start long-running shell commands as managed background tasks`]:c),u=e.persona,d=e.selfVerification,f=Fa(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 La(e,t,n,r){t&&(t.parentSessionId=e.getSessionId()),t&&(t.isParallelSubagentsEnabled=()=>e.getParallelSubagentsEnabled()),n&&(n.parentSessionId=e.getSessionId()),Bn(e,r),t&&Pr(e,t)}function Ra(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 za=new Set([`Write`,`Edit`]);function Ba(e,t){return e.map(e=>za.has(e.getName())?new Va(e,t):e)}var Va=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=Ha(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 Ha(e){if(!e||typeof e!=`object`)return;let t=e.filePath;return typeof t==`string`&&t.length>0?t:void 0}const Ua=new Set([`disable-model-invocation`,`user-invocable`]),Wa=new Set([`allowed-tools`]);function Ga(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Ka(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function qa(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=Ga(a);Ua.has(a)?n[s]=o===`true`:Wa.has(a)?n[s]=Ka(o):n[s]=o}return Object.keys(n).length>0?n:null}function Ja(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 Ya(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=b(e,i.name,`SKILL.md`);if(!t.existsSync(r))continue;let a=t.readFileSync(r,`utf-8`),o=qa(a);n.push(Ja(o,a,i.name))}return n}function Xa(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=b(e,i.name),a=t.readFileSync(r,`utf-8`),o=qa(a),s=oe(i.name,`.md`);n.push(Ja(o,a,s))}return n}var Za=class{name=`skill`;cwd;home;fs;cachedCommands=null;constructor(e,t,n=new A){this.cwd=e,this.home=t??C(),this.fs=n}getCommands(){if(this.cachedCommands)return this.cachedCommands;let e=[Ya(b(this.cwd,`.claude`,`skills`),this.fs),Xa(b(this.cwd,`.claude`,`commands`),this.fs),Ya(b(this.home,`.robota`,`skills`),this.fs),Ya(b(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)}},Qa=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 $a(){return b(process.env.HOME??process.env.USERPROFILE??`/`,`.robota`,`settings.json`)}function eo(e,t){return t===void 0||t===`user`?$a():b(e,`.robota`,`settings.local.json`)}function q(e){if(!w(e))return{};let t=fe(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new Qa(e,t instanceof Error?t.message:String(t))}}function J(e,t){de(y(e),{recursive:!0}),ve(e,JSON.stringify(t,null,2)+`
76
+ `,`utf8`)}function to(e,t){let n=q(e),r=n.currentProvider,i=n.providers;if(typeof r==`string`&&no(i)){let e=i;e[r]={...no(e[r])?e[r]:{},model:t},n.providers=e}else n.provider={...no(n.provider)?n.provider:{},model:t};J(e,n)}function no(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function ro(e){return w(e)?(_e(e),!0):!1}const io=`report_goal_status`,ao=T.object({status:T.enum([`continue`,`satisfied`]).describe(`"satisfied" when the assigned goal is fully achieved; otherwise "continue".`),reason:T.string().describe(`A short justification for the status — what was achieved or what remains.`)});function oo(){return Ve(io,`Report progress toward the currently assigned autonomous goal. Call this only when you have an assigned goal: use status "satisfied" once it is fully achieved, or "continue" with the remaining work. Do not call it when no goal has been assigned.`,ao,async e=>({acknowledged:!0,status:e.status===`satisfied`?`satisfied`:`continue`}))}const so=`When you have made as much progress as you can this turn, call \`${io}\`: use status "satisfied" once the goal is fully achieved, or status "continue" with a short reason describing the remaining work. Do the actual work with your tools first; the signal only reports your assessment.`;function co(e){return[`You have been assigned an autonomous goal to pursue across multiple turns:`,``,`GOAL: ${e}`,``,`Work toward this goal now. ${so}`].join(`
77
+ `)}function lo(e){let t=e.progress[e.progress.length-1],n=t?.reason?`\nMost recent assessment: ${t.reason}`:``;return[`Continue pursuing the assigned goal (iteration ${e.iterations+1} of at most ${e.maxIterations}).`,``,`GOAL: ${e.objective}${n}`,``,`Keep going from where you left off. ${so}`].join(`
78
+ `)}const uo=25,fo=2,po={now:()=>new Date().toISOString(),createId:()=>`goal_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`};function mo(e){let t;try{t=JSON.parse(e)}catch{return null}return{status:t.status===`satisfied`?`satisfied`:`continue`,reason:typeof t.reason==`string`?t.reason:``}}function ho(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!(!n||n.name!==`report_goal_status`))return mo(n.args)}return null}function go(e){return e.filter(e=>e.name!==io).length}var _o=class{deps;goal=null;consecutiveIdleTurns=0;noProgressLimit=2;constructor(e=po){this.deps=e}getState(){return this.goal}isActive(){return this.goal?.status===`active`}start(e,t={}){let n=e.trim();if(n.length===0)throw Error(`A goal objective must be a non-empty string.`);let r=t.maxIterations&&t.maxIterations>0?Math.floor(t.maxIterations):25;return this.noProgressLimit=t.noProgressLimit&&t.noProgressLimit>0?Math.floor(t.noProgressLimit):2,this.consecutiveIdleTurns=0,this.goal={id:this.deps.createId(),objective:n,status:`active`,iterations:0,maxIterations:r,startedAt:this.deps.now(),progress:[]},{goal:this.goal,prompt:co(n)}}restore(e,t=2){this.goal=e.status===`active`?e:null,this.noProgressLimit=t,this.consecutiveIdleTurns=0}cancel(){return!this.goal||this.goal.status!==`active`?null:(this.goal={...this.goal,status:`stopped`,stopReason:`cancelled`},this.goal)}onTurnComplete(e){if(!this.goal||this.goal.status!==`active`)return null;let t=ho(e.toolSummaries),n=this.goal.iterations+1;if(this.goal={...this.goal,iterations:n,progress:[...this.goal.progress,{iteration:n,signal:t?.status??`continue`,reason:t?.reason??``}]},t?.status===`satisfied`)return this.stop(`satisfied`);let r=go(e.toolSummaries)>0;return this.consecutiveIdleTurns=r?0:this.consecutiveIdleTurns+1,this.consecutiveIdleTurns>=this.noProgressLimit?this.stop(`no-progress`):n>=this.goal.maxIterations?this.stop(`max-iterations`):{action:`continue`,prompt:lo(this.goal),goal:this.goal}}stop(e){let t=e===`satisfied`?`satisfied`:`stopped`;return this.goal={...this.goal,status:t,stopReason:e},{action:`stop`,reason:e,goal:this.goal}}};function vo(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var yo=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=vo(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 bo(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var xo=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=bo(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 So=new Set([`Write`,`Edit`]),Co=new Set([`Shell`,`Bash`,`BackgroundProcess`]),wo=new Set([`Read`,`Glob`,`Grep`,`WebFetch`,`WebSearch`]);function To(e){let t=e.toolName;return wo.has(t)?{toolName:t,reversible:!0,sideEffect:`none`,rollbackLayer:`none`,status:`read-only`,message:`${t} does not mutate the local workspace.`}:So.has(t)?e.context.isolation===`worktree`||e.context.isolation===`provider-sandbox`?Oo(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.`}:Co.has(t)?Oo(t,`shell-process`,e.context):t===`Agent`?ko(e.toolArgs,e.context):{toolName:t,reversible:!1,sideEffect:`unknown`,rollbackLayer:`none`,status:`unknown`,message:`${t} has no reversible execution contract.`}}function Eo(e,t){let n={checkpointAvailable:t.checkpointAvailable,isolation:t.isolation??`none`},r=t.enforceUntrackedSideEffects??!0;return e.map(e=>new Do(e,{safetyContext:n,enforceUntrackedSideEffects:r}))}var Do=class{delegate;options;schema;constructor(e,t){this.delegate=e,this.options=t,this.schema=e.schema}setEventService(e){this.delegate.setEventService(e)}async execute(e,t){let n=To({toolName:this.getName(),toolArgs:No(e),context:this.options.safetyContext});return!n.reversible&&this.options.enforceUntrackedSideEffects?Po(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 Oo(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 ko(e,t){return t.isolation===`worktree`||t.isolation===`provider-sandbox`?Oo(`Agent`,`subagent`,t):Ao(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 Ao(e){if(!e)return!1;let t=e.jobs;return Array.isArray(t)?t.length>0&&t.every(e=>Mo(e)?jo(e)===`worktree`:!1):jo(e)===`worktree`}function jo(e){let t=e.isolation;return typeof t==`string`?t:void 0}function Mo(e){return e!==void 0&&typeof e==`object`&&!Array.isArray(e)}function No(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e}function Po(e){return{success:!0,data:{success:!1,output:``,error:e.message,reversibleSafety:{toolName:e.toolName,sideEffect:e.sideEffect,rollbackLayer:e.rollbackLayer,status:e.status}},metadata:{reversibleSafetyStatus:e.status,rollbackLayer:e.rollbackLayer}}}function Fo(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function Io(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Lo(e,t){return e.some(e=>Io(e.name)===t)}function Ro(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??zo(),i=new Za(n),a=Fo(e.commandDescriptors),o=a.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,s=o?pr(a):void 0,c=Lo(a,`skills`)?i.getModelInvocableSkills():[],l=na({sandboxClient:e.sandboxClient,cwd:n}),u=e.editCheckpointRecorder!==void 0&&e.sandboxClient===void 0,d=[...u&&e.editCheckpointRecorder?Ba(l,e.editCheckpointRecorder):l,...e.additionalTools??[],...e.includeGoalTool?[oo()]:[]],f=e.reversibleExecution?{...e.reversibleExecution,isolation:e.reversibleExecution.isolation??(e.sandboxClient?`provider-sandbox`:void 0)}:void 0,p=f?Eo(d,{...f,checkpointAvailable:u}):d;o&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&p.push(...gr({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:a}));let m=[];e.providerFactory&&m.push(new xo({providerFactory:e.providerFactory,defaultModel:e.config.provider.model})),e.sessionFactory&&m.push(new yo({sessionFactory:e.sessionFactory})),e.additionalHookExecutors&&m.push(...e.additionalHookExecutors);let{agentToolDeps:h,agentDefinitions:ee,backgroundTaskManager:g}=Na(e,r,n,t,p,m),{backgroundProcessToolDeps:te}=Pa(e,g,r,n,p),{finalSystemMessage:_,rebuildSystemMessage:ne}=Ia(e,n,a,s,te,c,ee),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}(*)`),v=(e.deniedTools??[]).map(e=>`${e}(*)`),oe={allow:[...re,...ie,...e.config.permissions.allow??[],...ae],deny:[...e.config.permissions.deny??[],...v]},y=b(n,`.robota`,`settings.local.json`);function se(e){let t=`${e}(*)`,n=q(y),r=Array.isArray(n.permissions)?[]:n.permissions?.allow??[];r.includes(t)||J(y,{...n,permissions:{...n.permissions??{},allow:[...r,t]}})}let x=new Je({tools:p,provider:t,systemMessage:_,terminal:e.terminal,permissions:oe,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,...e.ask?{ask:e.ask}:{},onProjectAllowTool:se,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 La(x,h,te,g),{session:x,rebuildSystemMessage:ne}}function zo(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function Bo(e,t,n,r=new A){let i=b(n,e,`subagents`);return r.mkdirSync(i,{recursive:!0}),new qe(i)}function Vo(e,t){return b(t,e,`subagents`)}const Y=T.lazy(()=>T.union([T.string(),T.number(),T.boolean(),T.null(),T.undefined(),T.date(),T.array(Y),T.record(Y)])),Ho=T.object({name:T.string().optional(),model:T.string().optional(),apiKey:T.string().optional(),baseURL:T.string().optional(),timeout:T.number().optional(),options:T.record(Y).optional()}),Uo=T.object({type:T.string().optional(),model:T.string().optional(),apiKey:T.string().optional(),baseURL:T.string().optional(),timeout:T.number().optional(),options:T.record(Y).optional()}),Wo=T.object({allow:T.array(T.string()).optional(),deny:T.array(T.string()).optional()}),Go=T.record(T.string()).optional(),Ko=T.object({type:T.literal(`command`),command:T.string(),timeout:T.number().optional()}),qo=T.object({type:T.literal(`http`),url:T.string(),headers:T.record(T.string()).optional(),timeout:T.number().optional()}),Jo=T.object({type:T.literal(`prompt`),prompt:T.string(),model:T.string().optional()}),Yo=T.object({type:T.literal(`agent`),agent:T.string(),maxTurns:T.number().optional(),timeout:T.number().optional()}),Xo=T.discriminatedUnion(`type`,[Ko,qo,Jo,Yo]),X=T.object({matcher:T.string(),hooks:T.array(Xo)}),Zo=T.object({PreToolUse:T.array(X).optional(),PostToolUse:T.array(X).optional(),SessionStart:T.array(X).optional(),SessionEnd:T.array(X).optional(),Stop:T.array(X).optional(),StopFailure:T.array(X).optional(),PreCompact:T.array(X).optional(),PostCompact:T.array(X).optional(),UserPromptSubmit:T.array(X).optional(),SubagentStart:T.array(X).optional(),SubagentStop:T.array(X).optional(),WorktreeCreate:T.array(X).optional(),WorktreeRemove:T.array(X).optional()}).optional(),Qo=T.record(T.boolean()).optional(),$o=T.object({source:T.object({type:T.enum([`github`,`git`,`local`,`url`]),repo:T.string().optional(),url:T.string().optional(),path:T.string().optional(),ref:T.string().optional()})}),es=T.record($o).optional().catch(void 0),ts=T.union([T.number().gt(0).lte(1),T.literal(!1)]).optional(),ns=T.object({enabled:T.boolean().optional(),options:T.record(Y).optional()}),rs=T.object({defaultTrustLevel:T.enum([`safe`,`moderate`,`full`]).optional(),language:T.string().optional(),preset:T.string().optional(),currentProvider:T.string().optional(),providers:T.record(Uo).optional(),provider:Ho.optional(),permissions:Wo.optional(),env:Go,hooks:Zo,enabledPlugins:Qo,extraKnownMarketplaces:es,autoCompactThreshold:ts,transports:T.record(ns).optional()});function is(){return process.env.HOME??process.env.USERPROFILE??`/`}const Z={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[]},env:{}};function as(e){if(!E(e))return;let t=D(e,`utf-8`).trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function os(e){if(e.startsWith(`$ENV:`)){let t=e.slice(5);return process.env[t]??e}return e}function ss(e){let t=e.provider?.apiKey===void 0?e.provider:cs(e.provider);if(e.providers!==void 0){let n=Object.fromEntries(Object.entries(e.providers).map(([e,t])=>[e,cs(t)]));return{...e,provider:t,providers:n}}return{...e,provider:t}}function cs(e){return{...e,...e.apiKey!==void 0&&{apiKey:os(e.apiKey)}}}function ls(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?us(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 us(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function ds(e){if(e.currentProvider!==void 0)return fs(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...Z.provider}}function fs(e){let t=e.currentProvider;if(t===void 0)throw Error(`currentProvider is required`);let n=e.providers?.[t];if(n===void 0)throw Error(`currentProvider "${t}" was not found in providers`);if(n.type===void 0)throw Error(`Provider profile "${t}" is missing type`);return{name:n.type,model:n.model??Z.provider.model,apiKey:n.apiKey??Z.provider.apiKey,...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function ps(e){return{defaultTrustLevel:e.defaultTrustLevel??Z.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:ds(e),permissions:{allow:e.permissions?.allow??Z.permissions.allow,deny:e.permissions?.deny??Z.permissions.deny},env:e.env??Z.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold}}function ms(e){let t=is();return[O(t,`.robota`,`settings.json`),O(t,`.claude`,`settings.json`),O(e,`.robota`,`settings.json`),O(e,`.robota`,`settings.local.json`),O(e,`.claude`,`settings.json`),O(e,`.claude`,`settings.local.json`)]}async function hs(e){let t=ms(e),n=[];for(let e of t){let t=as(e);t!==void 0&&n.push({raw:t,path:e})}return ps(ls(n.map(({raw:e,path:t})=>{let n=rs.safeParse(e);if(!n.success)throw Error(`Invalid settings in ${t}: ${n.error.message}`);return ss(n.data)})))}const gs=b(`.agents`,`tasks`),_s={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function vs(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function ys(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||oe(t,`.md`)}function bs(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function xs(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(`
79
+ `).trim();return o.length>0?o:void 0}function Ss(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(.+)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function Cs(e,t){return t&&e.branch===t?0:_s[e.status]}function ws(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(`
80
+ `)}function Ts(e){return e.toISOString().slice(0,10)}function Es(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(`
81
+ `)):(n.length>0&&/^#\s+/.test(n[0])?n.splice(1,0,``,r):n.unshift(r,``),n.join(`
82
+ `))}function Ds(e,t,n){let r=[`### ${Ts(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(`
83
+ `);let o=i.findIndex((e,t)=>t>a&&/^##\s+/.test(e));return o<0?[...i,``,...r,``].join(`
84
+ `):(i.splice(o,0,``,...r,``),i.join(`
85
+ `))}function Os(e,t){let n=S(e),r=!1;for(;!r;){let e=b(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 se(r)?r:S(n,r)}let i=y(n);r=i===n,n=i}}function ks(e,t=new A){let n=Os(e,t);if(!n)return;let r=b(n,`HEAD`);if(t.existsSync(r))return(t.readFileSync(r,`utf8`).trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1])?.trim()}function As(e,t=new A){let n=b(e,gs);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=>b(n,e)):[]}function js(e,t,n=new A){let r=n.readFileSync(e,`utf8`);return{path:e,relativePath:x(t,e),title:ys(r,e),status:vs(bs(r,`Status`)),branch:bs(r,`Branch`),scope:bs(r,`Scope`),objective:xs(r,`Objective`),openItems:Ss(r)}}function Ms(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>Cs(e,t.currentBranch)-Cs(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function Ns(e){return e.map(ws).join(`
86
+
87
+ `)}function Ps(e,t={},n=new A){let r=t.currentBranch??ks(e,n);return Ns(Ms(As(e,n).map(t=>js(t,e,n)),{...t,currentBranch:r}))}function Fs(e,t,n={},r=new A){let i=Es(r.readFileSync(e,`utf8`),t),a=n.progressMessage?Ds(i,n.now??new Date,n.progressMessage):i;r.writeFileSync(e,a,`utf8`)}const Is=200,Ls=25600,Rs=[`user`,`feedback`,`project`,`reference`];function zs(e){return Rs.includes(e)}function Bs(e){return O(e,`.robota`,`memory`)}function Vs(e,t){let n=Buffer.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function Hs(e,t){let n=e.split(/\r?\n/);return{content:n.slice(0,t).join(`
88
+ `).trimEnd(),truncated:n.length>t}}function Us(e){return e.trim().toLowerCase().replace(/[^a-z0-9가-힣_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`general`}function Ws(e,t,n){let r=e.toISOString().slice(0,10),i=t.text.trim().replace(/\s+/g,` `);return`[${r}] (${t.type}/${n}) ${i}`}function Gs(e){return e.trim().replace(/\s+/g,` `)}var Ks=class{cwd;now;constructor(e,t=()=>new Date){this.cwd=e,this.now=t}getIndexPath(){return O(Bs(this.cwd),`MEMORY.md`)}getTopicsPath(){return O(Bs(this.cwd),`topics`)}loadStartupMemory(){let e=this.getIndexPath();if(!E(e))return{content:``,path:e,lineCount:0,truncated:!1};let t=D(e,`utf8`),n=Vs(t,Ls),r=Buffer.byteLength(t,`utf8`)>Ls,i=Hs(n,200);return{content:i.content,path:e,lineCount:i.content.length===0?0:i.content.split(/\r?\n/).length,truncated:r||i.truncated}}list(){let e=this.getTopicsPath(),t=E(e)?tt(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(t=>({name:rt(t.name,`.md`),path:O(e,t.name)})).sort((e,t)=>e.name.localeCompare(t.name)):[];return{indexPath:this.getIndexPath(),topicsPath:e,topics:t}}readTopic(e){let t=Us(e),n=O(this.getTopicsPath(),`${t}.md`);return E(n)?D(n,`utf8`).trimEnd():``}append(e){let t=Us(e.topic),n=Bs(this.cwd),r=this.getTopicsPath();et(r,{recursive:!0});let i=this.getIndexPath(),a=O(r,`${t}.md`),o=Ws(this.now(),e,t),s=E(a)?``:`# ${t}\n\n`,c=Gs(e.text);return E(a)&&D(a,`utf8`).includes(`) ${c}`)?{indexPath:i,topicPath:a,topic:t,deduplicated:!0}:(E(i)||(et(n,{recursive:!0}),nt(i,`# Project Memory
89
+
90
+ `,`utf8`)),$e(i,`- ${o}\n`,`utf8`),$e(a,`${s}- ${o}\n`,`utf8`),{indexPath:i,topicPath:a,topic:t,deduplicated:!1})}};function qs(e,t){let n=[],r=at(e),i=!1;for(;!i;){let e=O(r,t);E(e)&&n.push(e);let a=it(r);i=a===r,i||(r=a)}return n.reverse()}function Js(e){let t=e.split(`
91
+ `),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(`
92
+ `).trim()||void 0}async function Ys(e){let t=qs(e,`AGENTS.md`),n=qs(e,`CLAUDE.md`),r=t.map(e=>ni(e)),i=n.map(e=>ni(e)),a=r.map(e=>e.content).join(`
93
+
94
+ `),o=i.map(e=>e.content).join(`
95
+
96
+ `),s=Js(o),c=new Ks(e).loadStartupMemory().content||void 0,l=Ps(e);return{agentsMd:a,claudeMd:o,memoryMd:c,taskContext:l.trim().length>0?l:void 0,compactInstructions:s,agentsFileEntries:r,claudeFileEntries:i}}function Xs(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(`
97
+ `)){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 Zs(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 Qs(e,t=new A){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}var $s=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new A){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){return this.discoverAndLoad()}async loadAll(){return this.discoverAndLoad()}discoverAndLoad(){let e=b(this.pluginsDir,`cache`);if(!this.fs.existsSync(e))return[];let t=[],n=Qs(e,this.fs);for(let r of n){let n=b(e,r),i=Qs(n,this.fs);for(let e of i){let i=b(n,e),a=Qs(i,this.fs);if(a.length===0)continue;let o=a[a.length-1],s=b(i,o),c=b(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 Zs(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=b(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=b(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let{metadata:r,content:a}=Xs(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=b(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}=Xs(this.fs.readFileSync(b(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=b(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=b(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=b(e,`agents`);return this.fs.existsSync(t)?this.fs.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.name.endsWith(`.md`)).map(e=>e.name.replace(/\.md$/,``)):[]}};function ec(e){let t=b(y(y(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function tc(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 nc(e){let t={};for(let n of e){let e=n.hooks;if(!e)continue;let r=ec(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=tc(e,n.pluginDir);return t.env=r,t});t[e].push(...i)}}return t}function rc(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 ic(e){let t=e.cwd,[n,r,i]=await Promise.all([e.config?Promise.resolve(e.config):hs(t),e.bare?Promise.resolve({agentsMd:``,claudeMd:``,agentsFileEntries:[],claudeFileEntries:[]}):Ys(t),e.bare?Promise.resolve({type:`unknown`,language:`unknown`}):qi(t)]),a=e.language?{...n,language:e.language}:n,o=new $s(b(C(),`.robota`,`plugins`));if(!e.bare)try{let e=o.loadPluginsSync();if(e.length>0){let t=nc(e);a={...a,hooks:rc(a.hooks,t)}}}catch{}let s=H(t);await oc(e)||await ac(e,t);let c=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,{session:l,rebuildSystemMessage:u}=Ro({config:a,cwd:t,context:r,projectInfo:i,permissionMode:e.permissionMode,maxTurns:e.maxTurns,terminal:tn,sessionLogger:new qe(s.logs),permissionHandler:e.permissionHandler,...e.askHandler?{ask:e.askHandler}:{},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}:{},includeGoalTool:!0,...e.responseFormat?{responseFormat:e.responseFormat}:{}});return{session:l,agentsFileEntries:r.agentsFileEntries??[],claudeFileEntries:r.claudeFileEntries??[],rebuildSystemMessage:u}}async function ac(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await Pe(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function oc(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 sc(e,t){let n=e.config??await hs(e.cwd),r=n.autoCompactThreshold===void 0?`default`:`settings`,i=new Mi({cwd:e.cwd});t.setEditCheckpointStore(i);let a=await ic({cwd:e.cwd,provider:e.provider,config:n,permissionMode:e.permissionMode,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler,...e.askHandler?{askHandler:e.askHandler}:{},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)Ji(a.session,e);a.session.syncContextFromHistory()}return{session:a.session,agentsFileEntries:a.agentsFileEntries,claudeFileEntries:a.claudeFileEntries,rebuildSystemMessage:a.rebuildSystemMessage,autoCompactThresholdSource:r}}function cc(e,t,n,r,i,a,o,s,c,l,u){try{let d=t.getSessionId(),f=e.load(d),p=l?.snapshotId??f?.sandboxSnapshotId;e.save(lc({session:t,sessionId:d,sessionName:n??f?.name,cwd:r,history:i,createdAt:f?.createdAt,backgroundState:a,memoryState:o,skillActivationState:s,contextReferenceState:c,...p===void 0?{}:{sandboxSnapshotId:p},...u===void 0?{}:{goalState:u}}))}catch{}}function lc(e){return{id:e.sessionId,...e.goalState===void 0?{}:{goal:e.goalState},...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},...uc(e.backgroundState),...dc(e.memoryState),...fc(e.skillActivationState),...pc(e.contextReferenceState)}}function uc(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function dc(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function fc(e){return e?{skillActivationEvents:[...e.events]}:{}}function pc(e){return e?{contextReferences:[...e.references]}:{}}function mc(e){return e.source===`skill`||e.source===`plugin`&&e.skillContent?`skill`:`builtin-command`}function hc(e){let t=e.source===`skill`||e.source===`plugin`&&!!e.skillContent;return{name:e.name,kind:mc(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 gc=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=>hc(e))}},_c=class{commands;constructor(e){this.commands=new Map;for(let t of e??Q())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 Q(){return[]}function vc(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 yc=class{name=`builtin`;commands;constructor(e=Q()){this.commands=e.map(vc)}getCommands(){return this.commands}};function bc(){let e=Q();return{name:`sdk-builtin`,commandSources:[new yc(e)],systemCommands:e}}function xc(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function Sc(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function Cc(e,t,n={}){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);let r={...e.providers};if(delete r[t],n.replacementCurrentProvider!==void 0&&r[n.replacementCurrentProvider]===void 0)throw Error(`Provider profile "${n.replacementCurrentProvider}" was not found`);let i={...e,providers:r};if(e.currentProvider!==t)return i;if(n.replacementCurrentProvider!==void 0)return{...i,currentProvider:n.replacementCurrentProvider};let a={...i};return delete a.currentProvider,a}function wc(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&&!kc(t,i?.defaults,a))throw Error(`Provider profile "${e}" is missing ${jc(a)}`)}function Tc(e,t={}){let n=Ec(e,t);return wc(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function Ec(e,t={}){let n=Oc(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:d(e.apiKeyEnv),i=e.baseURL??n.baseURL;return{type:e.type,model:e.model??n.model,...Mc(r)&&{apiKey:r},...i!==void 0&&{baseURL:i},...e.timeout!==void 0&&{timeout:e.timeout}}}function Dc(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=xc(e,n,r);return t.currentProvider?Sc(i,t.currentProvider):i}function Oc(e,t){return u(t,e)?.defaults??{}}function kc(e,t,n){return n.anyOf.some(n=>h(Ac(n,e,t)))}function Ac(e,t,n){return t[e]??n?.[e]}function jc(e){return e.anyOf.join(` or `)}function Mc(e){return e!==void 0&&e.length>0}async function Nc(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{wc(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??Pc)(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 Pc(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function Fc(e,t=[]){return Ic(e,t)?`valid`:`incomplete`}function Ic(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return Lc(n?.type,n,t)}return!!(e.provider&&Lc(e.provider.name,e.provider,t))}function Lc(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:Rc(t,r,i)}function Rc(e,t,n){return n.anyOf.some(n=>h(zc(n,e,t)))}function zc(e,t,n){return t[e]??n.defaults?.[e]}function Bc(e,t=[]){if(!w(e))return`missing`;try{let n=fe(e,`utf8`).trim();return n.length===0?`incomplete`:Fc(JSON.parse(n),t)}catch{return`corrupt`}}function Vc(e,t=new A){return e.reduce((e,n)=>{let r=Hc(n,t);return r===void 0?e:Uc(e,r)},{})}function Hc(e,t){if(!t.existsSync(e))return;let n=t.readFileSync(e,`utf8`);try{return JSON.parse(n)}catch(t){throw new Qa(e,t instanceof Error?t.message:String(t))}}function Uc(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?Wc(e.providers,t.providers):void 0}}function Wc(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function Gc(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 Ne({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 Ne({name:i.name,model:i.model,apiKey:i.apiKey,baseURL:i.baseURL,timeout:i.timeout,options:i.options},n)}function Kc(){return process.env.HOME??process.env.USERPROFILE??`/`}function qc(e){let t=Kc();return[b(t,`.robota`,`settings.json`),b(t,`.claude`,`settings.json`),b(e,`.robota`,`settings.json`),b(e,`.robota`,`settings.local.json`),b(e,`.claude`,`settings.json`),b(e,`.claude`,`settings.local.json`)]}function Jc(e,t={}){let n=t.settingsPaths??qc(e),r=el(n)??n[0];if(r===void 0)throw Error(`No settings path available for provider update`);return r}function $(e){return q(e)}function Yc(e,t,n={}){let r=Dc($(e),Tc(t,n));return J(e,r),r}function Xc(e,t,n={}){let r=$(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:Sc(r,t);return J(e,o),o}function Zc(e,t,n={}){let r=n.settingsPaths??qc(e),i=Vc(r),a=n.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Qc(r,a,t)}function Qc(e,t,n){let r=$c(e,t)??e[0];if(r===void 0)throw Error(`No settings path available for model update`);let i=$(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 $c(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&$(r).providers?.[t]!==void 0)return r}}function el(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&$(n).currentProvider!==void 0)return n}}var tl=class extends Error{constructor(e){super(e),this.name=`ProviderConfigError`}};function nl(e){return Vc(qc(e))}function rl(e,n=process.env){for(let r of e){let e=r.defaults;if(e?.apiKey===void 0||e.model===void 0||!g(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 il(e,t={}){let n=Gc(nl(e),t.providerOverride,t.providerDefinitions??[]);if(n!==void 0)return n;let r=rl(t.providerDefinitions??[],t.env);if(r!==void 0)return r;throw new tl("No provider configuration found. Run `robota` to set up.")}function al(e,t,n={}){let r=n.providerDefinitions??[],i=il(e,{...n,providerDefinitions:r}),a=t??i.model;return je({...i,model:a},r)}var ol=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 sl(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 cl=Ke,ll=`autoCompactThreshold`;function ul(e){return e.getContextState()}function dl(e){return e.getAutoCompactThreshold()}function fl(e){return e.getAutoCompactThresholdSource?.()??`session`}function pl(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 ml(e,t){let n=xl(e);return n?(n.write({...n.read(),[ll]:t}),!0):!1}function hl(e){let t=xl(e);if(!t)return!1;let n={...t.read()};return delete n[ll],t.write(n),!0}async function gl(e,t){let n=ul(e),r=e.getSession().getMessageCount();return await e.compactContext(t),{before:n,after:ul(e),beforeMessageCount:r,afterMessageCount:e.getSession().getMessageCount()}}function _l(e){return e.listContextReferences?.()??[]}async function vl(e,t){return e.addContextReference?e.addContextReference(t):{evicted:[],diagnostics:[`Command host does not support context reference additions.`]}}function yl(e,t){return e.removeContextReference?.(t)??{}}function bl(e){return e.clearContextReferences?.()??{removed:[]}}function xl(e){return e.getCommandHostAdapters?.().settings}function Sl(e,t={}){let n=Cl(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 Cl(e){let t=e?.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t!==void 0&&t.length>0?t:void 0}const wl=`Show available commands`;function Tl(e){return e.listCommands?.()??[]}function El(e){return[`Available commands:`,...Tl(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(`
98
+ `)}const Dl=`List and control background tasks`,Ol=`Usage: background list | background read <task-id> [offset] | background cancel <task-id> | background close <task-id>`;function kl(){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 Al(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=Nl(e),s=t?` — ${t}`:``;return`${e.id} [${e.status}${n}${i}${a}${o}] ${e.kind}:${e.label}${r}${s}`}function jl(e){return e.length===0?`No background tasks.`:[`Background tasks:`,...e.map(e=>` ${Al(e)}`)].join(`
99
+ `)}function Ml(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isNaN(t)?void 0:{offset:t}}function Nl(e){let t=[];return e.worktreePath&&t.push(`worktree=${e.worktreePath}`),e.branchName&&t.push(`branch=${e.branchName}`),e.worktreeStatus&&t.push(`worktreeStatus="${Pl(e.worktreeStatus)}"`),e.worktreeNextAction&&t.push(`next="${Pl(e.worktreeNextAction)}"`),t.length===0?``:` ${t.join(` `)}`}function Pl(e){let t=e.trim().replace(/\s+/g,` `);return t.length>160?`${t.slice(0,160)}...`:t}function Fl(e,t){return e.listBackgroundTasks(t)}function Il(e,t,n){return e.readBackgroundTaskLog(t,n)}function Ll(e,t,n){return e.cancelBackgroundTask(t,n)}function Rl(e,t){return e.closeBackgroundTask(t)}const zl=`Set response language`,Bl=`<code>`,Vl=[{code:`ko`,description:`Korean`},{code:`en`,description:`English`},{code:`ja`,description:`Japanese`},{code:`zh`,description:`Chinese`}];function Hl(e=`language`){return Vl.map(t=>({name:t.code,description:t.description,source:e}))}function Ul(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Wl(e=`language`){return`Usage: ${e} <code> (e.g., ko, en, ja, zh)`}const Gl=`Show/change permission mode`,Kl=`plan | default | acceptEdits | bypassPermissions`,ql=`Show/change permission mode and permission rules`,Jl=[`plan`,`default`,`acceptEdits`,`bypassPermissions`];function Yl(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 Xl(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Zl(e){return Jl.includes(e)}function Ql(){return`Invalid mode. Valid: ${Jl.join(` | `)}`}function $l(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 eu(e){return $l(e).getPermissionMode()}function tu(e,t){$l(e).setPermissionMode(t)}function nu(e){return $l(e).listSessionAllowedTools()}function ru(e){return{mode:eu(e),sessionAllowed:nu(e)}}function iu(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(`
100
+ `)}async function au(e,t,n){let r=[],i=[];e.getSession().setActivePresetId?.(t),n.permissionMode===void 0?i.push(`permissionMode`):(tu(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 ou=`Configure TUI status-line visibility and fields such as model, context, tokens, session, and git branch.`,su=`on | off | reset | git on | git off`,cu={enabled:!0,gitBranch:!0};function lu(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 uu(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function du(e){let t=e.statusline;return pu(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:cu.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:cu.gitBranch}:{...cu}}function fu(e,t){let n=q(e),r={...du(n),...t};return n.statusline=r,J(e,n),r}function pu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}const mu=`Manage plugins`,hu=`manage | install <name@marketplace> | uninstall <name@marketplace> | enable <name@marketplace> | disable <name@marketplace> | marketplace <action>`,gu=`Reload all plugin resources`;function _u(){return{type:`plugin-tui-requested`}}function vu(){return{type:`plugin-registry-reload-requested`}}function yu(e){return e.getCommandHostAdapters?.().plugin}function bu(){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 xu=`Clear conversation history`,Su=`Rename the current session`,Cu=`Usage: rename <name>`,wu=`Resume a previous session`,Tu=`Show session token usage and estimated cost. /cost budget <amount> sets a monthly budget.`,Eu=`Validate current session replay log`,Du=`Exit CLI`;function Ou(e){if(e.clearConversationHistory!==void 0){e.clearConversationHistory();return}e.getSession().clearHistory()}function ku(e){let t=e.trim();return t.length>0?t:void 0}function Au(e){return{type:`session-renamed`,name:e}}function ju(){return{type:`session-picker-requested`}}function Mu(){return{type:`session-exit-requested`}}function Nu(e){let t=e.getSession();return{sessionId:t.getSessionId(),messageCount:t.getMessageCount()}}function Pu(e){let t=e.validateCurrentSessionReplayLog?.();if(t!==void 0)return t;let n=e.getSession().getSessionId(),r=b(H(e.getCwd()).logs,`${n}.jsonl`),i=Xe(r);return{logFile:r,entryCount:i.length,validation:Qe(i)}}function Fu(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(`
101
+ `);let r=e.validation.issues.map((e,t)=>{let n=Iu(e);return`${t+1}. ${e.code}${n}: ${e.message}`});return[t,...n,``,...r].join(`
102
+ `)}function Iu(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 Lu=`List, inspect, restore, or rollback edit checkpoints.`,Ru=`list | inspect CHECKPOINT_ID | restore CHECKPOINT_ID | code CHECKPOINT_ID | rollback CHECKPOINT_ID`;function zu(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 Bu(e){return e.listEditCheckpoints()}function Vu(e,t){if(!e.inspectEditCheckpoint)throw Error(`Checkpoint inspection is not available in this command host.`);return e.inspectEditCheckpoint(t)}function Hu(e,t){return e.restoreEditCheckpoint(t)}function Uu(e,t){return e.rollbackEditCheckpoint(t)}const Wu=[/\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 Gu(e){return Wu.some(t=>t.test(e))}function Ku(e){return b(e,`.robota`,`memory`)}function qu(){return{version:1,records:[]}}var Ju=class{fs;path;now;constructor(e,t=()=>new Date,n=new A){this.fs=n,this.path=b(Ku(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 qu();try{return{version:1,records:JSON.parse(this.fs.readFileSync(this.path,`utf8`)).records??[]}}catch{return qu()}}write(e){this.fs.mkdirSync(y(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,JSON.stringify(e,null,2),`utf8`)}};const Yu=`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.`,Xu=`list | show [topic] | add <user|feedback|project|reference> <topic> <text> | pending | approve <id> | reject <id> | used`,Zu=`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 Qu(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 $u(e,t){return new Ks(e,t)}function ed(e,t){return new Ju(e,t)}function td(e,t){let n=e.getCwd();return{project:$u(n,t),pending:ed(n,t)}}function nd(e){return zs(e)}function rd(e){return Gu(e)}function id(e){return e.getUsedMemoryReferences()}function ad(e,t,n=()=>new Date){e.recordMemoryEvent({...t,at:n().toISOString()})}function od(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 sd(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 cd(e,t,n,r){return e.skillContent?od(await sd(e.skillContent,n.shellExec),t,r):null}async function ld(e,t,n,r){let i=await cd(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 ud(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 cd(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 ld(e,t,n,r)}}function dd(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function fd(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function pd(e,t){let n=t.trim();return n.length>0?`${e} ${n}`:e}function md(e){if(!e?.startsWith(`/`))return;let t=e.slice(1).trim().split(/\s+/)[0];return t&&t.length>0?t:void 0}var hd=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 _c(e.flatMap(e=>e.systemCommands??[])),this.skillCommandSource=new Za(t),this.commandHostAdapters=n}reapplyCommandModuleSelection(e,t){let n=sl(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=dd(e);return this.skillCommandSource.getCommands().find(e=>e.name.toLowerCase()===t.toLowerCase())}async executeCommand(e,t){let n=fd(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,pd(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=md(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 ud(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=Bi({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 gd(){let e=b(C(),`.robota`,`org-policy.json`);if(!w(e))return null;try{let t=fe(e,`utf8`);return JSON.parse(t)}catch{return null}}function _d(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function vd(e){return e?!e.startsWith(`$ENV:`):!1}function yd(e,t){if(!e)return;let n={type:`cancelled`};return{ask:r=>t()===`model`?Promise.resolve(n):e(r)}}var bd=class extends ei{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;goalController=new _o;currentTurnSource=`user`;terminalHandoff;askHandler;terminalHandoffActive=!1;constructor(e){super(),this.sessionStore=e.sessionStore,this.sessionName=e.sessionName,this.terminalHandoff=e.terminalHandoff,this.askHandler=e.askHandler,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 Mi({cwd:t})),this.bgTracker=new Br(()=>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))),e=>this.histTracker.append(e)),this.histTracker=new Wi(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 hd(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)=>xi(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 yi(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),this.on(`turn_source`,e=>{this.currentTurnSource=e}),this.on(`complete`,e=>this.handleGoalTurnComplete(e));let o=this.configureInjectedSession(e);this.restoreSessionRecordIfNeeded(e),this.startAsyncInitializationIfNeeded(e,o),this.initialized&&this.bgTracker.subscribe(this.session),this.initialized&&this.persistCurrentSession(),this.resumeGoalIfActive()}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=Yi(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.forkSession&&t.goal&&this.goalController.restore(t.goal),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 sc(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){return this.execCtrl.shuttingDown||this.execCtrl.wakeTaskIds.has(t)?!1:(this.execCtrl.wakeTaskIds.add(t),this.submit(e,void 0,void 0,{turnSource:`agent-wakeup`,wakeTaskId:t}),!0)}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(`
103
+
104
+ `),n=this.claudeFileEntries.map(e=>e.content).join(`
105
+
106
+ `),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(`
107
+
108
+ `),n=this.claudeFileEntries.map(e=>e.content).join(`
109
+
110
+ `),r=this.rebuildSystemMessage(t,n,{selfVerification:e});this.getSessionOrThrow().updateSystemMessage(r)}applyCommandModuleSelection(e,t){this.skillRouter.reapplyCommandModuleSelection(e,t)}getAgentJobCapability(){return this}getUserInteraction(){return yd(this.askHandler,()=>this.getCommandInvocationSource())}canHandoffTerminal(){return this.terminalHandoff?.canHandoffTerminal===!0}async runWithTerminal(e){if(!this.canHandoffTerminal()||this.terminalHandoff===void 0)throw Error(`Terminal handoff is unavailable: no interactive terminal (headless or non-TTY output).`);if(this.terminalHandoffActive)throw Error(`A terminal handoff is already in progress.`);this.terminalHandoffActive=!0;try{return await this.terminalHandoff.runWithTerminal(e)}finally{this.terminalHandoffActive=!1}}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 Vn(this.session)??B(this.session)?.backgroundTaskManager}reportBackgroundError(e,t=`background`){let n=_i(e);this.histTracker.append(_(c(`Error: ${n}`,{metadata:{kind:`error`,source:t}}))),this.emit(`error`,e)}async captureSandboxSnapshot(){if(this.sandboxClient?.snapshot)try{this.sandboxSnapshotId=await this.sandboxClient.snapshot()}catch(e){let t=e instanceof Error?e:Error(String(e));this.histTracker.append(_(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();cc(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},this.goalController.getState()??void 0)}async setGoal(e,t={}){await this.ensureInitialized();let{goal:n,prompt:r}=this.goalController.start(e,t);return this.emit(`goal_event`,{type:`goal_started`,goal:n}),this.persistCurrentSession(),this.scheduleGoalTurn(r,n),n}getGoalState(){return this.goalController.getState()}cancelGoal(){let e=this.goalController.cancel();return e&&(this.emit(`goal_event`,{type:`goal_stopped`,goal:e}),this.persistCurrentSession()),e}scheduleGoalTurn(e,t){if(this.execCtrl.shuttingDown)return;let n=`goal:${t.id}:${t.iterations}`;setTimeout(()=>this.requestWakeup(e,n),0)}handleGoalTurnComplete(e){if(!this.goalController.isActive()||this.currentTurnSource!==`agent-wakeup`)return;let t=this.goalController.onTurnComplete(e);t&&(this.persistCurrentSession(),t.action===`continue`?(this.emit(`goal_event`,{type:`goal_progress`,goal:t.goal}),this.scheduleGoalTurn(t.prompt,t.goal)):this.emit(`goal_event`,{type:`goal_stopped`,goal:t.goal}))}resumeGoalIfActive(){let e=this.goalController.getState();!e||e.status!==`active`||this.ensureInitialized().then(()=>{!this.goalController.isActive()||this.execCtrl.shuttingDown||this.scheduleGoalTurn(lo(e),e)})}async switchProvider(e){let t=this.getSessionOrThrow(),n=this.getCwd(),r=il(n,{providerOverride:e,providerDefinitions:this.providerDefinitions}),i=al(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:_d(`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:_d(`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 xd(e,t=new A){let n=H(e);return new Ed(n.sessions,n.logs,t)}function Sd(e=new A){return new Ed(Ti().sessions,void 0,e)}function Cd(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:Dd(e.messages)}))}function wd(e,t){return Cd(e,t)[0]?.id}function Td(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var Ed=class{store;logsDir;fs;constructor(e,t,n=new A){this.store=new Ye(e),this.logsDir=t,this.fs=n}save(e){this.store.save(Od(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):kd(t)}list(){let e=this.store.list().map(kd),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=Ze(Xe(b(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:Ad(n),backgroundTaskEvents:n,backgroundJobGroups:Md(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 Dd(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 Od(e){return{...e}}function kd(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 Ad(e){let t=new Map;for(let n of e){let e=jd(n);e&&t.set(e.id,e)}return[...t.values()]}function jd(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 Md(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function Nd(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,``).trim().replace(/\s+/g,`-`).replace(/-+/g,`-`).slice(0,60)}async function Pd(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=Nd(typeof r.content==`string`?r.content:``);return!i||i.length<3?Nd(t):i}export{gu as $,yo as $n,Nt as $r,fl as $t,Lu as A,wc as An,pr as Ar,Wl as At,Cu as B,zs as Bn,ar as Br,Ml as Bt,ed as C,Nc as Cn,zr as Cr,ru as Ct,id as D,Dc as Dn,Cr as Dr,zl as Dt,nd as E,Cc as En,Ar as Er,Bl as Et,Uu as F,gc as Fn,hr as Fr,Ll as Ft,ju as G,ks as Gn,N as Gr,Sl as Gt,Eu as H,Ns as Hn,Nn as Hr,wl as Ht,xu as I,$s as In,cr as Ir,Rl as It,ku as J,Bo as Jn,L as Jr,vl as Jt,Au as K,Ms as Kn,I as Kr,ll as Kt,Tu as L,Ls as Ln,sr as Lr,Al as Lt,Vu as M,bc as Mn,fr as Mr,Dl as Mt,Bu as N,Q as Nn,mr as Nr,Ol as Nt,ad as O,Sc as On,lr as Or,Vl as Ot,Hu as P,_c as Pn,dr as Pr,kl as Pt,mu as Q,xo as Qn,ln as Qr,dl as Qt,Du as R,Is as Rn,or as Rr,jl as Rt,td as S,Pc as Sn,Ti as Sr,eu as St,rd as T,Tc as Tn,Pr as Tr,tu as Tt,Ou as U,Ps as Un,Mn as Ur,El as Ut,wu as V,As as Vn,In as Vr,Il as Vt,Mu as W,js as Wn,mn as Wr,Cl as Wt,Pu as X,To as Xn,pn as Xr,gl as Xt,Nu as Y,Vo as Yn,P as Yr,bl as Yt,hu as Z,Eo as Zn,rn as Zr,_l as Zt,od as _,Uc as _n,Ba as _r,iu as _t,wd as a,xt as ai,ol as an,co as ar,su as at,Zu as b,Fc as bn,Mi as br,nu as bt,_d as c,k as ci,nl as cn,ro as cr,lu as ct,f as d,ut as di,Zc as dn,eo as dr,au as dt,Mt as ei,ul as en,uo as er,bu as et,ee as f,ct as fi,Yc as fn,to as fr,ql as ft,sd as g,Wc as gn,qa as gr,Yl as gt,ud as h,qc as hn,Za as hr,Jl as ht,Cd as i,vt as ii,ml as in,lo as ir,cu as it,zu as j,yc as jn,gr as jr,Ul as jt,Ru as k,xc as kn,ur as kr,Hl as kt,vd as l,lt as li,il as ln,$a as lr,uu as lt,ne as m,st as mi,Jc as mn,Qa as mr,Gl as mt,xd as n,jt as ni,hl as nn,_o as nr,_u as nt,Td as o,bt as oi,tl as on,io as or,ou as ot,te as p,dt as pi,Xc as pn,J as pr,Kl as pt,Fu as q,Fs as qn,F as qr,cl as qt,Sd as r,Tt as ri,pl as rn,ho as rr,yu as rt,bd as s,yt as si,al as sn,oo as sr,fu as st,Pd as t,A as ti,yl as tn,fo as tr,vu as tt,gd as u,ot as ui,rl as un,q as ur,du as ut,Xu as v,Vc as vn,Ma as vr,Ql as vt,$u as w,Ec as wn,B as wr,$l as wt,Qu as x,Bc as xn,H as xr,Xl as xt,Yu as y,Gc as yn,na as yr,Zl as yt,Su as z,Ks as zn,ir as zr,Fl as zt};
111
+ //# sourceMappingURL=interactive-C93XBn4U.js.map