@robota-sdk/agent-framework 3.0.0-beta.79 → 3.0.0-beta.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,110 +0,0 @@
1
- let e=require("@robota-sdk/agent-core"),t=require("node:crypto"),n=require("node:path"),r=require("node:os"),i=require("node:fs"),a=require("node:fs/promises"),o=require("@robota-sdk/agent-executor"),s=require("@robota-sdk/agent-tools"),c=require("zod"),l=require("@robota-sdk/agent-session"),u=require("fs"),d=require("path");function f(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 p(e,t,n){let r=e.find(e=>e.sourcePath===t.sourcePath),i=e.filter(e=>e.sourcePath!==t.sourcePath),a=r?ee(r,t):t;return te([...i,a],n)}function m(e,t){let n=ie(t),r=e.find(e=>ae(e,n));return r?{references:e.filter(e=>e.sourcePath!==r.sourcePath),result:{removed:r}}:{references:[...e],result:{}}}function h(e){return{removed:[...e]}}function g(e){return e.filter(e=>e.status===`active`)}function _(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 ee(e,t){return t.status===`active`?{...t,loadedAt:e.loadedAt}:{...e,byteLength:t.byteLength,originalReference:t.originalReference,lastUsedAt:t.lastUsedAt}}function te(e,t){let n=t?.maxActiveReferences??8,r=t?.maxActiveBytes??262144,i=t?.maxObservedReferences??32,a=[],o=[...e];for(;ne(o)>n||re(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 ne(e){return e.filter(e=>e.status===`active`).length}function re(e){return e.reduce((e,t)=>e+(t.status===`active`?t.byteLength:0),0)}function ie(e){return e.startsWith(`@`)?e.slice(1):e}function ae(e,t){return e.relativePath===t||e.sourcePath===t||e.originalReference===t||e.originalReference===`@${t}`}function oe(e,t){return t.length===0?e:[e,`<robota_file_references>`,...t.map(e=>{let t=e.content.replaceAll(`</file>`,`<\\/file>`);return[`<file path="${se(e.relativePath)}" bytes="${e.byteLength}" reason="${e.reason}">`,t,`</file>`].join(`
2
- `)}),`</robota_file_references>`].join(`
3
-
4
- `)}function v(e){return e.some(e=>e.severity===`error`)}function y(e){return e.length===0?``:[`File reference error:`,...e.map(e=>`- ${e.reference}: ${e.message}`)].join(`
5
- `)}function b(e){return e.map(({content:e,...t})=>t)}function x(e){let n=b(e);return{id:`prompt_file_reference_${(0,t.randomUUID)()}`,timestamp:new Date,category:`event`,type:`prompt-file-reference`,data:{message:ce(n),references:n}}}function se(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function ce(e){return`Loaded file references: ${e.map(e=>`${e.relativePath} (${e.byteLength} B)`).join(`, `)}`}const le=/(^|[\s([{])@([^\s)\]}>,;"'`]+)/g;function ue(e){let t=[];for(let n of e.matchAll(le)){let e=de(n[2]??``);fe(e)&&t.push({original:`@${e}`,path:e,index:n.index??0})}return t}function de(e){let t=e.length;for(;t>0&&/[.,:;!?]/.test(e[t-1]??``);)--t;return e.slice(0,t)}function fe(e){return e.length===0||e.includes(`://`)?!1:e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)||e.startsWith(`~/`)||e.startsWith(`.`)||e.includes(`.`)}function pe(e,t){return e.startsWith(`~/`)?(0,n.resolve)((0,r.homedir)(),e.slice(2)):(0,n.isAbsolute)(e)?(0,n.resolve)(e):(0,n.resolve)(t,e)}function me(e,t){let r=(0,n.relative)(t,e);return r===``||!r.startsWith(`..`)&&!(0,n.isAbsolute)(r)}function he(e,t){return(0,n.relative)(e,t).split(n.sep).join(`/`)}var S=class{existsSync(e){return(0,i.existsSync)(e)}readFileSync(e,t){return(0,i.readFileSync)(e,t)}writeFileSync(e,t,n){(0,i.writeFileSync)(e,t,n??`utf8`)}mkdirSync(e,t){(0,i.mkdirSync)(e,t)}readdirSync(e,t){return t?.withFileTypes?(0,i.readdirSync)(e,{withFileTypes:!0}):(0,i.readdirSync)(e)}statSync(e){return(0,i.statSync)(e)}rmSync(e,t){(0,i.rmSync)(e,t)}cpSync(e,t,n){(0,i.cpSync)(e,t,n)}renameSync(e,t){(0,i.renameSync)(e,t)}get constants(){return i.constants}},ge=class{async access(e,t){await(0,a.access)(e,t)}async copyFile(e,t,n){await(0,a.copyFile)(e,t,n)}async mkdir(e,t){await(0,a.mkdir)(e,t)}async readFile(e,t){return(0,a.readFile)(e,t)}async readdir(e,t){return t?.withFileTypes?await(0,a.readdir)(e,{withFileTypes:!0}):(0,a.readdir)(e)}async realpath(e){return(0,a.realpath)(e)}async rename(e,t){await(0,a.rename)(e,t)}async rm(e,t){await(0,a.rm)(e,t)}async stat(e){return(0,a.stat)(e)}async writeFile(e,t,n){await(0,a.writeFile)(e,t,n??`utf8`)}};async function _e(e,t){let n=await ye(t);for(let t of ue(e))await Ce(t,0,[],n);return be(n)}async function ve(e,t){let n=await ye(t);for(let t of e)await Ce({original:`@${t}`,path:t,index:0},0,[],n);return be(n)}async function ye(e){let t=e.fsAsync??new ge;return{rootPath:await Se(e.cwd,t),limits:xe(e.limits),reason:e.reason??`prompt-reference`,references:[],diagnostics:[],loadedPaths:new Set,totalBytes:0,fsAsync:t}}function be(e){return{references:e.references,diagnostics:e.diagnostics}}function xe(e){return{maxDepth:e?.maxDepth??2,maxReferences:e?.maxReferences??8,maxFileBytes:e?.maxFileBytes??65536,maxTotalBytes:e?.maxTotalBytes??262144}}async function Se(e,t){try{return await t.realpath(e)}catch{return(0,n.resolve)(e)}}async function Ce(e,t,n,r){if(!we(e,t,r))return;let i=await Te(e,r);if(i===void 0||!Ee(e,i,n,r))return;let a=await De(e,i,r);if(a===void 0)return;let o=await Oe(e,i,r);o!==void 0&&(r.loadedPaths.add(i),r.totalBytes+=a.byteLength,r.references.push(ke(e,a,t,o,r)),await Ae(o,t,[...n,i],r))}function we(e,t,n){return n.references.length>=n.limits.maxReferences?(C(n,`too-many-references`,e,`Too many file references.`),!1):t>n.limits.maxDepth?(C(n,`max-depth`,e,`File reference nesting is too deep.`),!1):!0}async function Te(e,t){let n=pe(e.path,t.rootPath);if(!me(n,t.rootPath)){C(t,`outside-root`,e,`Referenced path is outside the workspace.`);return}try{let r=await t.fsAsync.realpath(n);if(me(r,t.rootPath))return r;C(t,`outside-root`,e,`Referenced path resolves outside the workspace.`)}catch{C(t,`not-found`,e,`Referenced file was not found.`)}}function Ee(e,t,n,r){return n.includes(t)?(C(r,`circular-reference`,e,`Circular file reference detected.`),!1):!r.loadedPaths.has(t)}async function De(e,t,n){try{let r=await n.fsAsync.stat(t);if(r.isDirectory()){C(n,`directory-not-supported`,e,`Directory references are not supported.`);return}if(r.size>n.limits.maxFileBytes){C(n,`file-too-large`,e,`Referenced file exceeds the per-file size limit.`);return}if(n.totalBytes+r.size>n.limits.maxTotalBytes){C(n,`total-too-large`,e,`Referenced files exceed the total size limit.`);return}return{sourcePath:t,byteLength:r.size}}catch{C(n,`unreadable`,e,`Referenced file could not be inspected.`);return}}async function Oe(e,t,n){try{return await n.fsAsync.readFile(t,`utf8`)}catch{C(n,`unreadable`,e,`Referenced file could not be read.`);return}}function ke(e,t,n,r,i){return{originalReference:e.original,sourcePath:t.sourcePath,relativePath:he(i.rootPath,t.sourcePath),reason:i.reason,depth:n,byteLength:t.byteLength,content:r}}async function Ae(e,t,n,r){for(let i of ue(e))await Ce(i,t+1,n,r)}function C(e,t,n,r){e.diagnostics.push({code:t,severity:`error`,reference:n.original,message:r,path:n.path})}function je(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&(e.message.includes(`aborted`)||e.message.includes(`abort`))}function Me(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 Ne(e,t,n,r,i,a){let o=Me(t,r),s=ze(t,r,i);return{response:e,history:n,toolSummaries:o,contextState:i,...s&&{usage:s},...a&&a.length>0?{promptFileReferences:[...a]}:{}}}function Pe(e,t,n,r){let i=Me(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=ze(e,n,r);return{response:a.join(`
6
-
7
- `),history:t,toolSummaries:i,contextState:r,...o&&{usage:o}}}function Fe(e){return{id:`usage_${(0,t.randomUUID)()}`,timestamp:new Date,category:`event`,type:`usage-summary`,data:e}}function Ie(e,t){return Fe({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 Le(e,t,n,r=[]){let i=await ve(g(r).map(e=>e.sourcePath),{cwd:t,reason:`manual`}),a=await _e(e,{cwd:t}),o=[...i.diagnostics,...a.diagnostics];if(v(o))throw Error(y(o));let s=oe(e,Re([...i.references,...a.references])),c=n??(s===e?void 0:e),l=b(i.references),u=b(a.references),d=a.references.length>0?x(a.references):void 0;return{modelInput:s,...c===void 0?{}:{hookInput:c},activeContextReferenceRecords:l,promptFileReferenceRecords:u,...d===void 0?{}:{promptFileReferenceEntry:d}}}function Re(e){return[...new Map(e.map(e=>[e.sourcePath,e])).values()]}function ze(t,n,r){let i=t.slice(n),a=0,o=0,s=!1;for(let t of i){if(t.role!==`assistant`)continue;let n=(0,e.collectAssistantUsageMetadata)(t);n&&(s=!0,a+=n.inputTokens,o+=n.outputTokens)}if(s)return{kind:`exact`,scope:`turn`,promptTokens:a,completionTokens:o,totalTokens:a+o,contextUsedTokens:r.usedTokens,contextMaxTokens:r.maxTokens,contextUsedPercentage:r.usedPercentage,costStatus:`unknown`}}const Be={write:()=>{},writeLine:()=>{},writeMarkdown:()=>{},writeError:()=>{},prompt:()=>Promise.resolve(``),select:()=>Promise.resolve(0),spinner:()=>({stop:()=>{},update:()=>{}})},Ve=1e3;var He=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:w(r.state)}),this.evaluateCompletion(r),w(r.state)}listGroups(){return[...this.groups.values()].map(e=>w(e.state))}getGroup(e){let t=this.groups.get(e);return t?w(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(w(e));this.groups.set(e.id,t),e.status===`completed`&&t.resolve(w(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&&(0,o.isTerminalBackgroundTaskStatus)(n.status)&&this.captureTask(e,n)}}handleTaskEvent(e){let t=Ue(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:w(e.state)}))}captureTask(e,t){return e.state.results.some(e=>e.taskId===t.id)?!1:(e.state.results=[...e.state.results,Ge(t)],e.state.updatedAt=this.now(),!0)}evaluateCompletion(e){if(e.state.status===`completed`)return;if(!We(e.state)){this.emit({type:`background_job_group_updated`,group:w(e.state)});return}let t=this.now();e.state.status=`completed`,e.state.completedAt=t,e.state.updatedAt=t;let n=w(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 Ue(e){if(e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)return e.task}function We(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 Ge(e){return{taskId:e.id,label:e.label,status:e.status,...e.result?.output?{summary:Ke(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 Ke(e){let t=e.trim();return t.length<=Ve?t:`${t.slice(0,Ve)}...`}function qe(e){let t=Je(e,`completed`),n=Je(e,`failed`),r=Je(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=>Ye(e))}}function Je(e,t){return e.results.filter(e=>e.status===t).length}function Ye(e){let t=Xe(e),n=e.outputRef&&e.summary?` (output: ${e.outputRef})`:``;return`[${e.status}] ${e.label} ${e.taskId}: ${t}${n}`}function Xe(e){let t=(e.error?.message??e.summary??``).replace(/\s+/g,` `).trim();return t.length>0?t:`(no summary)`}function w(e){return{...e,taskIds:[...e.taskIds],results:e.results.map(e=>({...e,...e.error?{error:{...e.error}}:{}}))}}const T={kind:`executionOriginKind`,sessionId:`executionOriginSessionId`,turnId:`executionOriginTurnId`,commandName:`executionOriginCommandName`,toolCallId:`executionOriginToolCallId`,skillId:`executionOriginSkillId`,label:`executionOriginLabel`};function E(e){return[`main`,e].join(`:`)}function D(e){return[`task`,e].join(`:`)}function O(e){return[`group`,e].join(`:`)}function Ze(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 k(e){return{[T.kind]:e.kind,[T.sessionId]:e.sessionId,...e.turnId?{[T.turnId]:e.turnId}:{},...e.commandName?{[T.commandName]:e.commandName}:{},...e.toolCallId?{[T.toolCallId]:e.toolCallId}:{},...e.skillId?{[T.skillId]:e.skillId}:{},...e.label?{[T.label]:e.label}:{}}}function Qe(e){let t=rt(e.groups),n=[$e(e.mainThread),...mt(e.groups).map(e=>tt(e)),...pt(e.tasks).map(e=>et(e,t.get(e.id)))].filter(t=>ft(t,e.filter));return{sessionId:e.sessionId,selectedEntryId:e.selectedEntryId??n.find(e=>e.kind===`main_thread`)?.id??E(e.sessionId),updatedAt:n[0]?.updatedAt??e.mainThread.updatedAt,entries:n}}function $e(e){return{id:E(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:A(e.preview),unread:!1,attention:`none`,visibility:`default`,updatedAt:e.updatedAt,controls:[`select`]}}function et(e,t){return{id:D(e.id),sourceId:e.id,kind:`background_task`,parentId:e.parentTaskId?D(e.parentTaskId):E(e.parentSessionId),...t?{groupId:O(t)}:{},origin:nt(e.metadata,{kind:`system`,sessionId:e.parentSessionId}),taskKind:e.kind,status:e.status,title:e.label,subtitle:at(e),preview:ct(e),currentAction:e.currentAction,unread:e.unread,attention:lt(e),visibility:ut(e),updatedAt:e.lastActivityAt??e.updatedAt,controls:it(e)}}function tt(e){let t=A(e.results.map(e=>e.summary??e.error?.message).join(` `));return{id:O(e.id),sourceId:e.id,kind:`background_group`,parentId:E(e.parentSessionId),origin:{kind:`system`,sessionId:e.parentSessionId,label:e.label},status:e.status,title:e.label??e.id,subtitle:`${e.results.length}/${e.taskIds.length} tasks`,preview:t,unread:!1,attention:dt(e),visibility:e.status===`completed`?`collapsed`:`default`,updatedAt:e.updatedAt,controls:e.status===`running`?[`select`,`wait`]:[`select`]}}function nt(e,t){let n=ht(e?.[T.kind]),r=j(e?.[T.sessionId]);return{kind:n??t.kind,sessionId:r??t.sessionId,turnId:j(e?.[T.turnId])??t.turnId,commandName:j(e?.[T.commandName])??t.commandName,toolCallId:j(e?.[T.toolCallId])??t.toolCallId,skillId:j(e?.[T.skillId])??t.skillId,label:j(e?.[T.label])??t.label}}function rt(e){return new Map(e.flatMap(e=>e.taskIds.map(t=>[t,e.id])))}function it(e){let t=[`select`];return(0,o.isTerminalBackgroundTaskStatus)(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 at(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: ${st(e.nextFireAt)}`;return t===void 0?n:`↻ wake "${ot(t)}" · ${n}`}return e.cwd}function ot(e){let t=e.trim();return t.length>32?`${t.slice(0,32)}…`:t}function st(e){let t=new Date(e),n=new Date,r=t.getTime()-n.getTime();if(r<=0)return`now`;let i=Math.round(r/1e3);if(i<60)return`${i}s`;let a=Math.round(i/60);return a<60?`${a}m`:`${Math.round(a/60)}h`}function ct(e){return e.status===`failed`?A(e.error?.message):e.status===`completed`?A(e.result?.output):A(e.promptPreview??e.commandPreview)}function lt(e){return e.status===`failed`?`failed`:e.status===`waiting_permission`?`permission`:e.unread?`unread`:e.status===`completed`?`completed`:`none`}function ut(e){return e.status===`completed`&&!e.unread&&!e.error&&(e.result?.exitCode??0)===0&&!e.result?.signalCode&&!e.worktreePath&&!e.branchName?`collapsed`:`default`}function dt(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`none`}function ft(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 pt(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 mt(e){return[...e].sort((e,t)=>e.id.localeCompare(t.id))}function A(e){let t=e?.trim().replace(/\s+/g,` `);if(t)return t.length>120?`${t.slice(0,120)}...`:t}function j(e){return typeof e==`string`?e:void 0}function ht(e){if(e===`user_prompt`||e===`slash_command`||e===`model_command`||e===`tool_call`||e===`skill`||e===`transport`||e===`system`)return e}function gt(e){let t=_t(e.cursor?.offset),n=e.history.slice(t,t+80),r=n.map(e=>({id:e.id,kind:e.category===`chat`?`message`:`progress`,text:vt(e),timestamp:e.timestamp.toISOString(),sourceId:e.type}));return{entryId:e.entryId,...e.cursor?{cursor:e.cursor}:{},...t+n.length<e.history.length?{nextCursor:{offset:t+n.length}}:{},records:r}}function M(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 _t(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function vt(e){return typeof e.data==`string`?e.data:e.type}function yt(e){return{spawnAgent:t=>e.manager.spawn(bt(e,t)),spawnProcess:t=>e.manager.spawn(xt(e,t)),createGroup:t=>e.groupOrchestrator.createGroup({parentSessionId:e.sessionId,waitPolicy:t.waitPolicy,taskIds:[...t.taskIds],label:t.label})}}function bt(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:k(e.origin)}}function xt(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:k(e.origin)}}const St=new WeakMap;function Ct(e,t){St.set(e,t)}function wt(e){return St.get(e)}function Tt(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 Et(){return`agent_group_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function Dt(e,t){let n=e?.trim();return n&&n.length>0?n:t}function Ot(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:Dt(e.label,i?.name??r)}}function kt(e){return e.agentDef!==void 0}function At(e,t){return{index:e.index,success:!1,groupId:t,label:e.label,subagent_type:e.agentType,prompt:e.job.prompt,error:`Unknown agent type: ${e.agentType}`}}async function jt(e,t){try{let n=await t.manager.spawn(t.createSpawnRequest(e.job,e.agentType,e.agentDef,t.deps,e.label,t.toolCallId));return{...e,agentId:n.id}}catch(t){let n=t instanceof Error?t.message:String(t);return{...e,spawnError:n}}}function Mt(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 Nt(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 Pt(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 Ft(e,t,n){if(e.agentId===void 0)return Mt(e,t);try{let r=await n.wait(e.agentId);return Nt({...e,agentId:e.agentId},t,r)}catch(n){let r=n instanceof Error?n.message:String(n);return Pt({...e,agentId:e.agentId},t,r)}}async function It(e){let t=Et(),n=e.jobs.map((t,n)=>Ot(t,n,e)),r=n.filter(e=>!kt(e)).map(e=>At(e,t)),i=await Promise.all(n.filter(kt).map(t=>jt(t,e))),a=await Promise.all(i.map(n=>Ft(n,t,e.manager))),o=[...r,...a].sort((e,t)=>e.index-t.index);return Tt({groupId:t,requestedJobCount:e.jobs.length,jobs:o})}function Lt(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 Rt(){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 zt(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 Bt(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 Vt=[{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 N(e){return Vt.find(t=>t.name===e)}function Ht(){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 Ut(){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 Wt(e){let t=[e.agentBody];e.claudeMd&&t.push(e.claudeMd),e.agentsMd&&t.push(e.agentsMd);let n=e.isForkWorker?Ut():Ht();return t.push(n),t.join(`
52
-
53
- `)}const Gt=`robota_command_`,Kt=/^[A-Za-z0-9_-]{1,64}$/;function qt(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Jt(e){let n=qt(e);if(!n)throw Error(`Model command descriptor name must not be empty.`);let r=n.replace(/[^A-Za-z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``);if(!r)throw Error(`Model command descriptor name cannot be projected safely: ${e}`);let i=`${Gt}${r}`;if(Kt.test(i))return i;let a=(0,t.createHash)(`sha256`).update(n).digest(`hex`).slice(0,8),o=`${Gt}${r.slice(0,40).replace(/[_-]+$/g,``)||`command`}_${a}`;if(!Kt.test(o))throw Error(`Projected model command tool name is not provider-safe: ${o}`);return o}function Yt(e){let t=new Set,n=new Map,r=new Map,i=[];for(let a of e){let e=qt(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=Jt(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:en(e,a),descriptor:a,requiresPermission:a.requiresPermission!==!1})}return{commandTools:i,toolNameToCommandName:n,commandNameToToolName:r}}function Xt(e){return`${e.toolName} — ${e.descriptor.description}`}function Zt(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 Qt(e){return Yt(e.commandDescriptors).commandTools.map(t=>{let n=$t(t.descriptor);return(0,s.createZodFunctionTool)(t.toolName,t.description,n,async r=>{let i=n.parse(r);return e.isModelInvocable(t.commandName)?Zt(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 $t(e){let t=e.argumentHint?`Arguments for the command. Expected grammar: ${e.argumentHint}`:`Arguments for the command as a single string.`;return c.z.object({args:c.z.string().optional().describe(t)})}function en(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 tn={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`,opus:`claude-opus-4-6`},nn=Jt(`agent`);function rn(e,t){return tn[e]??e}function an(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()!==nn),n}function on(e){let{agentDefinition:t,parentConfig:n,parentContext:r,parentTools:i,terminal:a}=e,o=an(i,t),s=t.model?rn(t.model,n.provider.model):n.provider.model,c=Wt({agentBody:t.systemPrompt,claudeMd:r.claudeMd,agentsMd:r.agentsMd,isForkWorker:e.isForkWorker??!1}),u=e.provider;return new l.Session({tools:o,provider:u,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 sn(e,t){let n=t?.(e)??N(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function cn(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 ln(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function un(e){if(e.request.isolation===`worktree`)throw Error(`Worktree isolation requires a runtime shell subagent runner`)}function dn(e,t){if(t.type===`start`){e.emit?.({type:`background_task_tool_start`,toolName:t.toolName,firstArg:ln(t.toolArgs)});return}e.emit?.({type:`background_task_tool_end`,toolName:t.toolName,success:t.success??!0})}function fn(t){try{return(0,e.sumHistoryUsage)(t.getFullHistory())}catch{return}}function pn(e){return{start(t){un(t);let n=on({agentDefinition:cn(sn(t.request.type,e.customAgentRegistry),t),parentConfig:e.config,parentContext:e.context,parentTools:e.tools,provider:e.provider,terminal:e.terminal,permissionMode:e.permissionMode,permissionHandler:e.permissionHandler,hooks:e.hooks,hookTypeExecutors:e.hookTypeExecutors,onTextDelta:n=>{t.emit?.({type:`background_task_text_delta`,delta:n}),e.onTextDelta?.(n)},onToolExecution:n=>{dn(t,n),e.onToolExecution?.(n)}});return{jobId:t.jobId,result:n.run(t.request.prompt).then(e=>{let r=fn(n);return{jobId:t.jobId,output:e,...r?{usage:r}:{}}}),cancel:()=>(n.abort(),Promise.resolve())}}}}const mn=[`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(` `),hn=c.z.object({prompt:c.z.string().optional().describe(`The task for a single subagent to perform. Required when jobs is omitted.`),subagent_type:c.z.string().optional().describe(`Agent type: "general-purpose", "Explore", "Plan", or a custom agent name`),model:c.z.string().optional().describe(`Optional model override`),isolation:c.z.enum([`none`,`worktree`]).optional().describe(`Optional runtime isolation mode. "worktree" runs in a Git worktree.`),jobs:c.z.array(c.z.object({label:c.z.string().optional().describe(`Stable role label for this batch job`),prompt:c.z.string().describe(`The task for this subagent to perform`),subagent_type:c.z.string().optional().describe(`Agent type for this job`),model:c.z.string().optional().describe(`Optional model override for this job`),isolation:c.z.enum([`none`,`worktree`]).optional().describe(`Isolation for this job`)}).passthrough()).optional().describe(`Batch of subagent jobs to start in one Agent tool call`)}).passthrough(),gn=new WeakMap;function _n(e,t){gn.set(e,t)}function P(e){return gn.get(e)}function vn(e,t){if(t){let n=t(e);if(n)return n}let n=N(e);if(n)return n}function yn(e){return e.subagentManager??new o.SubagentManager({runner:pn(e)})}function bn(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:k({kind:`tool_call`,sessionId:r.parentSessionId??`unknown-session`,label:i,...a?{toolCallId:a}:{}})}}async function xn(e,t,n,r){if(typeof e.prompt!=`string`||e.prompt.length===0)return Bt(`prompt is required when jobs is omitted`);let i={...e,prompt:e.prompt},a=e.subagent_type??`general-purpose`,o=vn(a,t.customAgentRegistry);if(!o)return Lt(a);let s;try{let e=await n.spawn(bn(i,a,o,t,void 0,r));return s=e.id,zt(await n.wait(e.id))}catch(e){return Bt(e instanceof Error?e.message:String(e),s)}}function Sn(e){let t=yn(e);return(0,s.createZodFunctionTool)(`Agent`,mn,hn,async(n,r)=>{let i=n,a=r?.executionId;return e.isParallelSubagentsEnabled!==void 0&&!e.isParallelSubagentsEnabled()?Rt():Array.isArray(i.jobs)&&i.jobs.length>0?It({jobs:i.jobs,deps:e,manager:t,resolveAgentDefinition:vn,createSpawnRequest:bn,toolCallId:a}):xn({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 Cn=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=wt(e)??P(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 He({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 M({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 M({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 M({entryId:e,lines:qe(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`,wn(e))}recordCompletedTaskUsage(e){if(e.type!==`background_task_completed`)return;let t=e.task.result?.usage;!t||t.totalTokens<=0||this.appendHistoryEntry?.(Ie(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`,O(e.group.id))}};function wn(e){if(`task`in e)return D(e.task.id);if(`taskId`in e)return D(e.taskId)}function Tn(e){let t=P(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 F(e){let t=Tn(e);if(!t.subagentManager)throw Error(`Subagent manager is not available for this session.`);return t.subagentManager}function En(e,t){let n=t.customAgentRegistry?.(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Dn(e){return(P(e)?.agentDefinitions??[]).map(e=>({name:e.name,description:e.description}))}async function On(e,t,n,r){let i=Tn(e),a=En(t.agentType,i),o=e.getSessionId();return F(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:k({kind:r===`model`?`model_command`:`slash_command`,sessionId:o,commandName:`agent`,label:t.label})})}async function kn(e,t){return F(e).wait(t)}async function An(e,t,n){await F(e).send(t,n)}async function jn(e,t,n){await F(e).cancel(t,n)}async function Mn(e,t){await F(e).close(t)}function Nn(e){return F(e).list()}function Pn(e,t={}){let{sessionId:n,execCtrl:r,histTracker:i,bgTracker:a}=e,o=i.getHistory();return Qe({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 Fn(e,t,n,r,i){let a=Ze(e);if(!a)throw Error(`Unknown execution workspace entry: ${e}`);return a.kind===`main_thread`?gt({entryId:e,history:t(),cursor:i}):a.kind===`background_group`?n.readGroupDetail(e,a.sourceId,r):n.readTaskDetail(e,a.sourceId,i)}function In(e,t,n,r){return yt({manager:e.getManagerOrThrow(),groupOrchestrator:e.getOrchestratorOrThrow(t),sessionId:t,cwd:n,origin:{...r,sessionId:r.sessionId||t}})}var Ln=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 Pn({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(),Fn(e,()=>this.histTracker.getHistory(),this.bgTracker,this.getSessionOrThrow().getSessionId(),t)}createExecutionWorkspaceTaskSpawner(e){return In(this.bgTracker,this.getSessionOrThrow().getSessionId(),this.getCwd(),e)}listAgentDefinitions(){return Dn(this.getSessionOrThrow())}listAgentJobs(){return Nn(this.getSessionOrThrow())}async spawnAgentJob(e){return await this.ensureInitialized(),On(this.getSessionOrThrow(),e,this.getCwd(),this.skillRouter.getCommandInvocationSource())}async waitAgentJob(e){return await this.ensureInitialized(),kn(this.getSessionOrThrow(),e)}async sendAgentJob(e,t){await this.ensureInitialized(),await An(this.getSessionOrThrow(),e,t)}async cancelAgentJob(e,t){await this.ensureInitialized(),await jn(this.getSessionOrThrow(),e,t)}async closeAgentJob(e){await this.ensureInitialized(),await Mn(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 Rn(e){return(0,t.createHash)(`sha256`).update(e,`utf-8`).digest(`hex`)}function zn(e,t=new S){let n=t.readFileSync(e,`utf-8`);return{filePath:e,content:n,contentHash:Rn(n)}}async function Bn(e,t=new S){let n=[],r=[];for(let i of e){if(!t.existsSync(i.filePath)){r.push(i);continue}Rn(t.readFileSync(i.filePath,`utf-8`))===i.contentHash?r.push(i):n.push(i)}return{stale:n,fresh:r}}async function Vn(e,t=new S){let{stale:n}=await Bn(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:Rn(n)}}),refreshed:i}}async function Hn(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 Vn(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 Un(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 Wn(e,t,n){let r=e?.[t]??e?.[n];return typeof r==`string`?r:null}function Gn(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 Kn(e){if(e.toolName!==`Edit`)return{};let t=Wn(e.toolArgs,`file_path`,`filePath`),n=Wn(e.toolArgs,`old_string`,`oldString`),r=Wn(e.toolArgs,`new_string`,`newString`);return!t||n===null||r===null||n===r?{}:{diffFile:t,diffLines:Jn(n,r,Gn(e.toolResultData),t)}}function qn(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 Jn(e,t,n,r,i=new S){let a=qn(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 I(e){if(e.activeTools.length===0)return;let n=e.activeTools.map(e=>`${e.isRunning?`⟳`:e.result===`success`?`✓`:e.result===`error`?`✗`:`⊘`} ${e.toolName}${e.firstArg?`(${e.firstArg})`:``}`).join(`
66
- `);e.history.push({id:(0,t.randomUUID)(),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:n}})}function Yn(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 Xn(e,n){let r=Un(n.toolArgs),i={toolName:n.toolName,firstArg:r,isRunning:!0,...n.executionId?{executionId:n.executionId}:{}};return e.activeTools.push(i),e.history.push({id:(0,t.randomUUID)(),timestamp:new Date,category:`event`,type:`tool-start`,data:{toolName:n.toolName,firstArg:r,isRunning:!0}}),i}function Zn(e,n){let r=n.denied?`denied`:n.success===!1?`error`:`success`,i=e.activeTools.findIndex(e=>e.toolName===n.toolName&&e.isRunning);if(i===-1)return null;let a={...e.activeTools[i],...Kn(n),isRunning:!1,result:r,toolResultData:n.toolResultData};return e.activeTools[i]=a,e.activeTools=Yn(e.activeTools),e.history.push({id:(0,t.randomUUID)(),timestamp:new Date,category:`event`,type:`tool-end`,data:{toolName:a.toolName,firstArg:a.firstArg,isRunning:!1,result:r,toolResultData:n.toolResultData}}),a}const Qn=[{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 L(t){if(t instanceof e.AuthenticationError)return"Invalid API key. Run `/provider` to reconfigure, or check your settings file (~/.robota/settings.json).";if(t instanceof e.RateLimitError)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 e.NetworkError)return`Network connection failed. Check your internet connection and verify your provider URL in settings.`;if(t instanceof e.ProviderError&&t.originalError)return L(t.originalError);let n=t.message;for(let{pattern:e,message:t}of Qn)if(e.test(n))return t;return n}async function $n(t,n,r,i){let a=i.getHistory();a.push((0,e.messageToHistoryEntry)((0,e.createUserMessage)(n??t))),i.onWorkspaceUpdated();let o=i.getSession().getHistory().length;i.resetUsedMemoryReferences();try{let s=await Le(t,i.getCwd(),r,i.getContextReferences());s.promptFileReferenceEntry&&a.push(s.promptFileReferenceEntry),i.recordContextReferenceUsage(s.activeContextReferenceRecords),i.recordPromptContextReferences(s.promptFileReferenceRecords),await i.beginEditCheckpointTurn(n??t);let c=await i.getSession().run(s.modelInput,s.hookInput);i.flushStreaming(),I({activeTools:i.getActiveTools(),history:a}),i.clearStreaming();let l=Ne(c||`(empty response)`,i.getSession().getHistory(),a,o,i.getSession().getContextState(),s.promptFileReferenceRecords);a.push((0,e.messageToHistoryEntry)((0,e.createAssistantMessage)(l.response))),l.usage&&a.push(Fe(l.usage)),i.onComplete(l),i.onContextUpdate()}catch(t){if(i.flushStreaming(),je(t)){let t=Pe(i.getSession().getHistory(),a,o,i.getSession().getContextState());I({activeTools:i.getActiveTools(),history:a}),i.clearStreaming(),t.response&&a.push((0,e.messageToHistoryEntry)((0,e.createAssistantMessage)(t.response))),t.usage&&a.push(Fe(t.usage)),a.push((0,e.messageToHistoryEntry)((0,e.createSystemMessage)(`Interrupted by user.`))),i.onInterrupted(t)}else{I({activeTools:i.getActiveTools(),history:a});let n=i.getStreamingText();if(i.clearStreaming(),n.trim().length>0){let t=(0,e.createAssistantMessage)(n);t.state=`interrupted`,a.push((0,e.messageToHistoryEntry)(t))}let r=t instanceof Error?t:Error(String(t)),o=L(r);a.push((0,e.messageToHistoryEntry)((0,e.createSystemMessage)(`Error: ${o}`,{metadata:{kind:`error`}}))),i.onError(r)}}}var er=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(t){t.trigger===`auto`&&this.histTracker.append((0,e.messageToHistoryEntry)((0,e.createSystemMessage)(`Auto compacted context: ${Math.round(t.before.usedPercentage)}% -> ${Math.round(t.after.usedPercentage)}%`))),this.callbacks.emit(`compact`,t),this.callbacks.emit(`context_update`,t.after)}handleToolExecution(e){let t={activeTools:this.activeTools,history:this.histTracker.getHistory()};if(e.type===`start`){let n=Xn(t,e);this.activeTools=t.activeTools,this.callbacks.emit(`tool_start`,n)}else{let n=Zn(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 Hn(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 $n(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(t,n,r,i,a,o){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((0,e.messageToHistoryEntry)((0,e.createUserMessage)(r??`/${t.name}`))),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let e=await this.skillRouter.executeSkillWithActivation(t,n,a,i);return await this.applyForkSkillResult(e.result??`(empty response)`),e}catch(t){let n=t instanceof Error?t:Error(String(t));return this.histTracker.append((0,e.messageToHistoryEntry)((0,e.createSystemMessage)(`Error: ${L(n)}`))),this.callbacks.emit(`error`,n),{mode:`fork`,result:``}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(o)}}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(t){this.flushStreaming(),I({activeTools:this.activeTools,history:this.histTracker.getHistory()}),this.clearStreaming();let n={response:t,history:this.histTracker.getHistory(),toolSummaries:[],contextState:this.callbacks.getContextState()};this.histTracker.append((0,e.messageToHistoryEntry)((0,e.createAssistantMessage)(t))),this.callbacks.emit(`complete`,n),this.callbacks.emit(`context_update`,this.callbacks.getContextState())}};function tr(e,t,n){let r=P(n)?.customAgentRegistry?.(e)??N(e);if(!r)throw Error(`Unknown agent type: ${e}`);return t.allowedTools?{...r,tools:t.allowedTools}:r}async function nr(e,t,n){let r=P(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);return on({agentDefinition:tr(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 rr(e,t,n){let r=await ve([t],{cwd:n,reason:`manual`});if(v(r.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[y(r.diagnostics)]}};let i=r.references[0];if(!i)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let a=f(b([i])[0],`manual`,`active`),o=p(e,a);return{references:o.references,result:{reference:a,evicted:o.evicted,diagnostics:[]}}}function ir(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=f(e,n.loadType,n.status,r);i=p(i,t).references}return i}function ar(e,t){let r=new Date().toISOString();return e.map(e=>{let i=(0,n.relative)(t,e.filePath);return{id:`system:${i}`,sourcePath:e.filePath,relativePath:i,originalReference:i,loadType:`system`,status:`active`,byteLength:Buffer.byteLength(e.content,`utf-8`),loadedAt:r,lastUsedAt:r}})}function R(e){let t=(0,n.join)(e,`.robota`);return{settings:(0,n.join)(t,`settings.json`),settingsLocal:(0,n.join)(t,`settings.local.json`),logs:(0,n.join)(t,`logs`),sessions:(0,n.join)(t,`sessions`),memory:(0,n.join)(t,`memory`),checkpoints:(0,n.join)(t,`checkpoints`)}}function or(){let e=(0,n.join)((0,r.homedir)(),`.robota`);return{settings:(0,n.join)(e,`settings.json`),sessions:(0,n.join)(e,`sessions`),onboarded:(0,n.join)(e,`onboarded`)}}function sr(e){let t=e.fs??new S,r=e.manifests.filter(t=>t.sequence>e.target.sequence),i=e.manifests.filter(t=>t.sequence>=e.target.sequence);return{target:cr(e.target),capturedFiles:e.target.files.map(r=>{let i=r.snapshotFile?(0,n.join)(e.checkpointDir(e.sessionId,e.target.id),r.snapshotFile):void 0,a=i?ur(i,t):void 0;return{originalPath:r.originalPath,relativePath:(0,n.relative)(e.cwd,r.originalPath),existed:r.existed,restoreAction:r.existed?`restore-preimage`:`delete-created-file`,snapshotAvailable:r.existed?a!==void 0:!1,...a?{snapshotSizeBytes:a.size}:{}}}),restoreToCheckpoint:lr(r),rollbackThroughCheckpoint:lr(i)}}function cr(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function lr(e){return{checkpointIds:e.map(e=>e.id),fileCount:e.reduce((e,t)=>e+t.fileCount,0)}}function ur(e,t){try{return t.statSync(e)}catch{return}}const dr=`manifest.json`,fr=`files`;var z=class{fs;fsAsync;cwd;rootDir;now;activeTurn=null;constructor(e,t=new S,r=new ge){this.fs=t,this.fsAsync=r,this.cwd=(0,n.resolve)(e.cwd),this.rootDir=R(this.cwd).checkpoints,this.now=e.now??(()=>new Date)}async beginTurn(e){this.activeTurn&&await this.finalizeTurn();let t=this.nextSequence(e.sessionId),r=`turn-${String(t).padStart(4,`0`)}`,i=(0,n.join)(this.sessionDir(e.sessionId),r);await this.fsAsync.mkdir((0,n.join)(i,fr),{recursive:!0});let a={version:1,id:r,sessionId:e.sessionId,sequence:t,prompt:e.prompt,createdAt:this.now().toISOString(),fileCount:0,files:[]};return this.activeTurn={manifest:a,dir:i,capturedPaths:new Set},B(a)}async captureFile(e){if(!this.activeTurn)return;let t=(0,n.resolve)(this.cwd,e);if(this.activeTurn.capturedPaths.has(t)||mr(this.rootDir,t))return;let r=await this.createFileRecord(t,this.activeTurn);this.activeTurn.manifest.files.push(r),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),B(e.manifest)}list(e){return this.loadManifests(e).map(B)}inspect(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);return sr({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:B(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:B(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async createFileRecord(e,t){if(!await hr(this.fsAsync,this.fs,e))return{originalPath:e,existed:!1};let r=(0,n.join)(fr,`${String(t.manifest.files.length+1).padStart(6,`0`)}.content`);return await this.fsAsync.copyFile(e,(0,n.join)(t.dir,r)),{originalPath:e,existed:!0,snapshotFile:r}}async restoreFile(e,t,r){if(!r.existed){await this.fsAsync.rm(r.originalPath,{force:!0});return}if(!r.snapshotFile)throw Error(`Checkpoint file record is missing a snapshot: ${r.originalPath}`);await this.fsAsync.mkdir((0,n.dirname)(r.originalPath),{recursive:!0}),await this.fsAsync.copyFile((0,n.join)(this.checkpointDir(e,t),r.snapshotFile),r.originalPath)}loadManifests(e){let t=this.sessionDir(e);return gr(this.fs,t).map(e=>(0,n.join)(t,e,dr)).map(e=>_r(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 r=(0,n.join)(e,dr),i=`${r}.tmp`;await this.fsAsync.writeFile(i,JSON.stringify(t,null,2),`utf8`),await this.fsAsync.rename(i,r)}sessionDir(e){return(0,n.join)(this.rootDir,pr(e))}checkpointDir(e,t){return(0,n.join)(this.sessionDir(e),pr(t))}};function B(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function pr(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function mr(e,t){let r=(0,n.relative)(e,t);return r.length===0||!r.startsWith(`..`)&&!r.startsWith(`/`)}async function hr(e,t,n){try{return await e.access(n,t.constants.F_OK),!0}catch{return!1}}function gr(e,t){try{return e.readdirSync(t)}catch{return[]}}function _r(e,t){try{let n=e.readFileSync(t,`utf8`);return JSON.parse(n)}catch{return}}function vr(e){return e.source===`plugin`?`plugin`:`skill`}function yr(e){return e.context===`fork`?`fork`:`inject`}function br(e){return{type:`skill-activation`,skillName:e.skill.name,source:vr(e.skill),invocation:e.invocation,mode:yr(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function xr(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 Sr=new Set([`memory_candidate_saved`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`]);function Cr(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 wr=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=ir(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=ir(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(t){if(this.getExecuting())throw Error(`Cannot restore edit checkpoint while a prompt is running.`);let n=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),t);return this.history.push((0,e.messageToHistoryEntry)((0,e.createSystemMessage)(`Restored edit checkpoint: ${t}`))),this.persistSession(),n}async rollbackEditCheckpoint(t){if(this.getExecuting())throw Error(`Cannot rollback edit checkpoint while a prompt is running.`);let n=await this.getCheckpointStore().rollbackThroughCheckpoint(this.getSessionId(),t);return this.history.push((0,e.messageToHistoryEntry)((0,e.createSystemMessage)(`Rolled back edit checkpoint: ${t}`))),this.persistSession(),n}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(t){let n=t instanceof Error?t:Error(String(t));throw this.history.push((0,e.messageToHistoryEntry)((0,e.createSystemMessage)(`Checkpoint error: ${n.message}`))),n}}setEditCheckpointStore(e){this.editCheckpointStore=e}getUsedMemoryReferences(){return[...this.usedMemoryReferences]}recordMemoryEvent(e){this.memoryEvents.push(e),Sr.has(e.type)&&this.history.push({id:(0,t.randomUUID)(),timestamp:new Date(e.at),category:`event`,type:`memory-event`,data:{...e,message:Cr(e)}}),this.emitMemoryEvent(e),this.persistSession()}recordSystemContextFiles(e){this.systemContextReferences=ar(e,this.cwd)}listContextReferences(){return[...this.systemContextReferences,...this.contextReferences]}listInjectionContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await rr(this.contextReferences,e,this.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=m(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=h(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,n){this.skillActivationEvents.push(e),n&&this.history.push({id:(0,t.randomUUID)(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:xr(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){return this.editCheckpointStore||=new z({cwd:this.cwd}),this.editCheckpointStore}};function Tr(e){if((0,u.existsSync)(e))try{return JSON.parse((0,u.readFileSync)(e,`utf-8`))}catch{return}}function Er(e){if((0,u.existsSync)((0,d.join)(e,`pnpm-workspace.yaml`))||(0,u.existsSync)((0,d.join)(e,`pnpm-lock.yaml`)))return`pnpm`;if((0,u.existsSync)((0,d.join)(e,`yarn.lock`)))return`yarn`;if((0,u.existsSync)((0,d.join)(e,`bun.lockb`)))return`bun`;if((0,u.existsSync)((0,d.join)(e,`package-lock.json`)))return`npm`}async function Dr(e){let t=(0,d.join)(e,`package.json`),n=(0,d.join)(e,`tsconfig.json`),r=(0,d.join)(e,`pyproject.toml`),i=(0,d.join)(e,`Cargo.toml`),a=(0,d.join)(e,`go.mod`);if((0,u.existsSync)(t)){let r=Tr(t),i=(0,u.existsSync)(n)?`typescript`:`javascript`,a=Er(e);return{type:`node`,name:r?.name,packageManager:a,language:i}}return(0,u.existsSync)(r)||(0,u.existsSync)((0,d.join)(e,`setup.py`))?{type:`python`,language:`python`}:(0,u.existsSync)(i)?{type:`rust`,language:`rust`}:(0,u.existsSync)(a)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}function Or(e,t){e.injectRawMessage(t)}function kr(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}=Ar(a,o),g=r.name,_=null;if(r.messages)if(n)for(let e of r.messages)Or(n,e);else _=r.messages;return{history:i,sessionName:g,pendingRestoreMessages:_,backgroundTasks:m,backgroundTaskEvents:h,backgroundJobGroups:s,backgroundJobGroupEvents:c,skillActivationEvents:l,memoryEvents:u,usedMemoryReferences:d,contextReferences:f,sandboxSnapshotId:p,goal:r.goal}}function Ar(e,t){let n=new Date().toISOString(),r=[];return{backgroundTasks:e.map(e=>{if(jr(e.status)||Mr(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 jr(e){return e===`completed`||e===`failed`||e===`cancelled`}function Mr(e){return e.kind===`scheduled`&&e.status===`sleeping`&&e.schedule!==void 0}function Nr(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 Pr(t,n,r,i){let a=Nr(t);!a||!(`task`in t)||(0,e.runHooks)(r,a,{session_id:t.task.parentSessionId,cwd:n,hook_event_name:a,agent_id:t.task.id,agent_type:t.task.agentType??t.task.label,...t.task.transcriptPath?{agent_transcript_path:t.task.transcriptPath,transcript_path:t.task.transcriptPath}:{},...t.task.error?.message||t.task.timeoutReason?{reason:t.task.error?.message??t.task.timeoutReason}:{},...a===`SubagentStop`?{stop_hook_active:!1,...t.task.result?.output?{last_assistant_message:t.task.result.output}:{}}:{},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:t.task.parentSessionId,ROBOTA_AGENT_ID:t.task.id,ROBOTA_AGENT_TYPE:t.task.agentType??t.task.label}},i).catch(()=>void 0)}const Fr=[`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 Ir(e={}){return[(0,s.createShellTool)(e),(0,s.createBashTool)(e),(0,s.createReadTool)(e),(0,s.createWriteTool)(e),(0,s.createEditTool)(e),s.globTool,s.grepTool,s.webFetchTool,s.webSearchTool,(0,s.createAskUserQuestionTool)()]}const Lr=new Set([`tools`,`disallowedTools`]),Rr=new Set([`maxTurns`]);function zr(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Br(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();Lr.has(i)?r[i]=zr(a):Rr.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 V(e,t){if(!t.existsSync(e))return[];let r=[],i;try{i=t.readdirSync(e,{withFileTypes:!0})}catch{return[]}for(let a of i){if(!a.isFile()||!a.name.endsWith(`.md`))continue;let i=(0,n.join)(e,a.name),{frontmatter:o,body:s}=Br(t.readFileSync(i,`utf-8`)),c=(0,n.basename)(a.name,`.md`),l={name:o?.name??c,description:o?.description??``,systemPrompt:s};o?.model!==void 0&&(l.model=o.model),o?.maxTurns!==void 0&&(l.maxTurns=o.maxTurns),o?.tools!==void 0&&(l.tools=o.tools),o?.disallowedTools!==void 0&&(l.disallowedTools=o.disallowedTools),r.push(l)}return r}var Vr=class{cwd;home;fs;constructor(e,t,n=new S){this.cwd=e,this.home=t??(0,r.homedir)(),this.fs=n}loadAll(){let e=[V((0,n.join)(this.cwd,`.robota`,`agents`),this.fs),V((0,n.join)(this.cwd,`.agents`,`agents`),this.fs),V((0,n.join)(this.cwd,`.claude`,`agents`),this.fs),V((0,n.join)(this.home,`.robota`,`agents`),this.fs),V((0,n.join)(this.home,`.claude`,`agents`),this.fs)],t=new Set,r=[];for(let n of e)for(let e of n)t.has(e.name)||(t.add(e.name),r.push(e));let i=[...r];for(let e of Vt)t.has(e.name)||i.push(e);return i}getAgent(e){return this.loadAll().find(t=>t.name===e)}};function Hr(e){let t=e.content.trim();return e.title?[`## ${e.title}`,t].join(`
69
- `):t}function Ur(e){return[...e].filter(e=>e.content.trim().length>0).sort((e,t)=>e.priority-t.priority||e.id.localeCompare(t.id)).map(e=>Hr(e)).join(`
70
-
71
- `)}function H(e,t,n,r,i){return{id:e,title:t,priority:n,content:r,source:i}}function Wr(e){return H(`preset-persona`,void 0,5,e,`persona`)}function Gr(){return H(`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 Kr(e){if(e)return H(`runtime-cwd`,`Working Directory`,30,`\`${e}\``,`runtime`)}function qr(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}`),H(`runtime-project`,`Current Project`,40,t.join(`
72
- `),`runtime`)}function Jr(e){return H(`permission-mode`,`Permission Mode`,50,`- **Permission mode:** ${e}`,`permissions`)}function Yr(e){if(!(e===void 0||e.trim().length===0))return H(`runtime-response-language`,`Response Language`,45,e,`runtime`)}function Xr(e){if(e.trim().length!==0)return H(`project-agents-md`,`Agent Instructions`,10,e,`project-instructions`)}function Zr(e){if(e.trim().length!==0)return H(`project-claude-md`,`Project Notes`,20,e,`project-instructions`)}function Qr(e){if(!(e===void 0||e.trim().length===0))return H(`project-memory`,`Project Memory`,25,e,`project-instructions`)}function $r(e){if(!(e===void 0||e.trim().length===0))return H(`active-task-context`,`Active Task Context`,27,e,`project-instructions`)}function ei(e){if(e.length!==0)return H(`tool-descriptions`,`Available Tools`,60,e.map(e=>`- ${e}`).join(`
73
- `),`tool`)}function ti(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}`}function U(e,t,n,r,i){let a=i.filter(t=>t.modelInvocable&&t.kind===e).map(ti);if(a.length!==0)return H(`capability-${e}`,t,n,a.join(`
74
- `),r)}function ni(e){let t=[],n=U(`builtin-command`,`Built-in Commands`,70,`command`,e),r=U(`skill`,`Skills`,80,`skill`,e),i=U(`agent`,`Agents`,90,`agent`,e),a=U(`tool`,`Tools`,100,`tool`,e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),a&&t.push(a),t}function W(e,t){t!==void 0&&e.push(t)}function ri(e){return e.map(e=>({name:e.name,kind:`skill`,description:e.description,userInvocable:!0,modelInvocable:e.disableModelInvocation!==!0}))}function ii(e){return e.map(e=>({name:e.name,kind:`agent`,description:e.description,userInvocable:!1,modelInvocable:!0,safety:`background-agent`}))}function ai(e){return[...e.commandDescriptors??[],...e.skills?ri(e.skills):[],...e.agents?ii(e.agents):[]]}function oi(e){let t=[];return W(t,e.persona!==void 0&&e.persona.trim().length>0?Wr(e.persona):void 0),W(t,e.selfVerification===!0?Gr():void 0),W(t,Xr(e.agentsMd)),W(t,Zr(e.claudeMd)),W(t,Qr(e.memoryMd)),W(t,$r(e.taskContext)),W(t,Kr(e.cwd)),t.push(qr(e.projectInfo)),W(t,Yr(e.language)),t.push(Jr(e.permissionMode)),W(t,ei(e.toolDescriptions)),t.push(...ni(ai(e))),Ur(t)}const si=c.z.object({command:c.z.string().describe(`The shell command to start in the background`),timeout:c.z.number().optional().describe(`Optional timeout in milliseconds. Default is 120000.`),workingDirectory:c.z.string().optional().describe(`Working directory for the command. Defaults to the current project directory.`),stdin:c.z.string().optional().describe(`Optional stdin to write after the process starts.`),outputLimitBytes:c.z.number().optional().describe(`Maximum captured output bytes kept in the task result.`)});function ci(e,t,n){return JSON.stringify({success:!0,background:!0,output:``,taskId:e,status:t,command:n})}function li(e){return JSON.stringify({success:!1,background:!0,output:``,error:`Background process error: ${e}`})}async function ui(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 ci(n.id,n.status,e.command)}catch(e){return li(e instanceof Error?e.message:String(e))}}function di(e){return(0,s.createZodFunctionTool)(`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.`,si,async t=>ui(t,e))}function fi(e,t,n,r,i,a){let s,c=[],l;if(e.enableAgentRuntime||e.enableParallelSubagents){let u=new Vr(n);c=u.loadAll(),s={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=>u.getAgent(e),agentDefinitions:c};let d=new o.SubagentManager({runner:(e.subagentRunnerFactory??pn)(s),backgroundTaskRunners:e.backgroundTaskRunners});s.subagentManager=d,l=d.getBackgroundTaskManager(),s.backgroundTaskManager=l}else l=new o.BackgroundTaskManager({runners:e.backgroundTaskRunners??[]});let u=e.sessionLogger;return u&&l.subscribe(e=>_i(u,t,e)),l.subscribe(t=>Pr(t,n,e.config.hooks,a.length>0?a:void 0)),{agentToolDeps:s,agentDefinitions:c,backgroundTaskManager:l}}function pi(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:k({kind:`tool_call`,sessionId:n,label:`BackgroundProcess`})};return i.push(di(a)),{backgroundProcessToolDeps:a}}function mi(t,n,r,i,a){return{agentsMd:t.context.agentsMd,claudeMd:t.context.claudeMd,memoryMd:t.context.memoryMd,taskContext:t.context.taskContext,toolDescriptions:r,permissionMode:t.permissionMode??e.TRUST_TO_MODE[t.config.defaultTrustLevel]??`default`,projectInfo:t.projectInfo??{type:`unknown`,language:`unknown`},cwd:n,language:t.config.language,skills:i.map(e=>({name:e.name,description:e.description,disableModelInvocation:e.disableModelInvocation})),...a.length>0?{agents:a.map(e=>({name:e.name,description:e.description}))}:{},commandDescriptors:t.commandDescriptors??[]}}function hi(e,t,n,r,i,a,o){let s=e.systemPromptBuilder??oi,c=[...Fr,...r?r.commandTools.map(Xt):[]],l=e.toolDescriptions??(i?[...c,`BackgroundProcess — start long-running shell commands as managed background tasks`]:c),u=e.persona,d=e.selfVerification,f=mi(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 gi(e,t,n,r){t&&(t.parentSessionId=e.getSessionId()),t&&(t.isParallelSubagentsEnabled=()=>e.getParallelSubagentsEnabled()),n&&(n.parentSessionId=e.getSessionId()),Ct(e,r),t&&_n(e,t)}function _i(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 vi=new Set([`Write`,`Edit`]);function yi(e,t){return e.map(e=>vi.has(e.getName())?new bi(e,t):e)}var bi=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=xi(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 xi(e){if(!e||typeof e!=`object`)return;let t=e.filePath;return typeof t==`string`&&t.length>0?t:void 0}const Si=new Set([`disable-model-invocation`,`user-invocable`]),Ci=new Set([`allowed-tools`]);function wi(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Ti(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Ei(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=wi(a);Si.has(a)?n[s]=o===`true`:Ci.has(a)?n[s]=Ti(o):n[s]=o}return Object.keys(n).length>0?n:null}function Di(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 Oi(e,t){if(!t.existsSync(e))return[];let r=[],i=t.readdirSync(e,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let i=(0,n.join)(e,a.name,`SKILL.md`);if(!t.existsSync(i))continue;let o=t.readFileSync(i,`utf-8`),s=Ei(o);r.push(Di(s,o,a.name))}return r}function ki(e,t){if(!t.existsSync(e))return[];let r=[],i=t.readdirSync(e,{withFileTypes:!0});for(let a of i){if(!a.isFile()||!a.name.endsWith(`.md`))continue;let i=(0,n.join)(e,a.name),o=t.readFileSync(i,`utf-8`),s=Ei(o),c=(0,n.basename)(a.name,`.md`);r.push(Di(s,o,c))}return r}var Ai=class{name=`skill`;cwd;home;fs;cachedCommands=null;constructor(e,t,n=new S){this.cwd=e,this.home=t??(0,r.homedir)(),this.fs=n}getCommands(){if(this.cachedCommands)return this.cachedCommands;let e=[Oi((0,n.join)(this.cwd,`.claude`,`skills`),this.fs),ki((0,n.join)(this.cwd,`.claude`,`commands`),this.fs),Oi((0,n.join)(this.home,`.robota`,`skills`),this.fs),Oi((0,n.join)(this.cwd,`.agents`,`skills`),this.fs)],t=new Set,r=[];for(let n of e)for(let e of n)t.has(e.name)||(t.add(e.name),r.push(e));return this.cachedCommands=r,this.cachedCommands}getModelInvocableSkills(){return this.getCommands().filter(e=>e.disableModelInvocation!==!0)}getUserInvocableSkills(){return this.getCommands().filter(e=>e.userInvocable!==!1)}},ji=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 Mi(){return(0,n.join)(process.env.HOME??process.env.USERPROFILE??`/`,`.robota`,`settings.json`)}function Ni(e,t){return t===void 0||t===`user`?Mi():(0,n.join)(e,`.robota`,`settings.local.json`)}function G(e){if(!(0,i.existsSync)(e))return{};let t=(0,i.readFileSync)(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new ji(e,t instanceof Error?t.message:String(t))}}function K(e,t){(0,i.mkdirSync)((0,n.dirname)(e),{recursive:!0}),(0,i.writeFileSync)(e,JSON.stringify(t,null,2)+`
76
- `,`utf8`)}function Pi(e,t){let n=G(e),r=n.currentProvider,i=n.providers;if(typeof r==`string`&&Fi(i)){let e=i;e[r]={...Fi(e[r])?e[r]:{},model:t},n.providers=e}else n.provider={...Fi(n.provider)?n.provider:{},model:t};K(e,n)}function Fi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Ii(e){return(0,i.existsSync)(e)?((0,i.unlinkSync)(e),!0):!1}const q=`report_goal_status`,Li=c.z.object({status:c.z.enum([`continue`,`satisfied`]).describe(`"satisfied" when the assigned goal is fully achieved; otherwise "continue".`),reason:c.z.string().describe(`A short justification for the status — what was achieved or what remains.`)});function Ri(){return(0,s.createZodFunctionTool)(q,`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.`,Li,async e=>({acknowledged:!0,status:e.status===`satisfied`?`satisfied`:`continue`}))}const zi=`When you have made as much progress as you can this turn, call \`${q}\`: 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 Bi(e){return[`You have been assigned an autonomous goal to pursue across multiple turns:`,``,`GOAL: ${e}`,``,`Work toward this goal now. ${zi}`].join(`
77
- `)}function Vi(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. ${zi}`].join(`
78
- `)}const Hi={now:()=>new Date().toISOString(),createId:()=>`goal_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`};function Ui(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 Wi(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!(!n||n.name!==`report_goal_status`))return Ui(n.args)}return null}function Gi(e){return e.filter(e=>e.name!==q).length}var Ki=class{deps;goal=null;consecutiveIdleTurns=0;noProgressLimit=2;constructor(e=Hi){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:Bi(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=Wi(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=Gi(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:Vi(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 qi(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var Ji=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=qi(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 Yi(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var Xi=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=Yi(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 Zi=new Set([`Write`,`Edit`]),Qi=new Set([`Shell`,`Bash`,`BackgroundProcess`]),$i=new Set([`Read`,`Glob`,`Grep`,`WebFetch`,`WebSearch`]);function ea(e){let t=e.toolName;return $i.has(t)?{toolName:t,reversible:!0,sideEffect:`none`,rollbackLayer:`none`,status:`read-only`,message:`${t} does not mutate the local workspace.`}:Zi.has(t)?e.context.isolation===`worktree`||e.context.isolation===`provider-sandbox`?ra(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.`}:Qi.has(t)?ra(t,`shell-process`,e.context):t===`Agent`?ia(e.toolArgs,e.context):{toolName:t,reversible:!1,sideEffect:`unknown`,rollbackLayer:`none`,status:`unknown`,message:`${t} has no reversible execution contract.`}}function ta(e,t){let n={checkpointAvailable:t.checkpointAvailable,isolation:t.isolation??`none`},r=t.enforceUntrackedSideEffects??!0;return e.map(e=>new na(e,{safetyContext:n,enforceUntrackedSideEffects:r}))}var na=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=ea({toolName:this.getName(),toolArgs:ca(e),context:this.options.safetyContext});return!n.reversible&&this.options.enforceUntrackedSideEffects?la(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 ra(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 ia(e,t){return t.isolation===`worktree`||t.isolation===`provider-sandbox`?ra(`Agent`,`subagent`,t):aa(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 aa(e){if(!e)return!1;let t=e.jobs;return Array.isArray(t)?t.length>0&&t.every(e=>sa(e)?oa(e)===`worktree`:!1):oa(e)===`worktree`}function oa(e){let t=e.isolation;return typeof t==`string`?t:void 0}function sa(e){return e!==void 0&&typeof e==`object`&&!Array.isArray(e)}function ca(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e}function la(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 ua(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function da(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function fa(e,t){return e.some(e=>da(e.name)===t)}function pa(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,r=e.cwd??process.cwd(),i=e.sessionId??ma(),a=new Ai(r),o=ua(e.commandDescriptors),s=o.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,c=s?Yt(o):void 0,u=fa(o,`skills`)?a.getModelInvocableSkills():[],d=Ir({sandboxClient:e.sandboxClient,cwd:r}),f=e.editCheckpointRecorder!==void 0&&e.sandboxClient===void 0,p=[...f&&e.editCheckpointRecorder?yi(d,e.editCheckpointRecorder):d,...e.additionalTools??[],...e.includeGoalTool?[Ri()]:[]],m=e.reversibleExecution?{...e.reversibleExecution,isolation:e.reversibleExecution.isolation??(e.sandboxClient?`provider-sandbox`:void 0)}:void 0,h=m?ta(p,{...m,checkpointAvailable:f}):p;s&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&h.push(...Qt({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:o}));let g=[];e.providerFactory&&g.push(new Xi({providerFactory:e.providerFactory,defaultModel:e.config.provider.model})),e.sessionFactory&&g.push(new Ji({sessionFactory:e.sessionFactory})),e.additionalHookExecutors&&g.push(...e.additionalHookExecutors);let{agentToolDeps:_,agentDefinitions:ee,backgroundTaskManager:te}=fi(e,i,r,t,h,g),{backgroundProcessToolDeps:ne}=pi(e,te,i,r,h),{finalSystemMessage:re,rebuildSystemMessage:ie}=hi(e,r,o,c,ne,u,ee),ae=[`Read(.agents/**)`,`Read(.claude/**)`,`Read(.robota/**)`,`Glob(.agents/**)`,`Glob(.claude/**)`,`Glob(.robota/**)`],oe=c?c.commandTools.filter(e=>!e.requiresPermission).map(e=>e.toolName):[],v=(e.allowedTools??[]).map(e=>`${e}(*)`),y=(e.deniedTools??[]).map(e=>`${e}(*)`),b={allow:[...ae,...oe,...e.config.permissions.allow??[],...v],deny:[...e.config.permissions.deny??[],...y]},x=(0,n.join)(r,`.robota`,`settings.local.json`);function se(e){let t=`${e}(*)`,n=G(x),r=Array.isArray(n.permissions)?[]:n.permissions?.allow??[];r.includes(t)||K(x,{...n,permissions:{...n.permissions??{},allow:[...r,t]}})}let ce=new l.Session({tools:h,provider:t,systemMessage:re,terminal:e.terminal,permissions:b,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:i,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:g.length>0?g: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 gi(ce,_,ne,te),{session:ce,rebuildSystemMessage:ie}}function ma(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function ha(e,t,r,i=new S){let a=(0,n.join)(r,e,`subagents`);return i.mkdirSync(a,{recursive:!0}),new l.FileSessionLogger(a)}function ga(e,t){return(0,n.join)(t,e,`subagents`)}const J=c.z.lazy(()=>c.z.union([c.z.string(),c.z.number(),c.z.boolean(),c.z.null(),c.z.undefined(),c.z.date(),c.z.array(J),c.z.record(J)])),_a=c.z.object({name:c.z.string().optional(),model:c.z.string().optional(),apiKey:c.z.string().optional(),baseURL:c.z.string().optional(),timeout:c.z.number().optional(),options:c.z.record(J).optional()}),va=c.z.object({type:c.z.string().optional(),model:c.z.string().optional(),apiKey:c.z.string().optional(),baseURL:c.z.string().optional(),timeout:c.z.number().optional(),options:c.z.record(J).optional()}),ya=c.z.object({allow:c.z.array(c.z.string()).optional(),deny:c.z.array(c.z.string()).optional()}),ba=c.z.record(c.z.string()).optional(),xa=c.z.object({type:c.z.literal(`command`),command:c.z.string(),timeout:c.z.number().optional()}),Sa=c.z.object({type:c.z.literal(`http`),url:c.z.string(),headers:c.z.record(c.z.string()).optional(),timeout:c.z.number().optional()}),Ca=c.z.object({type:c.z.literal(`prompt`),prompt:c.z.string(),model:c.z.string().optional()}),wa=c.z.object({type:c.z.literal(`agent`),agent:c.z.string(),maxTurns:c.z.number().optional(),timeout:c.z.number().optional()}),Ta=c.z.discriminatedUnion(`type`,[xa,Sa,Ca,wa]),Y=c.z.object({matcher:c.z.string(),hooks:c.z.array(Ta)}),Ea=c.z.object({PreToolUse:c.z.array(Y).optional(),PostToolUse:c.z.array(Y).optional(),SessionStart:c.z.array(Y).optional(),SessionEnd:c.z.array(Y).optional(),Stop:c.z.array(Y).optional(),StopFailure:c.z.array(Y).optional(),PreCompact:c.z.array(Y).optional(),PostCompact:c.z.array(Y).optional(),UserPromptSubmit:c.z.array(Y).optional(),SubagentStart:c.z.array(Y).optional(),SubagentStop:c.z.array(Y).optional(),WorktreeCreate:c.z.array(Y).optional(),WorktreeRemove:c.z.array(Y).optional()}).optional(),Da=c.z.record(c.z.boolean()).optional(),Oa=c.z.object({source:c.z.object({type:c.z.enum([`github`,`git`,`local`,`url`]),repo:c.z.string().optional(),url:c.z.string().optional(),path:c.z.string().optional(),ref:c.z.string().optional()})}),ka=c.z.record(Oa).optional().catch(void 0),Aa=c.z.union([c.z.number().gt(0).lte(1),c.z.literal(!1)]).optional(),ja=c.z.object({enabled:c.z.boolean().optional(),options:c.z.record(J).optional()}),Ma=c.z.object({defaultTrustLevel:c.z.enum([`safe`,`moderate`,`full`]).optional(),language:c.z.string().optional(),preset:c.z.string().optional(),currentProvider:c.z.string().optional(),providers:c.z.record(va).optional(),provider:_a.optional(),permissions:ya.optional(),env:ba,hooks:Ea,enabledPlugins:Da,extraKnownMarketplaces:ka,autoCompactThreshold:Aa,transports:c.z.record(ja).optional()});function Na(){return process.env.HOME??process.env.USERPROFILE??`/`}const X={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[]},env:{}};function Pa(e){if(!(0,u.existsSync)(e))return;let t=(0,u.readFileSync)(e,`utf-8`).trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function Fa(e){if(e.startsWith(`$ENV:`)){let t=e.slice(5);return process.env[t]??e}return e}function Ia(e){let t=e.provider?.apiKey===void 0?e.provider:La(e.provider);if(e.providers!==void 0){let n=Object.fromEntries(Object.entries(e.providers).map(([e,t])=>[e,La(t)]));return{...e,provider:t,providers:n}}return{...e,provider:t}}function La(e){return{...e,...e.apiKey!==void 0&&{apiKey:Fa(e.apiKey)}}}function Ra(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?za(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 za(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function Ba(e){if(e.currentProvider!==void 0)return Va(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...X.provider}}function Va(e){let t=e.currentProvider;if(t===void 0)throw Error(`currentProvider is required`);let n=e.providers?.[t];if(n===void 0)throw Error(`currentProvider "${t}" was not found in providers`);if(n.type===void 0)throw Error(`Provider profile "${t}" is missing type`);return{name:n.type,model:n.model??X.provider.model,apiKey:n.apiKey??X.provider.apiKey,...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function Ha(e){return{defaultTrustLevel:e.defaultTrustLevel??X.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:Ba(e),permissions:{allow:e.permissions?.allow??X.permissions.allow,deny:e.permissions?.deny??X.permissions.deny},env:e.env??X.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold}}function Ua(e){let t=Na();return[(0,d.join)(t,`.robota`,`settings.json`),(0,d.join)(t,`.claude`,`settings.json`),(0,d.join)(e,`.robota`,`settings.json`),(0,d.join)(e,`.robota`,`settings.local.json`),(0,d.join)(e,`.claude`,`settings.json`),(0,d.join)(e,`.claude`,`settings.local.json`)]}async function Wa(e){let t=Ua(e),n=[];for(let e of t){let t=Pa(e);t!==void 0&&n.push({raw:t,path:e})}return Ha(Ra(n.map(({raw:e,path:t})=>{let n=Ma.safeParse(e);if(!n.success)throw Error(`Invalid settings in ${t}: ${n.error.message}`);return Ia(n.data)})))}const Ga=(0,n.join)(`.agents`,`tasks`),Ka={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function qa(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function Ja(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||(0,n.basename)(t,`.md`)}function Ya(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function Xa(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 Za(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(.+)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function Qa(e,t){return t&&e.branch===t?0:Ka[e.status]}function $a(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 eo(e){return e.toISOString().slice(0,10)}function to(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 no(e,t,n){let r=[`### ${eo(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 ro(e,t){let r=(0,n.resolve)(e),i=!1;for(;!i;){let e=(0,n.join)(r,`.git`);if(t.existsSync(e)){if(t.statSync(e).isDirectory())return e;let i=t.readFileSync(e,`utf8`).trim().match(/^gitdir:\s*(.+)$/)?.[1];if(i)return(0,n.isAbsolute)(i)?i:(0,n.resolve)(r,i)}let a=(0,n.dirname)(r);i=a===r,r=a}}function io(e,t=new S){let r=ro(e,t);if(!r)return;let i=(0,n.join)(r,`HEAD`);if(t.existsSync(i))return(t.readFileSync(i,`utf8`).trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1])?.trim()}function ao(e,t=new S){let r=(0,n.join)(e,Ga);return t.existsSync(r)?t.readdirSync(r,{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=>(0,n.join)(r,e)):[]}function oo(e,t,r=new S){let i=r.readFileSync(e,`utf8`);return{path:e,relativePath:(0,n.relative)(t,e),title:Ja(i,e),status:qa(Ya(i,`Status`)),branch:Ya(i,`Branch`),scope:Ya(i,`Scope`),objective:Xa(i,`Objective`),openItems:Za(i)}}function so(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>Qa(e,t.currentBranch)-Qa(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function co(e){return e.map($a).join(`
86
-
87
- `)}function lo(e,t={},n=new S){let r=t.currentBranch??io(e,n);return co(so(ao(e,n).map(t=>oo(t,e,n)),{...t,currentBranch:r}))}function uo(e,t,n={},r=new S){let i=to(r.readFileSync(e,`utf8`),t),a=n.progressMessage?no(i,n.now??new Date,n.progressMessage):i;r.writeFileSync(e,a,`utf8`)}const fo=25600,po=[`user`,`feedback`,`project`,`reference`];function mo(e){return po.includes(e)}function ho(e){return(0,d.join)(e,`.robota`,`memory`)}function go(e,t){let n=Buffer.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function _o(e,t){let n=e.split(/\r?\n/);return{content:n.slice(0,t).join(`
88
- `).trimEnd(),truncated:n.length>t}}function vo(e){return e.trim().toLowerCase().replace(/[^a-z0-9가-힣_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`general`}function yo(e,t,n){let r=e.toISOString().slice(0,10),i=t.text.trim().replace(/\s+/g,` `);return`[${r}] (${t.type}/${n}) ${i}`}function bo(e){return e.trim().replace(/\s+/g,` `)}var xo=class{cwd;now;constructor(e,t=()=>new Date){this.cwd=e,this.now=t}getIndexPath(){return(0,d.join)(ho(this.cwd),`MEMORY.md`)}getTopicsPath(){return(0,d.join)(ho(this.cwd),`topics`)}loadStartupMemory(){let e=this.getIndexPath();if(!(0,u.existsSync)(e))return{content:``,path:e,lineCount:0,truncated:!1};let t=(0,u.readFileSync)(e,`utf8`),n=go(t,fo),r=Buffer.byteLength(t,`utf8`)>fo,i=_o(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=(0,u.existsSync)(e)?(0,u.readdirSync)(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(t=>({name:(0,d.basename)(t.name,`.md`),path:(0,d.join)(e,t.name)})).sort((e,t)=>e.name.localeCompare(t.name)):[];return{indexPath:this.getIndexPath(),topicsPath:e,topics:t}}readTopic(e){let t=vo(e),n=(0,d.join)(this.getTopicsPath(),`${t}.md`);return(0,u.existsSync)(n)?(0,u.readFileSync)(n,`utf8`).trimEnd():``}append(e){let t=vo(e.topic),n=ho(this.cwd),r=this.getTopicsPath();(0,u.mkdirSync)(r,{recursive:!0});let i=this.getIndexPath(),a=(0,d.join)(r,`${t}.md`),o=yo(this.now(),e,t),s=(0,u.existsSync)(a)?``:`# ${t}\n\n`,c=bo(e.text);return(0,u.existsSync)(a)&&(0,u.readFileSync)(a,`utf8`).includes(`) ${c}`)?{indexPath:i,topicPath:a,topic:t,deduplicated:!0}:((0,u.existsSync)(i)||((0,u.mkdirSync)(n,{recursive:!0}),(0,u.writeFileSync)(i,`# Project Memory
89
-
90
- `,`utf8`)),(0,u.appendFileSync)(i,`- ${o}\n`,`utf8`),(0,u.appendFileSync)(a,`${s}- ${o}\n`,`utf8`),{indexPath:i,topicPath:a,topic:t,deduplicated:!1})}};function So(e,t){let n=[],r=(0,d.resolve)(e),i=!1;for(;!i;){let e=(0,d.join)(r,t);(0,u.existsSync)(e)&&n.push(e);let a=(0,d.dirname)(r);i=a===r,i||(r=a)}return n.reverse()}function Co(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 wo(e){let t=So(e,`AGENTS.md`),n=So(e,`CLAUDE.md`),r=t.map(e=>zn(e)),i=n.map(e=>zn(e)),a=r.map(e=>e.content).join(`
93
-
94
- `),o=i.map(e=>e.content).join(`
95
-
96
- `),s=Co(o),c=new xo(e).loadStartupMemory().content||void 0,l=lo(e);return{agentsMd:a,claudeMd:o,memoryMd:c,taskContext:l.trim().length>0?l:void 0,compactInstructions:s,agentsFileEntries:r,claudeFileEntries:i}}function To(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 Eo(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 Do(e,t=new S){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}var Oo=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new S){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){return this.discoverAndLoad()}async loadAll(){return this.discoverAndLoad()}discoverAndLoad(){let e=(0,n.join)(this.pluginsDir,`cache`);if(!this.fs.existsSync(e))return[];let t=[],r=Do(e,this.fs);for(let i of r){let r=(0,n.join)(e,i),a=Do(r,this.fs);for(let e of a){let a=(0,n.join)(r,e),o=Do(a,this.fs);if(o.length===0)continue;let s=o[o.length-1],c=(0,n.join)(a,s),l=(0,n.join)(c,`.claude-plugin`,`plugin.json`);if(!this.fs.existsSync(l))continue;let u=this.readManifest(l);if(!u)continue;let d=`${u.name}@${i}`;if(this.isDisabled(d,u.name))continue;let f=this.loadPlugin(c,u);t.push(f)}}return t}readManifest(e){let t=this.fs.readFileSync(e,`utf-8`);return Eo(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 r=(0,n.join)(e,`skills`);if(!this.fs.existsSync(r))return[];let i=this.fs.readdirSync(r,{withFileTypes:!0}),a=[];for(let e of i){if(!e.isDirectory())continue;let t=(0,n.join)(r,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let{metadata:i,content:o}=To(this.fs.readFileSync(t,`utf-8`)),s=typeof i.description==`string`?i.description:``,c={name:e.name,description:s,skillContent:o,...i};a.push(c)}return a}loadCommands(e,t){let r=(0,n.join)(e,`commands`);if(!this.fs.existsSync(r))return[];let i=this.fs.readdirSync(r,{withFileTypes:!0}),a=[];for(let e of i){if(!e.isFile()||!e.name.endsWith(`.md`))continue;let{metadata:i,content:o}=To(this.fs.readFileSync((0,n.join)(r,e.name),`utf-8`)),s=typeof i.name==`string`?i.name:e.name.replace(/\.md$/,``),c=typeof i.description==`string`?i.description:``;a.push({...i,name:`${t}:${s}`,description:c,skillContent:o})}return a}loadHooks(e){let t=(0,n.join)(e,`hooks`,`hooks.json`);if(!this.fs.existsSync(t))return{};let r=this.fs.readFileSync(t,`utf-8`),i=JSON.parse(r);return typeof i==`object`&&i?i:{}}loadMcpConfig(e){let t=(0,n.join)(e,`.mcp.json`);if(!this.fs.existsSync(t))return;let r=this.fs.readFileSync(t,`utf-8`);return JSON.parse(r)}loadAgents(e){let t=(0,n.join)(e,`agents`);return this.fs.existsSync(t)?this.fs.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.name.endsWith(`.md`)).map(e=>e.name.replace(/\.md$/,``)):[]}};function ko(e){let t=(0,n.join)((0,n.dirname)((0,n.dirname)(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function Ao(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 jo(e){let t={};for(let n of e){let e=n.hooks;if(!e)continue;let r=ko(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=Ao(e,n.pluginDir);return t.env=r,t});t[e].push(...i)}}return t}function Mo(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 No(e){let t=e.cwd,[i,a,o]=await Promise.all([e.config?Promise.resolve(e.config):Wa(t),e.bare?Promise.resolve({agentsMd:``,claudeMd:``,agentsFileEntries:[],claudeFileEntries:[]}):wo(t),e.bare?Promise.resolve({type:`unknown`,language:`unknown`}):Dr(t)]),s=e.language?{...i,language:e.language}:i,c=new Oo((0,n.join)((0,r.homedir)(),`.robota`,`plugins`));if(!e.bare)try{let e=c.loadPluginsSync();if(e.length>0){let t=jo(e);s={...s,hooks:Mo(s.hooks,t)}}}catch{}let u=R(t);await Fo(e)||await Po(e,t);let d=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,{session:f,rebuildSystemMessage:p}=pa({config:s,cwd:t,context:a,projectInfo:o,permissionMode:e.permissionMode,maxTurns:e.maxTurns,terminal:Be,sessionLogger:new l.FileSessionLogger(u.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:d,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:f,agentsFileEntries:a.agentsFileEntries??[],claudeFileEntries:a.claudeFileEntries??[],rebuildSystemMessage:p}}async function Po(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await(0,s.applyWorkspaceManifest)(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function Fo(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 Io(e,t){let n=e.config??await Wa(e.cwd),r=n.autoCompactThreshold===void 0?`default`:`settings`,i=new z({cwd:e.cwd});t.setEditCheckpointStore(i);let a=await No({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)Or(a.session,e);a.session.syncContextFromHistory()}return{session:a.session,agentsFileEntries:a.agentsFileEntries,claudeFileEntries:a.claudeFileEntries,rebuildSystemMessage:a.rebuildSystemMessage,autoCompactThresholdSource:r}}function Lo(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(Ro({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 Ro(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},...zo(e.backgroundState),...Bo(e.memoryState),...Vo(e.skillActivationState),...Ho(e.contextReferenceState)}}function zo(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function Bo(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function Vo(e){return e?{skillActivationEvents:[...e.events]}:{}}function Ho(e){return e?{contextReferences:[...e.references]}:{}}function Uo(e){return e.source===`skill`||e.source===`plugin`&&e.skillContent?`skill`:`builtin-command`}function Wo(e){let t=e.source===`skill`||e.source===`plugin`&&!!e.skillContent;return{name:e.name,kind:Uo(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 Go=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=>Wo(e))}},Ko=class{commands;constructor(e){this.commands=new Map;for(let t of e??Z())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 Z(){return[]}function qo(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 Jo=class{name=`builtin`;commands;constructor(e=Z()){this.commands=e.map(qo)}getCommands(){return this.commands}};function Yo(){let e=Z();return{name:`sdk-builtin`,commandSources:[new Jo(e)],systemCommands:e}}function Xo(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function Zo(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function Qo(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 $o(t,n,r={}){if(!n.type)throw Error(`Provider profile "${t}" is missing type`);let i=r.providerDefinitions??[],a=(0,e.findProviderDefinition)(i,n.type);if(a===void 0&&i.length>0)throw Error(`Unknown provider "${n.type}". Supported providers: ${(0,e.formatSupportedProviderTypes)(i)}`);if(!n.model)throw Error(`Provider profile "${t}" is missing model`);let o=(0,e.getProviderCredentialRequirement)(a);if(o!==void 0&&!is(n,a?.defaults,o))throw Error(`Provider profile "${t}" is missing ${os(o)}`)}function es(e,t={}){let n=ts(e,t);return $o(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function ts(t,n={}){let r=rs(t.type,n.providerDefinitions??[]);if(t.apiKey!==void 0&&t.apiKeyEnv===void 0&&console.warn(`API key stored as plain text in settings. Use --api-key-env for better security.`),t.apiKeyEnv!==void 0){let e=(n.env??process.env)[t.apiKeyEnv];if(e===void 0||e.length===0)throw Error(`Environment variable ${t.apiKeyEnv} is not set — set it before configuring (the profile will reference $ENV:${t.apiKeyEnv})`)}let i=t.apiKeyEnv===void 0?t.apiKey??r.apiKey:(0,e.formatEnvReference)(t.apiKeyEnv),a=t.baseURL??r.baseURL;return{type:t.type,model:t.model??r.model,...ss(i)&&{apiKey:i},...a!==void 0&&{baseURL:a},...t.timeout!==void 0&&{timeout:t.timeout}}}function ns(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=Xo(e,n,r);return t.currentProvider?Zo(i,t.currentProvider):i}function rs(t,n){return(0,e.findProviderDefinition)(n,t)?.defaults??{}}function is(t,n,r){return r.anyOf.some(r=>(0,e.hasUsableSecretReference)(as(r,t,n)))}function as(e,t,n){return t[e]??n?.[e]}function os(e){return e.anyOf.join(` or `)}function ss(e){return e!==void 0&&e.length>0}async function cs(t,n,r,i){let a=r??t;if(!a)return{message:`No provider profile selected.`,success:!1};let o=n?.[a];if(!o)return{message:`Provider profile "${a}" was not found.`,success:!1};try{$o(a,o,{providerDefinitions:i.providerDefinitions})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let s=await((o.type?(0,e.findProviderDefinition)(i.providerDefinitions,o.type):void 0)?.probeProfile??ls)(o);return{message:s.ok?`Provider "${a}" test passed: ${s.message}`:`Provider "${a}" test failed: ${s.message}; manual configuration can continue.`,success:!0,data:{providerTest:{profile:a}}}}async function ls(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function us(e,t=[]){return ds(e,t)?`valid`:`incomplete`}function ds(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return fs(n?.type,n,t)}return!!(e.provider&&fs(e.provider.name,e.provider,t))}function fs(t,n,r){if(!n)return!1;if(!t)return(0,e.hasUsableSecretReference)(n.apiKey);let i=(0,e.findProviderDefinition)(r,t);if(i===void 0)return!1;let a=(0,e.getProviderCredentialRequirement)(i);return a===void 0?!0:ps(n,i,a)}function ps(t,n,r){return r.anyOf.some(r=>(0,e.hasUsableSecretReference)(ms(r,t,n)))}function ms(e,t,n){return t[e]??n.defaults?.[e]}function hs(e,t=[]){if(!(0,i.existsSync)(e))return`missing`;try{let n=(0,i.readFileSync)(e,`utf8`).trim();return n.length===0?`incomplete`:us(JSON.parse(n),t)}catch{return`corrupt`}}function gs(e,t=new S){return e.reduce((e,n)=>{let r=_s(n,t);return r===void 0?e:vs(e,r)},{})}function _s(e,t){if(!t.existsSync(e))return;let n=t.readFileSync(e,`utf8`);try{return JSON.parse(n)}catch(t){throw new ji(e,t instanceof Error?t.message:String(t))}}function vs(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?ys(e.providers,t.providers):void 0}}function ys(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function bs(e,t,n){let r=t??e.currentProvider;if(r!==void 0){let t=e.providers?.[r];if(t===void 0)throw Error(`Provider profile "${r}" was not found in providers`);if(!t.type)throw Error(`Provider profile "${r}" is missing type`);return(0,o.normalizeProviderConfig)({name:t.type,model:t.model,apiKey:t.apiKey,baseURL:t.baseURL,timeout:t.timeout,options:t.options},n)}let i=e.provider;if(i?.name)return(0,o.normalizeProviderConfig)({name:i.name,model:i.model,apiKey:i.apiKey,baseURL:i.baseURL,timeout:i.timeout,options:i.options},n)}function xs(){return process.env.HOME??process.env.USERPROFILE??`/`}function Q(e){let t=xs();return[(0,n.join)(t,`.robota`,`settings.json`),(0,n.join)(t,`.claude`,`settings.json`),(0,n.join)(e,`.robota`,`settings.json`),(0,n.join)(e,`.robota`,`settings.local.json`),(0,n.join)(e,`.claude`,`settings.json`),(0,n.join)(e,`.claude`,`settings.local.json`)]}function Ss(e,t={}){let n=t.settingsPaths??Q(e),r=Os(n)??n[0];if(r===void 0)throw Error(`No settings path available for provider update`);return r}function $(e){return G(e)}function Cs(e,t,n={}){let r=ns($(e),es(t,n));return K(e,r),r}function ws(e,t,n={}){let r=$(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:Zo(r,t);return K(e,o),o}function Ts(e,t,n={}){let r=n.settingsPaths??Q(e),i=gs(r),a=n.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Es(r,a,t)}function Es(e,t,n){let r=Ds(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 K(r,s),{settingsPath:r,settings:s,profileName:t}}function Ds(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 Os(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 ks=class extends Error{constructor(e){super(e),this.name=`ProviderConfigError`}};function As(e){return gs(Q(e))}function js(t,n=process.env){for(let r of t){let t=r.defaults;if(t?.apiKey===void 0||t.model===void 0||!(0,e.isEnvReference)(t.apiKey))continue;let i=t.apiKey.slice(e.ENV_REFERENCE_PREFIX.length).trim();if(i.length===0)continue;let a=n[i];if(!(a===void 0||a.length===0))return{name:r.type,model:t.model,apiKey:a,...t.baseURL!==void 0&&{baseURL:t.baseURL},...t.timeout!==void 0&&{timeout:t.timeout},...t.options!==void 0&&{options:t.options},source:`env-default`,sourceEnvVar:i}}}function Ms(e,t={}){let n=bs(As(e),t.providerOverride,t.providerDefinitions??[]);if(n!==void 0)return n;let r=js(t.providerDefinitions??[],t.env);if(r!==void 0)return r;throw new ks("No provider configuration found. Run `robota` to set up.")}function Ns(e,t,n={}){let r=n.providerDefinitions??[],i=Ms(e,{...n,providerDefinitions:r}),a=t??i.model;return(0,o.createProviderFromConfig)({...i,model:a},r)}var Ps=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 Fs(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 Is=l.AUTO_COMPACT_THRESHOLD,Ls=`autoCompactThreshold`;function Rs(e){return e.getContextState()}function zs(e){return e.getAutoCompactThreshold()}function Bs(e){return e.getAutoCompactThresholdSource?.()??`session`}function Vs(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 Hs(e,t){let n=Ys(e);return n?(n.write({...n.read(),[Ls]:t}),!0):!1}function Us(e){let t=Ys(e);if(!t)return!1;let n={...t.read()};return delete n[Ls],t.write(n),!0}async function Ws(e,t){let n=Rs(e),r=e.getSession().getMessageCount();return await e.compactContext(t),{before:n,after:Rs(e),beforeMessageCount:r,afterMessageCount:e.getSession().getMessageCount()}}function Gs(e){return e.listContextReferences?.()??[]}async function Ks(e,t){return e.addContextReference?e.addContextReference(t):{evicted:[],diagnostics:[`Command host does not support context reference additions.`]}}function qs(e,t){return e.removeContextReference?.(t)??{}}function Js(e){return e.clearContextReferences?.()??{removed:[]}}function Ys(e){return e.getCommandHostAdapters?.().settings}function Xs(e,t={}){let n=Zs(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 Zs(e){let t=e?.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t!==void 0&&t.length>0?t:void 0}function Qs(e){return e.listCommands?.()??[]}function $s(e){return[`Available commands:`,...Qs(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
- `)}function ec(){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 tc(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=ic(e),s=t?` — ${t}`:``;return`${e.id} [${e.status}${n}${i}${a}${o}] ${e.kind}:${e.label}${r}${s}`}function nc(e){return e.length===0?`No background tasks.`:[`Background tasks:`,...e.map(e=>` ${tc(e)}`)].join(`
99
- `)}function rc(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isNaN(t)?void 0:{offset:t}}function ic(e){let t=[];return e.worktreePath&&t.push(`worktree=${e.worktreePath}`),e.branchName&&t.push(`branch=${e.branchName}`),e.worktreeStatus&&t.push(`worktreeStatus="${ac(e.worktreeStatus)}"`),e.worktreeNextAction&&t.push(`next="${ac(e.worktreeNextAction)}"`),t.length===0?``:` ${t.join(` `)}`}function ac(e){let t=e.trim().replace(/\s+/g,` `);return t.length>160?`${t.slice(0,160)}...`:t}function oc(e,t){return e.listBackgroundTasks(t)}function sc(e,t,n){return e.readBackgroundTaskLog(t,n)}function cc(e,t,n){return e.cancelBackgroundTask(t,n)}function lc(e,t){return e.closeBackgroundTask(t)}const uc=[{code:`ko`,description:`Korean`},{code:`en`,description:`English`},{code:`ja`,description:`Japanese`},{code:`zh`,description:`Chinese`}];function dc(e=`language`){return uc.map(t=>({name:t.code,description:t.description,source:e}))}function fc(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function pc(e=`language`){return`Usage: ${e} <code> (e.g., ko, en, ja, zh)`}const mc=[`plan`,`default`,`acceptEdits`,`bypassPermissions`];function hc(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 gc(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function _c(e){return mc.includes(e)}function vc(){return`Invalid mode. Valid: ${mc.join(` | `)}`}function yc(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 bc(e){return yc(e).getPermissionMode()}function xc(e,t){yc(e).setPermissionMode(t)}function Sc(e){return yc(e).listSessionAllowedTools()}function Cc(e){return{mode:bc(e),sessionAllowed:Sc(e)}}function wc(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 Tc(e,t,n){let r=[],i=[];e.getSession().setActivePresetId?.(t),n.permissionMode===void 0?i.push(`permissionMode`):(xc(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 Ec={enabled:!0,gitBranch:!0};function Dc(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 Oc(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function kc(e){let t=e.statusline;return jc(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:Ec.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:Ec.gitBranch}:{...Ec}}function Ac(e,t){let n=G(e),r={...kc(n),...t};return n.statusline=r,K(e,n),r}function jc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Mc(){return{type:`plugin-tui-requested`}}function Nc(){return{type:`plugin-registry-reload-requested`}}function Pc(e){return e.getCommandHostAdapters?.().plugin}function Fc(){return[{name:`manage`,description:`Open plugin manager`,source:`plugin-manager`},{name:`install`,description:`Install a plugin`,source:`plugin-manager`},{name:`uninstall`,description:`Uninstall a plugin`,source:`plugin-manager`},{name:`enable`,description:`Enable a plugin`,source:`plugin-manager`},{name:`disable`,description:`Disable a plugin`,source:`plugin-manager`},{name:`marketplace`,description:`Manage plugin marketplaces`,source:`plugin-manager`,subcommands:[{name:`add`,description:`Add marketplace source`,source:`plugin-manager`},{name:`remove`,description:`Remove marketplace source`,source:`plugin-manager`},{name:`update`,description:`Update marketplace source`,source:`plugin-manager`},{name:`list`,description:`List marketplace sources`,source:`plugin-manager`}]}]}function Ic(e){if(e.clearConversationHistory!==void 0){e.clearConversationHistory();return}e.getSession().clearHistory()}function Lc(e){let t=e.trim();return t.length>0?t:void 0}function Rc(e){return{type:`session-renamed`,name:e}}function zc(){return{type:`session-picker-requested`}}function Bc(){return{type:`session-exit-requested`}}function Vc(e){let t=e.getSession();return{sessionId:t.getSessionId(),messageCount:t.getMessageCount()}}function Hc(e){let t=e.validateCurrentSessionReplayLog?.();if(t!==void 0)return t;let r=e.getSession().getSessionId(),i=(0,n.join)(R(e.getCwd()).logs,`${r}.jsonl`),a=(0,l.loadSessionLogEntries)(i);return{logFile:i,entryCount:a.length,validation:(0,l.validateSessionReplayLogEntries)(a)}}function Uc(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=Wc(e);return`${t+1}. ${e.code}${n}: ${e.message}`});return[t,...n,``,...r].join(`
102
- `)}function Wc(e){let t=[];return e.executionId!==void 0&&t.push(`execution=${e.executionId}`),e.round!==void 0&&t.push(`round=${e.round}`),e.toolCallId!==void 0&&t.push(`tool=${e.toolCallId}`),t.length>0?` (${t.join(`, `)})`:``}function Gc(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 Kc(e){return e.listEditCheckpoints()}function qc(e,t){if(!e.inspectEditCheckpoint)throw Error(`Checkpoint inspection is not available in this command host.`);return e.inspectEditCheckpoint(t)}function Jc(e,t){return e.restoreEditCheckpoint(t)}function Yc(e,t){return e.rollbackEditCheckpoint(t)}const Xc=[/\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 Zc(e){return Xc.some(t=>t.test(e))}function Qc(e){return(0,n.join)(e,`.robota`,`memory`)}function $c(){return{version:1,records:[]}}var el=class{fs;path;now;constructor(e,t=()=>new Date,r=new S){this.fs=r,this.path=(0,n.join)(Qc(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 $c();try{return{version:1,records:JSON.parse(this.fs.readFileSync(this.path,`utf8`)).records??[]}}catch{return $c()}}write(e){this.fs.mkdirSync((0,n.dirname)(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,JSON.stringify(e,null,2),`utf8`)}};function tl(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 nl(e,t){return new xo(e,t)}function rl(e,t){return new el(e,t)}function il(e,t){let n=e.getCwd();return{project:nl(n,t),pending:rl(n,t)}}function al(e){return mo(e)}function ol(e){return Zc(e)}function sl(e){return e.getUsedMemoryReferences()}function cl(e,t,n=()=>new Date){e.recordMemoryEvent({...t,at:n().toISOString()})}function ll(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 ul(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 dl(e,t,n,r){return e.skillContent?ll(await ul(e.skillContent,n.shellExec),t,r):null}async function fl(e,t,n,r){let i=await dl(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 pl(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 dl(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 fl(e,t,n,r)}}function ml(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function hl(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function gl(e,t){let n=t.trim();return n.length>0?`${e} ${n}`:e}function _l(e){if(!e?.startsWith(`/`))return;let t=e.slice(1).trim().split(/\s+/)[0];return t&&t.length>0?t:void 0}var vl=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 Ko(e.flatMap(e=>e.systemCommands??[])),this.skillCommandSource=new Ai(t),this.commandHostAdapters=n}reapplyCommandModuleSelection(e,t){let n=Fs(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=ml(e);return this.skillCommandSource.getCommands().find(e=>e.name.toLowerCase()===t.toLowerCase())}async executeCommand(e,t){let n=hl(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,gl(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=_l(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 pl(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=br({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 yl(){let e=(0,n.join)((0,r.homedir)(),`.robota`,`org-policy.json`);if(!(0,i.existsSync)(e))return null;try{let t=(0,i.readFileSync)(e,`utf8`);return JSON.parse(t)}catch{return null}}function bl(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function xl(e){return e?!e.startsWith(`$ENV:`):!1}function Sl(e,t){if(!e)return;let n={type:`cancelled`};return{ask:r=>t()===`model`?Promise.resolve(n):e(r)}}var Cl=class extends Ln{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 Ki;currentTurnSource=`user`;terminalHandoff;askHandler;terminalHandoffActive=!1;constructor(t){super(),this.sessionStore=t.sessionStore,this.sessionName=t.sessionName,this.terminalHandoff=t.terminalHandoff,this.askHandler=t.askHandler,this.cwd=(`cwd`in t?t.cwd:void 0)??``,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession??!1,this.sandboxClient=`sandboxClient`in t?t.sandboxClient:void 0,this.sandboxSnapshotId=`sandboxSnapshotId`in t?t.sandboxSnapshotId:void 0;let n=this.cwd,r=null;`session`in t&&t.session&&n&&(r=new z({cwd:n})),this.bgTracker=new Cn(()=>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),t=>this.histTracker.append((0,e.messageToHistoryEntry)((0,e.createSystemMessage)(t))),e=>this.histTracker.append(e)),this.histTracker=new wr(n,()=>this.getSessionOrThrow().getSessionId(),()=>this.execCtrl.executing,()=>this.persistCurrentSession(),e=>this.emit(`skill_activation`,e),e=>this.emit(`memory_event`,e),r);let i=[...`commandModules`in t?t.commandModules??[]:[]],a=`commandHostAdapters`in t?t.commandHostAdapters:void 0,o=`shellExec`in t?t.shellExec:void 0;this.skillRouter=new vl(i,n,a,()=>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)=>nr(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)),o),this.execCtrl=new er(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 t&&(this.providerDefinitions=t.providerDefinitions??[]),`orgPolicy`in t&&(this.orgPolicy=t.orgPolicy??null),this.on(`turn_source`,e=>{this.currentTurnSource=e}),this.on(`complete`,e=>this.handleGoalTurnComplete(e));let s=this.configureInjectedSession(t);this.restoreSessionRecordIfNeeded(t),this.startAsyncInitializationIfNeeded(t,s),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=kr(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 Io(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 Sl(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 wt(this.session)??P(this.session)?.backgroundTaskManager}reportBackgroundError(t,n=`background`){let r=L(t);this.histTracker.append((0,e.messageToHistoryEntry)((0,e.createSystemMessage)(`Error: ${r}`,{metadata:{kind:`error`,source:n}}))),this.emit(`error`,t)}async captureSandboxSnapshot(){if(this.sandboxClient?.snapshot)try{this.sandboxSnapshotId=await this.sandboxClient.snapshot()}catch(t){let n=t instanceof Error?t:Error(String(t));this.histTracker.append((0,e.messageToHistoryEntry)((0,e.createSystemMessage)(`Sandbox snapshot error: ${n.message}`))),this.emit(`error`,n)}}persistCurrentSession(){if(!this.sessionStore||!this.session)return;let e=this.bgTracker.getState(),t=this.histTracker.getState();Lo(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(Vi(e),e)})}async switchProvider(e){let t=this.getSessionOrThrow(),n=this.getCwd(),r=Ms(n,{providerOverride:e,providerDefinitions:this.providerDefinitions}),i=Ns(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:bl(`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:bl(`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 wl(e,t=new S){let n=R(e);return new kl(n.sessions,n.logs,t)}function Tl(e=new S){return new kl(or().sessions,void 0,e)}function El(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:Al(e.messages)}))}function Dl(e,t){return El(e,t)[0]?.id}function Ol(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var kl=class{store;logsDir;fs;constructor(e,t,n=new S){this.store=new l.SessionStore(e),this.logsDir=t,this.fs=n}save(e){this.store.save(jl(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):Ml(t)}list(){let e=this.store.list().map(Ml),t=new Set(e.map(e=>e.id));for(let n of this.listReplayLogRecords())t.has(n.id)||e.push(n);return e.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime())}delete(e){this.store.delete(e)}loadFromReplayLog(e){if(!this.logsDir)return;let t=(0,l.replaySessionLogEntries)((0,l.loadSessionLogEntries)((0,n.join)(this.logsDir,`${e}.jsonl`)));if(!t.sessionId||t.messages.length===0)return;let r=t.backgroundTaskEvents,i=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:Nl(r),backgroundTaskEvents:r,backgroundJobGroups:Fl(i),backgroundJobGroupEvents:i,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 Al(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 jl(e){return{...e}}function Ml(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 Nl(e){let t=new Map;for(let n of e){let e=Pl(n);e&&t.set(e.id,e)}return[...t.values()]}function Pl(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 Fl(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function Il(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,``).trim().replace(/\s+/g,`-`).replace(/-+/g,`-`).slice(0,60)}async function Ll(t,n){let r=n.slice(0,200),i=await t.chat([(0,e.createSystemMessage)(`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.`),(0,e.createUserMessage)(r)],{maxTokens:20}),a=Il(typeof i.content==`string`?i.content:``);return!a||a.length<3?Il(n):a}Object.defineProperty(exports,"$",{enumerable:!0,get:function(){return Pc}}),Object.defineProperty(exports,"$n",{enumerable:!0,get:function(){return Wi}}),Object.defineProperty(exports,"$r",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,"$t",{enumerable:!0,get:function(){return Vs}}),Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return Jc}}),Object.defineProperty(exports,"An",{enumerable:!0,get:function(){return Ko}}),Object.defineProperty(exports,"Ar",{enumerable:!0,get:function(){return qt}}),Object.defineProperty(exports,"At",{enumerable:!0,get:function(){return ec}}),Object.defineProperty(exports,"B",{enumerable:!0,get:function(){return Bc}}),Object.defineProperty(exports,"Bn",{enumerable:!0,get:function(){return oo}}),Object.defineProperty(exports,"Br",{enumerable:!0,get:function(){return Qe}}),Object.defineProperty(exports,"Bt",{enumerable:!0,get:function(){return Zs}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return sl}}),Object.defineProperty(exports,"Cn",{enumerable:!0,get:function(){return ns}}),Object.defineProperty(exports,"Cr",{enumerable:!0,get:function(){return on}}),Object.defineProperty(exports,"Ct",{enumerable:!0,get:function(){return`Set response language`}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return Gc}}),Object.defineProperty(exports,"Dn",{enumerable:!0,get:function(){return Jo}}),Object.defineProperty(exports,"Dr",{enumerable:!0,get:function(){return Qt}}),Object.defineProperty(exports,"Dt",{enumerable:!0,get:function(){return fc}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return`List, inspect, restore, or rollback edit checkpoints.`}}),Object.defineProperty(exports,"En",{enumerable:!0,get:function(){return $o}}),Object.defineProperty(exports,"Er",{enumerable:!0,get:function(){return Yt}}),Object.defineProperty(exports,"Et",{enumerable:!0,get:function(){return pc}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return`Rename the current session`}}),Object.defineProperty(exports,"Fn",{enumerable:!0,get:function(){return xo}}),Object.defineProperty(exports,"Fr",{enumerable:!0,get:function(){return Vt}}),Object.defineProperty(exports,"Ft",{enumerable:!0,get:function(){return oc}}),Object.defineProperty(exports,"G",{enumerable:!0,get:function(){return Vc}}),Object.defineProperty(exports,"Gn",{enumerable:!0,get:function(){return ga}}),Object.defineProperty(exports,"Gr",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"Gt",{enumerable:!0,get:function(){return Js}}),Object.defineProperty(exports,"H",{enumerable:!0,get:function(){return Rc}}),Object.defineProperty(exports,"Hn",{enumerable:!0,get:function(){return so}}),Object.defineProperty(exports,"Hr",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"Ht",{enumerable:!0,get:function(){return Ls}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return`Usage: rename <name>`}}),Object.defineProperty(exports,"In",{enumerable:!0,get:function(){return mo}}),Object.defineProperty(exports,"Ir",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"It",{enumerable:!0,get:function(){return rc}}),Object.defineProperty(exports,"J",{enumerable:!0,get:function(){return`Manage plugins`}}),Object.defineProperty(exports,"Jn",{enumerable:!0,get:function(){return Xi}}),Object.defineProperty(exports,"Jr",{enumerable:!0,get:function(){return qe}}),Object.defineProperty(exports,"Jt",{enumerable:!0,get:function(){return zs}}),Object.defineProperty(exports,"K",{enumerable:!0,get:function(){return Hc}}),Object.defineProperty(exports,"Kn",{enumerable:!0,get:function(){return ea}}),Object.defineProperty(exports,"Kr",{enumerable:!0,get:function(){return Ze}}),Object.defineProperty(exports,"Kt",{enumerable:!0,get:function(){return Ws}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return`Resume a previous session`}}),Object.defineProperty(exports,"Ln",{enumerable:!0,get:function(){return ao}}),Object.defineProperty(exports,"Lr",{enumerable:!0,get:function(){return yt}}),Object.defineProperty(exports,"Lt",{enumerable:!0,get:function(){return sc}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return`Clear conversation history`}}),Object.defineProperty(exports,"Mn",{enumerable:!0,get:function(){return Oo}}),Object.defineProperty(exports,"Mr",{enumerable:!0,get:function(){return Wt}}),Object.defineProperty(exports,"Mt",{enumerable:!0,get:function(){return lc}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return`Show session token usage and estimated cost. /cost budget <amount> sets a monthly budget.`}}),Object.defineProperty(exports,"Nn",{enumerable:!0,get:function(){return fo}}),Object.defineProperty(exports,"Nr",{enumerable:!0,get:function(){return Ut}}),Object.defineProperty(exports,"Nt",{enumerable:!0,get:function(){return tc}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return qc}}),Object.defineProperty(exports,"On",{enumerable:!0,get:function(){return Yo}}),Object.defineProperty(exports,"Or",{enumerable:!0,get:function(){return Jt}}),Object.defineProperty(exports,"Ot",{enumerable:!0,get:function(){return`List and control background tasks`}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return`Exit CLI`}}),Object.defineProperty(exports,"Pn",{enumerable:!0,get:function(){return 200}}),Object.defineProperty(exports,"Pr",{enumerable:!0,get:function(){return Ht}}),Object.defineProperty(exports,"Pt",{enumerable:!0,get:function(){return nc}}),Object.defineProperty(exports,"Q",{enumerable:!0,get:function(){return Mc}}),Object.defineProperty(exports,"Qn",{enumerable:!0,get:function(){return Ki}}),Object.defineProperty(exports,"Qr",{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,"Qt",{enumerable:!0,get:function(){return Us}}),Object.defineProperty(exports,"R",{enumerable:!0,get:function(){return`Validate current session replay log`}}),Object.defineProperty(exports,"Rn",{enumerable:!0,get:function(){return co}}),Object.defineProperty(exports,"Rr",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"Rt",{enumerable:!0,get:function(){return`Show available commands`}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return al}}),Object.defineProperty(exports,"Sn",{enumerable:!0,get:function(){return Qo}}),Object.defineProperty(exports,"Sr",{enumerable:!0,get:function(){return pn}}),Object.defineProperty(exports,"St",{enumerable:!0,get:function(){return`<code>`}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return`list | inspect CHECKPOINT_ID | restore CHECKPOINT_ID | code CHECKPOINT_ID | rollback CHECKPOINT_ID`}}),Object.defineProperty(exports,"Tn",{enumerable:!0,get:function(){return Xo}}),Object.defineProperty(exports,"Tr",{enumerable:!0,get:function(){return Kt}}),Object.defineProperty(exports,"Tt",{enumerable:!0,get:function(){return dc}}),Object.defineProperty(exports,"U",{enumerable:!0,get:function(){return Uc}}),Object.defineProperty(exports,"Un",{enumerable:!0,get:function(){return uo}}),Object.defineProperty(exports,"Ur",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"Ut",{enumerable:!0,get:function(){return Is}}),Object.defineProperty(exports,"V",{enumerable:!0,get:function(){return zc}}),Object.defineProperty(exports,"Vn",{enumerable:!0,get:function(){return io}}),Object.defineProperty(exports,"Vr",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"Vt",{enumerable:!0,get:function(){return Xs}}),Object.defineProperty(exports,"W",{enumerable:!0,get:function(){return Lc}}),Object.defineProperty(exports,"Wn",{enumerable:!0,get:function(){return ha}}),Object.defineProperty(exports,"Wr",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"Wt",{enumerable:!0,get:function(){return Ks}}),Object.defineProperty(exports,"X",{enumerable:!0,get:function(){return Fc}}),Object.defineProperty(exports,"Xn",{enumerable:!0,get:function(){return 25}}),Object.defineProperty(exports,"Xr",{enumerable:!0,get:function(){return _e}}),Object.defineProperty(exports,"Xt",{enumerable:!0,get:function(){return Rs}}),Object.defineProperty(exports,"Y",{enumerable:!0,get:function(){return`Reload all plugin resources`}}),Object.defineProperty(exports,"Yn",{enumerable:!0,get:function(){return Ji}}),Object.defineProperty(exports,"Yr",{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,"Yt",{enumerable:!0,get:function(){return Bs}}),Object.defineProperty(exports,"Z",{enumerable:!0,get:function(){return Nc}}),Object.defineProperty(exports,"Zn",{enumerable:!0,get:function(){return 2}}),Object.defineProperty(exports,"Zr",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"Zt",{enumerable:!0,get:function(){return qs}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return tl}}),Object.defineProperty(exports,"_n",{enumerable:!0,get:function(){return hs}}),Object.defineProperty(exports,"_r",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"_t",{enumerable:!0,get:function(){return gc}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return Dl}}),Object.defineProperty(exports,"ai",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"an",{enumerable:!0,get:function(){return Ms}}),Object.defineProperty(exports,"ar",{enumerable:!0,get:function(){return Mi}}),Object.defineProperty(exports,"at",{enumerable:!0,get:function(){return Oc}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return nl}}),Object.defineProperty(exports,"bn",{enumerable:!0,get:function(){return ts}}),Object.defineProperty(exports,"br",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"bt",{enumerable:!0,get:function(){return yc}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return bl}}),Object.defineProperty(exports,"ci",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"cn",{enumerable:!0,get:function(){return Cs}}),Object.defineProperty(exports,"cr",{enumerable:!0,get:function(){return Pi}}),Object.defineProperty(exports,"ct",{enumerable:!0,get:function(){return`Show/change permission mode and permission rules`}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return pl}}),Object.defineProperty(exports,"dn",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"dr",{enumerable:!0,get:function(){return Ai}}),Object.defineProperty(exports,"dt",{enumerable:!0,get:function(){return mc}}),Object.defineProperty(exports,"ei",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,"en",{enumerable:!0,get:function(){return Hs}}),Object.defineProperty(exports,"er",{enumerable:!0,get:function(){return Vi}}),Object.defineProperty(exports,"et",{enumerable:!0,get:function(){return Ec}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return ul}}),Object.defineProperty(exports,"fn",{enumerable:!0,get:function(){return ys}}),Object.defineProperty(exports,"fr",{enumerable:!0,get:function(){return Ei}}),Object.defineProperty(exports,"ft",{enumerable:!0,get:function(){return hc}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return`Usage: memory list | memory show [topic] | memory add <user|feedback|project|reference> <topic> <text> | memory pending | memory approve <id> | memory reject <id> | memory used`}}),Object.defineProperty(exports,"gn",{enumerable:!0,get:function(){return us}}),Object.defineProperty(exports,"gr",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"gt",{enumerable:!0,get:function(){return Sc}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return`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.`}}),Object.defineProperty(exports,"hn",{enumerable:!0,get:function(){return bs}}),Object.defineProperty(exports,"hr",{enumerable:!0,get:function(){return Ir}}),Object.defineProperty(exports,"ht",{enumerable:!0,get:function(){return _c}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return El}}),Object.defineProperty(exports,"ii",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"in",{enumerable:!0,get:function(){return As}}),Object.defineProperty(exports,"ir",{enumerable:!0,get:function(){return Ii}}),Object.defineProperty(exports,"it",{enumerable:!0,get:function(){return Dc}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return Yc}}),Object.defineProperty(exports,"jn",{enumerable:!0,get:function(){return Go}}),Object.defineProperty(exports,"jr",{enumerable:!0,get:function(){return Zt}}),Object.defineProperty(exports,"jt",{enumerable:!0,get:function(){return cc}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return Kc}}),Object.defineProperty(exports,"kn",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"kr",{enumerable:!0,get:function(){return Xt}}),Object.defineProperty(exports,"kt",{enumerable:!0,get:function(){return`Usage: background list | background read <task-id> [offset] | background cancel <task-id> | background close <task-id>`}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return xl}}),Object.defineProperty(exports,"li",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"ln",{enumerable:!0,get:function(){return ws}}),Object.defineProperty(exports,"lr",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"lt",{enumerable:!0,get:function(){return`plan | default | acceptEdits | bypassPermissions`}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return`list | show [topic] | add <user|feedback|project|reference> <topic> <text> | pending | approve <id> | reject <id> | used`}}),Object.defineProperty(exports,"mn",{enumerable:!0,get:function(){return gs}}),Object.defineProperty(exports,"mr",{enumerable:!0,get:function(){return di}}),Object.defineProperty(exports,"mt",{enumerable:!0,get:function(){return vc}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return wl}}),Object.defineProperty(exports,"ni",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"nn",{enumerable:!0,get:function(){return ks}}),Object.defineProperty(exports,"nr",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"nt",{enumerable:!0,get:function(){return`Configure TUI status-line visibility and fields such as model, context, tokens, session, and git branch.`}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return Ol}}),Object.defineProperty(exports,"oi",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"on",{enumerable:!0,get:function(){return js}}),Object.defineProperty(exports,"or",{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,"ot",{enumerable:!0,get:function(){return kc}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return ll}}),Object.defineProperty(exports,"pn",{enumerable:!0,get:function(){return vs}}),Object.defineProperty(exports,"pr",{enumerable:!0,get:function(){return yi}}),Object.defineProperty(exports,"pt",{enumerable:!0,get:function(){return wc}}),Object.defineProperty(exports,"q",{enumerable:!0,get:function(){return`manage | install <name@marketplace> | uninstall <name@marketplace> | enable <name@marketplace> | disable <name@marketplace> | marketplace <action>`}}),Object.defineProperty(exports,"qn",{enumerable:!0,get:function(){return ta}}),Object.defineProperty(exports,"qr",{enumerable:!0,get:function(){return He}}),Object.defineProperty(exports,"qt",{enumerable:!0,get:function(){return Gs}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Tl}}),Object.defineProperty(exports,"ri",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"rn",{enumerable:!0,get:function(){return Ns}}),Object.defineProperty(exports,"rr",{enumerable:!0,get:function(){return Ri}}),Object.defineProperty(exports,"rt",{enumerable:!0,get:function(){return Ac}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return Cl}}),Object.defineProperty(exports,"si",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"sn",{enumerable:!0,get:function(){return Ts}}),Object.defineProperty(exports,"sr",{enumerable:!0,get:function(){return Ni}}),Object.defineProperty(exports,"st",{enumerable:!0,get:function(){return Tc}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Ll}}),Object.defineProperty(exports,"ti",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"tn",{enumerable:!0,get:function(){return Ps}}),Object.defineProperty(exports,"tr",{enumerable:!0,get:function(){return Bi}}),Object.defineProperty(exports,"tt",{enumerable:!0,get:function(){return`on | off | reset | git on | git off`}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return yl}}),Object.defineProperty(exports,"ui",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"un",{enumerable:!0,get:function(){return Ss}}),Object.defineProperty(exports,"ur",{enumerable:!0,get:function(){return ji}}),Object.defineProperty(exports,"ut",{enumerable:!0,get:function(){return`Show/change permission mode`}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return il}}),Object.defineProperty(exports,"vn",{enumerable:!0,get:function(){return ls}}),Object.defineProperty(exports,"vr",{enumerable:!0,get:function(){return or}}),Object.defineProperty(exports,"vt",{enumerable:!0,get:function(){return bc}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return cl}}),Object.defineProperty(exports,"wn",{enumerable:!0,get:function(){return Zo}}),Object.defineProperty(exports,"wr",{enumerable:!0,get:function(){return Gt}}),Object.defineProperty(exports,"wt",{enumerable:!0,get:function(){return uc}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return ol}}),Object.defineProperty(exports,"xn",{enumerable:!0,get:function(){return es}}),Object.defineProperty(exports,"xr",{enumerable:!0,get:function(){return _n}}),Object.defineProperty(exports,"xt",{enumerable:!0,get:function(){return xc}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return rl}}),Object.defineProperty(exports,"yn",{enumerable:!0,get:function(){return cs}}),Object.defineProperty(exports,"yr",{enumerable:!0,get:function(){return Sn}}),Object.defineProperty(exports,"yt",{enumerable:!0,get:function(){return Cc}}),Object.defineProperty(exports,"z",{enumerable:!0,get:function(){return Ic}}),Object.defineProperty(exports,"zn",{enumerable:!0,get:function(){return lo}}),Object.defineProperty(exports,"zr",{enumerable:!0,get:function(){return gt}}),Object.defineProperty(exports,"zt",{enumerable:!0,get:function(){return $s}});