@robota-sdk/agent-framework 3.0.0-beta.64
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.
- package/LICENSE +21 -0
- package/README.md +513 -0
- package/dist/node/index.cjs +100 -0
- package/dist/node/index.d.ts +2966 -0
- package/dist/node/index.d.ts.map +1 -0
- package/dist/node/index.js +101 -0
- package/dist/node/index.js.map +1 -0
- package/package.json +61 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`@robota-sdk/agent-core`),l=require(`zod`),u=require(`@robota-sdk/agent-tools`),d=require(`@robota-sdk/agent-executor`),f=require(`@robota-sdk/agent-session`),p=require(`node:crypto`),m=require(`node:path`);m=s(m,1);let h=require(`node:os`),g=require(`node:fs`),_=require(`node:fs/promises`),v=require(`fs`),y=require(`path`);const b=[{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.
|
|
2
|
+
|
|
3
|
+
Your role is to complete the assigned task thoroughly and accurately. Follow these guidelines:
|
|
4
|
+
|
|
5
|
+
- Execute the task as described in the prompt. Do not expand scope beyond what is requested.
|
|
6
|
+
- Use the most appropriate tools for each step. Prefer precise tools (Read, Grep, Glob) over broad ones (Bash) when possible.
|
|
7
|
+
- Report your findings clearly and concisely when the task is complete.
|
|
8
|
+
- If a task cannot be completed, explain why and what information is missing.
|
|
9
|
+
- 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.
|
|
10
|
+
|
|
11
|
+
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.
|
|
12
|
+
|
|
13
|
+
Your role is to answer questions about the codebase by:
|
|
14
|
+
|
|
15
|
+
- Searching for relevant files, symbols, and patterns using Glob and Grep.
|
|
16
|
+
- Reading source files, configuration, and documentation to understand structure and behavior.
|
|
17
|
+
- Tracing code paths across modules to understand how components interact.
|
|
18
|
+
- Summarizing findings in a clear, structured format with file paths and line references.
|
|
19
|
+
- Identifying architectural patterns, dependencies, and potential issues.
|
|
20
|
+
|
|
21
|
+
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.
|
|
22
|
+
|
|
23
|
+
You operate in read-only mode. You must NEVER attempt to write or edit files. Your tools are restricted to read-only operations.
|
|
24
|
+
|
|
25
|
+
Your role is to:
|
|
26
|
+
|
|
27
|
+
- Analyze the current codebase state relevant to the task by reading specs, source code, and tests.
|
|
28
|
+
- Research implementation approaches by examining existing patterns and architectural conventions in the repository.
|
|
29
|
+
- Identify affected files, modules, and interfaces that a proposed change would touch.
|
|
30
|
+
- Assess risks, dependencies, and potential breaking changes.
|
|
31
|
+
- Produce a structured implementation plan with clear steps, file lists, and ordering.
|
|
32
|
+
- Consider edge cases, error handling, and test coverage requirements.
|
|
33
|
+
|
|
34
|
+
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 x(e){return b.find(t=>t.name===e)}function ee(){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.
|
|
35
|
+
|
|
36
|
+
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.
|
|
37
|
+
|
|
38
|
+
Do not use emojis.`}function te(){return`You are a worker subagent executing a specific task. Do NOT spawn sub-agents; execute directly. Keep your report under 500 words. Use this structure:
|
|
39
|
+
- Scope: What was requested
|
|
40
|
+
- Result: What was done
|
|
41
|
+
- Key files: Relevant file paths (absolute)
|
|
42
|
+
- Files changed: List of modifications
|
|
43
|
+
- Issues: Any problems encountered`}function ne(e){let t=[e.agentBody];e.claudeMd&&t.push(e.claudeMd),e.agentsMd&&t.push(e.agentsMd);let n=e.isForkWorker?te():ee();return t.push(n),t.join(`
|
|
44
|
+
|
|
45
|
+
`)}const S=`robota_command_`,re=/^[A-Za-z0-9_-]{1,64}$/;function ie(e){return e}function C(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function ae(e){let t=C(e);if(!t)throw Error(`Model command descriptor name must not be empty.`);let n=t.replace(/[^A-Za-z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``);if(!n)throw Error(`Model command descriptor name cannot be projected safely: ${e}`);let r=`${S}${n}`;if(re.test(r))return r;let i=(0,p.createHash)(`sha256`).update(t).digest(`hex`).slice(0,8),a=`${S}${n.slice(0,40).replace(/[_-]+$/g,``)||`command`}_${i}`;if(!re.test(a))throw Error(`Projected model command tool name is not provider-safe: ${a}`);return a}function oe(e){let t=new Set,n=new Map,r=new Map,i=[];for(let a of e){let e=C(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=ae(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:de(e,a),descriptor:a})}return{commandTools:i,toolNameToCommandName:n,commandNameToToolName:r}}function se(e){return`${e.toolName} — ${e.descriptor.description}`}function ce(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 le(e){return oe(e.commandDescriptors).commandTools.map(t=>{let n=ue(t.descriptor);return(0,u.createZodFunctionTool)(t.toolName,t.description,ie(n),async r=>{let i=n.parse(r);return e.isModelInvocable(t.commandName)?ce(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 ue(e){let t=e.argumentHint?`Arguments for the command. Expected grammar: ${e.argumentHint}`:`Arguments for the command as a single string.`;return l.z.object({args:l.z.string().optional().describe(t)})}function de(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(`
|
|
46
|
+
|
|
47
|
+
`)}const fe={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`,opus:`claude-opus-4-6`},pe=ae(`agent`);function me(e,t){return fe[e]??e}function he(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()!==pe),n}function ge(e){let{agentDefinition:t,parentConfig:n,parentContext:r,parentTools:i,terminal:a}=e,o=he(i,t),s=t.model?me(t.model,n.provider.model):n.provider.model,c=ne({agentBody:t.systemPrompt,claudeMd:r.claudeMd,agentsMd:r.agentsMd,isForkWorker:e.isForkWorker??!1}),l=e.provider;return new f.Session({tools:o,provider:l,systemMessage:c,terminal:a,...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.sessionLogger===void 0?{}:{sessionLogger:e.sessionLogger},model:s,maxTurns:t.maxTurns,permissions:n.permissions,permissionMode:e.permissionMode,defaultTrustLevel:n.defaultTrustLevel,permissionHandler:e.permissionHandler,hooks:e.hooks,hookTypeExecutors:e.hookTypeExecutors,onTextDelta:e.onTextDelta,onToolExecution:e.onToolExecution})}function _e(e,t){let n=t?.(e)??x(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function ve(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 ye(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function be(e){if(e.request.isolation===`worktree`)throw Error(`Worktree isolation requires a runtime shell subagent runner`)}function xe(e,t){if(t.type===`start`){e.emit?.({type:`background_task_tool_start`,toolName:t.toolName,firstArg:ye(t.toolArgs)});return}e.emit?.({type:`background_task_tool_end`,toolName:t.toolName,success:t.success??!0})}function Se(e){return{start(t){be(t);let n=ge({agentDefinition:ve(_e(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=>{xe(t,n),e.onToolExecution?.(n)}});return{jobId:t.jobId,result:n.run(t.request.prompt).then(e=>({jobId:t.jobId,output:e})),cancel:()=>(n.abort(),Promise.resolve())}}}}const Ce=1e3;var we=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,d.isTerminalBackgroundTaskStatus)(n.status)&&this.captureTask(e,n)}}handleTaskEvent(e){let t=Te(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,De(t)],e.state.updatedAt=this.now(),!0)}evaluateCompletion(e){if(e.state.status===`completed`)return;if(!Ee(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 Te(e){if(e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)return e.task}function Ee(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 De(e){return{taskId:e.id,label:e.label,status:e.status,...e.result?.output?{summary:Oe(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 Oe(e){let t=e.trim();return t.length<=Ce?t:`${t.slice(0,Ce)}...`}function ke(e){let t=Ae(e,`completed`),n=Ae(e,`failed`),r=Ae(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=>je(e))}}function Ae(e,t){return e.results.filter(e=>e.status===t).length}function je(e){let t=Me(e),n=e.outputRef&&e.summary?` (output: ${e.outputRef})`:``;return`[${e.status}] ${e.label} ${e.taskId}: ${t}${n}`}function Me(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 Ne(e){return[`group`,e].join(`:`)}function Pe(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 O(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 Fe(e){let t=Be(e.groups),n=[Ie(e.mainThread),...Xe(e.groups).map(e=>Re(e)),...Ye(e.tasks).map(e=>Le(e,t.get(e.id)))].filter(t=>Je(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 Ie(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:k(e.preview),unread:!1,attention:`none`,visibility:`default`,updatedAt:e.updatedAt,controls:[`select`]}}function Le(e,t){return{id:D(e.id),sourceId:e.id,kind:`background_task`,parentId:e.parentTaskId?D(e.parentTaskId):E(e.parentSessionId),...t?{groupId:Ne(t)}:{},origin:ze(e.metadata,{kind:`system`,sessionId:e.parentSessionId}),taskKind:e.kind,status:e.status,title:e.label,subtitle:He(e),preview:We(e),currentAction:e.currentAction,unread:e.unread,attention:Ge(e),visibility:Ke(e),updatedAt:e.lastActivityAt??e.updatedAt,controls:Ve(e)}}function Re(e){let t=k(e.results.map(e=>e.summary??e.error?.message).join(` `));return{id:Ne(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:qe(e),visibility:e.status===`completed`?`collapsed`:`default`,updatedAt:e.updatedAt,controls:e.status===`running`?[`select`,`wait`]:[`select`]}}function ze(e,t){let n=Ze(e?.[T.kind]),r=A(e?.[T.sessionId]);return{kind:n??t.kind,sessionId:r??t.sessionId,turnId:A(e?.[T.turnId])??t.turnId,commandName:A(e?.[T.commandName])??t.commandName,toolCallId:A(e?.[T.toolCallId])??t.toolCallId,skillId:A(e?.[T.skillId])??t.skillId,label:A(e?.[T.label])??t.label}}function Be(e){return new Map(e.flatMap(e=>e.taskIds.map(t=>[t,e.id])))}function Ve(e){let t=[`select`];return(0,d.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 He(e){return e.kind===`agent`?e.agentType??e.cwd:e.status===`sleeping`&&e.nextFireAt!==void 0?`next: ${Ue(e.nextFireAt)}`:e.cwd}function Ue(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 We(e){return e.status===`failed`?k(e.error?.message):e.status===`completed`?k(e.result?.output):k(e.promptPreview??e.commandPreview)}function Ge(e){return e.status===`failed`?`failed`:e.status===`waiting_permission`?`permission`:e.unread?`unread`:e.status===`completed`?`completed`:`none`}function Ke(e){return e.status===`completed`&&!e.unread&&!e.error&&(e.result?.exitCode??0)===0&&!e.result?.signalCode&&!e.worktreePath&&!e.branchName?`collapsed`:`default`}function qe(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`none`}function Je(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 Ye(e){return[...e].sort((e,t)=>(t.lastActivityAt??t.updatedAt).localeCompare(e.lastActivityAt??e.updatedAt))}function Xe(e){return[...e].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}function k(e){let t=e?.trim().replace(/\s+/g,` `);if(t)return t.length>120?`${t.slice(0,120)}...`:t}function A(e){return typeof e==`string`?e:void 0}function Ze(e){if(e===`user_prompt`||e===`slash_command`||e===`model_command`||e===`tool_call`||e===`skill`||e===`transport`||e===`system`)return e}function Qe(e){let t=$e(e.cursor?.offset),n=e.history.slice(t,t+80),r=n.map(e=>({id:e.id,kind:e.category===`chat`?`message`:`progress`,text:et(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 j(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 $e(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function et(e){return typeof e.data==`string`?e.data:e.type}function tt(e){return{spawnAgent:t=>e.manager.spawn(nt(e,t)),spawnProcess:t=>e.manager.spawn(rt(e,t)),createGroup:t=>e.groupOrchestrator.createGroup({parentSessionId:e.sessionId,waitPolicy:t.waitPolicy,taskIds:[...t.taskIds],label:t.label})}}function nt(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:O(e.origin)}}function rt(e,t){return{kind:`process`,label:t.label??t.command,mode:t.mode??`background`,parentSessionId:e.sessionId,parentTaskId:t.parentTaskId,depth:t.depth??0,cwd:t.cwd??e.cwd,command:t.command,shell:t.shell,env:t.env,stdin:t.stdin,timeoutMs:t.timeoutMs,idleTimeoutMs:t.idleTimeoutMs,maxRuntimeMs:t.maxRuntimeMs,outputLimitBytes:t.outputLimitBytes,metadata:O(e.origin)}}function it(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(`
|
|
48
|
+
|
|
49
|
+
`),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 at(){return`agent_group_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function ot(e,t){let n=e?.trim();return n&&n.length>0?n:t}function st(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:ot(e.label,i?.name??r)}}function ct(e){return e.agentDef!==void 0}function lt(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 ut(e,t){try{let n=await t.manager.spawn(t.createSpawnRequest(e.job,e.agentType,e.agentDef,t.deps,e.label));return{...e,agentId:n.id}}catch(t){let n=t instanceof Error?t.message:String(t);return{...e,spawnError:n}}}function dt(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 ft(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 mt(e,t,n){if(e.agentId===void 0)return dt(e,t);try{let r=await n.wait(e.agentId);return ft({...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 ht(e){let t=at(),n=e.jobs.map((t,n)=>st(t,n,e)),r=n.filter(e=>!ct(e)).map(e=>lt(e,t)),i=await Promise.all(n.filter(ct).map(t=>ut(t,e))),a=await Promise.all(i.map(n=>mt(n,t,e.manager))),o=[...r,...a].sort((e,t)=>e.index-t.index);return it({groupId:t,requestedJobCount:e.jobs.length,jobs:o})}function gt(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 _t(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 vt(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 yt=[`Creates delegated subagent jobs in isolated contexts.`,`Without jobs, one tool call creates one subagent job from prompt.`,`For explicit multi-agent or parallel-agent requests, use one Agent tool call with jobs containing one entry per requested role and a stable label for each role.`,`When the user explicitly asks to create, run, spawn, delegate to, or use agents/subagents, start the requested subagent job immediately.`,`Do not ask a follow-up question unless execution is impossible or unsafe.`,`Subagent jobs run as background tasks by default.`,`The tool waits for a terminal result and returns completed, failed, or timed-out outcome data with structured requested/started job counts.`,`After the tool returns, base user-facing claims on returned mode and counts; do not say parallel or multiple jobs started unless the result proves those jobs started.`,`Execution is represented by a real tool call and runtime background task event.`].join(` `);function bt(e){return e}const xt=l.z.object({prompt:l.z.string().optional().describe(`The task for a single subagent to perform. Required when jobs is omitted.`),subagent_type:l.z.string().optional().describe(`Agent type: "general-purpose", "Explore", "Plan", or a custom agent name`),model:l.z.string().optional().describe(`Optional model override`),isolation:l.z.enum([`none`,`worktree`]).optional().describe(`Optional runtime isolation mode. "worktree" runs in a Git worktree.`),jobs:l.z.array(l.z.object({label:l.z.string().optional().describe(`Stable role label for this batch job`),prompt:l.z.string().describe(`The task for this subagent to perform`),subagent_type:l.z.string().optional().describe(`Agent type for this job`),model:l.z.string().optional().describe(`Optional model override for this job`),isolation:l.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(),St=new WeakMap;function Ct(e,t){St.set(e,t)}function M(e){return St.get(e)}function wt(e,t){if(t){let n=t(e);if(n)return n}let n=x(e);if(n)return n}function Tt(e){return e.subagentManager??new d.SubagentManager({runner:Se(e)})}function Et(e,t,n,r,i=n.name){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:O({kind:`tool_call`,sessionId:r.parentSessionId??`unknown-session`,label:i})}}async function Dt(e,t,n){if(typeof e.prompt!=`string`||e.prompt.length===0)return vt(`prompt is required when jobs is omitted`);let r={...e,prompt:e.prompt},i=e.subagent_type??`general-purpose`,a=wt(i,t.customAgentRegistry);if(!a)return gt(i);let o;try{let e=await n.spawn(Et(r,i,a,t));return o=e.id,_t(await n.wait(e.id))}catch(e){return vt(e instanceof Error?e.message:String(e),o)}}function Ot(e){let t=Tt(e);return(0,u.createZodFunctionTool)(`Agent`,yt,bt(xt),async n=>{let r=n;return Array.isArray(r.jobs)&&r.jobs.length>0?ht({jobs:r.jobs,deps:e,manager:t,resolveAgentDefinition:wt,createSpawnRequest:Et}):Dt({prompt:r.prompt,...r.subagent_type===void 0?{}:{subagent_type:r.subagent_type},...r.model===void 0?{}:{model:r.model},...r.isolation===void 0?{}:{isolation:r.isolation}},e,t)})}function kt(e,t,n){let r=M(n)?.customAgentRegistry?.(e)??x(e);if(!r)throw Error(`Unknown agent type: ${e}`);return t.allowedTools?{...r,tools:t.allowedTools}:r}async function At(e,t,n){let r=M(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);return ge({agentDefinition:kt(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)}const jt=new WeakMap;function Mt(e,t){jt.set(e,t)}function Nt(e){return jt.get(e)}function Pt(e,t,n,r,i,a,o,s,c,l){try{let u=t.getSessionId(),d=e.load(u),f=l?.snapshotId??d?.sandboxSnapshotId;e.save(Ft({session:t,sessionId:u,sessionName:n??d?.name,cwd:r,history:i,createdAt:d?.createdAt,backgroundState:a,memoryState:o,skillActivationState:s,contextReferenceState:c,...f===void 0?{}:{sandboxSnapshotId:f}}))}catch{}}function Ft(e){return{id:e.sessionId,...e.sessionName===void 0?{}:{name:e.sessionName},cwd:e.cwd,createdAt:e.createdAt??new Date().toISOString(),updatedAt:new Date().toISOString(),messages:e.session.getHistory(),history:e.history,systemPrompt:e.session.getSystemMessage(),toolSchemas:e.session.getToolSchemas(),...e.sandboxSnapshotId===void 0?{}:{sandboxSnapshotId:e.sandboxSnapshotId},...It(e.backgroundState),...Lt(e.memoryState),...Rt(e.skillActivationState),...zt(e.contextReferenceState)}}function It(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function Lt(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function Rt(e){return e?{skillActivationEvents:[...e.events]}:{}}function zt(e){return e?{contextReferences:[...e.references]}:{}}function Bt(e,t){typeof t.content==`string`&&(t.role===`tool`?e.injectMessage(`tool`,t.content,{toolCallId:t.toolCallId,...t.name===void 0?{}:{name:t.name}}):e.injectMessage(t.role,t.content))}function Vt(e,t,n,r){let i=e.load(t);if(!i)return{history:[],sessionName:void 0,pendingRestoreMessages:null,backgroundTasks:[],backgroundTaskEvents:[],backgroundJobGroups:[],backgroundJobGroupEvents:[],skillActivationEvents:[],memoryEvents:[],usedMemoryReferences:[],contextReferences:[],sandboxSnapshotId:void 0};let a=i.history??[],o=i.backgroundTasks??[],s=i.backgroundTaskEvents??[],c=i.backgroundJobGroups??[],l=i.backgroundJobGroupEvents??[],u=i.skillActivationEvents??[],d=i.memoryEvents??[],f=i.usedMemoryReferences??[],p=i.contextReferences??[],m=i.sandboxSnapshotId,{backgroundTasks:h,backgroundTaskEvents:g}=Ht(o,s),_=i.name,v=null;if(!n&&i.messages)if(r)for(let e of i.messages)Bt(r,e);else v=i.messages;return{history:a,sessionName:_,pendingRestoreMessages:v,backgroundTasks:h,backgroundTaskEvents:g,backgroundJobGroups:c,backgroundJobGroupEvents:l,skillActivationEvents:u,memoryEvents:d,usedMemoryReferences:f,contextReferences:p,sandboxSnapshotId:m}}function Ht(e,t){let n=new Date().toISOString(),r=[];return{backgroundTasks:e.map(e=>{if(Ut(e.status))return e;let t={...e,status:`failed`,timeoutReason:`stale_worker`,error:{category:`timeout`,message:`Restored background task is stale; worker cannot be reattached`,recoverable:!0},unread:!0,completedAt:n,updatedAt:n};return r.push({type:`background_task_failed`,task:t}),t}),backgroundTaskEvents:[...t,...r]}}function Ut(e){return e===`completed`||e===`failed`||e===`cancelled`}function Wt(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var Gt=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=Wt(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)}}}};function Kt(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var qt=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=Kt(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)}}}};const Jt=[`Bash — execute shell commands`,`Read — read file contents with line numbers`,`Write — write content to a file`,`Edit — replace a string in a file`,`Glob — find files matching a pattern`,`Grep — search file contents with regex`,`WebFetch — fetch URL content as text`,`WebSearch — search the internet through the configured local tool`];function Yt(e={}){return[(0,u.createBashTool)(e),(0,u.createReadTool)(e),(0,u.createWriteTool)(e),(0,u.createEditTool)(e),u.globTool,u.grepTool,u.webFetchTool,u.webSearchTool]}const Xt=new Set([`Write`,`Edit`]);function Zt(e,t){return e.map(e=>Xt.has(e.getName())?new Qt(e,t):e)}var Qt=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=$t(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 $t(e){if(!e||typeof e!=`object`)return;let t=e.filePath;return typeof t==`string`&&t.length>0?t:void 0}const en=new Set([`Write`,`Edit`]),tn=new Set([`Bash`,`BackgroundProcess`]),nn=new Set([`Read`,`Glob`,`Grep`,`WebFetch`,`WebSearch`]);function rn(e){let t=e.toolName;return nn.has(t)?{toolName:t,reversible:!0,sideEffect:`none`,rollbackLayer:`none`,status:`read-only`,message:`${t} does not mutate the local workspace.`}:en.has(t)?e.context.isolation===`worktree`||e.context.isolation===`provider-sandbox`?sn(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.`}:tn.has(t)?sn(t,`shell-process`,e.context):t===`Agent`?cn(e.toolArgs,e.context):{toolName:t,reversible:!1,sideEffect:`unknown`,rollbackLayer:`none`,status:`unknown`,message:`${t} has no reversible execution contract.`}}function an(e,t){let n={checkpointAvailable:t.checkpointAvailable,isolation:t.isolation??`none`},r=t.enforceUntrackedSideEffects??!0;return e.map(e=>new on(e,{safetyContext:n,enforceUntrackedSideEffects:r}))}var on=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=rn({toolName:this.getName(),toolArgs:fn(e),context:this.options.safetyContext});return!n.reversible&&this.options.enforceUntrackedSideEffects?pn(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 sn(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 cn(e,t){return t.isolation===`worktree`||t.isolation===`provider-sandbox`?sn(`Agent`,`subagent`,t):ln(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 ln(e){if(!e)return!1;let t=e.jobs;return Array.isArray(t)?t.length>0&&t.every(e=>dn(e)?un(e)===`worktree`:!1):un(e)===`worktree`}function un(e){let t=e.isolation;return typeof t==`string`?t:void 0}function dn(e){return e!==void 0&&typeof e==`object`&&!Array.isArray(e)}function fn(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e}function pn(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}}}var N=class{existsSync(e){return(0,g.existsSync)(e)}readFileSync(e,t){return(0,g.readFileSync)(e,t)}writeFileSync(e,t,n){(0,g.writeFileSync)(e,t,n??`utf8`)}mkdirSync(e,t){(0,g.mkdirSync)(e,t)}readdirSync(e,t){return t?.withFileTypes?(0,g.readdirSync)(e,{withFileTypes:!0}):(0,g.readdirSync)(e)}statSync(e){return(0,g.statSync)(e)}rmSync(e,t){(0,g.rmSync)(e,t)}cpSync(e,t,n){(0,g.cpSync)(e,t,n)}renameSync(e,t){(0,g.renameSync)(e,t)}get constants(){return g.constants}},P=class{async access(e,t){await(0,_.access)(e,t)}async copyFile(e,t,n){await(0,_.copyFile)(e,t,n)}async mkdir(e,t){await(0,_.mkdir)(e,t)}async readFile(e,t){return(0,_.readFile)(e,t)}async readdir(e,t){return t?.withFileTypes?await(0,_.readdir)(e,{withFileTypes:!0}):(0,_.readdir)(e)}async realpath(e){return(0,_.realpath)(e)}async rename(e,t){await(0,_.rename)(e,t)}async rm(e,t){await(0,_.rm)(e,t)}async stat(e){return(0,_.stat)(e)}async writeFile(e,t,n){await(0,_.writeFile)(e,t,n??`utf8`)}};const mn=new Set([`disable-model-invocation`,`user-invocable`]),hn=new Set([`allowed-tools`]);function gn(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function _n(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function vn(e){let t=e.split(`
|
|
50
|
+
`);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=gn(a);mn.has(a)?n[s]=o===`true`:hn.has(a)?n[s]=_n(o):n[s]=o}return Object.keys(n).length>0?n:null}function yn(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 bn(e,t){if(!t.existsSync(e))return[];let n=[],r=t.readdirSync(e,{withFileTypes:!0});for(let i of r){if(!i.isDirectory())continue;let r=(0,m.join)(e,i.name,`SKILL.md`);if(!t.existsSync(r))continue;let a=t.readFileSync(r,`utf-8`),o=vn(a);n.push(yn(o,a,i.name))}return n}function xn(e,t){if(!t.existsSync(e))return[];let n=[],r=t.readdirSync(e,{withFileTypes:!0});for(let i of r){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let r=(0,m.join)(e,i.name),a=t.readFileSync(r,`utf-8`),o=vn(a),s=(0,m.basename)(i.name,`.md`);n.push(yn(o,a,s))}return n}var Sn=class{name=`skill`;cwd;home;fs;cachedCommands=null;constructor(e,t,n=new N){this.cwd=e,this.home=t??(0,h.homedir)(),this.fs=n}getCommands(){if(this.cachedCommands)return this.cachedCommands;let e=[bn((0,m.join)(this.cwd,`.claude`,`skills`),this.fs),xn((0,m.join)(this.cwd,`.claude`,`commands`),this.fs),bn((0,m.join)(this.home,`.robota`,`skills`),this.fs),bn((0,m.join)(this.cwd,`.agents`,`skills`),this.fs)],t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.name)||(t.add(e.name),n.push(e));return this.cachedCommands=n,this.cachedCommands}getModelInvocableSkills(){return this.getCommands().filter(e=>e.disableModelInvocation!==!0)}getUserInvocableSkills(){return this.getCommands().filter(e=>e.userInvocable!==!1)}};const Cn=new Set([`tools`,`disallowedTools`]),wn=new Set([`maxTurns`]);function Tn(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function En(e){let t=e.split(`
|
|
51
|
+
`);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();Cn.has(i)?r[i]=Tn(a):wn.has(i)?r[i]=parseInt(a,10):r[i]=a}let i=t.slice(n+1).join(`
|
|
52
|
+
`).trim();return{frontmatter:Object.keys(r).length>0?r:null,body:i}}function F(e,t){if(!t.existsSync(e))return[];let n=[],r;try{r=t.readdirSync(e,{withFileTypes:!0})}catch{return[]}for(let i of r){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let r=(0,m.join)(e,i.name),{frontmatter:a,body:o}=En(t.readFileSync(r,`utf-8`)),s=(0,m.basename)(i.name,`.md`),c={name:a?.name??s,description:a?.description??``,systemPrompt:o};a?.model!==void 0&&(c.model=a.model),a?.maxTurns!==void 0&&(c.maxTurns=a.maxTurns),a?.tools!==void 0&&(c.tools=a.tools),a?.disallowedTools!==void 0&&(c.disallowedTools=a.disallowedTools),n.push(c)}return n}var Dn=class{cwd;home;fs;constructor(e,t,n=new N){this.cwd=e,this.home=t??(0,h.homedir)(),this.fs=n}loadAll(){let e=[F((0,m.join)(this.cwd,`.robota`,`agents`),this.fs),F((0,m.join)(this.cwd,`.agents`,`agents`),this.fs),F((0,m.join)(this.cwd,`.claude`,`agents`),this.fs),F((0,m.join)(this.home,`.robota`,`agents`),this.fs),F((0,m.join)(this.home,`.claude`,`agents`),this.fs)],t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.name)||(t.add(e.name),n.push(e));let r=[...n];for(let e of b)t.has(e.name)||r.push(e);return r}getAgent(e){return this.loadAll().find(t=>t.name===e)}};function On(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 kn(e,t,n,r){let i=On(e);!i||!(`task`in e)||(0,c.runHooks)(n,i,{session_id:e.task.parentSessionId,cwd:t,hook_event_name:i,agent_id:e.task.id,agent_type:e.task.agentType??e.task.label,...e.task.transcriptPath?{agent_transcript_path:e.task.transcriptPath,transcript_path:e.task.transcriptPath}:{},...e.task.error?.message||e.task.timeoutReason?{reason:e.task.error?.message??e.task.timeoutReason}:{},...i===`SubagentStop`?{stop_hook_active:!1,...e.task.result?.output?{last_assistant_message:e.task.result.output}:{}}:{},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e.task.parentSessionId,ROBOTA_AGENT_ID:e.task.id,ROBOTA_AGENT_TYPE:e.task.agentType??e.task.label}},r).catch(()=>void 0)}function An(e){return e}const jn=l.z.object({command:l.z.string().describe(`The shell command to start in the background`),timeout:l.z.number().optional().describe(`Optional timeout in milliseconds. Default is 120000.`),workingDirectory:l.z.string().optional().describe(`Working directory for the command. Defaults to the current project directory.`),stdin:l.z.string().optional().describe(`Optional stdin to write after the process starts.`),outputLimitBytes:l.z.number().optional().describe(`Maximum captured output bytes kept in the task result.`)});function Mn(e,t,n){return JSON.stringify({success:!0,background:!0,output:``,taskId:e,status:t,command:n})}function Nn(e){return JSON.stringify({success:!1,background:!0,output:``,error:`Background process error: ${e}`})}async function Pn(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 Mn(n.id,n.status,e.command)}catch(e){return Nn(e instanceof Error?e.message:String(e))}}function Fn(e){return(0,u.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.`,An(jn),async t=>Pn(t,e))}function In(e){let t=e.content.trim();return e.title?[`## ${e.title}`,t].join(`
|
|
53
|
+
`):t}function Ln(e){return[...e].filter(e=>e.content.trim().length>0).sort((e,t)=>e.priority-t.priority||e.id.localeCompare(t.id)).map(e=>In(e)).join(`
|
|
54
|
+
|
|
55
|
+
`)}const Rn={safe:`safe`,moderate:`moderate`,full:`full`};function I(e,t,n,r,i){return{id:e,title:t,priority:n,content:r,source:i}}function zn(e){if(e)return I(`runtime-cwd`,`Working Directory`,30,`\`${e}\``,`runtime`)}function Bn(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}`),I(`runtime-project`,`Current Project`,40,t.join(`
|
|
56
|
+
`),`runtime`)}function Vn(e){return I(`permission-mode`,`Permission Mode`,50,`- **Trust level:** ${Rn[e]}`,`permissions`)}function Hn(e){if(!(e===void 0||e.trim().length===0))return I(`runtime-response-language`,`Response Language`,45,e,`runtime`)}function Un(e){if(e.trim().length!==0)return I(`project-agents-md`,`Agent Instructions`,10,e,`project-instructions`)}function Wn(e){if(e.trim().length!==0)return I(`project-claude-md`,`Project Notes`,20,e,`project-instructions`)}function Gn(e){if(!(e===void 0||e.trim().length===0))return I(`project-memory`,`Project Memory`,25,e,`project-instructions`)}function Kn(e){if(!(e===void 0||e.trim().length===0))return I(`active-task-context`,`Active Task Context`,27,e,`project-instructions`)}function qn(e){if(e.length!==0)return I(`tool-descriptions`,`Available Tools`,60,e.map(e=>`- ${e}`).join(`
|
|
57
|
+
`),`tool`)}function Jn(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}`}function L(e,t,n,r,i){let a=i.filter(t=>t.modelInvocable&&t.kind===e).map(Jn);if(a.length!==0)return I(`capability-${e}`,t,n,a.join(`
|
|
58
|
+
`),r)}function Yn(e){let t=[],n=L(`builtin-command`,`Built-in Commands`,70,`command`,e),r=L(`skill`,`Skills`,80,`skill`,e),i=L(`agent`,`Agents`,90,`agent`,e),a=L(`tool`,`Tools`,100,`tool`,e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),a&&t.push(a),t}function R(e,t){t!==void 0&&e.push(t)}function Xn(e){return e.map(e=>({name:e.name,kind:`skill`,description:e.description,userInvocable:!0,modelInvocable:e.disableModelInvocation!==!0}))}function Zn(e){return e.map(e=>({name:e.name,kind:`agent`,description:e.description,userInvocable:!1,modelInvocable:!0,safety:`background-agent`}))}function Qn(e){return[...e.commandDescriptors??[],...e.skills?Xn(e.skills):[],...e.agents?Zn(e.agents):[]]}function $n(e){let t=[];return R(t,Un(e.agentsMd)),R(t,Wn(e.claudeMd)),R(t,Gn(e.memoryMd)),R(t,Kn(e.taskContext)),R(t,zn(e.cwd)),t.push(Bn(e.projectInfo)),R(t,Hn(e.language)),t.push(Vn(e.trustLevel)),R(t,qn(e.toolDescriptions)),t.push(...Yn(Qn(e))),Ln(t)}function er(e,t,n,r,i,a){let o,s=[],c;if(e.enableAgentRuntime){let l=new Dn(n);s=l.loadAll(),o={config:e.config,context:e.context,tools:i,terminal:e.terminal,provider:r,cwd:n,parentSessionId:t,permissionMode:e.permissionMode,permissionHandler:e.permissionHandler,hooks:e.config.hooks,hookTypeExecutors:a.length>0?a:void 0,onTextDelta:e.onTextDelta,onToolExecution:e.onToolExecution,customAgentRegistry:e=>l.getAgent(e),agentDefinitions:s};let u=new d.SubagentManager({runner:(e.subagentRunnerFactory??Se)(o),backgroundTaskRunners:e.backgroundTaskRunners});o.subagentManager=u,c=u.getBackgroundTaskManager(),o.backgroundTaskManager=c}else c=new d.BackgroundTaskManager({runners:e.backgroundTaskRunners??[]});let l=e.sessionLogger;return l&&c.subscribe(e=>ir(l,t,e)),c.subscribe(t=>kn(t,n,e.config.hooks,a.length>0?a:void 0)),{agentToolDeps:o,agentDefinitions:s,backgroundTaskManager:c}}function tr(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:O({kind:`tool_call`,sessionId:n,label:`BackgroundProcess`})};return i.push(Fn(a)),{backgroundProcessToolDeps:a}}function nr(e,t,n,r,i,a,o){let s=e.systemPromptBuilder??$n,c=[...Jt,...r?r.commandTools.map(se):[]],l=e.toolDescriptions??(i?[...c,`BackgroundProcess — start long-running shell commands as managed background tasks`]:c),u={agentsMd:e.context.agentsMd,claudeMd:e.context.claudeMd,memoryMd:e.context.memoryMd,taskContext:e.context.taskContext,toolDescriptions:l,trustLevel:e.config.defaultTrustLevel,projectInfo:e.projectInfo??{type:`unknown`,language:`unknown`},cwd:t,language:e.config.language,skills:a.map(e=>({name:e.name,description:e.description,disableModelInvocation:e.disableModelInvocation})),...o.length>0?{agents:o.map(e=>({name:e.name,description:e.description}))}:{},commandDescriptors:e.commandDescriptors??[]},d=s(u);return{finalSystemMessage:e.appendSystemPrompt?`${d}\n\n${e.appendSystemPrompt}`:d,rebuildSystemMessage:(t,n)=>{let r=s({...u,agentsMd:t,claudeMd:n});return e.appendSystemPrompt?`${r}\n\n${e.appendSystemPrompt}`:r}}}function rr(e,t,n,r){t&&(t.parentSessionId=e.getSessionId()),n&&(n.parentSessionId=e.getSessionId()),Mt(e,r),t&&Ct(e,t)}function ir(e,t,n){e.log(t,`background_task_event`,{backgroundEventType:n.type,backgroundEvent:n})}function ar(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function or(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function sr(e,t){return e.some(e=>or(e.name)===t)}function cr(e){if(!e.provider)throw Error(`provider is required. SDK is provider-neutral — consumer must create and pass a provider instance.`);let t=e.provider,n=e.cwd??process.cwd(),r=e.sessionId??lr(),i=new Sn(n),a=ar(e.commandDescriptors),o=a.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,s=o?oe(a):void 0,c=sr(a,`skills`)?i.getModelInvocableSkills():[],l=Yt({sandboxClient:e.sandboxClient}),u=e.editCheckpointRecorder!==void 0&&e.sandboxClient===void 0,d=[...u&&e.editCheckpointRecorder?Zt(l,e.editCheckpointRecorder):l,...e.additionalTools??[]],p=e.reversibleExecution?{...e.reversibleExecution,isolation:e.reversibleExecution.isolation??(e.sandboxClient?`provider-sandbox`:void 0)}:void 0,m=p?an(d,{...p,checkpointAvailable:u}):d;o&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&m.push(...le({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:a}));let h=[];e.providerFactory&&h.push(new Gt({providerFactory:e.providerFactory,defaultModel:e.config.provider.model})),e.sessionFactory&&h.push(new qt({sessionFactory:e.sessionFactory})),e.additionalHookExecutors&&h.push(...e.additionalHookExecutors);let{agentToolDeps:g,agentDefinitions:_,backgroundTaskManager:v}=er(e,r,n,t,m,h),{backgroundProcessToolDeps:y}=tr(e,v,r,n,m),{finalSystemMessage:b,rebuildSystemMessage:x}=nr(e,n,a,s,y,c,_),ee=[`Read(.agents/**)`,`Read(.claude/**)`,`Read(.robota/**)`,`Glob(.agents/**)`,`Glob(.claude/**)`,`Glob(.robota/**)`],te=(e.allowedTools??[]).map(e=>`${e}(*)`),ne={allow:[...ee,...e.config.permissions.allow??[],...te],deny:e.config.permissions.deny??[]},S=new f.Session({tools:m,provider:t,systemMessage:b,terminal:e.terminal,permissions:ne,hooks:e.config.hooks,permissionMode:e.permissionMode,defaultTrustLevel:e.config.defaultTrustLevel,model:e.config.provider.model,providerTimeout:e.config.provider.timeout??12e4,maxTurns:e.maxTurns,sessionStore:e.sessionStore,sessionId:r,permissionHandler:e.permissionHandler,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:h.length>0?h:void 0,agentName:e.agentName});return rr(S,g,y,v),{session:S,rebuildSystemMessage:x}}function lr(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function ur(e,t,n,r=new N){let i=(0,m.join)(n,e,`subagents`);return r.mkdirSync(i,{recursive:!0}),new f.FileSessionLogger(i)}function dr(e,t){return(0,m.join)(t,e,`subagents`)}function z(e){let t=(0,m.join)(e,`.robota`);return{settings:(0,m.join)(t,`settings.json`),settingsLocal:(0,m.join)(t,`settings.local.json`),logs:(0,m.join)(t,`logs`),sessions:(0,m.join)(t,`sessions`),memory:(0,m.join)(t,`memory`),checkpoints:(0,m.join)(t,`checkpoints`)}}function fr(){let e=(0,m.join)((0,h.homedir)(),`.robota`);return{settings:(0,m.join)(e,`settings.json`),sessions:(0,m.join)(e,`sessions`)}}const B=l.z.lazy(()=>l.z.union([l.z.string(),l.z.number(),l.z.boolean(),l.z.null(),l.z.undefined(),l.z.date(),l.z.array(B),l.z.record(B)])),pr=l.z.object({name:l.z.string().optional(),model:l.z.string().optional(),apiKey:l.z.string().optional(),baseURL:l.z.string().optional(),timeout:l.z.number().optional(),options:l.z.record(B).optional()}),mr=l.z.object({type:l.z.string().optional(),model:l.z.string().optional(),apiKey:l.z.string().optional(),baseURL:l.z.string().optional(),timeout:l.z.number().optional(),options:l.z.record(B).optional()}),hr=l.z.object({allow:l.z.array(l.z.string()).optional(),deny:l.z.array(l.z.string()).optional()}),gr=l.z.record(l.z.string()).optional(),_r=l.z.object({type:l.z.literal(`command`),command:l.z.string(),timeout:l.z.number().optional()}),vr=l.z.object({type:l.z.literal(`http`),url:l.z.string(),headers:l.z.record(l.z.string()).optional(),timeout:l.z.number().optional()}),yr=l.z.object({type:l.z.literal(`prompt`),prompt:l.z.string(),model:l.z.string().optional()}),br=l.z.object({type:l.z.literal(`agent`),agent:l.z.string(),maxTurns:l.z.number().optional(),timeout:l.z.number().optional()}),xr=l.z.discriminatedUnion(`type`,[_r,vr,yr,br]),V=l.z.object({matcher:l.z.string(),hooks:l.z.array(xr)}),Sr=l.z.object({PreToolUse:l.z.array(V).optional(),PostToolUse:l.z.array(V).optional(),SessionStart:l.z.array(V).optional(),SessionEnd:l.z.array(V).optional(),Stop:l.z.array(V).optional(),StopFailure:l.z.array(V).optional(),PreCompact:l.z.array(V).optional(),PostCompact:l.z.array(V).optional(),UserPromptSubmit:l.z.array(V).optional(),SubagentStart:l.z.array(V).optional(),SubagentStop:l.z.array(V).optional(),WorktreeCreate:l.z.array(V).optional(),WorktreeRemove:l.z.array(V).optional()}).optional(),Cr=l.z.record(l.z.boolean()).optional(),wr=l.z.object({source:l.z.object({type:l.z.enum([`github`,`git`,`local`,`url`]),repo:l.z.string().optional(),url:l.z.string().optional(),path:l.z.string().optional(),ref:l.z.string().optional()})}),Tr=l.z.record(wr).optional().catch(void 0),Er=l.z.union([l.z.number().gt(0).lte(1),l.z.literal(!1)]).optional(),Dr=l.z.object({enabled:l.z.boolean().optional(),options:l.z.record(B).optional()}),Or=l.z.object({defaultTrustLevel:l.z.enum([`safe`,`moderate`,`full`]).optional(),language:l.z.string().optional(),currentProvider:l.z.string().optional(),providers:l.z.record(mr).optional(),provider:pr.optional(),permissions:hr.optional(),env:gr,hooks:Sr,enabledPlugins:Cr,extraKnownMarketplaces:Tr,autoCompactThreshold:Er,transports:l.z.record(Dr).optional()});function kr(){return process.env.HOME??process.env.USERPROFILE??`/`}const H={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[]},env:{}};function Ar(e){if(!(0,v.existsSync)(e))return;let t=(0,v.readFileSync)(e,`utf-8`).trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function jr(e){if(e.startsWith(`$ENV:`)){let t=e.slice(5);return process.env[t]??e}return e}function Mr(e){let t=e.provider?.apiKey===void 0?e.provider:Nr(e.provider);if(e.providers!==void 0){let n=Object.fromEntries(Object.entries(e.providers).map(([e,t])=>[e,Nr(t)]));return{...e,provider:t,providers:n}}return{...e,provider:t}}function Nr(e){return{...e,...e.apiKey!==void 0&&{apiKey:jr(e.apiKey)}}}function Pr(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?Fr(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 Fr(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function Ir(e){if(e.currentProvider!==void 0)return Lr(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...H.provider}}function Lr(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??H.provider.model,apiKey:n.apiKey??H.provider.apiKey,...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function Rr(e){return{defaultTrustLevel:e.defaultTrustLevel??H.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:Ir(e),permissions:{allow:e.permissions?.allow??H.permissions.allow,deny:e.permissions?.deny??H.permissions.deny},env:e.env??H.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold}}function zr(e){let t=kr();return[(0,y.join)(t,`.robota`,`settings.json`),(0,y.join)(t,`.claude`,`settings.json`),(0,y.join)(e,`.robota`,`settings.json`),(0,y.join)(e,`.robota`,`settings.local.json`),(0,y.join)(e,`.claude`,`settings.json`),(0,y.join)(e,`.claude`,`settings.local.json`)]}async function Br(e){let t=zr(e),n=[];for(let e of t){let t=Ar(e);t!==void 0&&n.push({raw:t,path:e})}return Rr(Pr(n.map(({raw:e,path:t})=>{let n=Or.safeParse(e);if(!n.success)throw Error(`Invalid settings in ${t}: ${n.error.message}`);return Mr(n.data)})))}const Vr=25600,Hr=[`user`,`feedback`,`project`,`reference`];function Ur(e){return Hr.includes(e)}function Wr(e){return(0,y.join)(e,`.robota`,`memory`)}function Gr(e,t){let n=Buffer.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function Kr(e,t){let n=e.split(/\r?\n/);return{content:n.slice(0,t).join(`
|
|
59
|
+
`).trimEnd(),truncated:n.length>t}}function qr(e){return e.trim().toLowerCase().replace(/[^a-z0-9가-힣_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`general`}function Jr(e,t,n){let r=e.toISOString().slice(0,10),i=t.text.trim().replace(/\s+/g,` `);return`[${r}] (${t.type}/${n}) ${i}`}function Yr(e){return e.trim().replace(/\s+/g,` `)}var Xr=class{cwd;now;constructor(e,t=()=>new Date){this.cwd=e,this.now=t}getIndexPath(){return(0,y.join)(Wr(this.cwd),`MEMORY.md`)}getTopicsPath(){return(0,y.join)(Wr(this.cwd),`topics`)}loadStartupMemory(){let e=this.getIndexPath();if(!(0,v.existsSync)(e))return{content:``,path:e,lineCount:0,truncated:!1};let t=(0,v.readFileSync)(e,`utf8`),n=Gr(t,Vr),r=Buffer.byteLength(t,`utf8`)>Vr,i=Kr(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,v.existsSync)(e)?(0,v.readdirSync)(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(t=>({name:(0,y.basename)(t.name,`.md`),path:(0,y.join)(e,t.name)})).sort((e,t)=>e.name.localeCompare(t.name)):[];return{indexPath:this.getIndexPath(),topicsPath:e,topics:t}}readTopic(e){let t=qr(e),n=(0,y.join)(this.getTopicsPath(),`${t}.md`);return(0,v.existsSync)(n)?(0,v.readFileSync)(n,`utf8`).trimEnd():``}append(e){let t=qr(e.topic),n=Wr(this.cwd),r=this.getTopicsPath();(0,v.mkdirSync)(r,{recursive:!0});let i=this.getIndexPath(),a=(0,y.join)(r,`${t}.md`),o=Jr(this.now(),e,t),s=(0,v.existsSync)(a)?``:`# ${t}\n\n`,c=Yr(e.text);return(0,v.existsSync)(a)&&(0,v.readFileSync)(a,`utf8`).includes(`) ${c}`)?{indexPath:i,topicPath:a,topic:t,deduplicated:!0}:((0,v.existsSync)(i)||((0,v.mkdirSync)(n,{recursive:!0}),(0,v.writeFileSync)(i,`# Project Memory
|
|
60
|
+
|
|
61
|
+
`,`utf8`)),(0,v.appendFileSync)(i,`- ${o}\n`,`utf8`),(0,v.appendFileSync)(a,`${s}- ${o}\n`,`utf8`),{indexPath:i,topicPath:a,topic:t,deduplicated:!1})}};const Zr=(0,m.join)(`.agents`,`tasks`),Qr={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function $r(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function ei(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||(0,m.basename)(t,`.md`)}function ti(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function ni(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(`
|
|
62
|
+
`).trim();return o.length>0?o:void 0}function ri(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(.+)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function ii(e,t){return t&&e.branch===t?0:Qr[e.status]}function ai(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(`
|
|
63
|
+
`)}function oi(e){return e.toISOString().slice(0,10)}function si(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(`
|
|
64
|
+
`)):(n.length>0&&/^#\s+/.test(n[0])?n.splice(1,0,``,r):n.unshift(r,``),n.join(`
|
|
65
|
+
`))}function ci(e,t,n){let r=[`### ${oi(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(`
|
|
66
|
+
`);let o=i.findIndex((e,t)=>t>a&&/^##\s+/.test(e));return o<0?[...i,``,...r,``].join(`
|
|
67
|
+
`):(i.splice(o,0,``,...r,``),i.join(`
|
|
68
|
+
`))}function li(e,t){let n=(0,m.resolve)(e),r=!1;for(;!r;){let e=(0,m.join)(n,`.git`);if(t.existsSync(e)){if(t.statSync(e).isDirectory())return e;let r=t.readFileSync(e,`utf8`).trim().match(/^gitdir:\s*(.+)$/)?.[1];if(r)return(0,m.isAbsolute)(r)?r:(0,m.resolve)(n,r)}let i=(0,m.dirname)(n);r=i===n,n=i}}function ui(e,t=new N){let n=li(e,t);if(!n)return;let r=(0,m.join)(n,`HEAD`);if(t.existsSync(r))return(t.readFileSync(r,`utf8`).trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1])?.trim()}function di(e,t=new N){let n=(0,m.join)(e,Zr);return t.existsSync(n)?t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isFile()).map(e=>e.name).filter(e=>e!==`README.md`&&e.endsWith(`.md`)).sort((e,t)=>e.localeCompare(t)).map(e=>(0,m.join)(n,e)):[]}function fi(e,t,n=new N){let r=n.readFileSync(e,`utf8`);return{path:e,relativePath:(0,m.relative)(t,e),title:ei(r,e),status:$r(ti(r,`Status`)),branch:ti(r,`Branch`),scope:ti(r,`Scope`),objective:ni(r,`Objective`),openItems:ri(r)}}function pi(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>ii(e,t.currentBranch)-ii(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function mi(e){return e.map(ai).join(`
|
|
69
|
+
|
|
70
|
+
`)}function hi(e,t={},n=new N){let r=t.currentBranch??ui(e,n);return mi(pi(di(e,n).map(t=>fi(t,e,n)),{...t,currentBranch:r}))}function gi(e,t,n={},r=new N){let i=si(r.readFileSync(e,`utf8`),t),a=n.progressMessage?ci(i,n.now??new Date,n.progressMessage):i;r.writeFileSync(e,a,`utf8`)}function _i(e){return(0,p.createHash)(`sha256`).update(e,`utf-8`).digest(`hex`)}function vi(e,t=new N){let n=t.readFileSync(e,`utf-8`);return{filePath:e,content:n,contentHash:_i(n)}}async function yi(e,t=new N){let n=[],r=[];for(let i of e){if(!t.existsSync(i.filePath)){r.push(i);continue}_i(t.readFileSync(i.filePath,`utf-8`))===i.contentHash?r.push(i):n.push(i)}return{stale:n,fresh:r}}async function bi(e,t=new N){let{stale:n}=await yi(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:_i(n)}}),refreshed:i}}function xi(e,t){let n=[],r=(0,y.resolve)(e),i=!1;for(;!i;){let e=(0,y.join)(r,t);(0,v.existsSync)(e)&&n.push(e);let a=(0,y.dirname)(r);i=a===r,i||(r=a)}return n.reverse()}function Si(e){let t=e.split(`
|
|
71
|
+
`),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(`
|
|
72
|
+
`).trim()||void 0}async function Ci(e){let t=xi(e,`AGENTS.md`),n=xi(e,`CLAUDE.md`),r=t.map(e=>vi(e)),i=n.map(e=>vi(e)),a=r.map(e=>e.content).join(`
|
|
73
|
+
|
|
74
|
+
`),o=i.map(e=>e.content).join(`
|
|
75
|
+
|
|
76
|
+
`),s=Si(o),c=new Xr(e).loadStartupMemory().content||void 0,l=hi(e);return{agentsMd:a,claudeMd:o,memoryMd:c,taskContext:l.trim().length>0?l:void 0,compactInstructions:s,agentsFileEntries:r,claudeFileEntries:i}}function wi(e){if((0,v.existsSync)(e))try{return JSON.parse((0,v.readFileSync)(e,`utf-8`))}catch{return}}function Ti(e){if((0,v.existsSync)((0,y.join)(e,`pnpm-workspace.yaml`))||(0,v.existsSync)((0,y.join)(e,`pnpm-lock.yaml`)))return`pnpm`;if((0,v.existsSync)((0,y.join)(e,`yarn.lock`)))return`yarn`;if((0,v.existsSync)((0,y.join)(e,`bun.lockb`)))return`bun`;if((0,v.existsSync)((0,y.join)(e,`package-lock.json`)))return`npm`}async function Ei(e){let t=(0,y.join)(e,`package.json`),n=(0,y.join)(e,`tsconfig.json`),r=(0,y.join)(e,`pyproject.toml`),i=(0,y.join)(e,`Cargo.toml`),a=(0,y.join)(e,`go.mod`);if((0,v.existsSync)(t)){let r=wi(t),i=(0,v.existsSync)(n)?`typescript`:`javascript`,a=Ti(e);return{type:`node`,name:r?.name,packageManager:a,language:i}}return(0,v.existsSync)(r)||(0,v.existsSync)((0,y.join)(e,`setup.py`))?{type:`python`,language:`python`}:(0,v.existsSync)(i)?{type:`rust`,language:`rust`}:(0,v.existsSync)(a)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}var Di=class{settingsPath;fs;constructor(e,t=new N){this.settingsPath=e,this.fs=t}readAll(){if(!this.fs.existsSync(this.settingsPath))return{};try{let e=this.fs.readFileSync(this.settingsPath,`utf-8`),t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}writeAll(e){let t=(0,m.dirname)(this.settingsPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.settingsPath,JSON.stringify(e,null,2),`utf-8`)}getEnabledPlugins(){let e=this.readAll().enabledPlugins;return typeof e==`object`&&e?e:{}}setPluginEnabled(e,t){let n=this.readAll(),r=this.getEnabledPluginsFrom(n);r[e]=t,n.enabledPlugins=r,this.writeAll(n)}removePluginEntry(e){let t=this.readAll(),n=this.getEnabledPluginsFrom(t);delete n[e],t.enabledPlugins=n,this.writeAll(t)}getMarketplaceSources(){let e=this.readAll().extraKnownMarketplaces;return typeof e==`object`&&e?e:{}}setMarketplaceSource(e,t){let n=this.readAll(),r=this.getMarketplaceSourcesFrom(n);r[e]={source:t},n.extraKnownMarketplaces=r,this.writeAll(n)}removeMarketplaceSource(e){let t=this.readAll(),n=this.getMarketplaceSourcesFrom(t);delete n[e],t.extraKnownMarketplaces=n,this.writeAll(t)}getEnabledPluginsFrom(e){let t=e.enabledPlugins;return typeof t==`object`&&t?t:{}}getMarketplaceSourcesFrom(e){let t=e.extraKnownMarketplaces;return typeof t==`object`&&t?t:{}}};function Oi(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(`
|
|
77
|
+
`)){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 ki(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 Ai(e,t=new N){if(!t.existsSync(e))return[];try{return t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}var ji=class{pluginsDir;enabledPlugins;fs;constructor(e,t,n=new N){this.pluginsDir=e,this.enabledPlugins=t??{},this.fs=n}loadPluginsSync(){return this.discoverAndLoad()}async loadAll(){return this.discoverAndLoad()}discoverAndLoad(){let e=(0,m.join)(this.pluginsDir,`cache`);if(!this.fs.existsSync(e))return[];let t=[],n=Ai(e,this.fs);for(let r of n){let n=(0,m.join)(e,r),i=Ai(n,this.fs);for(let e of i){let i=(0,m.join)(n,e),a=Ai(i,this.fs);if(a.length===0)continue;let o=a[a.length-1],s=(0,m.join)(i,o),c=(0,m.join)(s,`.claude-plugin`,`plugin.json`);if(!this.fs.existsSync(c))continue;let l=this.readManifest(c);if(!l)continue;let u=`${l.name}@${r}`;if(this.isDisabled(u,l.name))continue;let d=this.loadPlugin(s,l);t.push(d)}}return t}readManifest(e){let t=this.fs.readFileSync(e,`utf-8`);return ki(JSON.parse(t))}isDisabled(e,t){return e in this.enabledPlugins?this.enabledPlugins[e]===!1:t in this.enabledPlugins?this.enabledPlugins[t]===!1:!1}loadPlugin(e,t){return{manifest:t,skills:this.loadSkills(e,t.name),commands:this.loadCommands(e,t.name),hooks:this.loadHooks(e),mcpConfig:this.loadMcpConfig(e),agents:this.loadAgents(e),pluginDir:e}}loadSkills(e,t){let n=(0,m.join)(e,`skills`);if(!this.fs.existsSync(n))return[];let r=this.fs.readdirSync(n,{withFileTypes:!0}),i=[];for(let e of r){if(!e.isDirectory())continue;let t=(0,m.join)(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let{metadata:r,content:a}=Oi(this.fs.readFileSync(t,`utf-8`)),o=typeof r.description==`string`?r.description:``,s={name:e.name,description:o,skillContent:a,...r};i.push(s)}return i}loadCommands(e,t){let n=(0,m.join)(e,`commands`);if(!this.fs.existsSync(n))return[];let r=this.fs.readdirSync(n,{withFileTypes:!0}),i=[];for(let e of r){if(!e.isFile()||!e.name.endsWith(`.md`))continue;let{metadata:r,content:a}=Oi(this.fs.readFileSync((0,m.join)(n,e.name),`utf-8`)),o=typeof r.name==`string`?r.name:e.name.replace(/\.md$/,``),s=typeof r.description==`string`?r.description:``;i.push({...r,name:`${t}:${o}`,description:s,skillContent:a})}return i}loadHooks(e){let t=(0,m.join)(e,`hooks`,`hooks.json`);if(!this.fs.existsSync(t))return{};let n=this.fs.readFileSync(t,`utf-8`),r=JSON.parse(n);return typeof r==`object`&&r?r:{}}loadMcpConfig(e){let t=(0,m.join)(e,`.mcp.json`);if(!this.fs.existsSync(t))return;let n=this.fs.readFileSync(t,`utf-8`);return JSON.parse(n)}loadAgents(e){let t=(0,m.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$/,``)):[]}},Mi=class{pluginsDir;cacheDir;registryPath;settingsStore;marketplaceClient;exec;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.cacheDir=(0,m.join)(this.pluginsDir,`cache`),this.registryPath=(0,m.join)(this.pluginsDir,`installed_plugins.json`),this.settingsStore=e.settingsStore,this.marketplaceClient=e.marketplaceClient,this.exec=e.exec,this.fs=e.fs??new N}async install(e,t){let n=this.marketplaceClient.fetchManifest(t).plugins.find(t=>t.name===e);if(!n)throw Error(`Plugin "${e}" not found in marketplace "${t}"`);let r=this.resolveVersion(n,t),i=(0,m.join)(this.cacheDir,t,e,r);if(this.fs.existsSync(i))throw Error(`Plugin "${e}" version "${r}" is already installed from "${t}"`);this.resolveAndInstall(n.source,t,e,i);let a=`${e}@${t}`,o=this.readRegistry();o[a]={pluginName:e,marketplace:t,version:r,installPath:i,installedAt:new Date().toISOString()},this.writeRegistry(o)}async uninstall(e){let t=this.readRegistry(),n=t[e];if(!n)throw Error(`Plugin "${e}" is not installed`);this.fs.existsSync(n.installPath)&&this.fs.rmSync(n.installPath,{recursive:!0,force:!0}),delete t[e],this.writeRegistry(t),this.settingsStore.removePluginEntry(e)}async enable(e){this.settingsStore.setPluginEnabled(e,!0)}async disable(e){this.settingsStore.setPluginEnabled(e,!1)}getInstalledPlugins(){return this.readRegistry()}getPluginsByMarketplace(e){let t=this.readRegistry();return Object.values(t).filter(t=>t.marketplace===e)}resolveVersion(e,t){let n=e;return typeof n.version==`string`&&n.version?n.version:this.marketplaceClient.getMarketplaceSha(t)}normalizeSource(e){if(typeof e==`string`)return e;let t=e;return!t.type&&typeof t.source==`string`?{...t,type:t.source}:e}resolveAndInstall(e,t,n,r){this.fs.mkdirSync(r,{recursive:!0});let i=this.normalizeSource(e);try{if(typeof i==`string`){let e=(0,m.join)(this.marketplaceClient.getMarketplaceDir(t),i);if(!this.fs.existsSync(e))throw Error(`Plugin source path "${i}" not found in marketplace "${t}"`);this.fs.cpSync(e,r,{recursive:!0})}else if(i.type===`github`){let e=`https://github.com/${i.repo}.git`;this.cloneToDir(e,r,n)}else if(i.type===`url`&&typeof i.url==`string`&&i.url.endsWith(`.git`))this.cloneToDir(i.url,r,n);else if(i.type===`url`)throw Error(`URL source "${i.url}" is not a git repository (must end with .git)`);else throw Error(`Unknown source type: ${JSON.stringify(i)}`)}catch(e){throw this.fs.existsSync(r)&&this.fs.rmSync(r,{recursive:!0,force:!0}),e}}cloneToDir(e,t,n){this.fs.rmSync(t,{recursive:!0,force:!0});let r=`git clone --depth 1 ${e} ${t}`;try{this.exec(r,{timeout:6e4,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone plugin "${n}": ${t}`)}}readRegistry(){if(!this.fs.existsSync(this.registryPath))return{};try{let e=this.fs.readFileSync(this.registryPath,`utf-8`),t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}writeRegistry(e){let t=(0,m.dirname)(this.registryPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.registryPath,JSON.stringify(e,null,2),`utf-8`)}};function U(e,t=new N){if(!t.existsSync(e))return{};try{let n=t.readFileSync(e,`utf-8`),r=JSON.parse(n);return typeof r==`object`&&r?r:{}}catch{return{}}}function Ni(e,t,n=new N){let r=(0,m.dirname)(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(e,JSON.stringify(t,null,2),`utf-8`)}function Pi(e,t,n=new N){let r=(0,m.join)(e,`installed_plugins.json`);if(!n.existsSync(r))return;let i;try{let e=n.readFileSync(r,`utf-8`),t=JSON.parse(e);if(typeof t!=`object`||!t)return;i=t}catch{return}let a=!1;for(let[e,r]of Object.entries(i))r.marketplace===t&&(r.installPath&&n.existsSync(r.installPath)&&n.rmSync(r.installPath,{recursive:!0,force:!0}),delete i[e],a=!0);if(a){let e=(0,m.dirname)(r);n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.writeFileSync(r,JSON.stringify(i,null,2),`utf-8`)}}const Fi=6e4;var Ii=class{pluginsDir;exec;marketplacesDir;registryPath;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.exec=e.exec,this.marketplacesDir=(0,m.join)(this.pluginsDir,`marketplaces`),this.registryPath=(0,m.join)(this.pluginsDir,`known_marketplaces.json`),this.fs=e.fs??new N}addMarketplace(e){let t=`temp-`+Date.now().toString(36),n=(0,m.join)(this.marketplacesDir,t);if(this.fs.mkdirSync(this.marketplacesDir,{recursive:!0}),e.type===`local`){if(!this.fs.existsSync(e.path))throw Error(`Local marketplace path does not exist: ${e.path}`);this.fs.cpSync(e.path,n,{recursive:!0})}else{let t=`git clone --depth 1 ${this.resolveCloneUrl(e)} ${n}`;try{this.exec(t,{timeout:Fi,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone marketplace: ${t}`)}}let r=(0,m.join)(n,`.claude-plugin`,`marketplace.json`);if(!this.fs.existsSync(r))throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(e.type===`local`?`Local directory does not contain .claude-plugin/marketplace.json`:`Cloned repository does not contain .claude-plugin/marketplace.json`);let i=this.readManifestFromPath(r).name;if(!i)throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace manifest does not contain a "name" field`);let a=U(this.registryPath,this.fs);if(a[i])throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace "${i}" already exists`);let o=(0,m.join)(this.marketplacesDir,i);return this.fs.renameSync(n,o),a[i]={source:e,installLocation:o,lastUpdated:new Date().toISOString()},Ni(this.registryPath,a,this.fs),i}removeMarketplace(e){let t=U(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);Pi(this.pluginsDir,e,this.fs),this.fs.existsSync(n.installLocation)&&this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),delete t[e],Ni(this.registryPath,t,this.fs)}updateMarketplace(e){let t=U(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);if(!this.fs.existsSync(n.installLocation))throw Error(`Marketplace directory for "${e}" does not exist`);if(n.source.type===`local`){let e=n.source;if(!this.fs.existsSync(e.path))throw Error(`Local marketplace path does not exist: ${e.path}`);this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),this.fs.cpSync(e.path,n.installLocation,{recursive:!0})}else{let t=`git -C ${n.installLocation} pull`;try{this.exec(t,{timeout:Fi,stdio:`pipe`})}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Failed to update marketplace "${e}": ${n}`)}}n.lastUpdated=new Date().toISOString(),Ni(this.registryPath,t,this.fs)}listMarketplaces(){let e=U(this.registryPath,this.fs);return Object.entries(e).map(([e,t])=>({name:e,source:t.source,lastUpdated:t.lastUpdated}))}fetchManifest(e){let t=U(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);let n=(0,m.join)(t.installLocation,`.claude-plugin`,`marketplace.json`);if(!this.fs.existsSync(n))throw Error(`Marketplace "${e}" does not contain .claude-plugin/marketplace.json`);return this.readManifestFromPath(n)}getMarketplaceDir(e){let t=U(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);return t.installLocation}getMarketplaceSha(e){let t=this.getMarketplaceDir(e);try{return this.exec(`git -C ${t} rev-parse HEAD`,{timeout:Fi,stdio:`pipe`}).toString().trim().slice(0,12)}catch{return`unknown`}}listAvailablePlugins(){let e=[],t=this.listMarketplaces();for(let{name:n}of t)try{let t=this.fetchManifest(n);for(let r of t.plugins)e.push({...r,marketplace:n})}catch{}return e}resolveCloneUrl(e){switch(e.type){case`github`:return`https://github.com/${e.repo}.git`;case`git`:return e.url;case`local`:throw Error(`Local source type does not use git cloning`);case`url`:throw Error(`URL marketplace source is not yet supported`)}}readManifestFromPath(e){let t=this.fs.readFileSync(e,`utf-8`),n=JSON.parse(t);if(typeof n!=`object`||!n)throw Error(`Invalid marketplace manifest: not an object`);if(typeof n.name!=`string`)throw Error(`Invalid marketplace manifest: missing "name" field`);return n}};function Li(e){let t=(0,m.join)((0,m.dirname)((0,m.dirname)(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function Ri(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 zi(e){let t={};for(let n of e){let e=n.hooks;if(!e)continue;let r=Li(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=Ri(e,n.pluginDir);return t.env=r,t});t[e].push(...i)}}return t}function Bi(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}function Vi(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 Hi(e,t,n){let r=e.find(e=>e.sourcePath===t.sourcePath),i=e.filter(e=>e.sourcePath!==t.sourcePath),a=r?qi(r,t):t;return Ji([...i,a],n)}function Ui(e,t){let n=Zi(t),r=e.find(e=>Qi(e,n));return r?{references:e.filter(e=>e.sourcePath!==r.sourcePath),result:{removed:r}}:{references:[...e],result:{}}}function Wi(e){return{removed:[...e]}}function Gi(e){return e.filter(e=>e.status===`active`)}function Ki(e){return e.map(e=>({originalReference:e.originalReference,sourcePath:e.sourcePath,relativePath:e.relativePath,reason:e.loadType,depth:0,byteLength:e.byteLength}))}function qi(e,t){return t.status===`active`?{...t,loadedAt:e.loadedAt}:{...e,byteLength:t.byteLength,originalReference:t.originalReference,lastUsedAt:t.lastUsedAt}}function Ji(e,t){let n=t?.maxActiveReferences??8,r=t?.maxActiveBytes??262144,i=t?.maxObservedReferences??32,a=[],o=[...e];for(;Yi(o)>n||Xi(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 Yi(e){return e.filter(e=>e.status===`active`).length}function Xi(e){return e.reduce((e,t)=>e+(t.status===`active`?t.byteLength:0),0)}function Zi(e){return e.startsWith(`@`)?e.slice(1):e}function Qi(e,t){return e.relativePath===t||e.sourcePath===t||e.originalReference===t||e.originalReference===`@${t}`}function $i(e,t){return t.length===0?e:[e,`<robota_file_references>`,...t.map(e=>{let t=e.content.replaceAll(`</file>`,`<\\/file>`);return[`<file path="${ra(e.relativePath)}" bytes="${e.byteLength}" reason="${e.reason}">`,t,`</file>`].join(`
|
|
78
|
+
`)}),`</robota_file_references>`].join(`
|
|
79
|
+
|
|
80
|
+
`)}function ea(e){return e.some(e=>e.severity===`error`)}function ta(e){return e.length===0?``:[`File reference error:`,...e.map(e=>`- ${e.reference}: ${e.message}`)].join(`
|
|
81
|
+
`)}function W(e){return e.map(({content:e,...t})=>t)}function na(e){let t=W(e);return{id:`prompt_file_reference_${(0,p.randomUUID)()}`,timestamp:new Date,category:`event`,type:`prompt-file-reference`,data:{message:ia(t),references:t}}}function ra(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function ia(e){return`Loaded file references: ${e.map(e=>`${e.relativePath} (${e.byteLength} B)`).join(`, `)}`}const aa=/(^|[\s([{])@([^\s)\]}>,;"'`]+)/g;function oa(e){let t=[];for(let n of e.matchAll(aa)){let e=sa(n[2]??``);ca(e)&&t.push({original:`@${e}`,path:e,index:n.index??0})}return t}function sa(e){let t=e.length;for(;t>0&&/[.,:;!?]/.test(e[t-1]??``);)--t;return e.slice(0,t)}function ca(e){return e.length===0||e.includes(`://`)?!1:e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)||e.startsWith(`~/`)||e.startsWith(`.`)||e.includes(`.`)}function la(e,t){return e.startsWith(`~/`)?(0,m.resolve)((0,h.homedir)(),e.slice(2)):(0,m.isAbsolute)(e)?(0,m.resolve)(e):(0,m.resolve)(t,e)}function ua(e,t){let n=(0,m.relative)(t,e);return n===``||!n.startsWith(`..`)&&!(0,m.isAbsolute)(n)}function da(e,t){return(0,m.relative)(e,t).split(m.sep).join(`/`)}const fa=1024;64*fa,256*fa;async function pa(e,t){let n=await ha(t);for(let t of oa(e))await ya(t,0,[],n);return ga(n)}async function ma(e,t){let n=await ha(t);for(let t of e)await ya({original:`@${t}`,path:t,index:0},0,[],n);return ga(n)}async function ha(e){let t=e.fsAsync??new P;return{rootPath:await va(e.cwd,t),limits:_a(e.limits),reason:e.reason??`prompt-reference`,references:[],diagnostics:[],loadedPaths:new Set,totalBytes:0,fsAsync:t}}function ga(e){return{references:e.references,diagnostics:e.diagnostics}}function _a(e){return{maxDepth:e?.maxDepth??2,maxReferences:e?.maxReferences??8,maxFileBytes:e?.maxFileBytes??65536,maxTotalBytes:e?.maxTotalBytes??262144}}async function va(e,t){try{return await t.realpath(e)}catch{return(0,m.resolve)(e)}}async function ya(e,t,n,r){if(!ba(e,t,r))return;let i=await xa(e,r);if(i===void 0||!Sa(e,i,n,r))return;let a=await Ca(e,i,r);if(a===void 0)return;let o=await wa(e,i,r);o!==void 0&&(r.loadedPaths.add(i),r.totalBytes+=a.byteLength,r.references.push(Ta(e,a,t,o,r)),await Ea(o,t,[...n,i],r))}function ba(e,t,n){return n.references.length>=n.limits.maxReferences?(G(n,`too-many-references`,e,`Too many file references.`),!1):t>n.limits.maxDepth?(G(n,`max-depth`,e,`File reference nesting is too deep.`),!1):!0}async function xa(e,t){let n=la(e.path,t.rootPath);if(!ua(n,t.rootPath)){G(t,`outside-root`,e,`Referenced path is outside the workspace.`);return}try{let r=await t.fsAsync.realpath(n);if(ua(r,t.rootPath))return r;G(t,`outside-root`,e,`Referenced path resolves outside the workspace.`)}catch{G(t,`not-found`,e,`Referenced file was not found.`)}}function Sa(e,t,n,r){return n.includes(t)?(G(r,`circular-reference`,e,`Circular file reference detected.`),!1):!r.loadedPaths.has(t)}async function Ca(e,t,n){try{let r=await n.fsAsync.stat(t);if(r.isDirectory()){G(n,`directory-not-supported`,e,`Directory references are not supported.`);return}if(r.size>n.limits.maxFileBytes){G(n,`file-too-large`,e,`Referenced file exceeds the per-file size limit.`);return}if(n.totalBytes+r.size>n.limits.maxTotalBytes){G(n,`total-too-large`,e,`Referenced files exceed the total size limit.`);return}return{sourcePath:t,byteLength:r.size}}catch{G(n,`unreadable`,e,`Referenced file could not be inspected.`);return}}async function wa(e,t,n){try{return await n.fsAsync.readFile(t,`utf8`)}catch{G(n,`unreadable`,e,`Referenced file could not be read.`);return}}function Ta(e,t,n,r,i){return{originalReference:e.original,sourcePath:t.sourcePath,relativePath:da(i.rootPath,t.sourcePath),reason:i.reason,depth:n,byteLength:t.byteLength,content:r}}async function Ea(e,t,n,r){for(let i of oa(e))await ya(i,t+1,n,r)}function G(e,t,n,r){e.diagnostics.push({code:t,severity:`error`,reference:n.original,message:r,path:n.path})}function Da(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&(e.message.includes(`aborted`)||e.message.includes(`abort`))}function Oa(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 ka(e,t,n,r,i,a){let o=Oa(t,r),s=Pa(t,r,i);return{response:e,history:n,toolSummaries:o,contextState:i,...s&&{usage:s},...a&&a.length>0?{promptFileReferences:[...a]}:{}}}function Aa(e,t,n,r){let i=Oa(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=Pa(e,n,r);return{response:a.join(`
|
|
82
|
+
|
|
83
|
+
`),history:t,toolSummaries:i,contextState:r,...o&&{usage:o}}}function ja(e){return{id:`usage_${(0,p.randomUUID)()}`,timestamp:new Date,category:`event`,type:`usage-summary`,data:e}}async function Ma(e,t,n,r=[]){let i=await ma(Gi(r).map(e=>e.sourcePath),{cwd:t,reason:`manual`}),a=await pa(e,{cwd:t}),o=[...i.diagnostics,...a.diagnostics];if(ea(o))throw Error(ta(o));let s=$i(e,Na([...i.references,...a.references])),c=n??(s===e?void 0:e),l=W(i.references),u=W(a.references),d=a.references.length>0?na(a.references):void 0;return{modelInput:s,...c===void 0?{}:{hookInput:c},activeContextReferenceRecords:l,promptFileReferenceRecords:u,...d===void 0?{}:{promptFileReferenceEntry:d}}}function Na(e){return[...new Map(e.map(e=>[e.sourcePath,e])).values()]}function Pa(e,t,n){let r=e.slice(t),i=0,a=0,o=!1;for(let e of r){if(e.role!==`assistant`)continue;let t=(0,c.collectAssistantUsageMetadata)(e);t&&(o=!0,i+=t.inputTokens,a+=t.outputTokens)}if(o)return{kind:`exact`,scope:`turn`,promptTokens:i,completionTokens:a,totalTokens:i+a,contextUsedTokens:n.usedTokens,contextMaxTokens:n.maxTokens,contextUsedPercentage:n.usedPercentage,costStatus:`unknown`}}const Fa={write:()=>{},writeLine:()=>{},writeMarkdown:()=>{},writeError:()=>{},prompt:()=>Promise.resolve(``),select:()=>Promise.resolve(0),spinner:()=>({stop:()=>{},update:()=>{}})};function Ia(e){let t=e.fs??new N,n=e.manifests.filter(t=>t.sequence>e.target.sequence),r=e.manifests.filter(t=>t.sequence>=e.target.sequence);return{target:La(e.target),capturedFiles:e.target.files.map(n=>{let r=n.snapshotFile?(0,m.join)(e.checkpointDir(e.sessionId,e.target.id),n.snapshotFile):void 0,i=r?za(r,t):void 0;return{originalPath:n.originalPath,relativePath:(0,m.relative)(e.cwd,n.originalPath),existed:n.existed,restoreAction:n.existed?`restore-preimage`:`delete-created-file`,snapshotAvailable:n.existed?i!==void 0:!1,...i?{snapshotSizeBytes:i.size}:{}}}),restoreToCheckpoint:Ra(n),rollbackThroughCheckpoint:Ra(r)}}function La(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function Ra(e){return{checkpointIds:e.map(e=>e.id),fileCount:e.reduce((e,t)=>e+t.fileCount,0)}}function za(e,t){try{return t.statSync(e)}catch{return}}const Ba=`manifest.json`,Va=`files`;var K=class{fs;fsAsync;cwd;rootDir;now;activeTurn=null;constructor(e,t=new N,n=new P){this.fs=t,this.fsAsync=n,this.cwd=(0,m.resolve)(e.cwd),this.rootDir=z(this.cwd).checkpoints,this.now=e.now??(()=>new Date)}async beginTurn(e){this.activeTurn&&await this.finalizeTurn();let t=this.nextSequence(e.sessionId),n=`turn-${String(t).padStart(4,`0`)}`,r=(0,m.join)(this.sessionDir(e.sessionId),n);await this.fsAsync.mkdir((0,m.join)(r,Va),{recursive:!0});let i={version:1,id:n,sessionId:e.sessionId,sequence:t,prompt:e.prompt,createdAt:this.now().toISOString(),fileCount:0,files:[]};return this.activeTurn={manifest:i,dir:r,capturedPaths:new Set},q(i)}async captureFile(e){if(!this.activeTurn)return;let t=(0,m.resolve)(this.cwd,e);if(this.activeTurn.capturedPaths.has(t)||Ua(this.rootDir,t))return;let n=await this.createFileRecord(t,this.activeTurn);this.activeTurn.manifest.files.push(n),this.activeTurn.manifest.fileCount=this.activeTurn.manifest.files.length,this.activeTurn.capturedPaths.add(t)}async finalizeTurn(){if(!this.activeTurn)return;let e=this.activeTurn;return this.activeTurn=null,await this.writeManifest(e.dir,e.manifest),q(e.manifest)}list(e){return this.loadManifests(e).map(q)}inspect(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);return Ia({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:q(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:q(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async createFileRecord(e,t){if(!await Wa(this.fsAsync,this.fs,e))return{originalPath:e,existed:!1};let n=(0,m.join)(Va,`${String(t.manifest.files.length+1).padStart(6,`0`)}.content`);return await this.fsAsync.copyFile(e,(0,m.join)(t.dir,n)),{originalPath:e,existed:!0,snapshotFile:n}}async restoreFile(e,t,n){if(!n.existed){await this.fsAsync.rm(n.originalPath,{force:!0});return}if(!n.snapshotFile)throw Error(`Checkpoint file record is missing a snapshot: ${n.originalPath}`);await this.fsAsync.mkdir((0,m.dirname)(n.originalPath),{recursive:!0}),await this.fsAsync.copyFile((0,m.join)(this.checkpointDir(e,t),n.snapshotFile),n.originalPath)}loadManifests(e){let t=this.sessionDir(e);return Ga(this.fs,t).map(e=>(0,m.join)(t,e,Ba)).map(e=>Ka(this.fs,e)).filter(e=>e!==void 0).sort((e,t)=>e.sequence-t.sequence)}nextSequence(e){return(this.list(e).at(-1)?.sequence??0)+1}async writeManifest(e,t){await this.fsAsync.mkdir(e,{recursive:!0});let n=(0,m.join)(e,Ba),r=`${n}.tmp`;await this.fsAsync.writeFile(r,JSON.stringify(t,null,2),`utf8`),await this.fsAsync.rename(r,n)}sessionDir(e){return(0,m.join)(this.rootDir,Ha(e))}checkpointDir(e,t){return(0,m.join)(this.sessionDir(e),Ha(t))}};function q(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function Ha(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function Ua(e,t){let n=(0,m.relative)(e,t);return n.length===0||!n.startsWith(`..`)&&!n.startsWith(`/`)}async function Wa(e,t,n){try{return await e.access(n,t.constants.F_OK),!0}catch{return!1}}function Ga(e,t){try{return e.readdirSync(t)}catch{return[]}}function Ka(e,t){try{let n=e.readFileSync(t,`utf8`);return JSON.parse(n)}catch{return}}async function qa(e){let t=e.cwd,[n,r,i]=await Promise.all([e.config?Promise.resolve(e.config):Br(t),e.bare?Promise.resolve({agentsMd:``,claudeMd:``,agentsFileEntries:[],claudeFileEntries:[]}):Ci(t),e.bare?Promise.resolve({type:`unknown`,language:`unknown`}):Ei(t)]),a=e.language?{...n,language:e.language}:n,o=new ji((0,m.join)((0,h.homedir)(),`.robota`,`plugins`));if(!e.bare)try{let e=o.loadPluginsSync();if(e.length>0){let t=zi(e);a={...a,hooks:Bi(a.hooks,t)}}}catch{}let s=z(t);await Ya(e)||await Ja(e,t);let c=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,{session:l,rebuildSystemMessage:u}=cr({config:a,cwd:t,context:r,projectInfo:i,permissionMode:e.permissionMode,maxTurns:e.maxTurns,terminal:Fa,sessionLogger:new f.FileSessionLogger(s.logs),permissionHandler:e.permissionHandler,provider:e.provider,onTextDelta:e.onTextDelta,onContextUpdate:e.onContextUpdate,onCompactEvent:e.onCompactEvent,onToolExecution:e.onToolExecution,sessionId:c,allowedTools:e.allowedTools,appendSystemPrompt:e.appendSystemPrompt,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,...e.commandModules?.some(e=>e.sessionRequirements?.includes(`agent-runtime`))?{enableAgentRuntime:!0}:{},...e.commandModules||e.commandDescriptors?{commandDescriptors:[...e.commandDescriptors??[],...e.commandModules?.flatMap(e=>e.commandDescriptors??[])??[]]}:{},modelCommandExecutor:e.modelCommandExecutor,isModelCommandInvocable:e.isModelCommandInvocable,editCheckpointRecorder:e.editCheckpointRecorder,reversibleExecution:e.reversibleExecution,sandboxClient:e.sandboxClient,agentName:e.agentName});return{session:l,agentsFileEntries:r.agentsFileEntries??[],claudeFileEntries:r.claudeFileEntries??[],rebuildSystemMessage:u}}async function Ja(e,t){if(e.workspaceManifest){if(!e.sandboxClient)throw Error(`workspaceManifest requires sandboxClient.`);await(0,u.applyWorkspaceManifest)(e.sandboxClient,e.workspaceManifest,{hostRoot:t,...e.sandboxWorkspaceRoot?{targetRoot:e.sandboxWorkspaceRoot}:{}})}}async function Ya(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 Xa(e,t){let n=e.config??await Br(e.cwd),r=n.autoCompactThreshold===void 0?`default`:`settings`,i=new K({cwd:e.cwd});t.setEditCheckpointStore(i);let a=await qa({cwd:e.cwd,provider:e.provider,config:n,permissionMode:e.permissionMode,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler,resumeSessionId:t.resumeSessionId,forkSession:e.forkSession,onTextDelta:t.onTextDelta,onContextUpdate:t.onContextUpdate,onCompactEvent:t.onCompactEvent,onToolExecution:t.onToolExecution,bare:e.bare,allowedTools:e.allowedTools,appendSystemPrompt:e.appendSystemPrompt,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}:{},commandDescriptors:t.commandDescriptors,...t.commandDescriptors.length>0?{modelCommandExecutor:t.executeModelCommand,isModelCommandInvocable:t.isModelCommandInvocable}:{}});if(t.pendingRestoreMessages)for(let e of t.pendingRestoreMessages)Bt(a.session,e);return{session:a.session,agentsFileEntries:a.agentsFileEntries,claudeFileEntries:a.claudeFileEntries,rebuildSystemMessage:a.rebuildSystemMessage,autoCompactThresholdSource:r}}var Za=class{getManager;onChanged;emitTaskEvent;emitGroupEvent;persistSession;backgroundTasks=[];backgroundTaskEvents=[];backgroundJobGroups=[];backgroundJobGroupEvents=[];backgroundTaskUnsubscribe=null;backgroundJobUnsubscribe=null;backgroundJobOrchestrator=null;constructor(e,t,n,r,i){this.getManager=e,this.onChanged=t,this.emitTaskEvent=n,this.emitGroupEvent=r,this.persistSession=i}subscribe(e){if(this.backgroundTaskUnsubscribe)return;let t=Nt(e)??M(e)?.backgroundTaskManager;t&&(this.backgroundTaskUnsubscribe=t.subscribe(e=>{this.recordTaskEvent(e),this.emitTaskEvent(e)}))}dispose(){this.backgroundTaskUnsubscribe?.(),this.backgroundTaskUnsubscribe=null,this.backgroundJobUnsubscribe?.(),this.backgroundJobUnsubscribe=null,this.backgroundJobOrchestrator?.dispose(),this.backgroundJobOrchestrator=null}restoreState(e){this.backgroundTasks=e.tasks,this.backgroundTaskEvents=e.taskEvents,this.backgroundJobGroups=e.groups,this.backgroundJobGroupEvents=e.groupEvents}getState(){return{tasks:this.getTaskSnapshots(),taskEvents:this.backgroundTaskEvents,groups:this.getGroupSnapshots(),groupEvents:this.backgroundJobGroupEvents}}getManagerOrThrow(){let e=this.getManager();if(!e)throw Error(`Background task manager is not available for this session.`);return e}getOrchestratorOrThrow(e){if(this.backgroundJobOrchestrator)return this.backgroundJobOrchestrator;let t=this.getManagerOrThrow();return this.backgroundJobOrchestrator=new we({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 j({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 j({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 j({entryId:e,lines:ke(r).lines,kind:`group_summary`})}getTaskSnapshots(){try{return this.getManagerOrThrow().list()}catch{return this.backgroundTasks}}getGroupSnapshots(){try{return this.backgroundJobOrchestrator?.listGroups()??this.backgroundJobGroups}catch{return this.backgroundJobGroups}}subscribeGroupEvents(e){this.backgroundJobUnsubscribe||!this.backgroundJobOrchestrator||(this.backgroundJobUnsubscribe=this.backgroundJobOrchestrator.subscribe(t=>{this.recordGroupEvent(t,e),this.emitGroupEvent(t)}))}recordTaskEvent(e){this.backgroundTasks=this.getTaskSnapshots(),this.backgroundTaskEvents.push(e),this.persistSession(),this.onChanged(`background_task`,Qa(e))}recordGroupEvent(e,t){this.backgroundJobGroups=this.getGroupSnapshots(),this.backgroundJobGroupEvents.push(e),this.persistSession(),this.onChanged(`background_group`,Ne(e.group.id))}};function Qa(e){if(`task`in e)return D(e.task.id);if(`taskId`in e)return D(e.taskId)}async function $a(e,t,n){let r=await ma([t],{cwd:n,reason:`manual`});if(ea(r.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[ta(r.diagnostics)]}};let i=r.references[0];if(!i)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let a=Vi(W([i])[0],`manual`,`active`),o=Hi(e,a);return{references:o.references,result:{reference:a,evicted:o.evicted,diagnostics:[]}}}function eo(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=Vi(e,n.loadType,n.status,r);i=Hi(i,t).references}return i}function to(e){return e.source===`plugin`?`plugin`:`skill`}function no(e){return e.context===`fork`?`fork`:`inject`}function ro(e){return{type:`skill-activation`,skillName:e.skill.name,source:to(e.skill),invocation:e.invocation,mode:no(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function io(e){let t=e.source===`plugin`?`plugin skill`:`skill`;return e.status===`failed`?`Skill failed: ${e.skillName}${e.error?` (${e.error})`:``}`:e.status===`completed`?`Skill completed: ${e.skillName}`:`Invoking ${t}: ${e.skillName}`}var ao=class{cwd;getSessionId;getExecuting;persistSession;emitSkillActivation;history=[];editCheckpointStore=null;memoryEvents=[];usedMemoryReferences=[];contextReferences=[];skillActivationEvents=[];constructor(e,t,n,r,i,a=null){this.cwd=e,this.getSessionId=t,this.getExecuting=n,this.persistSession=r,this.emitSkillActivation=i,this.editCheckpointStore=a}restoreState(e){this.history=e.history,this.memoryEvents=e.memoryEvents,this.usedMemoryReferences=e.usedMemoryReferences,this.contextReferences=e.contextReferences,this.skillActivationEvents=e.skillActivationEvents}getState(){return{history:this.history,memoryEvents:this.memoryEvents,usedMemoryReferences:this.usedMemoryReferences,contextReferences:this.contextReferences,skillActivationEvents:this.skillActivationEvents}}append(e){this.history.push(e)}getHistory(){return this.history}clearHistory(){this.history=[],this.memoryEvents=[],this.usedMemoryReferences=[]}resetUsedMemoryReferences(){this.usedMemoryReferences=[]}recordContextReferenceUsage(e){this.contextReferences=eo(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=eo(this.contextReferences,e,{loadType:`prompt-reference`,status:`observed`}),this.persistSession()}listEditCheckpoints(){let e=this.getSessionId();return this.getCheckpointStore().list(e)}inspectEditCheckpoint(e){let t=this.getSessionId();return this.getCheckpointStore().inspect(t,e)}async restoreEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot restore edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push((0,c.messageToHistoryEntry)((0,c.createSystemMessage)(`Restored edit checkpoint: ${e}`))),this.persistSession(),t}async rollbackEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot rollback edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().rollbackThroughCheckpoint(this.getSessionId(),e);return this.history.push((0,c.messageToHistoryEntry)((0,c.createSystemMessage)(`Rolled back edit checkpoint: ${e}`))),this.persistSession(),t}async beginEditCheckpointTurn(e){this.editCheckpointStore&&await this.editCheckpointStore.beginTurn({sessionId:this.getSessionId(),prompt:e})}async finalizeEditCheckpointTurn(){if(this.editCheckpointStore)try{await this.editCheckpointStore.finalizeTurn()}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.history.push((0,c.messageToHistoryEntry)((0,c.createSystemMessage)(`Checkpoint error: ${t.message}`))),t}}setEditCheckpointStore(e){this.editCheckpointStore=e}getUsedMemoryReferences(){return[...this.usedMemoryReferences]}recordMemoryEvent(e){this.memoryEvents.push(e),this.persistSession()}listContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await $a(this.contextReferences,e,this.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=Ui(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=Wi(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,t){this.skillActivationEvents.push(e),t&&this.history.push({id:(0,p.randomUUID)(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:io(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){return this.editCheckpointStore||=new K({cwd:this.cwd}),this.editCheckpointStore}};function oo(e){return e.source===`skill`||e.source===`plugin`&&e.skillContent?`skill`:`builtin-command`}function so(e){let t=e.source===`skill`||e.source===`plugin`&&!!e.skillContent;return{name:e.name,kind:oo(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 co=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=>so(e))}},lo=class{commands;constructor(e){this.commands=new Map;for(let t of e??J())this.commands.set(t.name,t)}register(e){this.commands.set(e.name,e)}async execute(e,t,n){let r=this.getCommand(e);return r?await this.executeCommand(r,t,n):null}getCommand(e){return this.commands.get(e)}resolveRequiresPermission(e){return e.requiresPermission===void 0?e.safety!==`read-only`:e.requiresPermission}async executeCommand(e,t,n){return await e.execute(t,n)}listCommands(){return[...this.commands.values()]}listModelInvocableCommands(){return this.listCommands().filter(e=>e.modelInvocable===!0).map(e=>({name:e.name,kind:`builtin-command`,description:e.description,userInvocable:e.userInvocable!==!1,modelInvocable:!0,...e.argumentHint?{argumentHint:e.argumentHint}:{},...e.safety?{safety:e.safety}:{}}))}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 J(){return[]}function uo(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 fo=class{name=`builtin`;commands;constructor(e=J()){this.commands=e.map(uo)}getCommands(){return this.commands}};function po(){let e=J();return{name:`sdk-builtin`,commandSources:[new fo(e)],systemCommands:e}}function mo(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function ho(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function go(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(e,t,n={}){if(!t.type)throw Error(`Provider profile "${e}" is missing type`);if(!t.model)throw Error(`Provider profile "${e}" is missing model`);let r=(0,c.findProviderDefinition)(n.providerDefinitions??[],t.type),i=(0,c.getProviderCredentialRequirement)(r);if(i!==void 0&&!So(t,r?.defaults,i))throw Error(`Provider profile "${e}" is missing ${wo(i)}`)}function vo(e,t={}){let n=yo(e,t);return _o(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function yo(e,t={}){let n=xo(e.type,t.providerDefinitions??[]),r=e.apiKeyEnv===void 0?e.apiKey??n.apiKey:(0,c.formatEnvReference)(e.apiKeyEnv),i=e.baseURL??n.baseURL;return{type:e.type,model:e.model??n.model,...To(r)&&{apiKey:r},...i!==void 0&&{baseURL:i},...e.timeout!==void 0&&{timeout:e.timeout}}}function bo(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=mo(e,n,r);return t.currentProvider?ho(i,t.currentProvider):i}function xo(e,t){return(0,c.findProviderDefinition)(t,e)?.defaults??{}}function So(e,t,n){return n.anyOf.some(n=>(0,c.hasUsableSecretReference)(Co(n,e,t)))}function Co(e,t,n){return t[e]??n?.[e]}function wo(e){return e.anyOf.join(` or `)}function To(e){return e!==void 0&&e.length>0}async function Eo(e,t,n,r){let i=n??e;if(!i)return{message:`No provider profile selected.`,success:!1};let a=t?.[i];if(!a)return{message:`Provider profile "${i}" was not found.`,success:!1};try{_o(i,a,{providerDefinitions:r.providerDefinitions})}catch(e){return{message:e instanceof Error?e.message:String(e),success:!1}}let o=await((a.type?(0,c.findProviderDefinition)(r.providerDefinitions,a.type):void 0)?.probeProfile??Do)(a);return{message:o.ok?`Provider "${i}" test passed: ${o.message}`:`Provider "${i}" test failed: ${o.message}; manual configuration can continue.`,success:!0,data:{providerTest:{profile:i}}}}async function Do(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function Oo(e,t=[]){return ko(e,t)?`valid`:`incomplete`}function ko(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return Ao(n?.type,n,t)}return!!(e.provider&&Ao(e.provider.name,e.provider,t))}function Ao(e,t,n){if(!t)return!1;if(!e)return(0,c.hasUsableSecretReference)(t.apiKey);let r=(0,c.findProviderDefinition)(n,e);if(r===void 0)return!1;let i=(0,c.getProviderCredentialRequirement)(r);return i===void 0?!0:jo(t,r,i)}function jo(e,t,n){return n.anyOf.some(n=>(0,c.hasUsableSecretReference)(Mo(n,e,t)))}function Mo(e,t,n){return t[e]??n.defaults?.[e]}function No(e,t=new N){return e.reduce((e,n)=>{let r=Po(n,t);return r===void 0?e:Fo(e,r)},{})}function Po(e,t){if(t.existsSync(e))try{let n=t.readFileSync(e,`utf8`);return JSON.parse(n)}catch{return}}function Fo(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?Io(e.providers,t.providers):void 0}}function Io(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function Lo(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,d.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,d.normalizeProviderConfig)({name:i.name,model:i.model,apiKey:i.apiKey,baseURL:i.baseURL,timeout:i.timeout,options:i.options},n)}var Ro=class{name=`plugin`;plugins;constructor(e){this.plugins=e}getCommands(){let e=[];for(let t of this.plugins){for(let n of t.skills){let r=n.name.includes(`@`)?n.name.split(`@`)[0]:n.name;e.push({name:r,description:`(${t.manifest.name}) ${n.description}`,source:`plugin`,skillContent:n.skillContent,pluginDir:t.pluginDir})}for(let n of t.commands)e.push({name:n.name,description:n.description,source:`plugin`,skillContent:n.skillContent,pluginDir:t.pluginDir})}return e}};const zo=f.AUTO_COMPACT_THRESHOLD,Bo=`autoCompactThreshold`;function Vo(e){return e.getContextState()}function Ho(e){return e.getAutoCompactThreshold()}function Uo(e){return e.getAutoCompactThresholdSource?.()??`session`}function Wo(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 Go(e,t){let n=Qo(e);return n?(n.write({...n.read(),[Bo]:t}),!0):!1}function Ko(e){let t=Qo(e);if(!t)return!1;let n={...t.read()};return delete n[Bo],t.write(n),!0}async function qo(e,t){let n=Vo(e);return await e.compactContext(t),{before:n,after:Vo(e)}}function Jo(e){return e.listContextReferences?.()??[]}async function Yo(e,t){return e.addContextReference?e.addContextReference(t):{evicted:[],diagnostics:[`Command host does not support context reference additions.`]}}function Xo(e,t){return e.removeContextReference?.(t)??{}}function Zo(e){return e.clearContextReferences?.()??{removed:[]}}function Qo(e){return e.getCommandHostAdapters?.().settings}function $o(e,t={}){let n=es(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 es(e){let t=e?.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t!==void 0&&t.length>0?t:void 0}function ts(e){return e.listCommands?.()??[]}function ns(e){return[`Available commands:`,...ts(e).map(e=>{let t=e.displayName??e.name,n=`/${e.name}`;return` ${(e.displayName?`${t} (${n})`:n).padEnd(32)} — ${e.description}`})].join(`
|
|
84
|
+
`)}function rs(){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 is(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=ss(e),s=t?` — ${t}`:``;return`${e.id} [${e.status}${n}${i}${a}${o}] ${e.kind}:${e.label}${r}${s}`}function as(e){return e.length===0?`No background tasks.`:[`Background tasks:`,...e.map(e=>` ${is(e)}`)].join(`
|
|
85
|
+
`)}function os(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isNaN(t)?void 0:{offset:t}}function ss(e){let t=[];return e.worktreePath&&t.push(`worktree=${e.worktreePath}`),e.branchName&&t.push(`branch=${e.branchName}`),e.worktreeStatus&&t.push(`worktreeStatus="${cs(e.worktreeStatus)}"`),e.worktreeNextAction&&t.push(`next="${cs(e.worktreeNextAction)}"`),t.length===0?``:` ${t.join(` `)}`}function cs(e){let t=e.trim().replace(/\s+/g,` `);return t.length>160?`${t.slice(0,160)}...`:t}function ls(e,t){return e.listBackgroundTasks(t)}function us(e,t,n){return e.readBackgroundTaskLog(t,n)}function ds(e,t,n){return e.cancelBackgroundTask(t,n)}function fs(e,t){return e.closeBackgroundTask(t)}function ps(e=`model`){let t=typeof e==`string`?{source:e}:e,n=t.source??`model`,r=gs(t.settings,t.providerDefinitions);return r===void 0?t.settings===void 0?vs(n):[]:ys(r,n)}function ms(e={}){let t=xs(e.settings,e.providerDefinitions);return Ds(t===void 0?void 0:Cs(t))}async function hs(e={}){return Ds(await _s(e))}function gs(e,t=[]){return xs(e,t)?.catalog}async function _s(e){let t=xs(e.settings,e.providerDefinitions);if(t!==void 0){if(!(e.refresh===!0||ws(t.catalog,t.definition?.modelCatalogCacheTtlSeconds))||t.definition?.refreshModelCatalog===void 0)return Cs(t);try{let e=await t.definition.refreshModelCatalog({profile:Ts(t)});return e.status===`unavailable`?{providerType:t.providerType,catalog:t.catalog??e,refreshAttempted:!0,...e.message===void 0?{}:{refreshMessage:e.message}}:{providerType:t.providerType,catalog:e,refreshAttempted:!0}}catch(e){return{providerType:t.providerType,...t.catalog===void 0?{}:{catalog:t.catalog},refreshAttempted:!0,refreshMessage:e instanceof Error?e.message:String(e)}}}}function vs(e){let t=new Set,n=[];for(let r of Object.values(c.CLAUDE_MODELS))t.has(r.name)||(t.add(r.name),n.push({name:r.id,description:`${r.name} (${(0,c.formatTokenCount)(r.contextWindow).toUpperCase()})`,source:e}));return n}function ys(e,t){return(e.entries??[]).filter(e=>e.lifecycle!==`unavailable`).map(e=>({name:e.id,description:bs(e),source:t}))}function bs(e){return e.contextWindow===void 0?e.displayName:`${e.displayName} (${(0,c.formatTokenCount)(e.contextWindow).toUpperCase()})`}function xs(e,t=[]){let n=Ss(e),r=n?.type??n?.name;if(r===void 0)return;let i=(0,c.findProviderDefinition)(t,r);return{providerType:r,...n===void 0?{}:{profile:n},...i===void 0?{}:{definition:i},...i?.modelCatalog===void 0?{}:{catalog:i.modelCatalog}}}function Ss(e){return e?.currentProvider===void 0?e?.provider:e.providers?.[e.currentProvider]}function Cs(e){return{providerType:e.providerType,...e.catalog===void 0?{}:{catalog:e.catalog},refreshAttempted:!1}}function ws(e,t){return e===void 0||t===void 0||e.lastVerifiedAt===void 0?!1:Date.now()-new Date(e.lastVerifiedAt).getTime()>t*1e3}function Ts(e){let t=e.profile,n=e.definition?.defaults,r=Es(t?.apiKey??n?.apiKey),i=Y(t?.model,n?.model),a=Y(t?.baseURL,n?.baseURL),o=Y(t?.timeout,n?.timeout),s=Y(t?.options,n?.options),c={type:t?.type??e.providerType};return i!==void 0&&(c.model=i),r!==void 0&&(c.apiKey=r),a!==void 0&&(c.baseURL=a),o!==void 0&&(c.timeout=o),s!==void 0&&(c.options=s),c}function Y(e,t){return e??t}function Es(e){return e===void 0?void 0:(0,c.resolveEnvReference)(e)}function Ds(e){let t=e?.providerType!==void 0&&(e.catalog?.entries===void 0||e.catalog.entries.length===0)?`No model catalog available for provider ${e.providerType}. Usage: model <model-id>`:`Usage: model <model-id>`,n=Os(e);return n===void 0?t:`${t}\n${n}`}function Os(e){let t=e?.catalog;if(t===void 0)return;let n=[`Catalog: ${t.status}`];t.entries!==void 0&&n.push(`${t.entries.length} model(s)`),t.lastVerifiedAt!==void 0&&n.push(`verified ${t.lastVerifiedAt}`),t.sourceUrl!==void 0&&n.push(`source ${t.sourceUrl}`);let r=e?.refreshMessage;return r===void 0?t.message!==void 0&&n.push(t.message):n.push(`refresh ${r}`),n.join(`; `)}const ks=[{code:`ko`,description:`Korean`},{code:`en`,description:`English`},{code:`ja`,description:`Japanese`},{code:`zh`,description:`Chinese`}];function As(e=`language`){return ks.map(t=>({name:t.code,description:t.description,source:e}))}function js(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Ms(e=`language`){return`Usage: ${e} <code> (e.g., ko, en, ja, zh)`}const Ns=[`plan`,`default`,`acceptEdits`,`bypassPermissions`];function Ps(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 Fs(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Is(e){return Ns.includes(e)}function Ls(){return`Invalid mode. Valid: ${Ns.join(` | `)}`}function X(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 Rs(e){return X(e).getPermissionMode()}function zs(e,t){X(e).setPermissionMode(t)}function Bs(e){return X(e).listSessionAllowedTools()}function Vs(e){return{mode:Rs(e),sessionAllowed:Bs(e)}}function Hs(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(`
|
|
86
|
+
`)}const Us={enabled:!0,gitBranch:!0};function Ws(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 Gs(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function Ks(){return{type:`plugin-tui-requested`}}function qs(){return{type:`plugin-registry-reload-requested`}}function Js(e){return e.getCommandHostAdapters?.().plugin}function Ys(){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 Xs(e){if(e.clearConversationHistory!==void 0){e.clearConversationHistory();return}e.getSession().clearHistory()}function Zs(e){let t=e.trim();return t.length>0?t:void 0}function Qs(e){return{type:`session-renamed`,name:e}}function $s(){return{type:`session-picker-requested`}}function ec(){return{type:`session-exit-requested`}}function tc(e){let t=e.getSession();return{sessionId:t.getSessionId(),messageCount:t.getMessageCount()}}function nc(e){let t=e.validateCurrentSessionReplayLog?.();if(t!==void 0)return t;let n=e.getSession().getSessionId(),r=(0,m.join)(z(e.getCwd()).logs,`${n}.jsonl`),i=(0,f.loadSessionLogEntries)(r);return{logFile:r,entryCount:i.length,validation:(0,f.validateSessionReplayLogEntries)(i)}}function rc(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(`
|
|
87
|
+
`);let r=e.validation.issues.map((e,t)=>{let n=ic(e);return`${t+1}. ${e.code}${n}: ${e.message}`});return[t,...n,``,...r].join(`
|
|
88
|
+
`)}function ic(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 ac(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 oc(e){return e.listEditCheckpoints()}function sc(e,t){if(!e.inspectEditCheckpoint)throw Error(`Checkpoint inspection is not available in this command host.`);return e.inspectEditCheckpoint(t)}function cc(e,t){return e.restoreEditCheckpoint(t)}function lc(e,t){return e.rollbackEditCheckpoint(t)}const uc=[/\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 dc(e){return uc.some(t=>t.test(e))}function fc(e){return(0,m.join)(e,`.robota`,`memory`)}function pc(){return{version:1,records:[]}}var mc=class{fs;path;now;constructor(e,t=()=>new Date,n=new N){this.fs=n,this.path=(0,m.join)(fc(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 pc();try{return{version:1,records:JSON.parse(this.fs.readFileSync(this.path,`utf8`)).records??[]}}catch{return pc()}}write(e){this.fs.mkdirSync((0,m.dirname)(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,JSON.stringify(e,null,2),`utf8`)}};function hc(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 gc(e,t){return new Xr(e,t)}function _c(e,t){return new mc(e,t)}function vc(e,t){let n=e.getCwd();return{project:gc(n,t),pending:_c(n,t)}}function yc(e){return Ur(e)}function bc(e){return dc(e)}function xc(e){return e.getUsedMemoryReferences()}function Sc(e,t,n=()=>new Date){e.recordMemoryEvent({...t,at:n().toISOString()})}function Cc(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 wc(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 Tc(e,t,n,r){return e.skillContent?Cc(await wc(e.skillContent,n.shellExec),t,r):null}async function Ec(e,t,n,r){let i=await Tc(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 Dc(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 Tc(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 Ec(e,t,n,r)}}function Oc(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function kc(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Ac(e,t){let n=t.trim();return n.length>0?`${e} ${n}`:e}function jc(e){if(!e?.startsWith(`/`))return;let t=e.slice(1).trim().split(/\s+/)[0];return t&&t.length>0?t:void 0}var Mc=class{getSession;getSessionId;onSubmit;onApplyResult;recordSkillActivation;runSkillInFork;onForkSkill;onBlockingCommand;shellExec;commandExecutor;skillCommandSource;commandHostAdapters;commandInvocationSource=`user`;constructor(e,t,n,r,i,a,o,s,c,l,u,d){this.getSession=r,this.getSessionId=i,this.onSubmit=a,this.onApplyResult=o,this.recordSkillActivation=s,this.runSkillInFork=c,this.onForkSkill=l,this.onBlockingCommand=u,this.shellExec=d,this.commandExecutor=new lo(e.flatMap(e=>e.systemCommands??[])),this.skillCommandSource=new Sn(t),this.commandHostAdapters=n}getCommandInvocationSource(){return this.commandInvocationSource}getCommandHostAdapters(){return this.commandHostAdapters??{}}listCommands(){return this.commandExecutor.listCommands().map(e=>({name:e.name,...e.displayName===void 0?{}:{displayName:e.displayName},description:e.description}))}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=Oc(e);return this.skillCommandSource.getCommands().find(e=>e.name.toLowerCase()===t.toLowerCase())}async executeCommand(e,t){let n=kc(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,Ac(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=jc(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 Dc(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=ro({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)}`}}}};async function Nc(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 bi(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(`
|
|
89
|
+
|
|
90
|
+
`),d.map(e=>e.content).join(`
|
|
91
|
+
|
|
92
|
+
`));i().updateSystemMessage(f);for(let e of l)a(`context_file_refreshed`,{filePath:e})}function Pc(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 Fc(e,t,n){let r=e?.[t]??e?.[n];return typeof r==`string`?r:null}function Ic(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 Lc(e){if(e.toolName!==`Edit`)return{};let t=Fc(e.toolArgs,`file_path`,`filePath`),n=Fc(e.toolArgs,`old_string`,`oldString`),r=Fc(e.toolArgs,`new_string`,`newString`);return!t||n===null||r===null||n===r?{}:{diffFile:t,diffLines:zc(n,r,Ic(e.toolResultData),t)}}function Rc(e,t,n){return[...e.split(`
|
|
93
|
+
`).map((e,t)=>({type:`remove`,text:e,lineNumber:n+t})),...t.split(`
|
|
94
|
+
`).map((e,t)=>({type:`add`,text:e,lineNumber:n+t}))]}function zc(e,t,n,r,i=new N){let a=Rc(e,t,n),o;try{o=i.readFileSync(r,`utf8`).split(`
|
|
95
|
+
`)}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(`
|
|
96
|
+
`).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(`
|
|
97
|
+
`).length,p=t.split(`
|
|
98
|
+
`).length;return[{type:`hunk`,text:`@@ -${d},${s.length+f+l.length} +${d},${s.length+p+l.length} @@`,lineNumber:d},...s,...a,...l]}function Z(e){if(e.activeTools.length===0)return;let t=e.activeTools.map(e=>`${e.isRunning?`⟳`:e.result===`success`?`✓`:e.result===`error`?`✗`:`⊘`} ${e.toolName}${e.firstArg?`(${e.firstArg})`:``}`).join(`
|
|
99
|
+
`);e.history.push({id:(0,p.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:t}})}function Bc(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 Vc(e,t){let n=Pc(t.toolArgs),r={toolName:t.toolName,firstArg:n,isRunning:!0};return e.activeTools.push(r),e.history.push({id:(0,p.randomUUID)(),timestamp:new Date,category:`event`,type:`tool-start`,data:{toolName:t.toolName,firstArg:n,isRunning:!0}}),r}function Hc(e,t){let n=t.denied?`denied`:t.success===!1?`error`:`success`,r=e.activeTools.findIndex(e=>e.toolName===t.toolName&&e.isRunning);if(r===-1)return null;let i={...e.activeTools[r],...Lc(t),isRunning:!1,result:n,toolResultData:t.toolResultData};return e.activeTools[r]=i,e.activeTools=Bc(e.activeTools),e.history.push({id:(0,p.randomUUID)(),timestamp:new Date,category:`event`,type:`tool-end`,data:{toolName:i.toolName,firstArg:i.firstArg,isRunning:!1,result:n,toolResultData:t.toolResultData}}),i}async function Uc(e,t,n,r){let i=r.getHistory();i.push((0,c.messageToHistoryEntry)((0,c.createUserMessage)(t??e))),r.onWorkspaceUpdated();let a=r.getSession().getHistory().length;r.resetUsedMemoryReferences();try{let o=await Ma(e,r.getCwd(),n,r.getContextReferences());o.promptFileReferenceEntry&&i.push(o.promptFileReferenceEntry),r.recordContextReferenceUsage(o.activeContextReferenceRecords),r.recordPromptContextReferences(o.promptFileReferenceRecords),await r.beginEditCheckpointTurn(t??e);let s=await r.getSession().run(o.modelInput,o.hookInput);r.flushStreaming(),Z({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let l=ka(s||`(empty response)`,r.getSession().getHistory(),i,a,r.getSession().getContextState(),o.promptFileReferenceRecords);i.push((0,c.messageToHistoryEntry)((0,c.createAssistantMessage)(l.response))),l.usage&&i.push(ja(l.usage)),r.onComplete(l),r.onContextUpdate()}catch(e){if(r.flushStreaming(),Da(e)){let e=Aa(r.getSession().getHistory(),i,a,r.getSession().getContextState());Z({activeTools:r.getActiveTools(),history:i}),r.clearStreaming(),e.response&&i.push((0,c.messageToHistoryEntry)((0,c.createAssistantMessage)(e.response))),e.usage&&i.push(ja(e.usage)),i.push((0,c.messageToHistoryEntry)((0,c.createSystemMessage)(`Interrupted by user.`))),r.onInterrupted(e)}else{Z({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let t=e instanceof Error?e.message:String(e);i.push((0,c.messageToHistoryEntry)((0,c.createSystemMessage)(`Error: ${t}`))),r.onError(e instanceof Error?e:Error(t))}}}var Wc=class{histTracker;skillRouter;callbacks;executing=!1;streamingText=``;flushTimer=null;activeTools=[];pendingPrompt=null;pendingDisplayInput;pendingRawInput;shuttingDown=!1;constructor(e,t,n){this.histTracker=e,this.skillRouter=t,this.callbacks=n}clearPendingQueue(){this.pendingPrompt=null,this.pendingDisplayInput=void 0,this.pendingRawInput=void 0}clearStreaming(){this.streamingText=``,this.activeTools=[],this.flushTimer&&=(clearTimeout(this.flushTimer),null)}flushStreaming(){this.flushTimer&&=(clearTimeout(this.flushTimer),null)}handleTextDelta(e){this.streamingText+=e,this.callbacks.emit(`text_delta`,e),this.flushTimer||=setTimeout(()=>{this.flushTimer=null},16)}handleCompactEvent(e){e.trigger===`auto`&&this.histTracker.append((0,c.messageToHistoryEntry)((0,c.createSystemMessage)(`Auto compacted context: ${Math.round(e.before.usedPercentage)}% -> ${Math.round(e.after.usedPercentage)}%`))),this.callbacks.emit(`compact`,e),this.callbacks.emit(`context_update`,e.after)}handleToolExecution(e){let t={activeTools:this.activeTools,history:this.histTracker.getHistory()};if(e.type===`start`){let n=Vc(t,e);this.activeTools=t.activeTools,this.callbacks.emit(`tool_start`,n)}else{let n=Hc(t,e);this.activeTools=t.activeTools,n&&this.callbacks.emit(`tool_end`,n)}}emitExecutionWorkspaceUpdated(e,t){this.callbacks.getSession()&&this.callbacks.emit(`execution_workspace_event`,{type:`execution_workspace_updated`,cause:e,...t?{entryId:t}:{},snapshot:this.callbacks.getExecutionWorkspaceSnapshot()})}drainPendingQueue(e){if(!this.shuttingDown&&this.pendingPrompt){let t=this.pendingPrompt,n=this.pendingDisplayInput,r=this.pendingRawInput;this.clearPendingQueue(),setTimeout(()=>void e(t,n,r),0)}}async executePrompt(e,t,n,r,i,a,o,s){await Nc(r,i,a,o,()=>this.callbacks.getSessionOrThrow(),(e,t)=>this.callbacks.emit(e,t)),this.executing=!0,this.clearStreaming(),this.callbacks.emit(`user_message`,t??e),this.callbacks.emit(`thinking`,!0);try{await Uc(e,t,n,{getSession:()=>this.callbacks.getSessionOrThrow(),getCwd:()=>this.callbacks.getCwd(),getHistory:()=>this.histTracker.getHistory(),getContextReferences:()=>this.histTracker.listContextReferences(),getActiveTools:()=>this.activeTools,resetUsedMemoryReferences:()=>this.histTracker.resetUsedMemoryReferences(),recordContextReferenceUsage:e=>this.histTracker.recordContextReferenceUsage(e),recordPromptContextReferences:e=>this.histTracker.recordPromptContextReferences(e),beginEditCheckpointTurn:e=>this.histTracker.beginEditCheckpointTurn(e),flushStreaming:()=>this.flushStreaming(),clearStreaming:()=>this.clearStreaming(),onWorkspaceUpdated:()=>this.emitExecutionWorkspaceUpdated(`main_thread`),onComplete:e=>{this.callbacks.emit(`complete`,e)},onInterrupted:e=>{this.callbacks.emit(`interrupted`,e)},onError:e=>{this.callbacks.emit(`error`,e)},onContextUpdate:()=>{this.callbacks.emit(`context_update`,this.callbacks.getContextState())}})}finally{try{await this.histTracker.finalizeEditCheckpointTurn()}catch(e){this.callbacks.emit(`error`,e instanceof Error?e:Error(String(e)))}this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(s)}}async executeForkSkillCommand(e,t,n,r,i,a){if(this.executing)throw Error(`Cannot execute fork skill while another prompt is running.`);this.executing=!0,this.clearStreaming(),this.callbacks.emit(`thinking`,!0),this.histTracker.append((0,c.messageToHistoryEntry)((0,c.createUserMessage)(n??`/${e.name}`))),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let n=await this.skillRouter.executeSkillWithActivation(e,t,i,r);return await this.applyForkSkillResult(n.result??`(empty response)`),n}catch(e){let t=e instanceof Error?e:Error(String(e));return this.histTracker.append((0,c.messageToHistoryEntry)((0,c.createSystemMessage)(`Error: ${t.message}`))),this.callbacks.emit(`error`,t),{mode:`fork`,result:``}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(a)}}async executeForegroundCommand(e,t){this.executing=!0,this.clearStreaming(),this.callbacks.emit(`thinking`,!0),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let t=await e();return this.callbacks.emit(`context_update`,this.callbacks.getContextState()),t}catch(e){return{success:!1,message:`Error: ${e instanceof Error?e.message:String(e)}`}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(t)}}async applyForkSkillResult(e){this.flushStreaming(),Z({activeTools:this.activeTools,history:this.histTracker.getHistory()}),this.clearStreaming();let t={response:e,history:this.histTracker.getHistory(),toolSummaries:[],contextState:this.callbacks.getContextState()};this.histTracker.append((0,c.messageToHistoryEntry)((0,c.createAssistantMessage)(e))),this.callbacks.emit(`complete`,t),this.callbacks.emit(`context_update`,this.callbacks.getContextState())}};function Gc(e){let t=M(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 Q(e){let t=Gc(e);if(!t.subagentManager)throw Error(`Subagent manager is not available for this session.`);return t.subagentManager}function Kc(e,t){let n=t.customAgentRegistry?.(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function qc(e){return(M(e)?.agentDefinitions??[]).map(e=>({name:e.name,description:e.description}))}async function Jc(e,t,n,r){let i=Gc(e),a=Kc(t.agentType,i),o=e.getSessionId();return Q(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:O({kind:r===`model`?`model_command`:`slash_command`,sessionId:o,commandName:`agent`,label:t.label})})}async function Yc(e,t){return Q(e).wait(t)}async function Xc(e,t,n){await Q(e).send(t,n)}async function Zc(e,t,n){await Q(e).cancel(t,n)}async function Qc(e,t){await Q(e).close(t)}function $c(e){return Q(e).list()}function el(e,t={}){let{sessionId:n,execCtrl:r,histTracker:i,bgTracker:a}=e,o=i.getHistory();return Fe({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 tl(e,t,n,r,i){let a=Pe(e);if(!a)throw Error(`Unknown execution workspace entry: ${e}`);return a.kind===`main_thread`?Qe({entryId:e,history:t(),cursor:i}):a.kind===`background_group`?n.readGroupDetail(e,a.sourceId,r):n.readTaskDetail(e,a.sourceId,i)}function nl(e,t,n,r){return tt({manager:e.getManagerOrThrow(),groupOrchestrator:e.getOrchestratorOrThrow(t),sessionId:t,cwd:n,origin:{...r,sessionId:r.sessionId||t}})}var rl=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 el({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(),tl(e,()=>this.histTracker.getHistory(),this.bgTracker,this.getSessionOrThrow().getSessionId(),t)}createExecutionWorkspaceTaskSpawner(e){return nl(this.bgTracker,this.getSessionOrThrow().getSessionId(),this.getCwd(),e)}listAgentDefinitions(){return qc(this.getSessionOrThrow())}listAgentJobs(){return $c(this.getSessionOrThrow())}async spawnAgentJob(e){return await this.ensureInitialized(),Jc(this.getSessionOrThrow(),e,this.getCwd(),this.skillRouter.getCommandInvocationSource())}async waitAgentJob(e){return await this.ensureInitialized(),Yc(this.getSessionOrThrow(),e)}async sendAgentJob(e,t){await this.ensureInitialized(),await Xc(this.getSessionOrThrow(),e,t)}async cancelAgentJob(e,t){await this.ensureInitialized(),await Zc(this.getSessionOrThrow(),e,t)}async closeAgentJob(e){await this.ensureInitialized(),await Qc(this.getSessionOrThrow(),e)}},il=class extends rl{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;bgTracker;histTracker;skillRouter;execCtrl;constructor(e){super(),this.sessionStore=e.sessionStore,this.sessionName=e.sessionName,this.cwd=(`cwd`in e?e.cwd:void 0)??``,this.resumeSessionId=e.resumeSessionId,this.forkSession=e.forkSession??!1,this.sandboxClient=`sandboxClient`in e?e.sandboxClient:void 0,this.sandboxSnapshotId=`sandboxSnapshotId`in e?e.sandboxSnapshotId:void 0;let t=this.cwd,n=null;`session`in e&&e.session&&t&&(n=new K({cwd:t})),this.bgTracker=new Za(()=>this.getBackgroundTaskManager(),(e,t)=>this.execCtrl.emitExecutionWorkspaceUpdated(e,t),e=>this.emit(`background_task_event`,e),e=>this.emit(`background_job_group_event`,e),()=>this.persistCurrentSession()),this.histTracker=new ao(t,()=>this.getSessionOrThrow().getSessionId(),()=>this.execCtrl.executing,()=>this.persistCurrentSession(),e=>this.emit(`skill_activation`,e),n);let r=[...`commandModules`in e?e.commandModules??[]:[]],i=`commandHostAdapters`in e?e.commandHostAdapters:void 0,a=`shellExec`in e?e.shellExec:void 0;this.skillRouter=new Mc(r,t,i,()=>this,()=>this.session?.getSessionId()??``,(e,t,n)=>this.submit(e,t,n),e=>this.execCtrl.applyForkSkillResult(e),(e,t)=>this.histTracker.recordSkillActivationEvent(e,t),(e,t)=>At(e,t,this.getSessionOrThrow()),(e,t,n,r,i)=>this.execCtrl.executeForkSkillCommand(e,t,n,r,i,(e,t,n)=>this.submit(e,t,n)),e=>this.execCtrl.executeForegroundCommand(e,(e,t,n)=>this.submit(e,t,n)),a),this.execCtrl=new Wc(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()});let o=this.configureInjectedSession(e);this.restoreSessionRecordIfNeeded(e),this.startAsyncInitializationIfNeeded(e,o),this.initialized&&this.bgTracker.subscribe(this.session),this.initialized&&this.persistCurrentSession()}configureInjectedSession(e){return`session`in e&&e.session?(this.session=e.session,this.autoCompactThresholdSource=`session`,this.initialized=!0,!0):!1}restoreSessionRecordIfNeeded(e){if(!e.resumeSessionId||!this.sessionStore)return;let t=Vt(this.sessionStore,e.resumeSessionId,this.forkSession,this.session);this.histTracker.restoreState({history:t.history,memoryEvents:t.memoryEvents,usedMemoryReferences:t.usedMemoryReferences,contextReferences:t.contextReferences,skillActivationEvents:t.skillActivationEvents}),t.sessionName&&(this.sessionName=t.sessionName),this.bgTracker.restoreState({tasks:t.backgroundTasks,taskEvents:t.backgroundTaskEvents,groups:t.backgroundJobGroups,groupEvents:t.backgroundJobGroupEvents}),this.pendingRestoreMessages=t.pendingRestoreMessages,this.sandboxSnapshotId=this.forkSession?void 0:t.sandboxSnapshotId}startAsyncInitializationIfNeeded(e,t){if(t)return;let n=e;this.initPromise=this.initializeAsync(n)}async initializeAsync(e){let t=await Xa(e,{sandboxSnapshotId:this.sandboxSnapshotId,resumeSessionId:this.resumeSessionId,pendingRestoreMessages:this.pendingRestoreMessages,onTextDelta:e=>this.execCtrl.handleTextDelta(e),onContextUpdate:e=>this.emit(`context_update`,e),onCompactEvent:e=>this.execCtrl.handleCompactEvent(e),onToolExecution:e=>this.execCtrl.handleToolExecution(e),executeModelCommand:(e,t)=>this.executeModelCommand(e,t),isModelCommandInvocable:e=>this.skillRouter.commandExecutor.isModelInvocable(e),commandDescriptors:this.skillRouter.commandExecutor.listModelInvocableCommands(),setEditCheckpointStore:e=>this.histTracker.setEditCheckpointStore(e)});this.session=t.session,this.agentsFileEntries=t.agentsFileEntries,this.claudeFileEntries=t.claudeFileEntries,this.rebuildSystemMessage=t.rebuildSystemMessage,this.autoCompactThresholdSource=t.autoCompactThresholdSource,this.pendingRestoreMessages=null,this.initialized=!0,this.bgTracker.subscribe(this.session),this.persistCurrentSession()}async ensureInitialized(){!this.initialized&&this.initPromise&&await this.initPromise}getSessionOrThrow(){if(!this.session)throw Error(`InteractiveSession not initialized. Call submit() or await initialization.`);return this.session}getCwd(){if(!this.cwd)throw Error(`cwd is not set — provide cwd in session options`);return this.cwd}get sessionId(){return this.session?.getSessionId()??``}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,...t){let n=this.listeners.get(e);if(n)for(let e of n)e(...t)}async submit(e,t,n){if(await this.ensureInitialized(),this.execCtrl.shuttingDown)throw Error(`Interactive session is shutting down.`);if(this.execCtrl.executing){this.execCtrl.pendingPrompt=e,this.execCtrl.pendingDisplayInput=t,this.execCtrl.pendingRawInput=n;return}await this.execCtrl.executePrompt(e,t,n,this.agentsFileEntries,this.claudeFileEntries,this.rebuildSystemMessage,(e,t)=>{this.agentsFileEntries=e,this.claudeFileEntries=t},(e,t,n)=>this.submit(e,t,n))}abort(){this.execCtrl.clearPendingQueue(),this.session?.abort()}shutdown(e={}){return this.shutdownPromise?this.shutdownPromise:(this.execCtrl.shuttingDown=!0,this.shutdownPromise=(async()=>{await this.ensureInitialized(),this.execCtrl.clearPendingQueue();let t=this.session;t?.abort(),await this.getBackgroundTaskManager()?.shutdown(e.message??`Session shutdown`),this.bgTracker.dispose(),await this.captureSandboxSnapshot(),this.persistCurrentSession(),await t?.shutdown({reason:e.reason??`other`})})(),this.shutdownPromise)}get isInitialized(){return this.initialized}getAutoCompactThresholdSource(){return this.autoCompactThresholdSource}getAutoCompactThreshold(){return this.getSessionOrThrow().getAutoCompactThreshold()}getSession(){return this.getSessionOrThrow()}getAgentJobCapability(){return this}setAutoCompactThreshold(e,t=`session`){this.getSessionOrThrow().setAutoCompactThreshold(e),this.autoCompactThresholdSource=t,this.emit(`context_update`,this.getContextState()),this.persistCurrentSession()}clearConversationHistory(){this.getSessionOrThrow().clearHistory(),this.histTracker.clearHistory(),this.persistCurrentSession(),this.emit(`context_update`,this.getContextState())}getName(){return this.sessionName}attachTransport(e){e.attach(this)}setName(e){if(this.sessionName=e,this.sessionStore&&this.session)try{let t=this.getSessionOrThrow().getSessionId(),n=this.sessionStore.load(t);n&&(n.name=e,n.updatedAt=new Date().toISOString(),this.sessionStore.save(n))}catch{}}getBackgroundTaskManager(){if(this.session)return Nt(this.session)??M(this.session)?.backgroundTaskManager}async captureSandboxSnapshot(){if(this.sandboxClient?.snapshot)try{this.sandboxSnapshotId=await this.sandboxClient.snapshot()}catch(e){let t=e instanceof Error?e:Error(String(e));this.histTracker.append((0,c.messageToHistoryEntry)((0,c.createSystemMessage)(`Sandbox snapshot error: ${t.message}`))),this.emit(`error`,t)}}persistCurrentSession(){if(!this.sessionStore||!this.session)return;let e=this.bgTracker.getState(),t=this.histTracker.getState();Pt(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})}};function al(e,t=new N){let n=z(e);return new ll(n.sessions,n.logs,t)}function ol(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:ul(e.messages)}))}function sl(e,t){return ol(e,t)[0]?.id}function cl(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var ll=class{store;logsDir;fs;constructor(e,t,n=new N){this.store=new f.SessionStore(e),this.logsDir=t,this.fs=n}save(e){this.store.save(dl(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):fl(t)}list(){let e=this.store.list().map(fl),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,f.replaySessionLogEntries)((0,f.loadSessionLogEntries)((0,m.join)(this.logsDir,`${e}.jsonl`)));if(!t.sessionId||t.messages.length===0)return;let n=t.backgroundTaskEvents,r=t.backgroundJobGroupEvents;return{id:t.sessionId,cwd:t.cwd??``,createdAt:t.createdAt??t.updatedAt??new Date(0).toISOString(),updatedAt:t.updatedAt??t.createdAt??new Date(0).toISOString(),messages:t.messages,history:t.history,backgroundTasks:pl(n),backgroundTaskEvents:n,backgroundJobGroups:hl(r),backgroundJobGroupEvents:r,skillActivationEvents:[],memoryEvents:t.memoryEvents}}listReplayLogRecords(){return!this.logsDir||!this.fs.existsSync(this.logsDir)?[]:this.fs.readdirSync(this.logsDir).filter(e=>e.endsWith(`.jsonl`)).map(e=>this.loadFromReplayLog(e.slice(0,-6))).filter(e=>e!==void 0)}};function ul(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 dl(e){return{...e}}function fl(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 pl(e){let t=new Map;for(let n of e){let e=ml(n);e&&t.set(e.id,e)}return[...t.values()]}function ml(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 hl(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function gl(e){let t=new il({cwd:e.cwd??process.cwd(),provider:e.provider,permissionMode:e.permissionMode??`bypassPermissions`,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler});return e.onTextDelta&&t.on(`text_delta`,e.onTextDelta),async e=>new Promise((n,r)=>{let i=e=>{s(),n(e.response)},a=e=>{s(),n(e.response)},o=e=>{s(),r(e)},s=()=>{t.off(`complete`,i),t.off(`interrupted`,a),t.off(`error`,o)};t.on(`complete`,i),t.on(`interrupted`,a),t.on(`error`,o),t.submit(e).catch(e=>{s(),r(e instanceof Error?e:Error(String(e)))})})}const _l=[`preferences`,`view-state`,`memory-projections`,`task-associations`,`workflow-metadata`,`inspection-index`],vl=[{category:`preferences`,purpose:`User-local UI and display preferences.`,mayExecuteCommands:!1},{category:`view-state`,purpose:`Last selected panels, filters, and navigation state.`,mayExecuteCommands:!1},{category:`memory-projections`,purpose:`Inspectable local memory item projections and user choices.`,mayExecuteCommands:!1},{category:`task-associations`,purpose:`User-local associations between sessions, tasks, and background items.`,mayExecuteCommands:!1},{category:`workflow-metadata`,purpose:`Transparent workflow metadata that is not repo-owned.`,mayExecuteCommands:!1},{category:`inspection-index`,purpose:`Category and item summaries for user inspection and deletion.`,mayExecuteCommands:!1}];function yl(e){return e.toISOString()}function bl(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!m.default.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function xl(){return process.env.HOME??(0,h.homedir)()}function Sl(e,t){let n=m.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!m.default.isAbsolute(n)}async function Cl(e,t){let n=e;for(;m.default.dirname(n)!==n;)try{let r=await t.realpath(n),i=m.default.relative(n,e);return m.default.resolve(r,i)}catch{n=m.default.dirname(n)}try{return await t.realpath(n)}catch{return m.default.resolve(e)}}async function wl(e){let t=e.fsAsync??new P,n=m.default.resolve(e.activeRepositoryRoot);bl(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?m.default.join(e.homeDir??xl(),`.robota`):e.storageRoot;bl(`userLocalStorageRoot`,r);let i=m.default.resolve(r),a=await Cl(i,t);if(Sl(await Cl(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function Tl(e,t){return m.default.join(e,t)}async function El(e,t,n){let r=Tl(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=m.default.join(r,i.name),o=await n.stat(a),s=i.name;return{root:e,category:t,key:s,summary:`${t}/${s}`,source:`user-local-storage`,scope:`user`,storageLocation:a,createdAt:yl(new Date(o.birthtimeMs)),lastUsedAt:yl(new Date(o.mtimeMs)),enabled:!0,deleteAvailable:!0,disableAvailable:!1}}))).sort((e,t)=>e.key.localeCompare(t.key))}async function Dl(e){let t=e.fsAsync??new P,n=await wl(e),r=m.default.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all(vl.map(async e=>{let r=Tl(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await El(n,e.category,t);return{category:e.category,purpose:e.purpose,mayExecuteCommands:e.mayExecuteCommands,storageLocation:r,itemCount:a.length,items:a}})),generatedAt:yl((e.now??(()=>new Date))())}}const Ol=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],kl=`.json`,Al=/^[a-z0-9][a-z0-9._-]*$/u,jl={"view-preference":`May affect UI panel, filter, density, or sorting display/navigation only.`,"last-visible-cwd":`May display or preselect an already visible workspace context only.`,"background-selection":`May restore the selected background entry in local UI only.`,"task-association":`May group visible tasks by a local association only.`,"display-preference":`May affect local text wrapping, compactness, or visibility only.`,"inspection-choice":`May affect inspection display choices only.`};function Ml(e){return e.toISOString()}function Nl(e){return Ol.includes(e)}function Pl(e){if(!Nl(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function Fl(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!Al.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function Il(e,t,n){let r=t.trim().replace(/\s+/g,` `);if(r.length===0)throw Error(`${e} must not be empty.`);return r.length>n?r.slice(0,n):r}function Ll(e){return Il(`value`,e,240)}function Rl(e,t){return`${e}__${t}${kl}`}async function zl(e){let t=await wl(e);return{root:t,memoryRoot:m.default.join(t,`memory-projections`)}}function Bl(e,t){let n=JSON.parse(e),r=$(n,`category`);if(n.schemaVersion!==1)throw Error(`Unsupported user-local memory schema at ${t}`);return{schemaVersion:1,category:Pl(r),key:$(n,`key`),value:$(n,`value`),summary:$(n,`summary`),source:$(n,`source`),scope:$(n,`scope`),createdAt:$(n,`createdAt`),lastUsedAt:$(n,`lastUsedAt`),enabled:Vl(n,`enabled`)}}function $(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function Vl(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function Hl(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:Ll(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:jl[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function Ul(e,t,n){return Hl(e,t,Bl(await n.readFile(t,`utf8`),t))}async function Wl(e){let t=Pl(e.category),n=Fl(`key`,e.key),{root:r,memoryRoot:i}=await zl(e);return{root:r,storageLocation:m.default.join(i,Rl(t,n))}}async function Gl(e){let t=e.fsAsync??new P,n=Pl(e.category),r=Fl(`key`,e.key),i=Il(`summary`,e.summary,240),a=Il(`source`,e.source,80),o=Il(`scope`,e.scope??`user`,120),s=Ll(e.value),c=Ml((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await zl(e),d=m.default.join(u,Rl(n,r)),f=c;try{f=Bl(await t.readFile(d,`utf8`),d).createdAt}catch(e){if(e instanceof Error&&e.message.includes(`ENOENT`))f=c;else throw e}let p={schemaVersion:1,category:n,key:r,value:s,summary:i,source:a,scope:o,createdAt:f,lastUsedAt:c,enabled:!0};return await t.mkdir(u,{recursive:!0}),await t.writeFile(d,`${JSON.stringify(p,null,2)}\n`,`utf8`),Hl(l,d,p)}async function Kl(e){let t=e.fsAsync??new P,{root:n,memoryRoot:r}=await zl(e),i;try{i=await t.readdir(r,{withFileTypes:!0})}catch{i=[]}let a=await Promise.all(i.filter(e=>e.isFile()&&e.name.endsWith(kl)).map(e=>Ul(n,m.default.join(r,e.name),t)));return{root:n,activeRepositoryRoot:m.default.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function ql(e){let t=e.fsAsync??new P,{root:n,storageLocation:r}=await Wl(e);return Ul(n,r,t)}async function Jl(e){let t=e.fsAsync??new P,{root:n,storageLocation:r}=await Wl(e),i={...Bl(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:Ml((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),Hl(n,r,i)}async function Yl(e){let t=e.fsAsync??new P,{storageLocation:n}=await Wl(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}async function Xl(e){let t=await ql(e);return t.enabled?t:null}const Zl=[`test`,`typecheck`,`build`],Ql={idle:{checkpoint_created:`checkpointed`,cancelled:`cancelled`},checkpointed:{edits_started:`editing`,cancelled:`cancelled`},editing:{edits_applied:`verifying`,verify_failed:`failed`,cancelled:`cancelled`},verifying:{verify_passed:`passed`,verify_failed:`failed`,cancelled:`cancelled`},passed:{},failed:{rollback_completed:`rolled_back`,cancelled:`cancelled`},rolled_back:{},cancelled:{}};function $l(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))):[]}function eu(e){return e.flatMap(e=>Zl.map(t=>({id:`package-${t}:${e}`,phase:`verify`,description:`Run ${t} for ${e} in a child process against the new on-disk tree.`,required:!0,command:`pnpm --filter ${e} ${t}`})))}function tu(){return[{id:`checkpoint`,phase:`checkpoint`,description:`Create a recoverable turn-level checkpoint before the first mutation.`,required:!0},{id:`atomic-edit`,phase:`edit`,description:`Apply Write/Edit mutations through same-directory temp files and atomic rename.`,required:!0},{id:`handoff`,phase:`handoff`,description:`Keep the current process on already-loaded code and run verification child processes against disk.`,required:!0}]}function nu(e){return{id:`harness-verify`,phase:`verify`,description:`Run Robota harness verification as the local CI-like gate.`,required:!0,command:`pnpm harness:verify -- --base-ref ${e} --skip-record-check`}}function ru(){return{id:`rollback-on-failure`,phase:`recover`,description:`Use the existing edit checkpoint restore path if verification fails.`,required:!0}}function iu(e){if(e.changedFiles.length===0)throw Error(`Self-hosting verification requires at least one changed file.`);let t=e.baseRef??`origin/develop`,n=$l(e.packageScopes),r=[...tu(),...eu(n),nu(t),ru()];return{changedFiles:[...e.changedFiles],packageScopes:n,baseRef:t,steps:r}}function au(e,t){let n=Ql[e][t];if(!n)throw Error(`Invalid self-hosting loop transition: ${e} -> ${t}`);return n}function ou(e){return e}function su(e){if(!e||e.length===0)return;let[t,...n]=e;if(t!==void 0)return[t,...n]}function cu(e){let t=su(e),n=t===void 0?l.z.string().describe(`Registered model-invocable command name to execute`):l.z.enum(t).describe(`Registered model-invocable command name to execute`);return l.z.object({command:n,args:l.z.string().optional().describe(`Arguments to pass to the command`)})}function lu(e){if(e.commandNames!==void 0)return e.commandNames;if(e.commandDescriptors!==void 0)return e.commandDescriptors.map(e=>C(e.name))}function uu(e){return`- ${C(e.name)}${e.argumentHint?` ${e.argumentHint}`:``}: ${e.description}`}function du(e){let t=`Executes a registered model-invocable Robota command through the command registry. Accepted command names and argument grammar come from registered command descriptors.`;return e===void 0||e.length===0?t:[t,`Use the registered command descriptors below as the authority for when to call this tool.`,``,`Registered model-invocable commands:`,...e.map(uu)].join(`
|
|
100
|
+
`)}function fu(e){let t=cu(lu(e));return(0,u.createZodFunctionTool)(`ExecuteCommand`,du(e.commandDescriptors),ou(t),async n=>{let r=t.parse(n),i=C(r.command);return e.isModelInvocable(i)?ce(i,await e.execute(i,r.args??``)):JSON.stringify({success:!1,command:i,error:`Command is not model-invocable: ${i}`})})}const pu=[`Allow`,`Deny`];function mu(e){let t=Object.entries(e);return t.length===0?`(no arguments)`:t.map(([e,t])=>`${e}: ${typeof t==`string`?t:JSON.stringify(t)}`).join(`, `)}async function hu(e,t,n){return e.writeLine(``),e.writeError(`[Permission Required] Tool: ${t}`),e.writeLine(` ${mu(n)}`),e.writeLine(``),await e.select(pu,0)===0}const gu={usedTokens:0,maxTokens:2e5,usedPercentage:0,remainingPercentage:100},_u={sessionId:`test-session-id`,updatedAt:new Date().toISOString(),entries:[]},vu={id:``,parentSessionId:`test-session-id`,waitPolicy:`wait_all`,taskIds:[],status:`completed`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),results:[]};function yu(e){return{submit:()=>Promise.resolve(),abort:()=>{},cancelQueue:()=>{},shutdown:()=>Promise.resolve(),isExecuting:()=>!1,getPendingPrompt:()=>null,getMessages:()=>[],getContextState:()=>({...gu}),getSession:()=>({getSessionId:()=>`test-session-id`}),getCwd:()=>`/workspace`,executeCommand:()=>Promise.resolve(null),listCommands:()=>[],on:()=>{},off:()=>{},listBackgroundTasks:()=>[],getBackgroundTask:()=>void 0,cancelBackgroundTask:()=>Promise.resolve(),closeBackgroundTask:()=>Promise.resolve(),sendBackgroundTask:()=>Promise.resolve(),readBackgroundTaskLog:()=>Promise.resolve({taskId:``,lines:[]}),listBackgroundJobGroups:()=>[],getBackgroundJobGroup:()=>void 0,createBackgroundJobGroup:()=>({...vu}),waitBackgroundJobGroup:()=>Promise.resolve({...vu}),getExecutionWorkspaceSnapshot:()=>({..._u}),listAgentDefinitions:()=>[],listAgentJobs:()=>[],spawnAgentJob:()=>Promise.resolve({id:`agent_1`,type:`general-purpose`,label:`general-purpose`,parentSessionId:`test-session-id`,status:`running`,mode:`background`,depth:1,cwd:`/workspace`,promptPreview:``,updatedAt:new Date().toISOString()}),sendAgentJob:()=>Promise.resolve(),cancelAgentJob:()=>Promise.resolve(),closeAgentJob:()=>Promise.resolve(),...e}}exports.AUTO_COMPACT_THRESHOLD_SETTINGS_KEY=Bo,exports.AgentExecutor=qt,exports.BACKGROUND_COMMAND_DESCRIPTION=`List and control background tasks`,exports.BACKGROUND_COMMAND_USAGE=`Usage: background list | background read <task-id> [offset] | background cancel <task-id> | background close <task-id>`,exports.BUILT_IN_AGENTS=b,exports.BackgroundJobOrchestrator=we,exports.BuiltinCommandSource=fo,exports.BundlePluginInstaller=Mi,exports.BundlePluginLoader=ji,exports.CLEAR_COMMAND_DESCRIPTION=`Clear conversation history`,exports.COST_COMMAND_DESCRIPTION=`Show session info`,exports.CommandRegistry=co,exports.DEFAULT_AUTO_COMPACT_THRESHOLD=zo,exports.DEFAULT_STATUS_LINE_COMMAND_SETTINGS=Us,exports.EXECUTION_ORIGIN_METADATA_KEYS=T,exports.EXIT_COMMAND_DESCRIPTION=`Exit CLI`,exports.EditCheckpointStore=K,exports.HELP_COMMAND_DESCRIPTION=`Show available commands`,exports.InteractiveSession=il,exports.LANGUAGE_COMMAND_ARGUMENT_HINT=`<code>`,exports.LANGUAGE_COMMAND_DESCRIPTION=`Set response language`,exports.MEMORY_COMMAND_ARGUMENT_HINT=`list | show [topic] | add <user|feedback|project|reference> <topic> <text> | pending | approve <id> | reject <id> | used`,exports.MEMORY_COMMAND_DESCRIPTION=`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.`,exports.MEMORY_COMMAND_USAGE=`Usage: memory list | memory show [topic] | memory add <user|feedback|project|reference> <topic> <text> | memory pending | memory approve <id> | memory reject <id> | memory used`,exports.MEMORY_INDEX_MAX_BYTES=Vr,exports.MEMORY_INDEX_MAX_LINES=200,exports.MODEL_COMMAND_ARGUMENT_HINT=`<model-id>`,exports.MODEL_COMMAND_DESCRIPTION=`Change AI model`,exports.MODEL_COMMAND_TOOL_PREFIX=S,exports.MarketplaceClient=Ii,exports.PERMISSIONS_COMMAND_DESCRIPTION=`Show/change permission mode and permission rules`,exports.PERMISSION_MODE_ARGUMENT_HINT=`plan | default | acceptEdits | bypassPermissions`,exports.PERMISSION_MODE_COMMAND_DESCRIPTION=`Show/change permission mode`,exports.PLUGIN_COMMAND_ARGUMENT_HINT=`manage | install <name@marketplace> | uninstall <name@marketplace> | enable <name@marketplace> | disable <name@marketplace> | marketplace <action>`,exports.PLUGIN_COMMAND_DESCRIPTION=`Manage plugins`,exports.PROVIDER_SAFE_TOOL_NAME_PATTERN=re,exports.PluginCommandSource=Ro,exports.PluginSettingsStore=Di,exports.ProjectMemoryStore=Xr,exports.PromptExecutor=Gt,exports.RECOMMENDED_RESPONSE_LANGUAGES=ks,exports.RELOAD_PLUGINS_COMMAND_DESCRIPTION=`Reload all plugin resources`,exports.RENAME_COMMAND_DESCRIPTION=`Rename the current session`,exports.RENAME_COMMAND_USAGE=`Usage: rename <name>`,exports.RESUME_COMMAND_DESCRIPTION=`Resume a previous session`,exports.REWIND_COMMAND_ARGUMENT_HINT=`list | inspect CHECKPOINT_ID | restore CHECKPOINT_ID | code CHECKPOINT_ID | rollback CHECKPOINT_ID`,exports.REWIND_COMMAND_DESCRIPTION=`List, inspect, restore, or rollback edit checkpoints.`,exports.STATUSLINE_COMMAND_ARGUMENT_HINT=`on | off | reset | git on | git off`,exports.STATUSLINE_COMMAND_DESCRIPTION=`Configure TUI status-line visibility and fields such as model, context, tokens, session, and git branch.`,exports.SkillCommandSource=Sn,exports.SystemCommandExecutor=lo,exports.USER_LOCAL_MEMORY_CATEGORIES=Ol,exports.USER_LOCAL_STORAGE_CATEGORIES=_l,exports.USER_LOCAL_STORAGE_CATEGORY_DEFINITIONS=vl,exports.VALIDATE_SESSION_COMMAND_DESCRIPTION=`Validate current session replay log`,exports.VALID_PERMISSION_MODES=Ns,exports.addCommandContextReference=Yo,exports.assembleSubagentPrompt=ne,exports.buildBackgroundCommandSubcommands=rs,exports.buildLanguageCommandSubcommands=As,exports.buildMemoryCommandSubcommands=hc,exports.buildModelCommandSubcommands=ps,exports.buildPermissionModeSubcommands=Ps,exports.buildPluginCommandSubcommands=Ys,exports.buildPromptWithFileReferences=$i,exports.buildProviderProfile=yo,exports.buildProviderSetupPatch=vo,exports.buildRewindCommandSubcommands=ac,exports.buildStatusLineCommandSubcommands=Ws,exports.cancelCommandBackgroundTask=ds,exports.checkSettingsDocument=Oo,exports.clearCommandContextReferences=Zo,exports.clearContextReferences=Wi,exports.clearConversationHistory=Xs,exports.closeCommandBackgroundTask=fs,exports.compactCommandContext=qo,exports.createAgentTool=Ot,exports.createBackgroundGroupExecutionEntryId=Ne,exports.createBackgroundProcessTool=Fn,exports.createBackgroundTaskExecutionEntryId=D,exports.createBuiltinCommandModule=po,exports.createCommandExecutionTool=fu,exports.createCommandMemoryStores=vc,exports.createCommandPendingMemoryStore=_c,exports.createCommandProjectMemoryStore=gc,exports.createContextReferenceItem=Vi,exports.createDefaultTools=Yt,exports.createExecutionOriginMetadata=O,exports.createExecutionWorkspaceSnapshot=Fe,exports.createExecutionWorkspaceTaskSpawner=tt,exports.createInProcessSubagentRunner=Se,exports.createLineDetailPage=j,exports.createMainThreadDetailPage=Qe,exports.createMainThreadExecutionEntryId=E,exports.createModelCommandToolProjection=oe,exports.createPluginRegistryReloadRequestedEffect=qs,exports.createPluginTuiRequestedEffect=Ks,exports.createProjectSessionStore=al,exports.createProjectedCommandExecutionTools=le,exports.createPromptFileReferenceHistoryEntry=na,exports.createProviderSafeModelCommandToolName=ae,exports.createQuery=gl,exports.createSessionExitRequestedEffect=ec,exports.createSessionPickerRequestedEffect=$s,exports.createSessionRenamedEffect=Qs,exports.createSubagentLogger=ur,exports.createSubagentSession=ge,exports.createSystemCommands=J,exports.createTestInteractiveSession=yu,exports.deleteProviderProfile=go,exports.deleteUserLocalMemoryItem=Yl,exports.disableUserLocalMemoryItem=Jl,exports.discoverTaskFiles=di,exports.evaluateReversibleToolSafety=rn,exports.executeSkill=Dc,Object.defineProperty(exports,`findProviderDefinition`,{enumerable:!0,get:function(){return c.findProviderDefinition}}),exports.formatCommandBackgroundTask=is,exports.formatCommandBackgroundTaskList=as,exports.formatCommandHelpMessage=ns,exports.formatCommandPermissionsMessage=Hs,exports.formatCommandSessionReplayValidationReport=rc,Object.defineProperty(exports,`formatEnvReference`,{enumerable:!0,get:function(){return c.formatEnvReference}}),exports.formatInvalidPermissionModeMessage=Ls,exports.formatLanguageUsageMessage=Ms,exports.formatModelCommandUsageMessage=ms,exports.formatModelCommandUsageMessageAsync=hs,exports.formatProjectedModelCommandToolPromptDescription=se,exports.formatPromptFileReferenceDiagnostics=ta,exports.formatTaskContext=mi,exports.getBuiltInAgent=x,exports.getForkWorkerSuffix=te,Object.defineProperty(exports,`getProviderCredentialRequirement`,{enumerable:!0,get:function(){return c.getProviderCredentialRequirement}}),exports.getSubagentSuffix=ee,exports.hasBlockingPromptFileReferenceDiagnostics=ea,exports.hasSensitiveCommandMemoryContent=bc,Object.defineProperty(exports,`hasUsableSecretReference`,{enumerable:!0,get:function(){return c.hasUsableSecretReference}}),exports.inspectCommandEditCheckpoint=sc,exports.inspectUserLocalMemoryItem=ql,exports.inspectUserLocalStorage=Dl,exports.isCommandMemoryType=yc,Object.defineProperty(exports,`isEnvReference`,{enumerable:!0,get:function(){return c.isEnvReference}}),exports.isMemoryType=Ur,exports.isPermissionMode=Is,exports.isStatusLineCommandSettingsPatch=Gs,exports.listActiveContextReferences=Gi,exports.listCommandBackgroundTasks=ls,exports.listCommandContextReferences=Jo,exports.listCommandEditCheckpoints=oc,exports.listCommandSessionAllowedTools=Bs,exports.listCommandUsedMemoryReferences=xc,exports.listResumableSessionSummaries=ol,exports.listUserLocalMemoryItems=Kl,exports.loadTaskContext=hi,exports.mergeProviderPatch=bo,exports.mergeProviders=Io,exports.mergeSettings=Fo,exports.normalizeModelCommandName=C,exports.parseCommandBackgroundLogCursor=os,exports.parseExecutionWorkspaceEntryId=Pe,exports.parseFrontmatter=vn,exports.parseLanguageArgument=js,exports.parsePermissionModeArgument=Fs,exports.parsePromptFileReferences=oa,exports.parseSessionNameArgument=Zs,exports.parseTaskFile=fi,exports.planSelfHostingVerification=iu,exports.preprocessShellCommands=wc,exports.probeProviderProfile=Do,exports.projectPaths=z,exports.promptForApproval=hu,exports.readAutoCompactThreshold=Ho,exports.readAutoCompactThresholdSource=Uo,exports.readCommandBackgroundTaskLog=us,exports.readCommandContextState=Vo,exports.readCommandPermissionMode=Rs,exports.readCommandPermissionsState=Vs,exports.readCommandSessionInfo=tc,exports.readCurrentGitBranch=ui,exports.readEnabledUserLocalMemoryItem=Xl,exports.readMergedProviderSettingsFromPaths=No,exports.recordCommandMemoryEvent=Sc,exports.removeCommandContextReference=Xo,exports.removeContextReference=Ui,exports.resetAutoCompactThresholdSetting=Ko,exports.resolveActiveProvider=Lo,exports.resolveActiveProviderModelCatalog=gs,exports.resolveActiveProviderModelCatalogState=_s,Object.defineProperty(exports,`resolveEnvReference`,{enumerable:!0,get:function(){return c.resolveEnvReference}}),exports.resolveLatestSessionId=sl,exports.resolvePermissionModeAdapter=X,exports.resolvePluginCommandAdapter=Js,exports.resolvePromptFileReferencePaths=ma,exports.resolvePromptFileReferences=pa,exports.resolveSessionIdByIdOrName=cl,exports.resolveSubagentLogDir=dr,exports.resolveUserLocalStorageRoot=wl,exports.restoreCommandEditCheckpoint=cc,exports.retrieveAgentToolDeps=M,exports.rollbackCommandEditCheckpoint=lc,exports.sanitizeProviderProfileName=es,exports.selectRelevantTasks=pi,exports.setCommandAutoCompactThreshold=Wo,exports.setCurrentProvider=ho,exports.setUserLocalMemoryItem=Gl,exports.storeAgentToolDeps=Ct,exports.substituteVariables=Cc,exports.suggestProviderProfileName=$o,exports.summarizeBackgroundJobGroup=ke,exports.testProviderProfileCommand=Eo,exports.toContextReferenceRecords=Ki,exports.toPromptFileReferenceRecords=W,exports.transitionSelfHostingLoop=au,exports.updateTaskFileStatus=gi,exports.upsertContextReference=Hi,exports.upsertProviderProfile=mo,exports.userPaths=fr,exports.validateCommandSessionReplayLog=nc,exports.validateProviderProfile=_o,exports.wrapEditCheckpointTools=Zt,exports.wrapReversibleExecutionTools=an,exports.writeAutoCompactThresholdSetting=Go,exports.writeCommandPermissionMode=zs;
|