@robota-sdk/agent-framework 3.0.0-beta.75 → 3.0.0-beta.76
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/dist/node/index.cjs +7 -7
- package/dist/node/index.d.ts +20 -4
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +4 -4
- package/dist/node/index.js.map +1 -1
- package/package.json +6 -6
package/dist/node/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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("@robota-sdk/agent-executor"),u=require("@robota-sdk/agent-tools"),d=require("zod"),f=require("@robota-sdk/agent-session"),p=require("node:crypto"),m=require("node:fs"),h=require("node:fs/promises"),g=require("node:path");g=s(g,1);let _=require("node:os"),v=require("fs"),y=require("path"),ee=require("node:url");const te=1e3;var ne=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:x(r.state)}),this.evaluateCompletion(r),x(r.state)}listGroups(){return[...this.groups.values()].map(e=>x(e.state))}getGroup(e){let t=this.groups.get(e);return t?x(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(x(e));this.groups.set(e.id,t),e.status===`completed`&&t.resolve(x(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,l.isTerminalBackgroundTaskStatus)(n.status)&&this.captureTask(e,n)}}handleTaskEvent(e){let t=re(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:x(e.state)}))}captureTask(e,t){return e.state.results.some(e=>e.taskId===t.id)?!1:(e.state.results=[...e.state.results,ae(t)],e.state.updatedAt=this.now(),!0)}evaluateCompletion(e){if(e.state.status===`completed`)return;if(!ie(e.state)){this.emit({type:`background_job_group_updated`,group:x(e.state)});return}let t=this.now();e.state.status=`completed`,e.state.completedAt=t,e.state.updatedAt=t;let n=x(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 re(e){if(e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)return e.task}function ie(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 ae(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<=te?t:`${t.slice(0,te)}...`}function se(e){let t=b(e,`completed`),n=b(e,`failed`),r=b(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=>ce(e))}}function b(e,t){return e.results.filter(e=>e.status===t).length}function ce(e){let t=le(e),n=e.outputRef&&e.summary?` (output: ${e.outputRef})`:``;return`[${e.status}] ${e.label} ${e.taskId}: ${t}${n}`}function le(e){let t=(e.error?.message??e.summary??``).replace(/\s+/g,` `).trim();return t.length>0?t:`(no summary)`}function x(e){return{...e,taskIds:[...e.taskIds],results:e.results.map(e=>({...e,...e.error?{error:{...e.error}}:{}}))}}const S={kind:`executionOriginKind`,sessionId:`executionOriginSessionId`,turnId:`executionOriginTurnId`,commandName:`executionOriginCommandName`,toolCallId:`executionOriginToolCallId`,skillId:`executionOriginSkillId`,label:`executionOriginLabel`};function C(e){return[`main`,e].join(`:`)}function w(e){return[`task`,e].join(`:`)}function ue(e){return[`group`,e].join(`:`)}function de(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 T(e){return{[S.kind]:e.kind,[S.sessionId]:e.sessionId,...e.turnId?{[S.turnId]:e.turnId}:{},...e.commandName?{[S.commandName]:e.commandName}:{},...e.toolCallId?{[S.toolCallId]:e.toolCallId}:{},...e.skillId?{[S.skillId]:e.skillId}:{},...e.label?{[S.label]:e.label}:{}}}function fe(e){let t=_e(e.groups),n=[pe(e.mainThread),...Oe(e.groups).map(e=>he(e)),...De(e.tasks).map(e=>me(e,t.get(e.id)))].filter(t=>Ee(t,e.filter));return{sessionId:e.sessionId,selectedEntryId:e.selectedEntryId??n.find(e=>e.kind===`main_thread`)?.id??C(e.sessionId),updatedAt:n[0]?.updatedAt??e.mainThread.updatedAt,entries:n}}function pe(e){return{id:C(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:E(e.preview),unread:!1,attention:`none`,visibility:`default`,updatedAt:e.updatedAt,controls:[`select`]}}function me(e,t){return{id:w(e.id),sourceId:e.id,kind:`background_task`,parentId:e.parentTaskId?w(e.parentTaskId):C(e.parentSessionId),...t?{groupId:ue(t)}:{},origin:ge(e.metadata,{kind:`system`,sessionId:e.parentSessionId}),taskKind:e.kind,status:e.status,title:e.label,subtitle:ye(e),preview:Se(e),currentAction:e.currentAction,unread:e.unread,attention:Ce(e),visibility:we(e),updatedAt:e.lastActivityAt??e.updatedAt,controls:ve(e)}}function he(e){let t=E(e.results.map(e=>e.summary??e.error?.message).join(` `));return{id:ue(e.id),sourceId:e.id,kind:`background_group`,parentId:C(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:Te(e),visibility:e.status===`completed`?`collapsed`:`default`,updatedAt:e.updatedAt,controls:e.status===`running`?[`select`,`wait`]:[`select`]}}function ge(e,t){let n=ke(e?.[S.kind]),r=D(e?.[S.sessionId]);return{kind:n??t.kind,sessionId:r??t.sessionId,turnId:D(e?.[S.turnId])??t.turnId,commandName:D(e?.[S.commandName])??t.commandName,toolCallId:D(e?.[S.toolCallId])??t.toolCallId,skillId:D(e?.[S.skillId])??t.skillId,label:D(e?.[S.label])??t.label}}function _e(e){return new Map(e.flatMap(e=>e.taskIds.map(t=>[t,e.id])))}function ve(e){let t=[`select`];return(0,l.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 ye(e){if(e.kind===`agent`)return e.agentType??e.cwd;let t=e.schedule?.agentInstruction;if(e.status===`sleeping`&&e.nextFireAt!==void 0){let n=`next: ${xe(e.nextFireAt)}`;return t===void 0?n:`↻ wake "${be(t)}" · ${n}`}return e.cwd}function be(e){let t=e.trim();return t.length>32?`${t.slice(0,32)}…`:t}function xe(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 Se(e){return e.status===`failed`?E(e.error?.message):e.status===`completed`?E(e.result?.output):E(e.promptPreview??e.commandPreview)}function Ce(e){return e.status===`failed`?`failed`:e.status===`waiting_permission`?`permission`:e.unread?`unread`:e.status===`completed`?`completed`:`none`}function we(e){return e.status===`completed`&&!e.unread&&!e.error&&(e.result?.exitCode??0)===0&&!e.result?.signalCode&&!e.worktreePath&&!e.branchName?`collapsed`:`default`}function Te(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`none`}function Ee(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 De(e){return[...e].sort((e,t)=>(t.lastActivityAt??t.updatedAt).localeCompare(e.lastActivityAt??e.updatedAt))}function Oe(e){return[...e].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}function E(e){let t=e?.trim().replace(/\s+/g,` `);if(t)return t.length>120?`${t.slice(0,120)}...`:t}function D(e){return typeof e==`string`?e:void 0}function ke(e){if(e===`user_prompt`||e===`slash_command`||e===`model_command`||e===`tool_call`||e===`skill`||e===`transport`||e===`system`)return e}function Ae(e){let t=je(e.cursor?.offset),n=e.history.slice(t,t+80),r=n.map(e=>({id:e.id,kind:e.category===`chat`?`message`:`progress`,text:Me(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 O(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 je(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function Me(e){return typeof e.data==`string`?e.data:e.type}function Ne(e){return{spawnAgent:t=>e.manager.spawn(Pe(e,t)),spawnProcess:t=>e.manager.spawn(Fe(e,t)),createGroup:t=>e.groupOrchestrator.createGroup({parentSessionId:e.sessionId,waitPolicy:t.waitPolicy,taskIds:[...t.taskIds],label:t.label})}}function Pe(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:T(e.origin)}}function Fe(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:T(e.origin)}}const Ie=new WeakMap;function Le(e,t){Ie.set(e,t)}function Re(e){return Ie.get(e)}function ze(e){let t=e.jobs.filter(e=>e.success),n=e.jobs.map(e=>e.agentId).filter(e=>typeof e==`string`&&e.length>0),r=e.jobs.filter(e=>!e.success).length;return JSON.stringify({success:e.jobs.every(e=>e.success),mode:`batch`,output:t.map(e=>e.output??``).filter(Boolean).join(`
|
|
1
|
+
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("@robota-sdk/agent-executor"),u=require("@robota-sdk/agent-tools"),d=require("zod"),f=require("@robota-sdk/agent-session"),p=require("node:crypto"),m=require("node:fs"),h=require("node:fs/promises"),g=require("node:path");g=s(g,1);let _=require("node:os"),v=require("fs"),y=require("path"),ee=require("node:url");const te=1e3;var ne=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:x(r.state)}),this.evaluateCompletion(r),x(r.state)}listGroups(){return[...this.groups.values()].map(e=>x(e.state))}getGroup(e){let t=this.groups.get(e);return t?x(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(x(e));this.groups.set(e.id,t),e.status===`completed`&&t.resolve(x(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,l.isTerminalBackgroundTaskStatus)(n.status)&&this.captureTask(e,n)}}handleTaskEvent(e){let t=re(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:x(e.state)}))}captureTask(e,t){return e.state.results.some(e=>e.taskId===t.id)?!1:(e.state.results=[...e.state.results,ae(t)],e.state.updatedAt=this.now(),!0)}evaluateCompletion(e){if(e.state.status===`completed`)return;if(!ie(e.state)){this.emit({type:`background_job_group_updated`,group:x(e.state)});return}let t=this.now();e.state.status=`completed`,e.state.completedAt=t,e.state.updatedAt=t;let n=x(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 re(e){if(e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)return e.task}function ie(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 ae(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<=te?t:`${t.slice(0,te)}...`}function se(e){let t=b(e,`completed`),n=b(e,`failed`),r=b(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=>ce(e))}}function b(e,t){return e.results.filter(e=>e.status===t).length}function ce(e){let t=le(e),n=e.outputRef&&e.summary?` (output: ${e.outputRef})`:``;return`[${e.status}] ${e.label} ${e.taskId}: ${t}${n}`}function le(e){let t=(e.error?.message??e.summary??``).replace(/\s+/g,` `).trim();return t.length>0?t:`(no summary)`}function x(e){return{...e,taskIds:[...e.taskIds],results:e.results.map(e=>({...e,...e.error?{error:{...e.error}}:{}}))}}const S={kind:`executionOriginKind`,sessionId:`executionOriginSessionId`,turnId:`executionOriginTurnId`,commandName:`executionOriginCommandName`,toolCallId:`executionOriginToolCallId`,skillId:`executionOriginSkillId`,label:`executionOriginLabel`};function C(e){return[`main`,e].join(`:`)}function w(e){return[`task`,e].join(`:`)}function T(e){return[`group`,e].join(`:`)}function ue(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 E(e){return{[S.kind]:e.kind,[S.sessionId]:e.sessionId,...e.turnId?{[S.turnId]:e.turnId}:{},...e.commandName?{[S.commandName]:e.commandName}:{},...e.toolCallId?{[S.toolCallId]:e.toolCallId}:{},...e.skillId?{[S.skillId]:e.skillId}:{},...e.label?{[S.label]:e.label}:{}}}function de(e){let t=ge(e.groups),n=[fe(e.mainThread),...De(e.groups).map(e=>me(e)),...Ee(e.tasks).map(e=>pe(e,t.get(e.id)))].filter(t=>Te(t,e.filter));return{sessionId:e.sessionId,selectedEntryId:e.selectedEntryId??n.find(e=>e.kind===`main_thread`)?.id??C(e.sessionId),updatedAt:n[0]?.updatedAt??e.mainThread.updatedAt,entries:n}}function fe(e){return{id:C(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:D(e.preview),unread:!1,attention:`none`,visibility:`default`,updatedAt:e.updatedAt,controls:[`select`]}}function pe(e,t){return{id:w(e.id),sourceId:e.id,kind:`background_task`,parentId:e.parentTaskId?w(e.parentTaskId):C(e.parentSessionId),...t?{groupId:T(t)}:{},origin:he(e.metadata,{kind:`system`,sessionId:e.parentSessionId}),taskKind:e.kind,status:e.status,title:e.label,subtitle:ve(e),preview:xe(e),currentAction:e.currentAction,unread:e.unread,attention:Se(e),visibility:Ce(e),updatedAt:e.lastActivityAt??e.updatedAt,controls:_e(e)}}function me(e){let t=D(e.results.map(e=>e.summary??e.error?.message).join(` `));return{id:T(e.id),sourceId:e.id,kind:`background_group`,parentId:C(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:we(e),visibility:e.status===`completed`?`collapsed`:`default`,updatedAt:e.updatedAt,controls:e.status===`running`?[`select`,`wait`]:[`select`]}}function he(e,t){let n=Oe(e?.[S.kind]),r=O(e?.[S.sessionId]);return{kind:n??t.kind,sessionId:r??t.sessionId,turnId:O(e?.[S.turnId])??t.turnId,commandName:O(e?.[S.commandName])??t.commandName,toolCallId:O(e?.[S.toolCallId])??t.toolCallId,skillId:O(e?.[S.skillId])??t.skillId,label:O(e?.[S.label])??t.label}}function ge(e){return new Map(e.flatMap(e=>e.taskIds.map(t=>[t,e.id])))}function _e(e){let t=[`select`];return(0,l.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 ve(e){if(e.kind===`agent`)return e.agentType??e.cwd;let t=e.schedule?.agentInstruction;if(e.status===`sleeping`&&e.nextFireAt!==void 0){let n=`next: ${be(e.nextFireAt)}`;return t===void 0?n:`↻ wake "${ye(t)}" · ${n}`}return e.cwd}function ye(e){let t=e.trim();return t.length>32?`${t.slice(0,32)}…`:t}function be(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 xe(e){return e.status===`failed`?D(e.error?.message):e.status===`completed`?D(e.result?.output):D(e.promptPreview??e.commandPreview)}function Se(e){return e.status===`failed`?`failed`:e.status===`waiting_permission`?`permission`:e.unread?`unread`:e.status===`completed`?`completed`:`none`}function Ce(e){return e.status===`completed`&&!e.unread&&!e.error&&(e.result?.exitCode??0)===0&&!e.result?.signalCode&&!e.worktreePath&&!e.branchName?`collapsed`:`default`}function we(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`none`}function Te(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 Ee(e){return[...e].sort((e,t)=>(t.lastActivityAt??t.updatedAt).localeCompare(e.lastActivityAt??e.updatedAt))}function De(e){return[...e].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}function D(e){let t=e?.trim().replace(/\s+/g,` `);if(t)return t.length>120?`${t.slice(0,120)}...`:t}function O(e){return typeof e==`string`?e:void 0}function Oe(e){if(e===`user_prompt`||e===`slash_command`||e===`model_command`||e===`tool_call`||e===`skill`||e===`transport`||e===`system`)return e}function ke(e){let t=je(e.cursor?.offset),n=e.history.slice(t,t+80),r=n.map(e=>({id:e.id,kind:e.category===`chat`?`message`:`progress`,text:Me(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 Ae(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 je(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function Me(e){return typeof e.data==`string`?e.data:e.type}function Ne(e){return{spawnAgent:t=>e.manager.spawn(Pe(e,t)),spawnProcess:t=>e.manager.spawn(Fe(e,t)),createGroup:t=>e.groupOrchestrator.createGroup({parentSessionId:e.sessionId,waitPolicy:t.waitPolicy,taskIds:[...t.taskIds],label:t.label})}}function Pe(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:E(e.origin)}}function Fe(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:E(e.origin)}}const Ie=new WeakMap;function Le(e,t){Ie.set(e,t)}function Re(e){return Ie.get(e)}function ze(e){let t=e.jobs.filter(e=>e.success),n=e.jobs.map(e=>e.agentId).filter(e=>typeof e==`string`&&e.length>0),r=e.jobs.filter(e=>!e.success).length;return JSON.stringify({success:e.jobs.every(e=>e.success),mode:`batch`,output:t.map(e=>e.output??``).filter(Boolean).join(`
|
|
2
2
|
|
|
3
3
|
`),groupId:e.groupId,requestedJobCount:e.requestedJobCount,startedJobCount:n.length,failedJobCount:r,agentIds:n,jobs:e.jobs,provenance:{source:`agent-tool-batch`,groupId:e.groupId,requestedJobCount:e.requestedJobCount,startedJobCount:n.length,failedJobCount:r}})}function Be(){return`agent_group_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function Ve(e,t){let n=e?.trim();return n&&n.length>0?n:t}function He(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:Ve(e.label,i?.name??r)}}function Ue(e){return e.agentDef!==void 0}function We(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 Ge(e,t){try{let n=await t.manager.spawn(t.createSpawnRequest(e.job,e.agentType,e.agentDef,t.deps,e.label,t.toolCallId));return{...e,agentId:n.id}}catch(t){let n=t instanceof Error?t.message:String(t);return{...e,spawnError:n}}}function Ke(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 qe(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 Je(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 Ye(e,t,n){if(e.agentId===void 0)return Ke(e,t);try{let r=await n.wait(e.agentId);return qe({...e,agentId:e.agentId},t,r)}catch(n){let r=n instanceof Error?n.message:String(n);return Je({...e,agentId:e.agentId},t,r)}}async function Xe(e){let t=Be(),n=e.jobs.map((t,n)=>He(t,n,e)),r=n.filter(e=>!Ue(e)).map(e=>We(e,t)),i=await Promise.all(n.filter(Ue).map(t=>Ge(t,e))),a=await Promise.all(i.map(n=>Ye(n,t,e.manager))),o=[...r,...a].sort((e,t)=>e.index-t.index);return ze({groupId:t,requestedJobCount:e.jobs.length,jobs:o})}function Ze(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 Qe(){return JSON.stringify({success:!1,mode:`single`,requestedJobCount:0,startedJobCount:0,failedJobCount:0,output:``,error:`Parallel subagents are disabled for the active preset.`,provenance:{source:`agent-tool-single`,requestedJobCount:0,startedJobCount:0,failedJobCount:0}})}function $e(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 et(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 tt=[{name:`general-purpose`,description:`General-purpose task execution agent with full tool access.`,systemPrompt:`You are a general-purpose task execution agent. You have access to all tools available in the parent session and can perform any task delegated to you.
|
|
4
4
|
|
|
@@ -46,7 +46,7 @@ Do not use emojis.`}function rt(){return`You are a worker subagent executing a s
|
|
|
46
46
|
|
|
47
47
|
`)}const at=`robota_command_`,ot=/^[A-Za-z0-9_-]{1,64}$/;function st(e){return e}function A(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function ct(e){let t=A(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=`${at}${n}`;if(ot.test(r))return r;let i=(0,p.createHash)(`sha256`).update(t).digest(`hex`).slice(0,8),a=`${at}${n.slice(0,40).replace(/[_-]+$/g,``)||`command`}_${i}`;if(!ot.test(a))throw Error(`Projected model command tool name is not provider-safe: ${a}`);return a}function lt(e){let t=new Set,n=new Map,r=new Map,i=[];for(let a of e){let e=A(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=ct(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:mt(e,a),descriptor:a,requiresPermission:a.requiresPermission!==!1})}return{commandTools:i,toolNameToCommandName:n,commandNameToToolName:r}}function ut(e){return`${e.toolName} — ${e.descriptor.description}`}function dt(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 ft(e){return lt(e.commandDescriptors).commandTools.map(t=>{let n=pt(t.descriptor);return(0,u.createZodFunctionTool)(t.toolName,t.description,st(n),async r=>{let i=n.parse(r);return e.isModelInvocable(t.commandName)?dt(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 pt(e){let t=e.argumentHint?`Arguments for the command. Expected grammar: ${e.argumentHint}`:`Arguments for the command as a single string.`;return d.z.object({args:d.z.string().optional().describe(t)})}function mt(e,t){let n=[t.description.trim(),`Robota command id: ${e}.`];return t.argumentHint&&n.push(`Argument grammar: ${t.argumentHint}`),n.filter(e=>e.length>0).join(`
|
|
48
48
|
|
|
49
|
-
`)}const ht={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`,opus:`claude-opus-4-6`},gt=ct(`agent`);function _t(e,t){return ht[e]??e}function vt(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()!==gt),n}function yt(e){let{agentDefinition:t,parentConfig:n,parentContext:r,parentTools:i,terminal:a}=e,o=vt(i,t),s=t.model?_t(t.model,n.provider.model):n.provider.model,c=it({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 bt(e,t){let n=t?.(e)??k(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function xt(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 St(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function Ct(e){if(e.request.isolation===`worktree`)throw Error(`Worktree isolation requires a runtime shell subagent runner`)}function wt(e,t){if(t.type===`start`){e.emit?.({type:`background_task_tool_start`,toolName:t.toolName,firstArg:St(t.toolArgs)});return}e.emit?.({type:`background_task_tool_end`,toolName:t.toolName,success:t.success??!0})}function Tt(e){return{start(t){Ct(t);let n=yt({agentDefinition:xt(bt(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=>{wt(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 Et=[`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 Dt(e){return e}const Ot=d.z.object({prompt:d.z.string().optional().describe(`The task for a single subagent to perform. Required when jobs is omitted.`),subagent_type:d.z.string().optional().describe(`Agent type: "general-purpose", "Explore", "Plan", or a custom agent name`),model:d.z.string().optional().describe(`Optional model override`),isolation:d.z.enum([`none`,`worktree`]).optional().describe(`Optional runtime isolation mode. "worktree" runs in a Git worktree.`),jobs:d.z.array(d.z.object({label:d.z.string().optional().describe(`Stable role label for this batch job`),prompt:d.z.string().describe(`The task for this subagent to perform`),subagent_type:d.z.string().optional().describe(`Agent type for this job`),model:d.z.string().optional().describe(`Optional model override for this job`),isolation:d.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(),kt=new WeakMap;function At(e,t){kt.set(e,t)}function j(e){return kt.get(e)}function jt(e,t){if(t){let n=t(e);if(n)return n}let n=k(e);if(n)return n}function Mt(e){return e.subagentManager??new l.SubagentManager({runner:Tt(e)})}function Nt(e,t,n,r,i=n.name,a){return{type:t,label:i,parentSessionId:r.parentSessionId??`unknown-session`,mode:`background`,depth:r.subagentDepth??1,cwd:r.cwd??process.cwd(),prompt:e.prompt,model:e.model,isolation:e.isolation,metadata:T({kind:`tool_call`,sessionId:r.parentSessionId??`unknown-session`,label:i,...a?{toolCallId:a}:{}})}}async function Pt(e,t,n,r){if(typeof e.prompt!=`string`||e.prompt.length===0)return et(`prompt is required when jobs is omitted`);let i={...e,prompt:e.prompt},a=e.subagent_type??`general-purpose`,o=jt(a,t.customAgentRegistry);if(!o)return Ze(a);let s;try{let e=await n.spawn(Nt(i,a,o,t,void 0,r));return s=e.id,$e(await n.wait(e.id))}catch(e){return et(e instanceof Error?e.message:String(e),s)}}function Ft(e){let t=Mt(e);return(0,u.createZodFunctionTool)(`Agent`,Et,Dt(Ot),async(n,r)=>{let i=n,a=r?.executionId;return e.isParallelSubagentsEnabled!==void 0&&!e.isParallelSubagentsEnabled()?Qe():Array.isArray(i.jobs)&&i.jobs.length>0?Xe({jobs:i.jobs,deps:e,manager:t,resolveAgentDefinition:jt,createSpawnRequest:Nt,toolCallId:a}):Pt({prompt:i.prompt,...i.subagent_type===void 0?{}:{subagent_type:i.subagent_type},...i.model===void 0?{}:{model:i.model},...i.isolation===void 0?{}:{isolation:i.isolation}},e,t,a)})}var It=class{getManager;onChanged;emitTaskEvent;emitGroupEvent;persistSession;onWake;appendSystemNote;backgroundTasks=[];backgroundTaskEvents=[];backgroundJobGroups=[];backgroundJobGroupEvents=[];backgroundTaskUnsubscribe=null;backgroundJobUnsubscribe=null;backgroundJobOrchestrator=null;constructor(e,t,n,r,i,a,o){this.getManager=e,this.onChanged=t,this.emitTaskEvent=n,this.emitGroupEvent=r,this.persistSession=i,this.onWake=a,this.appendSystemNote=o}subscribe(e){if(this.backgroundTaskUnsubscribe)return;let t=Re(e)??j(e)?.backgroundTaskManager;t&&(this.backgroundTaskUnsubscribe=t.subscribe(e=>{this.recordTaskEvent(e),this.emitTaskEvent(e),e.type===`background_task_waking`&&e.instruction!==void 0&&this.onWake?.(e.instruction,e.taskId)}),this.reArmRestoredSchedules(t))}reArmRestoredSchedules(e){let t=Date.now();for(let n of this.backgroundTasks)n.kind!==`scheduled`||n.status!==`sleeping`||!n.schedule||(n.nextFireAt!==void 0&&new Date(n.nextFireAt).getTime()<t&&this.appendSystemNote?.(`Missed scheduled wake "${n.label}" (was due ${n.nextFireAt} while the session was closed); re-arming.`),e.spawn({kind:`scheduled`,cronExpression:n.schedule.cronExpression,label:n.label,mode:n.mode,parentSessionId:n.parentSessionId,depth:n.depth,cwd:n.cwd,...n.schedule.agentInstruction===void 0?{}:{agentInstruction:n.schedule.agentInstruction},...n.schedule.command===void 0?{}:{command:n.schedule.command},...n.schedule.shell===void 0?{}:{shell:n.schedule.shell},...n.schedule.env===void 0?{}:{env:{...n.schedule.env}}}))}dispose(){this.backgroundTaskUnsubscribe?.(),this.backgroundTaskUnsubscribe=null,this.backgroundJobUnsubscribe?.(),this.backgroundJobUnsubscribe=null,this.backgroundJobOrchestrator?.dispose(),this.backgroundJobOrchestrator=null}restoreState(e){this.backgroundTasks=e.tasks,this.backgroundTaskEvents=e.taskEvents,this.backgroundJobGroups=e.groups,this.backgroundJobGroupEvents=e.groupEvents}getState(){return{tasks:this.getTaskSnapshots(),taskEvents:this.backgroundTaskEvents,groups:this.getGroupSnapshots(),groupEvents:this.backgroundJobGroupEvents}}getManagerOrThrow(){let e=this.getManager();if(!e)throw Error(`Background task manager is not available for this session.`);return e}getOrchestratorOrThrow(e){if(this.backgroundJobOrchestrator)return this.backgroundJobOrchestrator;let t=this.getManagerOrThrow();return this.backgroundJobOrchestrator=new ne({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 O({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 O({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 O({entryId:e,lines:se(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`,Lt(e))}recordGroupEvent(e,t){this.backgroundJobGroups=this.getGroupSnapshots(),this.backgroundJobGroupEvents.push(e),this.persistSession(),this.onChanged(`background_group`,ue(e.group.id))}};function Lt(e){if(`task`in e)return w(e.task.id);if(`taskId`in e)return w(e.taskId)}function Rt(e){let t=j(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 M(e){let t=Rt(e);if(!t.subagentManager)throw Error(`Subagent manager is not available for this session.`);return t.subagentManager}function zt(e,t){let n=t.customAgentRegistry?.(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Bt(e){return(j(e)?.agentDefinitions??[]).map(e=>({name:e.name,description:e.description}))}async function Vt(e,t,n,r){let i=Rt(e),a=zt(t.agentType,i),o=e.getSessionId();return M(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:T({kind:r===`model`?`model_command`:`slash_command`,sessionId:o,commandName:`agent`,label:t.label})})}async function Ht(e,t){return M(e).wait(t)}async function Ut(e,t,n){await M(e).send(t,n)}async function Wt(e,t,n){await M(e).cancel(t,n)}async function Gt(e,t){await M(e).close(t)}function Kt(e){return M(e).list()}function qt(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 Jt(e,t,n,r,i){let a=de(e);if(!a)throw Error(`Unknown execution workspace entry: ${e}`);return a.kind===`main_thread`?Ae({entryId:e,history:t(),cursor:i}):a.kind===`background_group`?n.readGroupDetail(e,a.sourceId,r):n.readTaskDetail(e,a.sourceId,i)}function Yt(e,t,n,r){return Ne({manager:e.getManagerOrThrow(),groupOrchestrator:e.getOrchestratorOrThrow(t),sessionId:t,cwd:n,origin:{...r,sessionId:r.sessionId||t}})}var Xt=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 qt({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(),Jt(e,()=>this.histTracker.getHistory(),this.bgTracker,this.getSessionOrThrow().getSessionId(),t)}createExecutionWorkspaceTaskSpawner(e){return Yt(this.bgTracker,this.getSessionOrThrow().getSessionId(),this.getCwd(),e)}listAgentDefinitions(){return Bt(this.getSessionOrThrow())}listAgentJobs(){return Kt(this.getSessionOrThrow())}async spawnAgentJob(e){return await this.ensureInitialized(),Vt(this.getSessionOrThrow(),e,this.getCwd(),this.skillRouter.getCommandInvocationSource())}async waitAgentJob(e){return await this.ensureInitialized(),Ht(this.getSessionOrThrow(),e)}async sendAgentJob(e,t){await this.ensureInitialized(),await Ut(this.getSessionOrThrow(),e,t)}async cancelAgentJob(e,t){await this.ensureInitialized(),await Wt(this.getSessionOrThrow(),e,t)}async closeAgentJob(e){await this.ensureInitialized(),await Gt(this.getSessionOrThrow(),e)}async spawnScheduledWake(e){return await this.ensureInitialized(),this.bgTracker.getManagerOrThrow().spawn({kind:`scheduled`,label:e.label,mode:`background`,parentSessionId:this.getSessionOrThrow().getSessionId(),depth:0,cwd:this.getCwd(),cronExpression:e.cronExpression,agentInstruction:e.agentInstruction})}async spawnMonitorWake(e){return await this.ensureInitialized(),this.bgTracker.getManagerOrThrow().spawn({kind:`process`,label:e.label,mode:`background`,parentSessionId:this.getSessionOrThrow().getSessionId(),depth:0,cwd:this.getCwd(),command:e.command,matchPattern:e.matchPattern,agentInstruction:e.agentInstruction})}},N=class{existsSync(e){return(0,m.existsSync)(e)}readFileSync(e,t){return(0,m.readFileSync)(e,t)}writeFileSync(e,t,n){(0,m.writeFileSync)(e,t,n??`utf8`)}mkdirSync(e,t){(0,m.mkdirSync)(e,t)}readdirSync(e,t){return t?.withFileTypes?(0,m.readdirSync)(e,{withFileTypes:!0}):(0,m.readdirSync)(e)}statSync(e){return(0,m.statSync)(e)}rmSync(e,t){(0,m.rmSync)(e,t)}cpSync(e,t,n){(0,m.cpSync)(e,t,n)}renameSync(e,t){(0,m.renameSync)(e,t)}get constants(){return m.constants}},P=class{async access(e,t){await(0,h.access)(e,t)}async copyFile(e,t,n){await(0,h.copyFile)(e,t,n)}async mkdir(e,t){await(0,h.mkdir)(e,t)}async readFile(e,t){return(0,h.readFile)(e,t)}async readdir(e,t){return t?.withFileTypes?await(0,h.readdir)(e,{withFileTypes:!0}):(0,h.readdir)(e)}async realpath(e){return(0,h.realpath)(e)}async rename(e,t){await(0,h.rename)(e,t)}async rm(e,t){await(0,h.rm)(e,t)}async stat(e){return(0,h.stat)(e)}async writeFile(e,t,n){await(0,h.writeFile)(e,t,n??`utf8`)}};function Zt(e){return(0,p.createHash)(`sha256`).update(e,`utf-8`).digest(`hex`)}function Qt(e,t=new N){let n=t.readFileSync(e,`utf-8`);return{filePath:e,content:n,contentHash:Zt(n)}}async function $t(e,t=new N){let n=[],r=[];for(let i of e){if(!t.existsSync(i.filePath)){r.push(i);continue}Zt(t.readFileSync(i.filePath,`utf-8`))===i.contentHash?r.push(i):n.push(i)}return{stale:n,fresh:r}}async function en(e,t=new N){let{stale:n}=await $t(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:Zt(n)}}),refreshed:i}}async function tn(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 en(o);if(l.length===0)return;let u=c.slice(0,s),d=c.slice(s);r(u,d);let f=n(u.map(e=>e.content).join(`
|
|
49
|
+
`)}const ht={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`,opus:`claude-opus-4-6`},gt=ct(`agent`);function _t(e,t){return ht[e]??e}function vt(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()!==gt),n}function yt(e){let{agentDefinition:t,parentConfig:n,parentContext:r,parentTools:i,terminal:a}=e,o=vt(i,t),s=t.model?_t(t.model,n.provider.model):n.provider.model,c=it({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 bt(e,t){let n=t?.(e)??k(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function xt(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 St(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function Ct(e){if(e.request.isolation===`worktree`)throw Error(`Worktree isolation requires a runtime shell subagent runner`)}function wt(e,t){if(t.type===`start`){e.emit?.({type:`background_task_tool_start`,toolName:t.toolName,firstArg:St(t.toolArgs)});return}e.emit?.({type:`background_task_tool_end`,toolName:t.toolName,success:t.success??!0})}function Tt(e){return{start(t){Ct(t);let n=yt({agentDefinition:xt(bt(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=>{wt(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 Et=[`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 Dt(e){return e}const Ot=d.z.object({prompt:d.z.string().optional().describe(`The task for a single subagent to perform. Required when jobs is omitted.`),subagent_type:d.z.string().optional().describe(`Agent type: "general-purpose", "Explore", "Plan", or a custom agent name`),model:d.z.string().optional().describe(`Optional model override`),isolation:d.z.enum([`none`,`worktree`]).optional().describe(`Optional runtime isolation mode. "worktree" runs in a Git worktree.`),jobs:d.z.array(d.z.object({label:d.z.string().optional().describe(`Stable role label for this batch job`),prompt:d.z.string().describe(`The task for this subagent to perform`),subagent_type:d.z.string().optional().describe(`Agent type for this job`),model:d.z.string().optional().describe(`Optional model override for this job`),isolation:d.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(),kt=new WeakMap;function At(e,t){kt.set(e,t)}function j(e){return kt.get(e)}function jt(e,t){if(t){let n=t(e);if(n)return n}let n=k(e);if(n)return n}function Mt(e){return e.subagentManager??new l.SubagentManager({runner:Tt(e)})}function Nt(e,t,n,r,i=n.name,a){return{type:t,label:i,parentSessionId:r.parentSessionId??`unknown-session`,mode:`background`,depth:r.subagentDepth??1,cwd:r.cwd??process.cwd(),prompt:e.prompt,model:e.model,isolation:e.isolation,metadata:E({kind:`tool_call`,sessionId:r.parentSessionId??`unknown-session`,label:i,...a?{toolCallId:a}:{}})}}async function Pt(e,t,n,r){if(typeof e.prompt!=`string`||e.prompt.length===0)return et(`prompt is required when jobs is omitted`);let i={...e,prompt:e.prompt},a=e.subagent_type??`general-purpose`,o=jt(a,t.customAgentRegistry);if(!o)return Ze(a);let s;try{let e=await n.spawn(Nt(i,a,o,t,void 0,r));return s=e.id,$e(await n.wait(e.id))}catch(e){return et(e instanceof Error?e.message:String(e),s)}}function Ft(e){let t=Mt(e);return(0,u.createZodFunctionTool)(`Agent`,Et,Dt(Ot),async(n,r)=>{let i=n,a=r?.executionId;return e.isParallelSubagentsEnabled!==void 0&&!e.isParallelSubagentsEnabled()?Qe():Array.isArray(i.jobs)&&i.jobs.length>0?Xe({jobs:i.jobs,deps:e,manager:t,resolveAgentDefinition:jt,createSpawnRequest:Nt,toolCallId:a}):Pt({prompt:i.prompt,...i.subagent_type===void 0?{}:{subagent_type:i.subagent_type},...i.model===void 0?{}:{model:i.model},...i.isolation===void 0?{}:{isolation:i.isolation}},e,t,a)})}var It=class{getManager;onChanged;emitTaskEvent;emitGroupEvent;persistSession;onWake;appendSystemNote;backgroundTasks=[];backgroundTaskEvents=[];backgroundJobGroups=[];backgroundJobGroupEvents=[];backgroundTaskUnsubscribe=null;backgroundJobUnsubscribe=null;backgroundJobOrchestrator=null;constructor(e,t,n,r,i,a,o){this.getManager=e,this.onChanged=t,this.emitTaskEvent=n,this.emitGroupEvent=r,this.persistSession=i,this.onWake=a,this.appendSystemNote=o}subscribe(e){if(this.backgroundTaskUnsubscribe)return;let t=Re(e)??j(e)?.backgroundTaskManager;t&&(this.backgroundTaskUnsubscribe=t.subscribe(e=>{this.recordTaskEvent(e),this.emitTaskEvent(e),e.type===`background_task_waking`&&e.instruction!==void 0&&this.onWake?.(e.instruction,e.taskId)}),this.reArmRestoredSchedules(t))}reArmRestoredSchedules(e){let t=Date.now();for(let n of this.backgroundTasks)n.kind!==`scheduled`||n.status!==`sleeping`||!n.schedule||(n.nextFireAt!==void 0&&new Date(n.nextFireAt).getTime()<t&&this.appendSystemNote?.(`Missed scheduled wake "${n.label}" (was due ${n.nextFireAt} while the session was closed); re-arming.`),e.spawn({kind:`scheduled`,cronExpression:n.schedule.cronExpression,label:n.label,mode:n.mode,parentSessionId:n.parentSessionId,depth:n.depth,cwd:n.cwd,...n.schedule.agentInstruction===void 0?{}:{agentInstruction:n.schedule.agentInstruction},...n.schedule.command===void 0?{}:{command:n.schedule.command},...n.schedule.shell===void 0?{}:{shell:n.schedule.shell},...n.schedule.env===void 0?{}:{env:{...n.schedule.env}}}))}dispose(){this.backgroundTaskUnsubscribe?.(),this.backgroundTaskUnsubscribe=null,this.backgroundJobUnsubscribe?.(),this.backgroundJobUnsubscribe=null,this.backgroundJobOrchestrator?.dispose(),this.backgroundJobOrchestrator=null}restoreState(e){this.backgroundTasks=e.tasks,this.backgroundTaskEvents=e.taskEvents,this.backgroundJobGroups=e.groups,this.backgroundJobGroupEvents=e.groupEvents}getState(){return{tasks:this.getTaskSnapshots(),taskEvents:this.backgroundTaskEvents,groups:this.getGroupSnapshots(),groupEvents:this.backgroundJobGroupEvents}}getManagerOrThrow(){let e=this.getManager();if(!e)throw Error(`Background task manager is not available for this session.`);return e}getOrchestratorOrThrow(e){if(this.backgroundJobOrchestrator)return this.backgroundJobOrchestrator;let t=this.getManagerOrThrow();return this.backgroundJobOrchestrator=new ne({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 Ae({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 Ae({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 Ae({entryId:e,lines:se(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`,Lt(e))}recordGroupEvent(e,t){this.backgroundJobGroups=this.getGroupSnapshots(),this.backgroundJobGroupEvents.push(e),this.persistSession(),this.onChanged(`background_group`,T(e.group.id))}};function Lt(e){if(`task`in e)return w(e.task.id);if(`taskId`in e)return w(e.taskId)}function Rt(e){let t=j(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 M(e){let t=Rt(e);if(!t.subagentManager)throw Error(`Subagent manager is not available for this session.`);return t.subagentManager}function zt(e,t){let n=t.customAgentRegistry?.(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Bt(e){return(j(e)?.agentDefinitions??[]).map(e=>({name:e.name,description:e.description}))}async function Vt(e,t,n,r){let i=Rt(e),a=zt(t.agentType,i),o=e.getSessionId();return M(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:E({kind:r===`model`?`model_command`:`slash_command`,sessionId:o,commandName:`agent`,label:t.label})})}async function Ht(e,t){return M(e).wait(t)}async function Ut(e,t,n){await M(e).send(t,n)}async function Wt(e,t,n){await M(e).cancel(t,n)}async function Gt(e,t){await M(e).close(t)}function Kt(e){return M(e).list()}function qt(e,t={}){let{sessionId:n,execCtrl:r,histTracker:i,bgTracker:a}=e,o=i.getHistory();return de({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 Jt(e,t,n,r,i){let a=ue(e);if(!a)throw Error(`Unknown execution workspace entry: ${e}`);return a.kind===`main_thread`?ke({entryId:e,history:t(),cursor:i}):a.kind===`background_group`?n.readGroupDetail(e,a.sourceId,r):n.readTaskDetail(e,a.sourceId,i)}function Yt(e,t,n,r){return Ne({manager:e.getManagerOrThrow(),groupOrchestrator:e.getOrchestratorOrThrow(t),sessionId:t,cwd:n,origin:{...r,sessionId:r.sessionId||t}})}var Xt=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 qt({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(),Jt(e,()=>this.histTracker.getHistory(),this.bgTracker,this.getSessionOrThrow().getSessionId(),t)}createExecutionWorkspaceTaskSpawner(e){return Yt(this.bgTracker,this.getSessionOrThrow().getSessionId(),this.getCwd(),e)}listAgentDefinitions(){return Bt(this.getSessionOrThrow())}listAgentJobs(){return Kt(this.getSessionOrThrow())}async spawnAgentJob(e){return await this.ensureInitialized(),Vt(this.getSessionOrThrow(),e,this.getCwd(),this.skillRouter.getCommandInvocationSource())}async waitAgentJob(e){return await this.ensureInitialized(),Ht(this.getSessionOrThrow(),e)}async sendAgentJob(e,t){await this.ensureInitialized(),await Ut(this.getSessionOrThrow(),e,t)}async cancelAgentJob(e,t){await this.ensureInitialized(),await Wt(this.getSessionOrThrow(),e,t)}async closeAgentJob(e){await this.ensureInitialized(),await Gt(this.getSessionOrThrow(),e)}async spawnScheduledWake(e){return await this.ensureInitialized(),this.bgTracker.getManagerOrThrow().spawn({kind:`scheduled`,label:e.label,mode:`background`,parentSessionId:this.getSessionOrThrow().getSessionId(),depth:0,cwd:this.getCwd(),cronExpression:e.cronExpression,agentInstruction:e.agentInstruction})}async spawnMonitorWake(e){return await this.ensureInitialized(),this.bgTracker.getManagerOrThrow().spawn({kind:`process`,label:e.label,mode:`background`,parentSessionId:this.getSessionOrThrow().getSessionId(),depth:0,cwd:this.getCwd(),command:e.command,matchPattern:e.matchPattern,agentInstruction:e.agentInstruction})}},N=class{existsSync(e){return(0,m.existsSync)(e)}readFileSync(e,t){return(0,m.readFileSync)(e,t)}writeFileSync(e,t,n){(0,m.writeFileSync)(e,t,n??`utf8`)}mkdirSync(e,t){(0,m.mkdirSync)(e,t)}readdirSync(e,t){return t?.withFileTypes?(0,m.readdirSync)(e,{withFileTypes:!0}):(0,m.readdirSync)(e)}statSync(e){return(0,m.statSync)(e)}rmSync(e,t){(0,m.rmSync)(e,t)}cpSync(e,t,n){(0,m.cpSync)(e,t,n)}renameSync(e,t){(0,m.renameSync)(e,t)}get constants(){return m.constants}},P=class{async access(e,t){await(0,h.access)(e,t)}async copyFile(e,t,n){await(0,h.copyFile)(e,t,n)}async mkdir(e,t){await(0,h.mkdir)(e,t)}async readFile(e,t){return(0,h.readFile)(e,t)}async readdir(e,t){return t?.withFileTypes?await(0,h.readdir)(e,{withFileTypes:!0}):(0,h.readdir)(e)}async realpath(e){return(0,h.realpath)(e)}async rename(e,t){await(0,h.rename)(e,t)}async rm(e,t){await(0,h.rm)(e,t)}async stat(e){return(0,h.stat)(e)}async writeFile(e,t,n){await(0,h.writeFile)(e,t,n??`utf8`)}};function Zt(e){return(0,p.createHash)(`sha256`).update(e,`utf-8`).digest(`hex`)}function Qt(e,t=new N){let n=t.readFileSync(e,`utf-8`);return{filePath:e,content:n,contentHash:Zt(n)}}async function $t(e,t=new N){let n=[],r=[];for(let i of e){if(!t.existsSync(i.filePath)){r.push(i);continue}Zt(t.readFileSync(i.filePath,`utf-8`))===i.contentHash?r.push(i):n.push(i)}return{stale:n,fresh:r}}async function en(e,t=new N){let{stale:n}=await $t(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:Zt(n)}}),refreshed:i}}async function tn(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 en(o);if(l.length===0)return;let u=c.slice(0,s),d=c.slice(s);r(u,d);let f=n(u.map(e=>e.content).join(`
|
|
50
50
|
|
|
51
51
|
`),d.map(e=>e.content).join(`
|
|
52
52
|
|
|
@@ -71,7 +71,7 @@ Do not use emojis.`}function rt(){return`You are a worker subagent executing a s
|
|
|
71
71
|
`)}function H(e,t,n,r,i){return{id:e,title:t,priority:n,content:r,source:i}}function $r(e){return H(`preset-persona`,void 0,5,e,`persona`)}function ei(){return H(`preset-self-verification`,void 0,6,`Before you report a task complete, verify your work against this session's tool results — re-run the relevant checks and confirm the outcome matches what was asked. If something is not yet verified, say so plainly rather than implying it is done.`,`self-verification`)}function ti(e){if(e)return H(`runtime-cwd`,`Working Directory`,30,`\`${e}\``,`runtime`)}function ni(e){let t=[];return e.name!==void 0&&t.push(`- **Name:** ${e.name}`),e.type!==`unknown`&&t.push(`- **Type:** ${e.type}`),e.language!==`unknown`&&t.push(`- **Language:** ${e.language}`),e.packageManager!==void 0&&t.push(`- **Package manager:** ${e.packageManager}`),H(`runtime-project`,`Current Project`,40,t.join(`
|
|
72
72
|
`),`runtime`)}function ri(e){return H(`permission-mode`,`Permission Mode`,50,`- **Permission mode:** ${e}`,`permissions`)}function ii(e){if(!(e===void 0||e.trim().length===0))return H(`runtime-response-language`,`Response Language`,45,e,`runtime`)}function ai(e){if(e.trim().length!==0)return H(`project-agents-md`,`Agent Instructions`,10,e,`project-instructions`)}function oi(e){if(e.trim().length!==0)return H(`project-claude-md`,`Project Notes`,20,e,`project-instructions`)}function si(e){if(!(e===void 0||e.trim().length===0))return H(`project-memory`,`Project Memory`,25,e,`project-instructions`)}function ci(e){if(!(e===void 0||e.trim().length===0))return H(`active-task-context`,`Active Task Context`,27,e,`project-instructions`)}function li(e){if(e.length!==0)return H(`tool-descriptions`,`Available Tools`,60,e.map(e=>`- ${e}`).join(`
|
|
73
73
|
`),`tool`)}function ui(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}`}function di(e,t,n,r,i){let a=i.filter(t=>t.modelInvocable&&t.kind===e).map(ui);if(a.length!==0)return H(`capability-${e}`,t,n,a.join(`
|
|
74
|
-
`),r)}function fi(e){let t=[],n=di(`builtin-command`,`Built-in Commands`,70,`command`,e),r=di(`skill`,`Skills`,80,`skill`,e),i=di(`agent`,`Agents`,90,`agent`,e),a=di(`tool`,`Tools`,100,`tool`,e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),a&&t.push(a),t}function U(e,t){t!==void 0&&e.push(t)}function pi(e){return e.map(e=>({name:e.name,kind:`skill`,description:e.description,userInvocable:!0,modelInvocable:e.disableModelInvocation!==!0}))}function mi(e){return e.map(e=>({name:e.name,kind:`agent`,description:e.description,userInvocable:!1,modelInvocable:!0,safety:`background-agent`}))}function hi(e){return[...e.commandDescriptors??[],...e.skills?pi(e.skills):[],...e.agents?mi(e.agents):[]]}function gi(e){let t=[];return U(t,e.persona!==void 0&&e.persona.trim().length>0?$r(e.persona):void 0),U(t,e.selfVerification===!0?ei():void 0),U(t,ai(e.agentsMd)),U(t,oi(e.claudeMd)),U(t,si(e.memoryMd)),U(t,ci(e.taskContext)),U(t,ti(e.cwd)),t.push(ni(e.projectInfo)),U(t,ii(e.language)),t.push(ri(e.permissionMode)),U(t,li(e.toolDescriptions)),t.push(...fi(hi(e))),Qr(t)}function _i(e){return e}const vi=d.z.object({command:d.z.string().describe(`The shell command to start in the background`),timeout:d.z.number().optional().describe(`Optional timeout in milliseconds. Default is 120000.`),workingDirectory:d.z.string().optional().describe(`Working directory for the command. Defaults to the current project directory.`),stdin:d.z.string().optional().describe(`Optional stdin to write after the process starts.`),outputLimitBytes:d.z.number().optional().describe(`Maximum captured output bytes kept in the task result.`)});function yi(e,t,n){return JSON.stringify({success:!0,background:!0,output:``,taskId:e,status:t,command:n})}function bi(e){return JSON.stringify({success:!1,background:!0,output:``,error:`Background process error: ${e}`})}async function xi(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 yi(n.id,n.status,e.command)}catch(e){return bi(e instanceof Error?e.message:String(e))}}function Si(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.`,_i(vi),async t=>xi(t,e))}function Ci(e,t,n,r,i,a){let o,s=[],c;if(e.enableAgentRuntime||e.enableParallelSubagents){let u=new Xr(n);s=u.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=>u.getAgent(e),agentDefinitions:s};let d=new l.SubagentManager({runner:(e.subagentRunnerFactory??Tt)(o),backgroundTaskRunners:e.backgroundTaskRunners});o.subagentManager=d,c=d.getBackgroundTaskManager(),o.backgroundTaskManager=c}else c=new l.BackgroundTaskManager({runners:e.backgroundTaskRunners??[]});let u=e.sessionLogger;return u&&c.subscribe(e=>Oi(u,t,e)),c.subscribe(t=>Ur(t,n,e.config.hooks,a.length>0?a:void 0)),{agentToolDeps:o,agentDefinitions:s,backgroundTaskManager:c}}function wi(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:
|
|
74
|
+
`),r)}function fi(e){let t=[],n=di(`builtin-command`,`Built-in Commands`,70,`command`,e),r=di(`skill`,`Skills`,80,`skill`,e),i=di(`agent`,`Agents`,90,`agent`,e),a=di(`tool`,`Tools`,100,`tool`,e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),a&&t.push(a),t}function U(e,t){t!==void 0&&e.push(t)}function pi(e){return e.map(e=>({name:e.name,kind:`skill`,description:e.description,userInvocable:!0,modelInvocable:e.disableModelInvocation!==!0}))}function mi(e){return e.map(e=>({name:e.name,kind:`agent`,description:e.description,userInvocable:!1,modelInvocable:!0,safety:`background-agent`}))}function hi(e){return[...e.commandDescriptors??[],...e.skills?pi(e.skills):[],...e.agents?mi(e.agents):[]]}function gi(e){let t=[];return U(t,e.persona!==void 0&&e.persona.trim().length>0?$r(e.persona):void 0),U(t,e.selfVerification===!0?ei():void 0),U(t,ai(e.agentsMd)),U(t,oi(e.claudeMd)),U(t,si(e.memoryMd)),U(t,ci(e.taskContext)),U(t,ti(e.cwd)),t.push(ni(e.projectInfo)),U(t,ii(e.language)),t.push(ri(e.permissionMode)),U(t,li(e.toolDescriptions)),t.push(...fi(hi(e))),Qr(t)}function _i(e){return e}const vi=d.z.object({command:d.z.string().describe(`The shell command to start in the background`),timeout:d.z.number().optional().describe(`Optional timeout in milliseconds. Default is 120000.`),workingDirectory:d.z.string().optional().describe(`Working directory for the command. Defaults to the current project directory.`),stdin:d.z.string().optional().describe(`Optional stdin to write after the process starts.`),outputLimitBytes:d.z.number().optional().describe(`Maximum captured output bytes kept in the task result.`)});function yi(e,t,n){return JSON.stringify({success:!0,background:!0,output:``,taskId:e,status:t,command:n})}function bi(e){return JSON.stringify({success:!1,background:!0,output:``,error:`Background process error: ${e}`})}async function xi(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 yi(n.id,n.status,e.command)}catch(e){return bi(e instanceof Error?e.message:String(e))}}function Si(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.`,_i(vi),async t=>xi(t,e))}function Ci(e,t,n,r,i,a){let o,s=[],c;if(e.enableAgentRuntime||e.enableParallelSubagents){let u=new Xr(n);s=u.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=>u.getAgent(e),agentDefinitions:s};let d=new l.SubagentManager({runner:(e.subagentRunnerFactory??Tt)(o),backgroundTaskRunners:e.backgroundTaskRunners});o.subagentManager=d,c=d.getBackgroundTaskManager(),o.backgroundTaskManager=c}else c=new l.BackgroundTaskManager({runners:e.backgroundTaskRunners??[]});let u=e.sessionLogger;return u&&c.subscribe(e=>Oi(u,t,e)),c.subscribe(t=>Ur(t,n,e.config.hooks,a.length>0?a:void 0)),{agentToolDeps:o,agentDefinitions:s,backgroundTaskManager:c}}function wi(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:E({kind:`tool_call`,sessionId:n,label:`BackgroundProcess`})};return i.push(Si(a)),{backgroundProcessToolDeps:a}}function Ti(e,t,n,r,i){return{agentsMd:e.context.agentsMd,claudeMd:e.context.claudeMd,memoryMd:e.context.memoryMd,taskContext:e.context.taskContext,toolDescriptions:n,permissionMode:e.permissionMode??c.TRUST_TO_MODE[e.config.defaultTrustLevel]??`default`,projectInfo:e.projectInfo??{type:`unknown`,language:`unknown`},cwd:t,language:e.config.language,skills:r.map(e=>({name:e.name,description:e.description,disableModelInvocation:e.disableModelInvocation})),...i.length>0?{agents:i.map(e=>({name:e.name,description:e.description}))}:{},commandDescriptors:e.commandDescriptors??[]}}function Ei(e,t,n,r,i,a,o){let s=e.systemPromptBuilder??gi,c=[...Wr,...r?r.commandTools.map(ut):[]],l=e.toolDescriptions??(i?[...c,`BackgroundProcess — start long-running shell commands as managed background tasks`]:c),u=e.persona,d=e.selfVerification,f=Ti(e,t,l,a,o),p=s({...f,...u===void 0?{}:{persona:u},...d===void 0?{}:{selfVerification:d}});return{finalSystemMessage:e.appendSystemPrompt?`${p}\n\n${e.appendSystemPrompt}`:p,rebuildSystemMessage:(t,n,r)=>{r?.persona!==void 0&&(u=r.persona),r?.selfVerification!==void 0&&(d=r.selfVerification);let i=s({...f,...u===void 0?{}:{persona:u},...d===void 0?{}:{selfVerification:d},agentsMd:t,claudeMd:n});return e.appendSystemPrompt?`${i}\n\n${e.appendSystemPrompt}`:i}}}function Di(e,t,n,r){t&&(t.parentSessionId=e.getSessionId()),t&&(t.isParallelSubagentsEnabled=()=>e.getParallelSubagentsEnabled()),n&&(n.parentSessionId=e.getSessionId()),Le(e,r),t&&At(e,t)}function Oi(e,t,n){let r={};if(n.type===`background_task_created`){r.taskId=n.task.id;let e=n.task.metadata?.executionOriginToolCallId;typeof e==`string`&&(r.originToolCallId=e)}e.log(t,`background_task_event`,{backgroundEventType:n.type,backgroundEvent:n,...r})}const ki=new Set([`Write`,`Edit`]);function Ai(e,t){return e.map(e=>ki.has(e.getName())?new ji(e,t):e)}var ji=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=Mi(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 Mi(e){if(!e||typeof e!=`object`)return;let t=e.filePath;return typeof t==`string`&&t.length>0?t:void 0}const Ni=new Set([`disable-model-invocation`,`user-invocable`]),Pi=new Set([`allowed-tools`]);function Fi(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Ii(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Li(e){let t=e.split(`
|
|
75
75
|
`);if(t[0]?.trim()!==`---`)return null;let n={};for(let e=1;e<t.length;e++){let r=t[e];if(r.trim()===`---`)break;let i=r.match(/^([a-z][a-z0-9-]*):\s*(.+)/);if(!i)continue;let a=i[1],o=i[2].trim(),s=Fi(a);Ni.has(a)?n[s]=o===`true`:Pi.has(a)?n[s]=Ii(o):n[s]=o}return Object.keys(n).length>0?n:null}function Ri(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 zi(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,g.join)(e,i.name,`SKILL.md`);if(!t.existsSync(r))continue;let a=t.readFileSync(r,`utf-8`),o=Li(a);n.push(Ri(o,a,i.name))}return n}function Bi(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,g.join)(e,i.name),a=t.readFileSync(r,`utf-8`),o=Li(a),s=(0,g.basename)(i.name,`.md`);n.push(Ri(o,a,s))}return n}var Vi=class{name=`skill`;cwd;home;fs;cachedCommands=null;constructor(e,t,n=new N){this.cwd=e,this.home=t??(0,_.homedir)(),this.fs=n}getCommands(){if(this.cachedCommands)return this.cachedCommands;let e=[zi((0,g.join)(this.cwd,`.claude`,`skills`),this.fs),Bi((0,g.join)(this.cwd,`.claude`,`commands`),this.fs),zi((0,g.join)(this.home,`.robota`,`skills`),this.fs),zi((0,g.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)}},Hi=class extends Error{filePath;constructor(e,t){super(`Settings file ${e} contains invalid JSON: ${t}. Fix or delete the file, or run robota diagnose.`),this.name=`SettingsParseError`,this.filePath=e}};function Ui(){return(0,g.join)(process.env.HOME??process.env.USERPROFILE??`/`,`.robota`,`settings.json`)}function Wi(e,t){return t===void 0||t===`user`?Ui():(0,g.join)(e,`.robota`,`settings.local.json`)}function W(e){if(!(0,m.existsSync)(e))return{};let t=(0,m.readFileSync)(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new Hi(e,t instanceof Error?t.message:String(t))}}function G(e,t){(0,m.mkdirSync)((0,g.dirname)(e),{recursive:!0}),(0,m.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
76
76
|
`,`utf8`)}function Gi(e,t){let n=W(e),r=n.currentProvider,i=n.providers;if(typeof r==`string`&&Ki(i)){let e=i;e[r]={...Ki(e[r])?e[r]:{},model:t},n.providers=e}else n.provider={...Ki(n.provider)?n.provider:{},model:t};G(e,n)}function Ki(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function qi(e){return(0,m.existsSync)(e)?((0,m.unlinkSync)(e),!0):!1}function Ji(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var Yi=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=Ji(a),s;try{s=JSON.parse(o)}catch{return{exitCode:1,stdout:``,stderr:`Failed to parse agent response as JSON: ${a}`}}return s.ok?{exitCode:0,stdout:JSON.stringify(s),stderr:``}:{exitCode:2,stdout:``,stderr:s.reason??`Blocked by agent hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};function Xi(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var Zi=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=Xi(a),s;try{s=JSON.parse(o)}catch{return{exitCode:1,stdout:``,stderr:`Failed to parse AI response as JSON: ${a}`}}return s.ok?{exitCode:0,stdout:JSON.stringify(s),stderr:``}:{exitCode:2,stdout:``,stderr:s.reason??`Blocked by prompt hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};const Qi=new Set([`Write`,`Edit`]),$i=new Set([`Bash`,`BackgroundProcess`]),ea=new Set([`Read`,`Glob`,`Grep`,`WebFetch`,`WebSearch`]);function ta(e){let t=e.toolName;return ea.has(t)?{toolName:t,reversible:!0,sideEffect:`none`,rollbackLayer:`none`,status:`read-only`,message:`${t} does not mutate the local workspace.`}:Qi.has(t)?e.context.isolation===`worktree`||e.context.isolation===`provider-sandbox`?ia(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.`}:$i.has(t)?ia(t,`shell-process`,e.context):t===`Agent`?aa(e.toolArgs,e.context):{toolName:t,reversible:!1,sideEffect:`unknown`,rollbackLayer:`none`,status:`unknown`,message:`${t} has no reversible execution contract.`}}function na(e,t){let n={checkpointAvailable:t.checkpointAvailable,isolation:t.isolation??`none`},r=t.enforceUntrackedSideEffects??!0;return e.map(e=>new ra(e,{safetyContext:n,enforceUntrackedSideEffects:r}))}var ra=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=ta({toolName:this.getName(),toolArgs:la(e),context:this.options.safetyContext});return!n.reversible&&this.options.enforceUntrackedSideEffects?ua(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 ia(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 aa(e,t){return t.isolation===`worktree`||t.isolation===`provider-sandbox`?ia(`Agent`,`subagent`,t):oa(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 oa(e){if(!e)return!1;let t=e.jobs;return Array.isArray(t)?t.length>0&&t.every(e=>ca(e)?sa(e)===`worktree`:!1):sa(e)===`worktree`}function sa(e){let t=e.isolation;return typeof t==`string`?t:void 0}function ca(e){return e!==void 0&&typeof e==`object`&&!Array.isArray(e)}function la(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e}function ua(e){return{success:!0,data:{success:!1,output:``,error:e.message,reversibleSafety:{toolName:e.toolName,sideEffect:e.sideEffect,rollbackLayer:e.rollbackLayer,status:e.status}},metadata:{reversibleSafetyStatus:e.status,rollbackLayer:e.rollbackLayer}}}function da(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function fa(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function pa(e,t){return e.some(e=>fa(e.name)===t)}function ma(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??ha(),i=new Vi(n),a=da(e.commandDescriptors),o=a.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,s=o?lt(a):void 0,c=pa(a,`skills`)?i.getModelInvocableSkills():[],l=Gr({sandboxClient:e.sandboxClient,cwd:n}),u=e.editCheckpointRecorder!==void 0&&e.sandboxClient===void 0,d=[...u&&e.editCheckpointRecorder?Ai(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?na(d,{...p,checkpointAvailable:u}):d;o&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&m.push(...ft({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:a}));let h=[];e.providerFactory&&h.push(new Zi({providerFactory:e.providerFactory,defaultModel:e.config.provider.model})),e.sessionFactory&&h.push(new Yi({sessionFactory:e.sessionFactory})),e.additionalHookExecutors&&h.push(...e.additionalHookExecutors);let{agentToolDeps:_,agentDefinitions:v,backgroundTaskManager:y}=Ci(e,r,n,t,m,h),{backgroundProcessToolDeps:ee}=wi(e,y,r,n,m),{finalSystemMessage:te,rebuildSystemMessage:ne}=Ei(e,n,a,s,ee,c,v),re=[`Read(.agents/**)`,`Read(.claude/**)`,`Read(.robota/**)`,`Glob(.agents/**)`,`Glob(.claude/**)`,`Glob(.robota/**)`],ie=s?s.commandTools.filter(e=>!e.requiresPermission).map(e=>e.toolName):[],ae=(e.allowedTools??[]).map(e=>`${e}(*)`),oe=(e.deniedTools??[]).map(e=>`${e}(*)`),se={allow:[...re,...ie,...e.config.permissions.allow??[],...ae],deny:[...e.config.permissions.deny??[],...oe]},b=(0,g.join)(n,`.robota`,`settings.local.json`);function ce(e){let t=`${e}(*)`,n=W(b),r=Array.isArray(n.permissions)?[]:n.permissions?.allow??[];r.includes(t)||G(b,{...n,permissions:{...n.permissions??{},allow:[...r,t]}})}let le=new f.Session({tools:m,provider:t,systemMessage:te,terminal:e.terminal,permissions:se,hooks:e.config.hooks,permissionMode:e.permissionMode,defaultTrustLevel:e.config.defaultTrustLevel,model:e.model??e.config.provider.model,providerTimeout:e.config.provider.timeout??12e4,maxTurns:e.maxTurns,sessionStore:e.sessionStore,sessionId:r,permissionHandler:e.permissionHandler,onProjectAllowTool:ce,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,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.effort===void 0?{}:{effort:e.effort}});return Di(le,_,ee,y),{session:le,rebuildSystemMessage:ne}}function ha(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function ga(e,t,n,r=new N){let i=(0,g.join)(n,e,`subagents`);return r.mkdirSync(i,{recursive:!0}),new f.FileSessionLogger(i)}function _a(e,t){return(0,g.join)(t,e,`subagents`)}const K=d.z.lazy(()=>d.z.union([d.z.string(),d.z.number(),d.z.boolean(),d.z.null(),d.z.undefined(),d.z.date(),d.z.array(K),d.z.record(K)])),va=d.z.object({name:d.z.string().optional(),model:d.z.string().optional(),apiKey:d.z.string().optional(),baseURL:d.z.string().optional(),timeout:d.z.number().optional(),options:d.z.record(K).optional()}),ya=d.z.object({type:d.z.string().optional(),model:d.z.string().optional(),apiKey:d.z.string().optional(),baseURL:d.z.string().optional(),timeout:d.z.number().optional(),options:d.z.record(K).optional()}),ba=d.z.object({allow:d.z.array(d.z.string()).optional(),deny:d.z.array(d.z.string()).optional()}),xa=d.z.record(d.z.string()).optional(),Sa=d.z.object({type:d.z.literal(`command`),command:d.z.string(),timeout:d.z.number().optional()}),Ca=d.z.object({type:d.z.literal(`http`),url:d.z.string(),headers:d.z.record(d.z.string()).optional(),timeout:d.z.number().optional()}),wa=d.z.object({type:d.z.literal(`prompt`),prompt:d.z.string(),model:d.z.string().optional()}),Ta=d.z.object({type:d.z.literal(`agent`),agent:d.z.string(),maxTurns:d.z.number().optional(),timeout:d.z.number().optional()}),Ea=d.z.discriminatedUnion(`type`,[Sa,Ca,wa,Ta]),q=d.z.object({matcher:d.z.string(),hooks:d.z.array(Ea)}),Da=d.z.object({PreToolUse:d.z.array(q).optional(),PostToolUse:d.z.array(q).optional(),SessionStart:d.z.array(q).optional(),SessionEnd:d.z.array(q).optional(),Stop:d.z.array(q).optional(),StopFailure:d.z.array(q).optional(),PreCompact:d.z.array(q).optional(),PostCompact:d.z.array(q).optional(),UserPromptSubmit:d.z.array(q).optional(),SubagentStart:d.z.array(q).optional(),SubagentStop:d.z.array(q).optional(),WorktreeCreate:d.z.array(q).optional(),WorktreeRemove:d.z.array(q).optional()}).optional(),Oa=d.z.record(d.z.boolean()).optional(),ka=d.z.object({source:d.z.object({type:d.z.enum([`github`,`git`,`local`,`url`]),repo:d.z.string().optional(),url:d.z.string().optional(),path:d.z.string().optional(),ref:d.z.string().optional()})}),Aa=d.z.record(ka).optional().catch(void 0),ja=d.z.union([d.z.number().gt(0).lte(1),d.z.literal(!1)]).optional(),Ma=d.z.object({enabled:d.z.boolean().optional(),options:d.z.record(K).optional()}),Na=d.z.object({defaultTrustLevel:d.z.enum([`safe`,`moderate`,`full`]).optional(),language:d.z.string().optional(),preset:d.z.string().optional(),currentProvider:d.z.string().optional(),providers:d.z.record(ya).optional(),provider:va.optional(),permissions:ba.optional(),env:xa,hooks:Da,enabledPlugins:Oa,extraKnownMarketplaces:Aa,autoCompactThreshold:ja,transports:d.z.record(Ma).optional()});function Pa(){return process.env.HOME??process.env.USERPROFILE??`/`}const J={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[]},env:{}};function Fa(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 Ia(e){if(e.startsWith(`$ENV:`)){let t=e.slice(5);return process.env[t]??e}return e}function La(e){let t=e.provider?.apiKey===void 0?e.provider:Ra(e.provider);if(e.providers!==void 0){let n=Object.fromEntries(Object.entries(e.providers).map(([e,t])=>[e,Ra(t)]));return{...e,provider:t,providers:n}}return{...e,provider:t}}function Ra(e){return{...e,...e.apiKey!==void 0&&{apiKey:Ia(e.apiKey)}}}function za(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?Ba(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 Ba(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function Va(e){if(e.currentProvider!==void 0)return Ha(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...J.provider}}function Ha(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??J.provider.model,apiKey:n.apiKey??J.provider.apiKey,...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function Ua(e){return{defaultTrustLevel:e.defaultTrustLevel??J.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:Va(e),permissions:{allow:e.permissions?.allow??J.permissions.allow,deny:e.permissions?.deny??J.permissions.deny},env:e.env??J.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold}}function Wa(e){let t=Pa();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 Ga(e){let t=Wa(e),n=[];for(let e of t){let t=Fa(e);t!==void 0&&n.push({raw:t,path:e})}return Ua(za(n.map(({raw:e,path:t})=>{let n=Na.safeParse(e);if(!n.success)throw Error(`Invalid settings in ${t}: ${n.error.message}`);return La(n.data)})))}const Ka=(0,g.join)(`.agents`,`tasks`),qa={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function Ja(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function Ya(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||(0,g.basename)(t,`.md`)}function Xa(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function Za(e,t){let n=e.split(/\r?\n/),r=RegExp(`^(#{2,6})\\s+${t}\\b`,`i`),i=n.findIndex(e=>r.test(e));if(i<0)return;let a=[];for(let e of n.slice(i+1)){if(/^##\s+/.test(e))break;a.push(e)}let o=a.join(`
|
|
77
77
|
`).trim();return o.length>0?o:void 0}function Qa(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(.+)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function $a(e,t){return t&&e.branch===t?0:qa[e.status]}function eo(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(`
|
|
@@ -95,7 +95,7 @@ Do not use emojis.`}function rt(){return`You are a worker subagent executing a s
|
|
|
95
95
|
`)){let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();typeof r==`string`&&r.startsWith(`[`)&&r.endsWith(`]`)&&(r=r.slice(1,-1).split(`,`).map(e=>e.trim()).filter(e=>e.length>0)),n&&(a[n]=r)}return{metadata:a,content:i}}function Oo(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 ko(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 Ao=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,g.join)(this.pluginsDir,`cache`);if(!this.fs.existsSync(e))return[];let t=[],n=ko(e,this.fs);for(let r of n){let n=(0,g.join)(e,r),i=ko(n,this.fs);for(let e of i){let i=(0,g.join)(n,e),a=ko(i,this.fs);if(a.length===0)continue;let o=a[a.length-1],s=(0,g.join)(i,o),c=(0,g.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 Oo(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,g.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,g.join)(n,e.name,`SKILL.md`);if(!this.fs.existsSync(t))continue;let{metadata:r,content:a}=Do(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,g.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}=Do(this.fs.readFileSync((0,g.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,g.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,g.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,g.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$/,``)):[]}},jo=class{pluginsDir;cacheDir;registryPath;settingsStore;marketplaceClient;exec;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.cacheDir=(0,g.join)(this.pluginsDir,`cache`),this.registryPath=(0,g.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,g.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,g.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,g.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 Y(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 Mo(e,t,n=new N){let r=(0,g.dirname)(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(e,JSON.stringify(t,null,2),`utf-8`)}function No(e,t,n=new N){let r=(0,g.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,g.dirname)(r);n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.writeFileSync(r,JSON.stringify(i,null,2),`utf-8`)}}const Po=6e4;var Fo=class{pluginsDir;exec;marketplacesDir;registryPath;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.exec=e.exec,this.marketplacesDir=(0,g.join)(this.pluginsDir,`marketplaces`),this.registryPath=(0,g.join)(this.pluginsDir,`known_marketplaces.json`),this.fs=e.fs??new N}addMarketplace(e){let t=`temp-`+Date.now().toString(36),n=(0,g.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:Po,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone marketplace: ${t}`)}}let r=(0,g.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=Y(this.registryPath,this.fs);if(a[i])throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace "${i}" already exists`);let o=(0,g.join)(this.marketplacesDir,i);return this.fs.renameSync(n,o),a[i]={source:e,installLocation:o,lastUpdated:new Date().toISOString()},Mo(this.registryPath,a,this.fs),i}removeMarketplace(e){let t=Y(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);No(this.pluginsDir,e,this.fs),this.fs.existsSync(n.installLocation)&&this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),delete t[e],Mo(this.registryPath,t,this.fs)}updateMarketplace(e){let t=Y(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:Po,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(),Mo(this.registryPath,t,this.fs)}listMarketplaces(){let e=Y(this.registryPath,this.fs);return Object.entries(e).map(([e,t])=>({name:e,source:t.source,lastUpdated:t.lastUpdated}))}fetchManifest(e){let t=Y(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);let n=(0,g.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=Y(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:Po,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 Io(e){let t=(0,g.join)((0,g.dirname)((0,g.dirname)(e.pluginDir)),`data`,e.manifest.name);return{CLAUDE_PLUGIN_ROOT:e.pluginDir,CLAUDE_PLUGIN_PATH:e.pluginDir,CLAUDE_PLUGIN_DATA:t}}function Lo(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 Ro(e){let t={};for(let n of e){let e=n.hooks;if(!e)continue;let r=Io(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=Lo(e,n.pluginDir);return t.env=r,t});t[e].push(...i)}}return t}function zo(e,t){if(Object.keys(t).length===0)return e;let n={};for(let[e,r]of Object.entries(t))n[e]=[...r];if(e)for(let[t,r]of Object.entries(e))Array.isArray(r)&&(n[t]||(n[t]=[]),n[t].push(...r));return n}async function Bo(e){let t=e.cwd,[n,r,i]=await Promise.all([e.config?Promise.resolve(e.config):Ga(t),e.bare?Promise.resolve({agentsMd:``,claudeMd:``,agentsFileEntries:[],claudeFileEntries:[]}):To(t),e.bare?Promise.resolve({type:`unknown`,language:`unknown`}):Ir(t)]),a=e.language?{...n,language:e.language}:n,o=new Ao((0,g.join)((0,_.homedir)(),`.robota`,`plugins`));if(!e.bare)try{let e=o.loadPluginsSync();if(e.length>0){let t=Ro(e);a={...a,hooks:zo(a.hooks,t)}}}catch{}let s=R(t);await Ho(e)||await Vo(e,t);let c=e.resumeSessionId&&!e.forkSession?e.resumeSessionId:void 0,{session:l,rebuildSystemMessage:u}=ma({config:a,cwd:t,context:r,projectInfo:i,permissionMode:e.permissionMode,maxTurns:e.maxTurns,terminal:Xn,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,deniedTools:e.deniedTools,model:e.model,appendSystemPrompt:e.appendSystemPrompt,...e.persona===void 0?{}:{persona:e.persona},...e.systemPrompt?{systemPromptBuilder:()=>e.systemPrompt}:{},backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,...e.commandModules?.some(e=>e.sessionRequirements?.includes(`agent-runtime`))?{enableAgentRuntime:!0}:{},...e.enableParallelSubagents===void 0?{}:{enableParallelSubagents:e.enableParallelSubagents},...e.selfVerification===void 0?{}:{selfVerification:e.selfVerification},...e.commandModules||e.commandDescriptors?{commandDescriptors:[...e.commandDescriptors??[],...e.commandModules?.flatMap(e=>e.commandDescriptors??[])??[]]}:{},modelCommandExecutor:e.modelCommandExecutor,isModelCommandInvocable:e.isModelCommandInvocable,editCheckpointRecorder:e.editCheckpointRecorder,reversibleExecution:e.reversibleExecution,sandboxClient:e.sandboxClient,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{}});return{session:l,agentsFileEntries:r.agentsFileEntries??[],claudeFileEntries:r.claudeFileEntries??[],rebuildSystemMessage:u}}async function Vo(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 Ho(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 Uo(e,t){let n=e.config??await Ga(e.cwd),r=n.autoCompactThreshold===void 0?`default`:`settings`,i=new z({cwd:e.cwd});t.setEditCheckpointStore(i);let a=await Bo({cwd:e.cwd,provider:e.provider,config:n,permissionMode:e.permissionMode,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler,resumeSessionId:t.resumeSessionId,forkSession:e.forkSession,onTextDelta:t.onTextDelta,onContextUpdate:t.onContextUpdate,onCompactEvent:t.onCompactEvent,onToolExecution:t.onToolExecution,bare:e.bare,allowedTools:e.allowedTools,deniedTools:e.deniedTools,model:e.model,appendSystemPrompt:e.appendSystemPrompt,...e.persona===void 0?{}:{persona:e.persona},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},language:e.language,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,...e.commandModules?{commandModules:e.commandModules}:{},editCheckpointRecorder:i,...e.reversibleExecution?{reversibleExecution:e.reversibleExecution}:{},...e.sandboxClient?{sandboxClient:e.sandboxClient}:{},...e.workspaceManifest?{workspaceManifest:e.workspaceManifest}:{},...e.sandboxWorkspaceRoot?{sandboxWorkspaceRoot:e.sandboxWorkspaceRoot}:{},...t.sandboxSnapshotId?{sandboxSnapshotId:t.sandboxSnapshotId}:{},...e.agentName?{agentName:e.agentName}:{},...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.enableParallelSubagents===void 0?{}:{enableParallelSubagents:e.enableParallelSubagents},...e.selfVerification===void 0?{}:{selfVerification:e.selfVerification},...e.additionalTools?{additionalTools:e.additionalTools}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},commandDescriptors:t.commandDescriptors,...t.commandDescriptors.length>0?{modelCommandExecutor:t.executeModelCommand,isModelCommandInvocable:t.isModelCommandInvocable}:{}});if(t.pendingRestoreMessages){for(let e of t.pendingRestoreMessages)Lr(a.session,e);a.session.syncContextFromHistory()}return{session:a.session,agentsFileEntries:a.agentsFileEntries,claudeFileEntries:a.claudeFileEntries,rebuildSystemMessage:a.rebuildSystemMessage,autoCompactThresholdSource:r}}function Wo(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(Go({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 Go(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},...Ko(e.backgroundState),...qo(e.memoryState),...Jo(e.skillActivationState),...Yo(e.contextReferenceState)}}function Ko(e){return e?{backgroundTasks:[...e.tasks],backgroundTaskEvents:[...e.events],backgroundJobGroups:[...e.groups??[]],backgroundJobGroupEvents:[...e.groupEvents??[]]}:{}}function qo(e){return e?{memoryEvents:[...e.events],usedMemoryReferences:[...e.usedReferences]}:{}}function Jo(e){return e?{skillActivationEvents:[...e.events]}:{}}function Yo(e){return e?{contextReferences:[...e.references]}:{}}function Xo(e){return e.source===`skill`||e.source===`plugin`&&e.skillContent?`skill`:`builtin-command`}function Zo(e){let t=e.source===`skill`||e.source===`plugin`&&!!e.skillContent;return{name:e.name,kind:Xo(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 Qo=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=>Zo(e))}},$o=class{commands;constructor(e){this.commands=new Map;for(let t of e??es())this.commands.set(t.name,t)}register(e){this.commands.set(e.name,e)}replaceCommands(e){this.commands.clear();for(let t of e)this.commands.set(t.name,t)}async execute(e,t,n){let r=this.getCommand(e);return r?await this.executeCommand(r,t,n):null}getCommand(e){return this.commands.get(e)}resolveRequiresPermission(e){return e.requiresPermission===void 0?e.safety!==`read-only`:e.requiresPermission}async executeCommand(e,t,n){return await e.execute(t,n)}listCommands(){return[...this.commands.values()]}listModelInvocableCommands(){return this.listCommands().filter(e=>e.modelInvocable===!0).map(e=>({name:e.name,kind:`builtin-command`,description:e.description,userInvocable:e.userInvocable!==!1,modelInvocable:!0,...e.argumentHint?{argumentHint:e.argumentHint}:{},...e.safety?{safety:e.safety}:{},requiresPermission:this.resolveRequiresPermission(e)}))}isModelInvocable(e){return this.commands.get(e)?.modelInvocable===!0}async executeModelInvocable(e,t,n){return this.isModelInvocable(e)?this.execute(e,t,n):null}hasCommand(e){return this.commands.has(e)}};function es(){return[]}function ts(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 ns=class{name=`builtin`;commands;constructor(e=es()){this.commands=e.map(ts)}getCommands(){return this.commands}};function rs(){let e=es();return{name:`sdk-builtin`,commandSources:[new ns(e)],systemCommands:e}}function is(e,t,n){return{...e,providers:{...e.providers??{},[t]:n}}}function as(e,t){if(!e.providers?.[t])throw Error(`Provider profile "${t}" was not found`);return{...e,currentProvider:t}}function os(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 ss(e,t,n={}){if(!t.type)throw Error(`Provider profile "${e}" is missing type`);let r=n.providerDefinitions??[],i=(0,c.findProviderDefinition)(r,t.type);if(i===void 0&&r.length>0)throw Error(`Unknown provider "${t.type}". Supported providers: ${(0,c.formatSupportedProviderTypes)(r)}`);if(!t.model)throw Error(`Provider profile "${e}" is missing model`);let a=(0,c.getProviderCredentialRequirement)(i);if(a!==void 0&&!fs(t,i?.defaults,a))throw Error(`Provider profile "${e}" is missing ${ms(a)}`)}function cs(e,t={}){let n=ls(e,t);return ss(e.profile,n,t),{...e.setCurrent&&{currentProvider:e.profile},providers:{[e.profile]:n}}}function ls(e,t={}){let n=ds(e.type,t.providerDefinitions??[]);if(e.apiKey!==void 0&&e.apiKeyEnv===void 0&&console.warn(`API key stored as plain text in settings. Use --api-key-env for better security.`),e.apiKeyEnv!==void 0){let n=(t.env??process.env)[e.apiKeyEnv];if(n===void 0||n.length===0)throw Error(`Environment variable ${e.apiKeyEnv} is not set — set it before configuring (the profile will reference $ENV:${e.apiKeyEnv})`)}let r=e.apiKeyEnv===void 0?e.apiKey??n.apiKey:(0,c.formatEnvReference)(e.apiKeyEnv),i=e.baseURL??n.baseURL;return{type:e.type,model:e.model??n.model,...hs(r)&&{apiKey:r},...i!==void 0&&{baseURL:i},...e.timeout!==void 0&&{timeout:e.timeout}}}function us(e,t){let[n,r]=Object.entries(t.providers)[0]??[];if(!n||!r)return e;let i=is(e,n,r);return t.currentProvider?as(i,t.currentProvider):i}function ds(e,t){return(0,c.findProviderDefinition)(t,e)?.defaults??{}}function fs(e,t,n){return n.anyOf.some(n=>(0,c.hasUsableSecretReference)(ps(n,e,t)))}function ps(e,t,n){return t[e]??n?.[e]}function ms(e){return e.anyOf.join(` or `)}function hs(e){return e!==void 0&&e.length>0}async function gs(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{ss(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??_s)(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 _s(e){return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`}}function vs(e,t=[]){return ys(e,t)?`valid`:`incomplete`}function ys(e,t){if(typeof e.currentProvider==`string`){let n=e.providers?.[e.currentProvider];return bs(n?.type,n,t)}return!!(e.provider&&bs(e.provider.name,e.provider,t))}function bs(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:xs(t,r,i)}function xs(e,t,n){return n.anyOf.some(n=>(0,c.hasUsableSecretReference)(Ss(n,e,t)))}function Ss(e,t,n){return t[e]??n.defaults?.[e]}function Cs(e,t=[]){if(!(0,m.existsSync)(e))return`missing`;try{let n=(0,m.readFileSync)(e,`utf8`).trim();return n.length===0?`incomplete`:vs(JSON.parse(n),t)}catch{return`corrupt`}}function ws(e,t=new N){return e.reduce((e,n)=>{let r=Ts(n,t);return r===void 0?e:Es(e,r)},{})}function Ts(e,t){if(!t.existsSync(e))return;let n=t.readFileSync(e,`utf8`);try{return JSON.parse(n)}catch(t){throw new Hi(e,t instanceof Error?t.message:String(t))}}function Es(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?Ds(e.providers,t.providers):void 0}}function Ds(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function Os(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,l.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,l.normalizeProviderConfig)({name:i.name,model:i.model,apiKey:i.apiKey,baseURL:i.baseURL,timeout:i.timeout,options:i.options},n)}function ks(){return process.env.HOME??process.env.USERPROFILE??`/`}function As(e){let t=ks();return[(0,g.join)(t,`.robota`,`settings.json`),(0,g.join)(t,`.claude`,`settings.json`),(0,g.join)(e,`.robota`,`settings.json`),(0,g.join)(e,`.robota`,`settings.local.json`),(0,g.join)(e,`.claude`,`settings.json`),(0,g.join)(e,`.claude`,`settings.local.json`)]}function js(e,t={}){let n=t.settingsPaths??As(e),r=Ls(n)??n[0];if(r===void 0)throw Error(`No settings path available for provider update`);return r}function X(e){return W(e)}function Ms(e,t,n={}){let r=us(X(e),cs(t,n));return G(e,r),r}function Ns(e,t,n={}){let r=X(e),i=r.providers?.[t]!==void 0,a=n.knownProviders?.[t]!==void 0,o=i||a?{...r,currentProvider:t}:as(r,t);return G(e,o),o}function Ps(e,t,n={}){let r=n.settingsPaths??As(e),i=ws(r),a=n.providerOverride??i.currentProvider;if(typeof a!=`string`)throw Error(`Cannot update model: no active provider profile. Set "currentProvider" in settings.`);return Fs(r,a,t)}function Fs(e,t,n){let r=Is(e,t)??e[0];if(r===void 0)throw Error(`No settings path available for model update`);let i=X(r),a=i.providers??{},o=a[t]??{},s={...i,providers:{...a,[t]:{...o,model:n}}};return G(r,s),{settingsPath:r,settings:s,profileName:t}}function Is(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&X(r).providers?.[t]!==void 0)return r}}function Ls(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0&&X(n).currentProvider!==void 0)return n}}var Rs=class extends Error{constructor(e){super(e),this.name=`ProviderConfigError`}};function zs(e){return ws(As(e))}function Bs(e,t=process.env){for(let n of e){let e=n.defaults;if(e?.apiKey===void 0||e.model===void 0||!(0,c.isEnvReference)(e.apiKey))continue;let r=e.apiKey.slice(c.ENV_REFERENCE_PREFIX.length).trim();if(r.length===0)continue;let i=t[r];if(!(i===void 0||i.length===0))return{name:n.type,model:e.model,apiKey:i,...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},...e.options!==void 0&&{options:e.options},source:`env-default`,sourceEnvVar:r}}}function Vs(e,t={}){let n=Os(zs(e),t.providerOverride,t.providerDefinitions??[]);if(n!==void 0)return n;let r=Bs(t.providerDefinitions??[],t.env);if(r!==void 0)return r;throw new Rs("No provider configuration found. Run `robota` to set up.")}function Hs(e,t,n={}){let r=n.providerDefinitions??[],i=Vs(e,{...n,providerDefinitions:r}),a=t??i.model;return(0,l.createProviderFromConfig)({...i,model:a},r)}var Us=class{name=`plugin`;plugins;constructor(e){this.plugins=e}getCommands(){let e=[];for(let t of this.plugins){for(let n of t.skills){let r=n.name.includes(`@`)?n.name.split(`@`)[0]:n.name;e.push({name:r,description:`(${t.manifest.name}) ${n.description}`,source:`plugin`,skillContent:n.skillContent,pluginDir:t.pluginDir})}for(let n of t.commands)e.push({name:n.name,description:n.description,source:`plugin`,skillContent:n.skillContent,pluginDir:t.pluginDir})}return e}};function Ws(e,t,n){let r=e;if(t!==void 0){let e=new Set(t);r=r.filter(t=>e.has(t.name))}if(n!==void 0){let e=new Set(n);r=r.filter(t=>!e.has(t.name))}return r}const Gs=f.AUTO_COMPACT_THRESHOLD,Ks=`autoCompactThreshold`;function qs(e){return e.getContextState()}function Js(e){return e.getAutoCompactThreshold()}function Ys(e){return e.getAutoCompactThresholdSource?.()??`session`}function Xs(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 Zs(e,t){let n=ic(e);return n?(n.write({...n.read(),[Ks]:t}),!0):!1}function Qs(e){let t=ic(e);if(!t)return!1;let n={...t.read()};return delete n[Ks],t.write(n),!0}async function $s(e,t){let n=qs(e),r=e.getSession().getMessageCount();return await e.compactContext(t),{before:n,after:qs(e),beforeMessageCount:r,afterMessageCount:e.getSession().getMessageCount()}}function ec(e){return e.listContextReferences?.()??[]}async function tc(e,t){return e.addContextReference?e.addContextReference(t):{evicted:[],diagnostics:[`Command host does not support context reference additions.`]}}function nc(e,t){return e.removeContextReference?.(t)??{}}function rc(e){return e.clearContextReferences?.()??{removed:[]}}function ic(e){return e.getCommandHostAdapters?.().settings}function ac(e,t={}){let n=oc(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 oc(e){let t=e?.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t!==void 0&&t.length>0?t:void 0}function sc(e){return e.listCommands?.()??[]}function cc(e){return[`Available commands:`,...sc(e).flatMap(e=>{let t=e.displayName??e.name,n=`/${e.name}`,r=` ${(e.displayName?`${t} (${n})`:n).padEnd(32)} — ${e.description}`;return e.example?[r,` Example: ${e.example}`]:[r]})].join(`
|
|
96
96
|
`)}function lc(){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 uc(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=pc(e),s=t?` — ${t}`:``;return`${e.id} [${e.status}${n}${i}${a}${o}] ${e.kind}:${e.label}${r}${s}`}function dc(e){return e.length===0?`No background tasks.`:[`Background tasks:`,...e.map(e=>` ${uc(e)}`)].join(`
|
|
97
97
|
`)}function fc(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isNaN(t)?void 0:{offset:t}}function pc(e){let t=[];return e.worktreePath&&t.push(`worktree=${e.worktreePath}`),e.branchName&&t.push(`branch=${e.branchName}`),e.worktreeStatus&&t.push(`worktreeStatus="${mc(e.worktreeStatus)}"`),e.worktreeNextAction&&t.push(`next="${mc(e.worktreeNextAction)}"`),t.length===0?``:` ${t.join(` `)}`}function mc(e){let t=e.trim().replace(/\s+/g,` `);return t.length>160?`${t.slice(0,160)}...`:t}function hc(e,t){return e.listBackgroundTasks(t)}function gc(e,t,n){return e.readBackgroundTaskLog(t,n)}function _c(e,t,n){return e.cancelBackgroundTask(t,n)}function vc(e,t){return e.closeBackgroundTask(t)}const yc=[{code:`ko`,description:`Korean`},{code:`en`,description:`English`},{code:`ja`,description:`Japanese`},{code:`zh`,description:`Chinese`}];function bc(e=`language`){return yc.map(t=>({name:t.code,description:t.description,source:e}))}function xc(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Sc(e=`language`){return`Usage: ${e} <code> (e.g., ko, en, ja, zh)`}const Cc=[`plan`,`default`,`acceptEdits`,`bypassPermissions`];function wc(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 Tc(e){let t=e.trim().split(/\s+/)[0];return t!==void 0&&t.length>0?t:void 0}function Ec(e){return Cc.includes(e)}function Dc(){return`Invalid mode. Valid: ${Cc.join(` | `)}`}function Oc(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 kc(e){return Oc(e).getPermissionMode()}function Ac(e,t){Oc(e).setPermissionMode(t)}function jc(e){return Oc(e).listSessionAllowedTools()}function Mc(e){return{mode:kc(e),sessionAllowed:jc(e)}}function Nc(e){let t=[`Permission mode: ${e.mode}`];return e.sessionAllowed.length>0?t.push(`Session-approved tools: ${e.sessionAllowed.join(`, `)}`):t.push(`No session-approved tools.`),t.join(`
|
|
98
|
-
`)}function Pc(e,t,n){let r=[],i=[];e.getSession().setActivePresetId?.(t),n.permissionMode===void 0?i.push(`permissionMode`):(Ac(e,n.permissionMode),r.push(`permissionMode`));let a={...n.model!==void 0&&{model:n.model},...n.effort!==void 0&&{effort:n.effort},...n.temperature!==void 0&&{temperature:n.temperature},...n.maxOutputTokens!==void 0&&{maxOutputTokens:n.maxOutputTokens}};for(let e of[`model`,`effort`,`temperature`,`maxOutputTokens`])n[e]===void 0?i.push(e):r.push(e);return Object.keys(a).length>0&&e.getSession().applyModelOptions?.(a),n.persona===void 0?i.push(`persona`):(e.applyPersona?.(n.persona),r.push(`persona`)),n.enabledCommandModules!==void 0||n.disabledCommandModules!==void 0?(e.applyCommandModuleSelection?.(n.enabledCommandModules,n.disabledCommandModules),r.push(`commandModules`)):i.push(`commandModules`),n.enableParallelSubagents===void 0?i.push(`enableParallelSubagents`):(e.getSession().setParallelSubagentsEnabled?.(n.enableParallelSubagents),r.push(`enableParallelSubagents`)),n.selfVerification===void 0?i.push(`selfVerification`):(e.applySelfVerification?.(n.selfVerification),r.push(`selfVerification`)),{applied:r,skipped:i}}const Fc={enabled:!0,gitBranch:!0};function Ic(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 Lc(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function Rc(e){let t=e.statusline;return Bc(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:Fc.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:Fc.gitBranch}:{...Fc}}function zc(e,t){let n=W(e),r={...Rc(n),...t};return n.statusline=r,G(e,n),r}function Bc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Vc(){return{type:`plugin-tui-requested`}}function Hc(){return{type:`plugin-registry-reload-requested`}}function Uc(e){return e.getCommandHostAdapters?.().plugin}function Wc(){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 Gc(e){if(e.clearConversationHistory!==void 0){e.clearConversationHistory();return}e.getSession().clearHistory()}function Kc(e){let t=e.trim();return t.length>0?t:void 0}function qc(e){return{type:`session-renamed`,name:e}}function Jc(){return{type:`session-picker-requested`}}function Yc(){return{type:`session-exit-requested`}}function Xc(e){let t=e.getSession();return{sessionId:t.getSessionId(),messageCount:t.getMessageCount()}}function Zc(e){let t=e.validateCurrentSessionReplayLog?.();if(t!==void 0)return t;let n=e.getSession().getSessionId(),r=(0,g.join)(R(e.getCwd()).logs,`${n}.jsonl`),i=(0,f.loadSessionLogEntries)(r);return{logFile:r,entryCount:i.length,validation:(0,f.validateSessionReplayLogEntries)(i)}}function Qc(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(`
|
|
98
|
+
`)}async function Pc(e,t,n){let r=[],i=[];e.getSession().setActivePresetId?.(t),n.permissionMode===void 0?i.push(`permissionMode`):(Ac(e,n.permissionMode),r.push(`permissionMode`));let a={...n.model!==void 0&&{model:n.model},...n.effort!==void 0&&{effort:n.effort},...n.temperature!==void 0&&{temperature:n.temperature},...n.maxOutputTokens!==void 0&&{maxOutputTokens:n.maxOutputTokens}};for(let e of[`model`,`effort`,`temperature`,`maxOutputTokens`])n[e]===void 0?i.push(e):r.push(e);return Object.keys(a).length>0&&await e.getSession().applyModelOptions?.(a),n.persona===void 0?i.push(`persona`):(e.applyPersona?.(n.persona),r.push(`persona`)),n.enabledCommandModules!==void 0||n.disabledCommandModules!==void 0?(e.applyCommandModuleSelection?.(n.enabledCommandModules,n.disabledCommandModules),r.push(`commandModules`)):i.push(`commandModules`),n.enableParallelSubagents===void 0?i.push(`enableParallelSubagents`):(e.getSession().setParallelSubagentsEnabled?.(n.enableParallelSubagents),r.push(`enableParallelSubagents`)),n.selfVerification===void 0?i.push(`selfVerification`):(e.applySelfVerification?.(n.selfVerification),r.push(`selfVerification`)),{applied:r,skipped:i}}const Fc={enabled:!0,gitBranch:!0};function Ic(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 Lc(e){return(e.enabled===void 0||typeof e.enabled==`boolean`)&&(e.gitBranch===void 0||typeof e.gitBranch==`boolean`)}function Rc(e){let t=e.statusline;return Bc(t)?{enabled:typeof t.enabled==`boolean`?t.enabled:Fc.enabled,gitBranch:typeof t.gitBranch==`boolean`?t.gitBranch:Fc.gitBranch}:{...Fc}}function zc(e,t){let n=W(e),r={...Rc(n),...t};return n.statusline=r,G(e,n),r}function Bc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Vc(){return{type:`plugin-tui-requested`}}function Hc(){return{type:`plugin-registry-reload-requested`}}function Uc(e){return e.getCommandHostAdapters?.().plugin}function Wc(){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 Gc(e){if(e.clearConversationHistory!==void 0){e.clearConversationHistory();return}e.getSession().clearHistory()}function Kc(e){let t=e.trim();return t.length>0?t:void 0}function qc(e){return{type:`session-renamed`,name:e}}function Jc(){return{type:`session-picker-requested`}}function Yc(){return{type:`session-exit-requested`}}function Xc(e){let t=e.getSession();return{sessionId:t.getSessionId(),messageCount:t.getMessageCount()}}function Zc(e){let t=e.validateCurrentSessionReplayLog?.();if(t!==void 0)return t;let n=e.getSession().getSessionId(),r=(0,g.join)(R(e.getCwd()).logs,`${n}.jsonl`),i=(0,f.loadSessionLogEntries)(r);return{logFile:r,entryCount:i.length,validation:(0,f.validateSessionReplayLogEntries)(i)}}function Qc(e){let t=e.validation.ok?`Session replay log is valid.`:`Session replay log has ${e.validation.issues.length} issue(s).`,n=[`Log: ${e.logFile}`,`Entries: ${e.entryCount}`];if(e.validation.ok)return[t,...n].join(`
|
|
99
99
|
`);let r=e.validation.issues.map((e,t)=>{let n=$c(e);return`${t+1}. ${e.code}${n}: ${e.message}`});return[t,...n,``,...r].join(`
|
|
100
100
|
`)}function $c(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 el(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 tl(e){return e.listEditCheckpoints()}function nl(e,t){if(!e.inspectEditCheckpoint)throw Error(`Checkpoint inspection is not available in this command host.`);return e.inspectEditCheckpoint(t)}function rl(e,t){return e.restoreEditCheckpoint(t)}function il(e,t){return e.rollbackEditCheckpoint(t)}const al=[/\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 ol(e){return al.some(t=>t.test(e))}function sl(e){return(0,g.join)(e,`.robota`,`memory`)}function cl(){return{version:1,records:[]}}var ll=class{fs;path;now;constructor(e,t=()=>new Date,n=new N){this.fs=n,this.path=(0,g.join)(sl(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 cl();try{return{version:1,records:JSON.parse(this.fs.readFileSync(this.path,`utf8`)).records??[]}}catch{return cl()}}write(e){this.fs.mkdirSync((0,g.dirname)(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,JSON.stringify(e,null,2),`utf8`)}};function ul(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 dl(e,t){return new So(e,t)}function fl(e,t){return new ll(e,t)}function pl(e,t){let n=e.getCwd();return{project:dl(n,t),pending:fl(n,t)}}function ml(e){return ho(e)}function hl(e){return ol(e)}function gl(e){return e.getUsedMemoryReferences()}function _l(e,t,n=()=>new Date){e.recordMemoryEvent({...t,at:n().toISOString()})}function vl(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 yl(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 bl(e,t,n,r){return e.skillContent?vl(await yl(e.skillContent,n.shellExec),t,r):null}async function xl(e,t,n,r){let i=await bl(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 Sl(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 bl(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 xl(e,t,n,r)}}function Cl(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function wl(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Tl(e,t){let n=t.trim();return n.length>0?`${e} ${n}`:e}function El(e){if(!e?.startsWith(`/`))return;let t=e.slice(1).trim().split(/\s+/)[0];return t&&t.length>0?t:void 0}var Dl=class{getSession;getSessionId;onSubmit;onApplyResult;recordSkillActivation;runSkillInFork;onForkSkill;onBlockingCommand;shellExec;commandExecutor;allCommandModules;skillCommandSource;commandHostAdapters;commandInvocationSource=`user`;constructor(e,t,n,r,i,a,o,s,c,l,u,d){this.getSession=r,this.getSessionId=i,this.onSubmit=a,this.onApplyResult=o,this.recordSkillActivation=s,this.runSkillInFork=c,this.onForkSkill=l,this.onBlockingCommand=u,this.shellExec=d,this.allCommandModules=e,this.commandExecutor=new $o(e.flatMap(e=>e.systemCommands??[])),this.skillCommandSource=new Vi(t),this.commandHostAdapters=n}reapplyCommandModuleSelection(e,t){let n=Ws(this.allCommandModules,e,t);this.commandExecutor.replaceCommands(n.flatMap(e=>e.systemCommands??[]))}getCommandInvocationSource(){return this.commandInvocationSource}getCommandHostAdapters(){return this.commandHostAdapters??{}}listCommands(){return this.commandExecutor.listCommands().map(e=>({name:e.name,...e.displayName===void 0?{}:{displayName:e.displayName},description:e.description,...e.example===void 0?{}:{example:e.example}}))}listSkills(){return this.skillCommandSource.getCommands().map(e=>({name:e.name,description:e.description,source:e.source,modelInvocable:e.disableModelInvocation!==!0,userInvocable:e.userInvocable!==!1,...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.context===void 0?{}:{context:e.context},...e.agent===void 0?{}:{agent:e.agent}}))}listModelInvocableCommands(){return this.commandExecutor.listModelInvocableCommands().map(e=>({name:e.name,description:e.description}))}findSkillCommand(e){let t=Cl(e);return this.skillCommandSource.getCommands().find(e=>e.name.toLowerCase()===t.toLowerCase())}async executeCommand(e,t){let n=wl(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,Tl(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=El(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 Sl(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=kr({skill:e,invocation:t,status:n,...r===void 0?{}:{qualifiedName:r},...i.error===void 0?{}:{error:i.error}});this.recordSkillActivation(a,i.appendHistory??n!==`completed`)}async executeForegroundCommand(e,t){try{return await this.commandExecutor.executeCommand(e,this.getSession(),t)}catch(e){return{success:!1,message:`Error: ${e instanceof Error?e.message:String(e)}`}}}};function Ol(){let e=(0,g.join)((0,_.homedir)(),`.robota`,`org-policy.json`);if(!(0,m.existsSync)(e))return null;try{let t=(0,m.readFileSync)(e,`utf8`);return JSON.parse(t)}catch{return null}}function kl(e,t){return`${e}${t?`\nContact your administrator: ${t}`:``}`}function Al(e){return e?!e.startsWith(`$ENV:`):!1}var jl=class extends Xt{session=null;listeners=new Map;initialized=!1;initPromise=null;sessionStore;sessionName;cwd;pendingRestoreMessages=null;resumeSessionId;forkSession;autoCompactThresholdSource=`default`;shutdownPromise=null;sandboxClient;sandboxSnapshotId;agentsFileEntries=[];claudeFileEntries=[];rebuildSystemMessage=null;providerDefinitions=[];orgPolicy=null;bgTracker;histTracker;skillRouter;execCtrl;constructor(e){super(),this.sessionStore=e.sessionStore,this.sessionName=e.sessionName,this.cwd=(`cwd`in e?e.cwd:void 0)??``,this.resumeSessionId=e.resumeSessionId,this.forkSession=e.forkSession??!1,this.sandboxClient=`sandboxClient`in e?e.sandboxClient:void 0,this.sandboxSnapshotId=`sandboxSnapshotId`in e?e.sandboxSnapshotId:void 0;let t=this.cwd,n=null;`session`in e&&e.session&&t&&(n=new z({cwd:t})),this.bgTracker=new It(()=>this.getBackgroundTaskManager(),(e,t)=>this.execCtrl.emitExecutionWorkspaceUpdated(e,t),e=>this.emit(`background_task_event`,e),e=>this.emit(`background_job_group_event`,e),()=>this.persistCurrentSession(),(e,t)=>this.requestWakeup(e,t),e=>this.histTracker.append((0,c.messageToHistoryEntry)((0,c.createSystemMessage)(e)))),this.histTracker=new Nr(t,()=>this.getSessionOrThrow().getSessionId(),()=>this.execCtrl.executing,()=>this.persistCurrentSession(),e=>this.emit(`skill_activation`,e),e=>this.emit(`memory_event`,e),n);let r=[...`commandModules`in e?e.commandModules??[]:[]],i=`commandHostAdapters`in e?e.commandHostAdapters:void 0,a=`shellExec`in e?e.shellExec:void 0;this.skillRouter=new Dl(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)=>dr(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 lr(this.histTracker,this.skillRouter,{getSession:()=>this.session,getSessionOrThrow:()=>this.getSessionOrThrow(),getCwd:()=>this.getCwd(),getContextState:()=>this.getContextState(),getExecutionWorkspaceSnapshot:()=>this.getExecutionWorkspaceSnapshot(),emit:(e,...t)=>this.emit(e,...t),persistSession:()=>this.persistCurrentSession()}),`providerDefinitions`in e&&(this.providerDefinitions=e.providerDefinitions??[]),`orgPolicy`in e&&(this.orgPolicy=e.orgPolicy??null);let o=this.configureInjectedSession(e);this.restoreSessionRecordIfNeeded(e),this.startAsyncInitializationIfNeeded(e,o),this.initialized&&this.bgTracker.subscribe(this.session),this.initialized&&this.persistCurrentSession()}configureInjectedSession(e){return`session`in e&&e.session?(this.session=e.session,this.autoCompactThresholdSource=`session`,this.initialized=!0,!0):!1}restoreSessionRecordIfNeeded(e){if(!e.resumeSessionId||!this.sessionStore)return;let t=Rr(this.sessionStore,e.resumeSessionId,this.session);this.histTracker.restoreState({history:t.history,memoryEvents:t.memoryEvents,usedMemoryReferences:t.usedMemoryReferences,contextReferences:t.contextReferences,skillActivationEvents:t.skillActivationEvents}),t.sessionName&&(this.sessionName=t.sessionName),this.bgTracker.restoreState({tasks:t.backgroundTasks,taskEvents:t.backgroundTaskEvents,groups:t.backgroundJobGroups,groupEvents:t.backgroundJobGroupEvents}),this.pendingRestoreMessages=t.pendingRestoreMessages,this.sandboxSnapshotId=this.forkSession?void 0:t.sandboxSnapshotId,this.session&&t.pendingRestoreMessages===null&&(this.session.syncContextFromHistory(),this.emit(`context_update`,this.getContextState()))}startAsyncInitializationIfNeeded(e,t){if(t)return;let n=e;this.initPromise=this.initializeAsync(n)}async initializeAsync(e){let t=await Uo(e,{sandboxSnapshotId:this.sandboxSnapshotId,resumeSessionId:this.resumeSessionId,pendingRestoreMessages:this.pendingRestoreMessages,onTextDelta:e=>this.execCtrl.handleTextDelta(e),onContextUpdate:e=>this.emit(`context_update`,e),onCompactEvent:e=>this.execCtrl.handleCompactEvent(e),onToolExecution:e=>this.execCtrl.handleToolExecution(e),executeModelCommand:(e,t)=>this.executeModelCommand(e,t),isModelCommandInvocable:e=>this.skillRouter.commandExecutor.isModelInvocable(e),commandDescriptors:this.skillRouter.commandExecutor.listModelInvocableCommands(),setEditCheckpointStore:e=>this.histTracker.setEditCheckpointStore(e)});this.session=t.session,this.agentsFileEntries=t.agentsFileEntries,this.claudeFileEntries=t.claudeFileEntries,this.rebuildSystemMessage=t.rebuildSystemMessage,this.autoCompactThresholdSource=t.autoCompactThresholdSource,this.histTracker.recordSystemContextFiles([...t.agentsFileEntries,...t.claudeFileEntries]),this.pendingRestoreMessages=null,this.initialized=!0,this.bgTracker.subscribe(this.session),this.persistCurrentSession(),this.emit(`context_update`,this.getContextState())}async ensureInitialized(){!this.initialized&&this.initPromise&&await this.initPromise}getSessionOrThrow(){if(!this.session)throw Error(`InteractiveSession not initialized. Call submit() or await initialization.`);return this.session}getCwd(){if(!this.cwd)throw Error(`cwd is not set — provide cwd in session options`);return this.cwd}get sessionId(){return this.session?.getSessionId()??``}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,...t){let n=this.listeners.get(e);if(n)for(let e of n)e(...t)}async submit(e,t,n,r={}){if(await this.ensureInitialized(),this.execCtrl.shuttingDown)throw Error(`Interactive session is shutting down.`);if(this.execCtrl.executing){this.execCtrl.pendingPrompt=e,this.execCtrl.pendingDisplayInput=t,this.execCtrl.pendingRawInput=n,this.execCtrl.pendingTurnOptions=r;return}await this.execCtrl.executePrompt(e,t,n,this.agentsFileEntries,this.claudeFileEntries,this.rebuildSystemMessage,(e,t)=>{this.agentsFileEntries=e,this.claudeFileEntries=t,this.histTracker.recordSystemContextFiles([...e,...t])},(e,t,n,r)=>this.submit(e,t,n,r),r)}requestWakeup(e,t){this.execCtrl.shuttingDown||this.execCtrl.wakeTaskIds.has(t)||(this.execCtrl.wakeTaskIds.add(t),this.submit(e,void 0,void 0,{turnSource:`agent-wakeup`,wakeTaskId:t}))}abort(){this.execCtrl.clearPendingQueue(),this.session?.abort()}shutdown(e={}){return this.shutdownPromise?this.shutdownPromise:(this.execCtrl.shuttingDown=!0,this.shutdownPromise=(async()=>{await this.ensureInitialized(),this.execCtrl.clearPendingQueue();let t=this.session;t?.abort(),await this.getBackgroundTaskManager()?.shutdown(e.message??`Session shutdown`),this.bgTracker.dispose(),await this.captureSandboxSnapshot(),this.persistCurrentSession(),await t?.shutdown({reason:e.reason??`other`}),this.listeners.clear()})(),this.shutdownPromise)}get isInitialized(){return this.initialized}getAutoCompactThresholdSource(){return this.autoCompactThresholdSource}getAutoCompactThreshold(){return this.getSessionOrThrow().getAutoCompactThreshold()}getSession(){return this.getSessionOrThrow()}applyPersona(e){if(this.rebuildSystemMessage===null)return;let t=this.agentsFileEntries.map(e=>e.content).join(`
|
|
101
101
|
|
|
@@ -105,6 +105,6 @@ Do not use emojis.`}function rt(){return`You are a worker subagent executing a s
|
|
|
105
105
|
|
|
106
106
|
`),n=this.claudeFileEntries.map(e=>e.content).join(`
|
|
107
107
|
|
|
108
|
-
`),r=this.rebuildSystemMessage(t,n,{selfVerification:e});this.getSessionOrThrow().updateSystemMessage(r)}applyCommandModuleSelection(e,t){this.skillRouter.reapplyCommandModuleSelection(e,t)}getAgentJobCapability(){return this}setAutoCompactThreshold(e,t=`session`){this.getSessionOrThrow().setAutoCompactThreshold(e),this.autoCompactThresholdSource=t,this.emit(`context_update`,this.getContextState()),this.persistCurrentSession()}clearConversationHistory(){this.getSessionOrThrow().clearHistory(),this.histTracker.clearHistory(),this.persistCurrentSession(),this.emit(`context_update`,this.getContextState())}getName(){return this.sessionName}attachTransport(e){e.attach(this)}setName(e){if(this.sessionName=e,this.sessionStore&&this.session)try{let t=this.getSessionOrThrow().getSessionId(),n=this.sessionStore.load(t);n&&(n.name=e,n.updatedAt=new Date().toISOString(),this.sessionStore.save(n))}catch{}}getBackgroundTaskManager(){if(this.session)return Re(this.session)??j(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();Wo(this.sessionStore,this.session,this.sessionName,this.cwd??``,t.history,{tasks:e.tasks,events:e.taskEvents,groups:e.groups,groupEvents:e.groupEvents},{events:t.memoryEvents,usedReferences:t.usedMemoryReferences},{events:t.skillActivationEvents},{references:t.contextReferences},{snapshotId:this.sandboxSnapshotId})}async switchProvider(e){let t=this.getSessionOrThrow(),n=this.getCwd(),r=Vs(n,{providerOverride:e,providerDefinitions:this.providerDefinitions}),i=Hs(n,void 0,{providerOverride:e,providerDefinitions:this.providerDefinitions});t.swapProvider(i,r.model)}async executeCommand(e,t){if(this.orgPolicy?.blockedCommands?.includes(e))return{message:kl(`Command /${e} is blocked by your organization policy.`,this.orgPolicy.adminContact),success:!1};let n=await super.executeCommand(e,t);if(n===null)return null;let r=n.effects?.find(e=>e.type===`provider-hot-swap-requested`);if(r){let{orgPolicy:e}=this;return e?.allowedProviders&&!e.allowedProviders.includes(r.profileName)?{message:kl(`Provider "${r.profileName}" is not allowed by your organization policy. Allowed: ${e.allowedProviders.join(`, `)}.`,e.adminContact),success:!1}:(await this.switchProvider(r.profileName),{...n,effects:n.effects?.filter(e=>e.type!==`provider-hot-swap-requested`)})}return n}};function Ml(e,t=new N){let n=R(e);return new Il(n.sessions,n.logs,t)}function Nl(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:Ll(e.messages)}))}function Pl(e,t){return Nl(e,t)[0]?.id}function Fl(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var Il=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(Rl(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):zl(t)}list(){let e=this.store.list().map(zl),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,g.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:Bl(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 Ll(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 Rl(e){return{...e}}function zl(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 Bl(e){let t=new Map;for(let n of e){let e=Vl(n);e&&t.set(e.id,e)}return[...t.values()]}function Vl(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 Ul(e){let t=new jl({cwd:e.cwd??process.cwd(),provider:e.provider,permissionMode:e.permissionMode??`bypassPermissions`,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler,additionalTools:e.additionalTools,...e.responseFormat?{responseFormat:e.responseFormat}:{}});return e.onTextDelta&&t.on(`text_delta`,e.onTextDelta),async e=>new Promise((n,r)=>{let i=e=>{s(),n(e.response)},a=e=>{s(),n(e.response)},o=e=>{s(),r(e)},s=()=>{t.off(`complete`,i),t.off(`interrupted`,a),t.off(`error`,o)};t.on(`complete`,i),t.on(`interrupted`,a),t.on(`error`,o),t.submit(e).catch(e=>{s(),r(e instanceof Error?e:Error(String(e)))})})}const Wl=[`preferences`,`view-state`,`memory-projections`,`task-associations`,`workflow-metadata`,`inspection-index`],Gl=[{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 Kl(e){return e.toISOString()}function ql(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!g.default.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function Jl(){return process.env.HOME??(0,_.homedir)()}function Yl(e,t){let n=g.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!g.default.isAbsolute(n)}async function Xl(e,t){let n=e;for(;g.default.dirname(n)!==n;)try{let r=await t.realpath(n),i=g.default.relative(n,e);return g.default.resolve(r,i)}catch{n=g.default.dirname(n)}try{return await t.realpath(n)}catch{return g.default.resolve(e)}}async function Zl(e){let t=e.fsAsync??new P,n=g.default.resolve(e.activeRepositoryRoot);ql(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?g.default.join(e.homeDir??Jl(),`.robota`):e.storageRoot;ql(`userLocalStorageRoot`,r);let i=g.default.resolve(r),a=await Xl(i,t);if(Yl(await Xl(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function Ql(e,t){return g.default.join(e,t)}async function $l(e,t,n){let r=Ql(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=g.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:Kl(new Date(o.birthtimeMs)),lastUsedAt:Kl(new Date(o.mtimeMs)),enabled:!0,deleteAvailable:!0,disableAvailable:!1}}))).sort((e,t)=>e.key.localeCompare(t.key))}async function eu(e){let t=e.fsAsync??new P,n=await Zl(e),r=g.default.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all(Gl.map(async e=>{let r=Ql(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await $l(n,e.category,t);return{category:e.category,purpose:e.purpose,mayExecuteCommands:e.mayExecuteCommands,storageLocation:r,itemCount:a.length,items:a}})),generatedAt:Kl((e.now??(()=>new Date))())}}const tu=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],nu=`.json`,ru=/^[a-z0-9][a-z0-9._-]*$/u,iu={"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 au(e){return e.toISOString()}function ou(e){return tu.includes(e)}function su(e){if(!ou(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function cu(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!ru.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function lu(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 uu(e){return lu(`value`,e,240)}function du(e,t){return`${e}__${t}${nu}`}async function fu(e){let t=await Zl(e);return{root:t,memoryRoot:g.default.join(t,`memory-projections`)}}function pu(e,t){let n=JSON.parse(e),r=Z(n,`category`);if(n.schemaVersion!==1)throw Error(`Unsupported user-local memory schema at ${t}`);return{schemaVersion:1,category:su(r),key:Z(n,`key`),value:Z(n,`value`),summary:Z(n,`summary`),source:Z(n,`source`),scope:Z(n,`scope`),createdAt:Z(n,`createdAt`),lastUsedAt:Z(n,`lastUsedAt`),enabled:mu(n,`enabled`)}}function Z(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function mu(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function hu(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:uu(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:iu[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function gu(e,t,n){return hu(e,t,pu(await n.readFile(t,`utf8`),t))}async function _u(e){let t=su(e.category),n=cu(`key`,e.key),{root:r,memoryRoot:i}=await fu(e);return{root:r,storageLocation:g.default.join(i,du(t,n))}}async function vu(e){let t=e.fsAsync??new P,n=su(e.category),r=cu(`key`,e.key),i=lu(`summary`,e.summary,240),a=lu(`source`,e.source,80),o=lu(`scope`,e.scope??`user`,120),s=uu(e.value),c=au((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await fu(e),d=g.default.join(u,du(n,r)),f=c;try{f=pu(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`),hu(l,d,p)}async function yu(e){let t=e.fsAsync??new P,{root:n,memoryRoot:r}=await fu(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(nu)).map(e=>gu(n,g.default.join(r,e.name),t)));return{root:n,activeRepositoryRoot:g.default.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function bu(e){let t=e.fsAsync??new P,{root:n,storageLocation:r}=await _u(e);return gu(n,r,t)}async function xu(e){let t=e.fsAsync??new P,{root:n,storageLocation:r}=await _u(e),i={...pu(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:au((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),hu(n,r,i)}async function Su(e){let t=e.fsAsync??new P,{storageLocation:n}=await _u(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}async function Cu(e){let t=await bu(e);return t.enabled?t:null}const wu=[`test`,`typecheck`,`build`],Tu={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 Eu(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))):[]}function Du(e){return e.flatMap(e=>wu.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 Ou(){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 ku(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 Au(){return{id:`rollback-on-failure`,phase:`recover`,description:`Use the existing edit checkpoint restore path if verification fails.`,required:!0}}function ju(e){if(e.changedFiles.length===0)throw Error(`Self-hosting verification requires at least one changed file.`);let t=e.baseRef??`origin/develop`,n=Eu(e.packageScopes),r=[...Ou(),...Du(n),ku(t),Au()];return{changedFiles:[...e.changedFiles],packageScopes:n,baseRef:t,steps:r}}function Mu(e,t){let n=Tu[e][t];if(!n)throw Error(`Invalid self-hosting loop transition: ${e} -> ${t}`);return n}function Nu(e){return e}function Pu(e){if(!e||e.length===0)return;let[t,...n]=e;if(t!==void 0)return[t,...n]}function Fu(e){let t=Pu(e),n=t===void 0?d.z.string().describe(`Registered model-invocable command name to execute`):d.z.enum(t).describe(`Registered model-invocable command name to execute`);return d.z.object({command:n,args:d.z.string().optional().describe(`Arguments to pass to the command`)})}function Iu(e){if(e.commandNames!==void 0)return e.commandNames;if(e.commandDescriptors!==void 0)return e.commandDescriptors.map(e=>A(e.name))}function Lu(e){return`- ${A(e.name)}${e.argumentHint?` ${e.argumentHint}`:``}: ${e.description}`}function Ru(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(Lu)].join(`
|
|
109
|
-
`)}function
|
|
110
|
-
`,`utf8`)}async function md(e){if(e.disabled===!0)return{status:`skipped`,reason:`disabled`};let t=e.packageName??`@robota-sdk/agent-cli`,n=e.cachePath??dd(),r=e.now??new Date,i=e.ttlMs??864e5;if(e.force!==!0){let a=fd(n);if(a!==void 0&&Cd(a,r,i,t))return xd(a,e.currentVersion)}let a=await hd(e,t,n,r);return typeof a==`string`?Sd(e.currentVersion,a):a}async function hd(e,t,n,r){let i=await wd({fetchImpl:e.fetchImpl??fetch,packageName:t,registryUrl:e.registryUrl??`https://registry.npmjs.org`,timeoutMs:e.timeoutMs??1500});return i.ok?(gd(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,latestVersion:i.version}),i.version):(gd(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,errorMessage:i.errorMessage}),{status:`error`,errorMessage:i.errorMessage})}function gd(e,t){try{pd(e,t)}catch{}}async function _d(e){let t=await md(e);return t.status===`update_available`?t.notice:void 0}function vd(e){return e.printMode===!1&&e.disableUpdateCheck===!1}function yd(e){return[`Robota update available: ${e.currentVersion} -> ${e.latestVersion}.`,`Run ${e.installCommand}`].join(` `)}function bd(e){return e.status===`update_available`?yd(e.notice):e.status===`current`?`Robota is up to date (${e.currentVersion}).`:e.status===`skipped`?`Robota update check skipped.`:`Robota update check failed: ${e.errorMessage}`}function xd(e,t){return e.errorMessage===void 0?e.latestVersion===void 0?{status:`error`,errorMessage:`Cached update check has no latest version`}:Sd(t,e.latestVersion):{status:`error`,errorMessage:e.errorMessage}}function Sd(e,t){return od(t,e)?{status:`update_available`,notice:{currentVersion:e,latestVersion:t,installCommand:`npm install -g '@robota-sdk/agent-cli@latest'`}}:{status:`current`,currentVersion:e,latestVersion:t}}function Cd(e,t,n,r){if(e.packageName!==r)return!1;let i=Date.parse(e.checkedAt);return Number.isFinite(i)?t.getTime()-i<n:!1}async function wd(e){try{return{ok:!0,version:await Td(e)}}catch(e){return{ok:!1,errorMessage:e instanceof Error?e.message:String(e)}}}async function Td(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=Ed(e.registryUrl,e.packageName),r=await e.fetchImpl(n,{headers:{accept:`application/json`},signal:t.signal});if(!r.ok)throw Error(`registry responded with HTTP ${r.status}`);let i=(await r.json())[`dist-tags`]?.latest;if(typeof i!=`string`||i.trim().length===0)throw Error(`registry metadata is missing dist-tags.latest`);return i}finally{clearTimeout(n)}}function Ed(e,t){return`${e.replace(/\/+$/,``)}/${encodeURIComponent(t)}`}function Dd(e){if(!Od(e))return;let t=e;if(typeof t.packageName==`string`&&typeof t.checkedAt==`string`&&typeof t.currentVersion==`string`&&(t.latestVersion===void 0||typeof t.latestVersion==`string`)&&(t.errorMessage===void 0||typeof t.errorMessage==`string`))return{packageName:t.packageName,checkedAt:t.checkedAt,currentVersion:t.currentVersion,...t.latestVersion!==void 0&&{latestVersion:t.latestVersion},...t.errorMessage!==void 0&&{errorMessage:t.errorMessage}}}function Od(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kd(e){let t=Ui(),n={settings:{read:()=>W(t),write:e=>G(t,e)}},r=e.backgroundTaskRunners??(0,l.createDefaultBackgroundTaskRunners)(),i=e.commandModules??[],a=e.commandHostAdapters??n,o=`sessionStore`in e?e.sessionStore:Ml(e.cwd);return{cwd:e.cwd,provider:e.provider,commandModules:i,commandHostAdapters:a,backgroundTaskRunners:r,subagentRunnerFactory:e.subagentRunnerFactory,sessionStore:o,transportRegistry:e.transportRegistry,reloadPluginCommandSource:e.reloadPluginCommandSource??(()=>{}),createSession(t){return new jl({cwd:e.cwd,provider:e.provider,backgroundTaskRunners:r,subagentRunnerFactory:e.subagentRunnerFactory,commandModules:i,commandHostAdapters:a,permissionMode:t.permissionMode,maxTurns:t.maxTurns,sessionStore:t.sessionStore,sessionName:t.sessionName,bare:t.bare,allowedTools:t.allowedTools,deniedTools:t.deniedTools,model:t.model,appendSystemPrompt:t.appendSystemPrompt,systemPrompt:t.systemPrompt,shellExec:t.shellExec,agentName:t.agentName,orgPolicy:e.orgPolicy,additionalTools:t.additionalTools,resumeSessionId:t.resumeSessionId,...t.responseFormat?{responseFormat:t.responseFormat}:{}})}}}function Ad(e){let t=kd({cwd:e.cwd??process.cwd(),provider:e.provider,sessionStore:void 0,commandHostAdapters:{settings:{read:()=>({}),write:()=>{}}}}),n=t.createSession.bind(t);return{...t,createSession(e){return n({bare:!0,...e})}}}exports.AUTO_COMPACT_THRESHOLD_SETTINGS_KEY=Ks,exports.AgentExecutor=Yi,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=tt,exports.BackgroundJobOrchestrator=ne,exports.BuiltinCommandSource=ns,exports.BundlePluginInstaller=jo,exports.BundlePluginLoader=Ao,exports.CLEAR_COMMAND_DESCRIPTION=`Clear conversation history`,exports.CLI_UPDATE_CACHE_TTL_MS=864e5,exports.CLI_UPDATE_PACKAGE_NAME=`@robota-sdk/agent-cli`,exports.CLI_UPDATE_REGISTRY_URL=`https://registry.npmjs.org`,exports.CLI_UPDATE_TIMEOUT_MS=1500,exports.COST_COMMAND_DESCRIPTION=`Show session token usage and estimated cost. /cost budget <amount> sets a monthly budget.`,exports.CommandRegistry=Qo,exports.DEFAULT_AUTO_COMPACT_THRESHOLD=Gs,exports.DEFAULT_STATUS_LINE_COMMAND_SETTINGS=Fc,exports.EXECUTION_ORIGIN_METADATA_KEYS=S,exports.EXIT_COMMAND_DESCRIPTION=`Exit CLI`,exports.EditCheckpointStore=z,exports.HELP_COMMAND_DESCRIPTION=`Show available commands`,exports.InteractiveSession=jl,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=po,exports.MEMORY_INDEX_MAX_LINES=200,exports.MODEL_COMMAND_TOOL_PREFIX=at,exports.MarketplaceClient=Fo,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=ot,exports.PluginCommandSource=Us,exports.PluginSettingsStore=Eo,exports.ProjectMemoryStore=So,exports.PromptExecutor=Zi,exports.ProviderConfigError=Rs,exports.RECOMMENDED_RESPONSE_LANGUAGES=yc,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.SettingsParseError=Hi,exports.SkillCommandSource=Vi,exports.SystemCommandExecutor=$o,exports.USER_LOCAL_MEMORY_CATEGORIES=tu,exports.USER_LOCAL_STORAGE_CATEGORIES=Wl,exports.USER_LOCAL_STORAGE_CATEGORY_DEFINITIONS=Gl,exports.VALIDATE_SESSION_COMMAND_DESCRIPTION=`Validate current session replay log`,exports.VALID_PERMISSION_MODES=Cc,exports.addCommandContextReference=tc,exports.applyActiveModelChange=Ps,exports.applyPresetToSession=Pc,exports.applyProviderConfiguration=Ms,exports.applyProviderSwitch=Ns,exports.applyStatusLineSettings=zc,exports.assembleSubagentPrompt=it,exports.buildBackgroundCommandSubcommands=lc,exports.buildLanguageCommandSubcommands=bc,exports.buildMemoryCommandSubcommands=ul,exports.buildPermissionModeSubcommands=wc,exports.buildPluginCommandSubcommands=Wc,exports.buildPromptWithFileReferences=hn,exports.buildProviderProfile=ls,exports.buildProviderSetupPatch=cs,exports.buildRewindCommandSubcommands=el,exports.buildStatusLineCommandSubcommands=Ic,exports.cancelCommandBackgroundTask=_c,exports.checkForCliUpdate=md,exports.checkSettingsDocument=vs,exports.checkSettingsFile=Cs,exports.clearCommandContextReferences=rc,exports.clearContextReferences=on,exports.clearConversationHistory=Gc,exports.closeCommandBackgroundTask=vc,exports.compactCommandContext=$s,exports.compareSemverVersions=ad,exports.createAgentRuntime=kd,exports.createAgentTool=Ft,exports.createBackgroundGroupExecutionEntryId=ue,exports.createBackgroundProcessTool=Si,exports.createBackgroundTaskExecutionEntryId=w,exports.createBuiltinCommandModule=rs,exports.createCommandExecutionTool=zu,exports.createCommandMemoryStores=pl,exports.createCommandPendingMemoryStore=fl,exports.createCommandProjectMemoryStore=dl,exports.createContextReferenceItem=nn,exports.createDefaultTools=Gr,exports.createExecutionOriginMetadata=T,exports.createExecutionWorkspaceSnapshot=fe,exports.createExecutionWorkspaceTaskSpawner=Ne,exports.createInProcessSubagentRunner=Tt,exports.createInteractiveRuntime=qu,exports.createLineDetailPage=O,exports.createMainThreadDetailPage=Ae,exports.createMainThreadExecutionEntryId=C,exports.createModelCommandToolProjection=lt,exports.createPluginRegistryReloadRequestedEffect=Hc,exports.createPluginTuiRequestedEffect=Vc,exports.createProjectSessionStore=Ml,exports.createProjectedCommandExecutionTools=ft,exports.createPromptFileReferenceHistoryEntry=vn,exports.createProviderFromSettings=Hs,exports.createProviderSafeModelCommandToolName=ct,exports.createQuery=Ul,exports.createSessionExitRequestedEffect=Yc,exports.createSessionPickerRequestedEffect=Jc,exports.createSessionRenamedEffect=qc,exports.createStatelessRuntime=Ad,exports.createSubagentLogger=ga,exports.createSubagentSession=yt,exports.createSystemCommands=es,exports.createTestInteractiveSession=ed,exports.deleteProviderProfile=os,exports.deleteSettings=qi,exports.deleteUserLocalMemoryItem=Su,exports.disableUserLocalMemoryItem=xu,exports.discoverTaskFiles=oo,exports.evaluateReversibleToolSafety=ta,exports.executeSkill=Sl,exports.formatCliUpdateCheckMessage=bd,exports.formatCliUpdateNotice=yd,exports.formatCommandBackgroundTask=uc,exports.formatCommandBackgroundTaskList=dc,exports.formatCommandHelpMessage=cc,exports.formatCommandPermissionsMessage=Nc,exports.formatCommandSessionReplayValidationReport=Qc,Object.defineProperty(exports,"formatEnvReference",{enumerable:!0,get:function(){return c.formatEnvReference}}),exports.formatInvalidPermissionModeMessage=Dc,exports.formatLanguageUsageMessage=Sc,exports.formatOrgPolicyViolationMessage=kl,exports.formatProjectedModelCommandToolPromptDescription=ut,exports.formatPromptFileReferenceDiagnostics=_n,exports.formatTaskContext=lo,exports.getBuiltInAgent=k,exports.getForkWorkerSuffix=rt,exports.getProviderSettingsPaths=As,exports.getStartupCliUpdateNotice=_d,exports.getSubagentSuffix=nt,exports.getUserSettingsPath=Ui,exports.getUserUpdateCheckCachePath=dd,exports.hasBlockingPromptFileReferenceDiagnostics=gn,exports.hasSensitiveCommandMemoryContent=hl,Object.defineProperty(exports,"hasUsableSecretReference",{enumerable:!0,get:function(){return c.hasUsableSecretReference}}),exports.inspectCommandEditCheckpoint=nl,exports.inspectUserLocalMemoryItem=bu,exports.inspectUserLocalStorage=eu,exports.isApiKeyPlaintext=Al,exports.isCommandMemoryType=ml,Object.defineProperty(exports,"isEnvReference",{enumerable:!0,get:function(){return c.isEnvReference}}),exports.isMemoryType=ho,exports.isNewerSemverVersion=od,exports.isPermissionMode=Ec,exports.isSlashCommand=Bu,exports.isStatusLineCommandSettingsPatch=Lc,exports.listActiveContextReferences=sn,exports.listCommandBackgroundTasks=hc,exports.listCommandContextReferences=ec,exports.listCommandEditCheckpoints=tl,exports.listCommandSessionAllowedTools=jc,exports.listCommandUsedMemoryReferences=gl,exports.listResumableSessionSummaries=Nl,exports.listUserLocalMemoryItems=yu,exports.loadOrgPolicy=Ol,exports.loadTaskContext=uo,exports.mergeProviderPatch=us,exports.mergeProviders=Ds,exports.mergeSettings=Es,exports.normalizeModelCommandName=A,exports.parseCommandBackgroundLogCursor=fc,exports.parseExecutionWorkspaceEntryId=de,exports.parseFrontmatter=Li,exports.parseInput=Hu,exports.parseLanguageArgument=xc,exports.parsePermissionModeArgument=Tc,exports.parsePromptFileReferences=Sn,exports.parseSessionNameArgument=Kc,exports.parseTaskFile=so,exports.planSelfHostingVerification=ju,exports.preprocessShellCommands=yl,exports.probeProviderProfile=_s,exports.projectPaths=R,exports.promptForApproval=Xu,exports.readAutoCompactThreshold=Js,exports.readAutoCompactThresholdSource=Ys,exports.readCommandBackgroundTaskLog=gc,exports.readCommandContextState=qs,exports.readCommandPermissionMode=kc,exports.readCommandPermissionsState=Mc,exports.readCommandSessionInfo=Xc,exports.readCurrentGitBranch=ao,exports.readEnabledUserLocalMemoryItem=Cu,exports.readMergedProviderSettings=zs,exports.readMergedProviderSettingsFromPaths=ws,exports.readPackageVersion=ud,exports.readProviderSettings=Vs,exports.readSettings=W,exports.readStatusLineSettings=Rc,exports.readUpdateCheckCache=fd,exports.recordCommandMemoryEvent=_l,exports.removeCommandContextReference=nc,exports.removeContextReference=an,exports.resetAutoCompactThresholdSetting=Qs,exports.resetUserConfig=td,exports.resolveActiveProvider=Os,exports.resolveEnvDefaultProvider=Bs,Object.defineProperty(exports,"resolveEnvReference",{enumerable:!0,get:function(){return c.resolveEnvReference}}),exports.resolveGitBranch=nd,exports.resolveLatestSessionId=Pl,exports.resolvePermissionModeAdapter=Oc,exports.resolvePluginCommandAdapter=Uc,exports.resolvePromptFileReferencePaths=kn,exports.resolvePromptFileReferences=On,exports.resolveProviderSettingsWriteTargetPath=js,exports.resolveSessionIdByIdOrName=Fl,exports.resolveSettingsPathForScope=Wi,exports.resolveSubagentLogDir=_a,exports.resolveUserLocalStorageRoot=Zl,exports.restoreCommandEditCheckpoint=rl,exports.retrieveAgentToolDeps=j,exports.rollbackCommandEditCheckpoint=il,exports.sanitizeProviderProfileName=oc,exports.selectRelevantTasks=co,exports.setCommandAutoCompactThreshold=Xs,exports.setCurrentProvider=as,exports.setUserLocalMemoryItem=vu,exports.shouldRunStartupCliUpdateCheck=vd,exports.storeAgentToolDeps=At,exports.substituteVariables=vl,exports.suggestProviderProfileName=ac,exports.summarizeBackgroundJobGroup=se,exports.testProviderProfileCommand=gs,exports.toContextReferenceRecords=cn,exports.toPromptFileReferenceRecords=F,exports.tokeniseSlashCommand=Vu,exports.transitionSelfHostingLoop=Mu,exports.updateModelInSettings=Gi,exports.updateTaskFileStatus=fo,exports.upsertContextReference=rn,exports.upsertProviderProfile=is,exports.userPaths=hr,exports.validateCommandSessionReplayLog=Zc,exports.validateProviderProfile=ss,exports.wrapEditCheckpointTools=Ai,exports.wrapReversibleExecutionTools=na,exports.writeAutoCompactThresholdSetting=Zs,exports.writeCommandPermissionMode=Ac,exports.writeSettings=G,exports.writeUpdateCheckCache=pd;
|
|
108
|
+
`),r=this.rebuildSystemMessage(t,n,{selfVerification:e});this.getSessionOrThrow().updateSystemMessage(r)}applyCommandModuleSelection(e,t){this.skillRouter.reapplyCommandModuleSelection(e,t)}getAgentJobCapability(){return this}setAutoCompactThreshold(e,t=`session`){this.getSessionOrThrow().setAutoCompactThreshold(e),this.autoCompactThresholdSource=t,this.emit(`context_update`,this.getContextState()),this.persistCurrentSession()}clearConversationHistory(){this.getSessionOrThrow().clearHistory(),this.histTracker.clearHistory(),this.persistCurrentSession(),this.emit(`context_update`,this.getContextState())}getName(){return this.sessionName}attachTransport(e){e.attach(this)}setName(e){if(this.sessionName=e,this.sessionStore&&this.session)try{let t=this.getSessionOrThrow().getSessionId(),n=this.sessionStore.load(t);n&&(n.name=e,n.updatedAt=new Date().toISOString(),this.sessionStore.save(n))}catch{}}getBackgroundTaskManager(){if(this.session)return Re(this.session)??j(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();Wo(this.sessionStore,this.session,this.sessionName,this.cwd??``,t.history,{tasks:e.tasks,events:e.taskEvents,groups:e.groups,groupEvents:e.groupEvents},{events:t.memoryEvents,usedReferences:t.usedMemoryReferences},{events:t.skillActivationEvents},{references:t.contextReferences},{snapshotId:this.sandboxSnapshotId})}async switchProvider(e){let t=this.getSessionOrThrow(),n=this.getCwd(),r=Vs(n,{providerOverride:e,providerDefinitions:this.providerDefinitions}),i=Hs(n,void 0,{providerOverride:e,providerDefinitions:this.providerDefinitions});t.swapProvider(i,r.model)}async executeCommand(e,t){if(this.orgPolicy?.blockedCommands?.includes(e))return{message:kl(`Command /${e} is blocked by your organization policy.`,this.orgPolicy.adminContact),success:!1};let n=await super.executeCommand(e,t);if(n===null)return null;let r=n.effects?.find(e=>e.type===`provider-hot-swap-requested`);if(r){let{orgPolicy:e}=this;return e?.allowedProviders&&!e.allowedProviders.includes(r.profileName)?{message:kl(`Provider "${r.profileName}" is not allowed by your organization policy. Allowed: ${e.allowedProviders.join(`, `)}.`,e.adminContact),success:!1}:(await this.switchProvider(r.profileName),{...n,effects:n.effects?.filter(e=>e.type!==`provider-hot-swap-requested`)})}return n}};function Ml(e,t=new N){let n=R(e);return new Ll(n.sessions,n.logs,t)}function Nl(e=new N){return new Ll(hr().sessions,void 0,e)}function Pl(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:Rl(e.messages)}))}function Fl(e,t){return Pl(e,t)[0]?.id}function Il(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(zl(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):Bl(t)}list(){let e=this.store.list().map(Bl),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,g.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:Vl(n),backgroundTaskEvents:n,backgroundJobGroups:Ul(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 Rl(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 zl(e){return{...e}}function Bl(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 Vl(e){let t=new Map;for(let n of e){let e=Hl(n);e&&t.set(e.id,e)}return[...t.values()]}function Hl(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 Ul(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function Wl(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,``).trim().replace(/\s+/g,`-`).replace(/-+/g,`-`).slice(0,60)}async function Gl(e,t){let n=t.slice(0,200),r=await e.chat([(0,c.createSystemMessage)(`You generate short session titles. Respond with ONLY a 3-5 word lowercase-hyphenated title (e.g. refactor-auth-middleware). No explanation, no punctuation, no quotes.`),(0,c.createUserMessage)(n)],{maxTokens:20}),i=Wl(typeof r.content==`string`?r.content:``);return!i||i.length<3?Wl(t):i}function Kl(e){let t=new jl({cwd:e.cwd??process.cwd(),provider:e.provider,permissionMode:e.permissionMode??`bypassPermissions`,maxTurns:e.maxTurns,permissionHandler:e.permissionHandler,additionalTools:e.additionalTools,...e.responseFormat?{responseFormat:e.responseFormat}:{}});return e.onTextDelta&&t.on(`text_delta`,e.onTextDelta),async e=>new Promise((n,r)=>{let i=e=>{s(),n(e.response)},a=e=>{s(),n(e.response)},o=e=>{s(),r(e)},s=()=>{t.off(`complete`,i),t.off(`interrupted`,a),t.off(`error`,o)};t.on(`complete`,i),t.on(`interrupted`,a),t.on(`error`,o),t.submit(e).catch(e=>{s(),r(e instanceof Error?e:Error(String(e)))})})}const ql=[`preferences`,`view-state`,`memory-projections`,`task-associations`,`workflow-metadata`,`inspection-index`],Jl=[{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 Xl(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!g.default.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function Zl(){return process.env.HOME??(0,_.homedir)()}function Ql(e,t){let n=g.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!g.default.isAbsolute(n)}async function $l(e,t){let n=e;for(;g.default.dirname(n)!==n;)try{let r=await t.realpath(n),i=g.default.relative(n,e);return g.default.resolve(r,i)}catch{n=g.default.dirname(n)}try{return await t.realpath(n)}catch{return g.default.resolve(e)}}async function eu(e){let t=e.fsAsync??new P,n=g.default.resolve(e.activeRepositoryRoot);Xl(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?g.default.join(e.homeDir??Zl(),`.robota`):e.storageRoot;Xl(`userLocalStorageRoot`,r);let i=g.default.resolve(r),a=await $l(i,t);if(Ql(await $l(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function tu(e,t){return g.default.join(e,t)}async function nu(e,t,n){let r=tu(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=g.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 ru(e){let t=e.fsAsync??new P,n=await eu(e),r=g.default.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all(Jl.map(async e=>{let r=tu(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await nu(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 iu=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],au=`.json`,ou=/^[a-z0-9][a-z0-9._-]*$/u,su={"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 cu(e){return e.toISOString()}function lu(e){return iu.includes(e)}function uu(e){if(!lu(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function du(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!ou.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function fu(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 pu(e){return fu(`value`,e,240)}function mu(e,t){return`${e}__${t}${au}`}async function hu(e){let t=await eu(e);return{root:t,memoryRoot:g.default.join(t,`memory-projections`)}}function gu(e,t){let n=JSON.parse(e),r=Z(n,`category`);if(n.schemaVersion!==1)throw Error(`Unsupported user-local memory schema at ${t}`);return{schemaVersion:1,category:uu(r),key:Z(n,`key`),value:Z(n,`value`),summary:Z(n,`summary`),source:Z(n,`source`),scope:Z(n,`scope`),createdAt:Z(n,`createdAt`),lastUsedAt:Z(n,`lastUsedAt`),enabled:_u(n,`enabled`)}}function Z(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function _u(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function vu(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:pu(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:su[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function yu(e,t,n){return vu(e,t,gu(await n.readFile(t,`utf8`),t))}async function bu(e){let t=uu(e.category),n=du(`key`,e.key),{root:r,memoryRoot:i}=await hu(e);return{root:r,storageLocation:g.default.join(i,mu(t,n))}}async function xu(e){let t=e.fsAsync??new P,n=uu(e.category),r=du(`key`,e.key),i=fu(`summary`,e.summary,240),a=fu(`source`,e.source,80),o=fu(`scope`,e.scope??`user`,120),s=pu(e.value),c=cu((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await hu(e),d=g.default.join(u,mu(n,r)),f=c;try{f=gu(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`),vu(l,d,p)}async function Su(e){let t=e.fsAsync??new P,{root:n,memoryRoot:r}=await hu(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(au)).map(e=>yu(n,g.default.join(r,e.name),t)));return{root:n,activeRepositoryRoot:g.default.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function Cu(e){let t=e.fsAsync??new P,{root:n,storageLocation:r}=await bu(e);return yu(n,r,t)}async function wu(e){let t=e.fsAsync??new P,{root:n,storageLocation:r}=await bu(e),i={...gu(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:cu((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),vu(n,r,i)}async function Tu(e){let t=e.fsAsync??new P,{storageLocation:n}=await bu(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}async function Eu(e){let t=await Cu(e);return t.enabled?t:null}const Du=[`test`,`typecheck`,`build`],Ou={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 ku(e){return e?Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))):[]}function Au(e){return e.flatMap(e=>Du.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 ju(){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 Mu(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 Nu(){return{id:`rollback-on-failure`,phase:`recover`,description:`Use the existing edit checkpoint restore path if verification fails.`,required:!0}}function Pu(e){if(e.changedFiles.length===0)throw Error(`Self-hosting verification requires at least one changed file.`);let t=e.baseRef??`origin/develop`,n=ku(e.packageScopes),r=[...ju(),...Au(n),Mu(t),Nu()];return{changedFiles:[...e.changedFiles],packageScopes:n,baseRef:t,steps:r}}function Fu(e,t){let n=Ou[e][t];if(!n)throw Error(`Invalid self-hosting loop transition: ${e} -> ${t}`);return n}function Iu(e){return e}function Lu(e){if(!e||e.length===0)return;let[t,...n]=e;if(t!==void 0)return[t,...n]}function Ru(e){let t=Lu(e),n=t===void 0?d.z.string().describe(`Registered model-invocable command name to execute`):d.z.enum(t).describe(`Registered model-invocable command name to execute`);return d.z.object({command:n,args:d.z.string().optional().describe(`Arguments to pass to the command`)})}function zu(e){if(e.commandNames!==void 0)return e.commandNames;if(e.commandDescriptors!==void 0)return e.commandDescriptors.map(e=>A(e.name))}function Bu(e){return`- ${A(e.name)}${e.argumentHint?` ${e.argumentHint}`:``}: ${e.description}`}function Vu(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(Bu)].join(`
|
|
109
|
+
`)}function Hu(e){let t=Ru(zu(e));return(0,u.createZodFunctionTool)(`ExecuteCommand`,Vu(e.commandDescriptors),Iu(t),async n=>{let r=t.parse(n),i=A(r.command);return e.isModelInvocable(i)?dt(i,await e.execute(i,r.args??``)):JSON.stringify({success:!1,command:i,error:`Command is not model-invocable: ${i}`})})}function Uu(e){return/^\/\S/.test(e)}function Wu(e){let t=e.slice(1).trim().split(/\s+/);return{name:t[0]??``,args:t.slice(1).filter(e=>e.length>0)}}function Gu(e){if(!Uu(e))return{type:`user-message`,text:e};let{name:t,args:n}=Wu(e);return{type:`slash-command`,name:t,args:n}}function Ku(e,t){return t.type===`pick`?{type:`pick`,id:e,title:`/${e}`,items:t.getItems()}:{type:`confirm`,id:e,message:t.message}}function qu(e,t){return t.type===`cancelled`?null:e.type===`pick`&&t.type===`pick`?[t.item.value]:e.type===`confirm`&&t.type===`confirm`?[]:null}function Ju(e){return e.map(e=>({name:e.name,description:e.description}))}function Yu(e,t){let n=``,r=e=>{n+=e,t.write({type:`assistant-chunk`,chunk:e})},i=()=>{t.write({type:`assistant-done`,fullText:n}),n=``,t.setBusy(!1)},a=e=>{t.write({type:`tool-call`,id:e.executionId??e.toolName,name:e.toolName,args:e.firstArg})},o=e=>{t.write({type:`tool-result`,id:e.executionId??e.toolName,name:e.toolName,result:e.toolResultData??e.result})},s=e=>{t.setBusy(!1),t.write({type:`error`,error:e})},c=()=>{t.setBusy(!1)};return e.on(`text_delta`,r),e.on(`complete`,i),e.on(`tool_start`,a),e.on(`tool_end`,o),e.on(`error`,s),e.on(`interrupted`,c),()=>{e.off(`text_delta`,r),e.off(`complete`,i),e.off(`tool_start`,a),e.off(`tool_end`,o),e.off(`error`,s),e.off(`interrupted`,c)}}function Xu(e){let{channel:t,commandModules:n,_testSession:r}=e,i=null,a=null,o={};for(let e of n)e.interactionHints&&Object.assign(o,e.interactionHints);async function s(e){if(!i)return;let n=Gu(e);if(n.type===`user-message`){t.write({type:`user-message`,text:e}),t.setBusy(!0),await i.submit(e);return}let{name:r,args:a}=n,s=o[r],c=a;if(s&&a.length===0){let e=qu(s,await t.requestAction(Ku(r,s)));if(e===null)return;c=e}let l=await i.executeCommand(r,c.join(` `));l?t.write({type:`command-result`,name:r,output:l.message}):t.write({type:`error`,error:Error(`Unknown command "/${r}". Type /help for help.`)})}return{async start(){if(r)i=r;else{let{provider:t,cwd:r,sessionStore:a}=e;if(!t)throw Error(`createInteractiveRuntime: provider is required`);if(!r)throw Error(`createInteractiveRuntime: cwd is required`);i=new jl({provider:t,cwd:r,sessionStore:a,commandModules:n})}a=Yu(i,t);let o=i.listCommands();t.setAvailableCommands(Ju(o)),t.onSubmit(s),await t.start()},async stop(){a?.(),await t.stop(),await i?.shutdown(),i=null}}}const Zu=[`Allow once`,`Allow for this session`,`Deny`];function Qu(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 $u(e,t,n){e.writeLine(``),e.writeError(`[Permission Required] Tool: ${t}`),e.writeLine(` ${Qu(n)}`),e.writeLine(``);let r=await e.select(Zu,0);return r===1?`allow-session`:r===0}const ed={usedTokens:0,maxTokens:2e5,usedPercentage:0,remainingPercentage:100},td={sessionId:`test-session-id`,updatedAt:new Date().toISOString(),entries:[]},nd={id:``,parentSessionId:`test-session-id`,waitPolicy:`wait_all`,taskIds:[],status:`completed`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),results:[]};function rd(e){return{submit:()=>Promise.resolve(),abort:()=>{},cancelQueue:()=>{},shutdown:()=>Promise.resolve(),isExecuting:()=>!1,getPendingPrompt:()=>null,getMessages:()=>[],getContextState:()=>({...ed}),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:()=>({...nd}),waitBackgroundJobGroup:()=>Promise.resolve({...nd}),getExecutionWorkspaceSnapshot:()=>({...td}),listAgentDefinitions:()=>[],listAgentJobs:()=>[],spawnAgentJob:()=>Promise.resolve({id:`agent_1`,type:`general-purpose`,label:`general-purpose`,parentSessionId:`test-session-id`,status:`running`,mode:`background`,depth:1,cwd:`/workspace`,promptPreview:``,updatedAt:new Date().toISOString()}),sendAgentJob:()=>Promise.resolve(),cancelAgentJob:()=>Promise.resolve(),closeAgentJob:()=>Promise.resolve(),...e}}function id(){let e=Ui();return{deleted:qi(e),path:e}}function ad(e){try{let t=od(e);if(!t)return;let n=(0,m.readFileSync)((0,g.join)(t,`HEAD`),`utf8`).trim();if(!n)return;if(n.startsWith(`ref: `)){let e=n.slice(5).trim();return e.startsWith(`refs/heads/`)?e.slice(11):e}return n.slice(0,7)}catch{return}}function od(e){let t=(0,g.resolve)(e),n=(0,g.dirname)(t);for(;n!==t;){let e=sd((0,g.join)(t,`.git`),t);if(e)return e;t=n,n=(0,g.dirname)(t)}return sd((0,g.join)(t,`.git`),t)}function sd(e,t){if(!(0,m.existsSync)(e))return;let n=(0,m.lstatSync)(e);if(n.isDirectory())return e;if(!n.isFile())return;let r=(0,m.readFileSync)(e,`utf8`).trim();if(!r.startsWith(`gitdir:`))return;let i=r.slice(7).trim();return(0,g.isAbsolute)(i)?i:(0,g.resolve)(t,i)}function cd(e,t){let n=ud(e),r=ud(t);if(n===void 0||r===void 0)return Math.sign(e.localeCompare(t));let i=$(n.major,r.major)||$(n.minor,r.minor)||$(n.patch,r.patch);return i===0?dd(n.prerelease,r.prerelease):i}function ld(e,t){return cd(e,t)>0}function ud(e){let[t,n]=(e.trim().replace(/^v/,``).split(`+`)[0]??``).split(`-`,2),[r,i,a]=t.split(`.`),o=Q(r),s=Q(i),c=Q(a);if(!(o===void 0||s===void 0||c===void 0))return{major:o,minor:s,patch:c,prerelease:n?n.split(`.`):[]}}function Q(e){if(!(e===void 0||!/^\d+$/.test(e)))return Number(e)}function $(e,t){return Math.sign(e-t)}function dd(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return 1;if(t.length===0)return-1;let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r],i=t[r];if(n===void 0)return-1;if(i===void 0)return 1;let a=fd(n,i);if(a!==0)return a}return 0}function fd(e,t){let n=Q(e),r=Q(t);return n!==void 0&&r!==void 0?$(n,r):n===void 0?r===void 0?Math.sign(e.localeCompare(t)):1:-1}function pd(e){let t=(0,g.dirname)((0,ee.fileURLToPath)(e)),n=[(0,g.join)(t,`..`,`..`,`package.json`),(0,g.join)(t,`..`,`package.json`)];for(let e of n)try{let t=(0,m.readFileSync)(e,`utf-8`),n=JSON.parse(t);if(n.version!==void 0&&n.name!==void 0)return n.version}catch{continue}return`0.0.0`}function md(e=process.env.HOME??process.env.USERPROFILE??`/`){return(0,g.join)(e,`.robota`,`update-check.json`)}function hd(e){if((0,m.existsSync)(e))try{return Ad(JSON.parse((0,m.readFileSync)(e,`utf8`)))}catch{return}}function gd(e,t){(0,m.mkdirSync)((0,g.dirname)(e),{recursive:!0}),(0,m.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
110
|
+
`,`utf8`)}async function _d(e){if(e.disabled===!0)return{status:`skipped`,reason:`disabled`};let t=e.packageName??`@robota-sdk/agent-cli`,n=e.cachePath??md(),r=e.now??new Date,i=e.ttlMs??864e5;if(e.force!==!0){let a=hd(n);if(a!==void 0&&Ed(a,r,i,t))return wd(a,e.currentVersion)}let a=await vd(e,t,n,r);return typeof a==`string`?Td(e.currentVersion,a):a}async function vd(e,t,n,r){let i=await Dd({fetchImpl:e.fetchImpl??fetch,packageName:t,registryUrl:e.registryUrl??`https://registry.npmjs.org`,timeoutMs:e.timeoutMs??1500});return i.ok?(yd(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,latestVersion:i.version}),i.version):(yd(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,errorMessage:i.errorMessage}),{status:`error`,errorMessage:i.errorMessage})}function yd(e,t){try{gd(e,t)}catch{}}async function bd(e){let t=await _d(e);return t.status===`update_available`?t.notice:void 0}function xd(e){return e.printMode===!1&&e.disableUpdateCheck===!1}function Sd(e){return[`Robota update available: ${e.currentVersion} -> ${e.latestVersion}.`,`Run ${e.installCommand}`].join(` `)}function Cd(e){return e.status===`update_available`?Sd(e.notice):e.status===`current`?`Robota is up to date (${e.currentVersion}).`:e.status===`skipped`?`Robota update check skipped.`:`Robota update check failed: ${e.errorMessage}`}function wd(e,t){return e.errorMessage===void 0?e.latestVersion===void 0?{status:`error`,errorMessage:`Cached update check has no latest version`}:Td(t,e.latestVersion):{status:`error`,errorMessage:e.errorMessage}}function Td(e,t){return ld(t,e)?{status:`update_available`,notice:{currentVersion:e,latestVersion:t,installCommand:`npm install -g '@robota-sdk/agent-cli@latest'`}}:{status:`current`,currentVersion:e,latestVersion:t}}function Ed(e,t,n,r){if(e.packageName!==r)return!1;let i=Date.parse(e.checkedAt);return Number.isFinite(i)?t.getTime()-i<n:!1}async function Dd(e){try{return{ok:!0,version:await Od(e)}}catch(e){return{ok:!1,errorMessage:e instanceof Error?e.message:String(e)}}}async function Od(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=kd(e.registryUrl,e.packageName),r=await e.fetchImpl(n,{headers:{accept:`application/json`},signal:t.signal});if(!r.ok)throw Error(`registry responded with HTTP ${r.status}`);let i=(await r.json())[`dist-tags`]?.latest;if(typeof i!=`string`||i.trim().length===0)throw Error(`registry metadata is missing dist-tags.latest`);return i}finally{clearTimeout(n)}}function kd(e,t){return`${e.replace(/\/+$/,``)}/${encodeURIComponent(t)}`}function Ad(e){if(!jd(e))return;let t=e;if(typeof t.packageName==`string`&&typeof t.checkedAt==`string`&&typeof t.currentVersion==`string`&&(t.latestVersion===void 0||typeof t.latestVersion==`string`)&&(t.errorMessage===void 0||typeof t.errorMessage==`string`))return{packageName:t.packageName,checkedAt:t.checkedAt,currentVersion:t.currentVersion,...t.latestVersion!==void 0&&{latestVersion:t.latestVersion},...t.errorMessage!==void 0&&{errorMessage:t.errorMessage}}}function jd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Md(e){let t=Ui(),n={settings:{read:()=>W(t),write:e=>G(t,e)}},r=e.backgroundTaskRunners??(0,l.createDefaultBackgroundTaskRunners)(),i=e.commandModules??[],a=e.commandHostAdapters??n,o=`sessionStore`in e?e.sessionStore:Ml(e.cwd);return{cwd:e.cwd,provider:e.provider,commandModules:i,commandHostAdapters:a,backgroundTaskRunners:r,subagentRunnerFactory:e.subagentRunnerFactory,sessionStore:o,transportRegistry:e.transportRegistry,reloadPluginCommandSource:e.reloadPluginCommandSource??(()=>{}),createSession(t){return new jl({cwd:e.cwd,provider:e.provider,backgroundTaskRunners:r,subagentRunnerFactory:e.subagentRunnerFactory,commandModules:i,commandHostAdapters:a,permissionMode:t.permissionMode,maxTurns:t.maxTurns,sessionStore:t.sessionStore,sessionName:t.sessionName,bare:t.bare,allowedTools:t.allowedTools,deniedTools:t.deniedTools,model:t.model,appendSystemPrompt:t.appendSystemPrompt,systemPrompt:t.systemPrompt,shellExec:t.shellExec,agentName:t.agentName,orgPolicy:e.orgPolicy,additionalTools:t.additionalTools,resumeSessionId:t.resumeSessionId,...t.responseFormat?{responseFormat:t.responseFormat}:{}})}}}function Nd(e){let t=Md({cwd:e.cwd??process.cwd(),provider:e.provider,sessionStore:void 0,commandHostAdapters:{settings:{read:()=>({}),write:()=>{}}}}),n=t.createSession.bind(t);return{...t,createSession(e){return n({bare:!0,...e})}}}exports.AUTO_COMPACT_THRESHOLD_SETTINGS_KEY=Ks,exports.AgentExecutor=Yi,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=tt,exports.BackgroundJobOrchestrator=ne,exports.BuiltinCommandSource=ns,exports.BundlePluginInstaller=jo,exports.BundlePluginLoader=Ao,exports.CLEAR_COMMAND_DESCRIPTION=`Clear conversation history`,exports.CLI_UPDATE_CACHE_TTL_MS=864e5,exports.CLI_UPDATE_PACKAGE_NAME=`@robota-sdk/agent-cli`,exports.CLI_UPDATE_REGISTRY_URL=`https://registry.npmjs.org`,exports.CLI_UPDATE_TIMEOUT_MS=1500,exports.COST_COMMAND_DESCRIPTION=`Show session token usage and estimated cost. /cost budget <amount> sets a monthly budget.`,exports.CommandRegistry=Qo,exports.DEFAULT_AUTO_COMPACT_THRESHOLD=Gs,exports.DEFAULT_STATUS_LINE_COMMAND_SETTINGS=Fc,exports.EXECUTION_ORIGIN_METADATA_KEYS=S,exports.EXIT_COMMAND_DESCRIPTION=`Exit CLI`,exports.EditCheckpointStore=z,exports.HELP_COMMAND_DESCRIPTION=`Show available commands`,exports.InteractiveSession=jl,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=po,exports.MEMORY_INDEX_MAX_LINES=200,exports.MODEL_COMMAND_TOOL_PREFIX=at,exports.MarketplaceClient=Fo,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=ot,exports.PluginCommandSource=Us,exports.PluginSettingsStore=Eo,exports.ProjectMemoryStore=So,exports.PromptExecutor=Zi,exports.ProviderConfigError=Rs,exports.RECOMMENDED_RESPONSE_LANGUAGES=yc,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.SettingsParseError=Hi,exports.SkillCommandSource=Vi,exports.SystemCommandExecutor=$o,exports.USER_LOCAL_MEMORY_CATEGORIES=iu,exports.USER_LOCAL_STORAGE_CATEGORIES=ql,exports.USER_LOCAL_STORAGE_CATEGORY_DEFINITIONS=Jl,exports.VALIDATE_SESSION_COMMAND_DESCRIPTION=`Validate current session replay log`,exports.VALID_PERMISSION_MODES=Cc,exports.addCommandContextReference=tc,exports.applyActiveModelChange=Ps,exports.applyPresetToSession=Pc,exports.applyProviderConfiguration=Ms,exports.applyProviderSwitch=Ns,exports.applyStatusLineSettings=zc,exports.assembleSubagentPrompt=it,exports.buildBackgroundCommandSubcommands=lc,exports.buildLanguageCommandSubcommands=bc,exports.buildMemoryCommandSubcommands=ul,exports.buildPermissionModeSubcommands=wc,exports.buildPluginCommandSubcommands=Wc,exports.buildPromptWithFileReferences=hn,exports.buildProviderProfile=ls,exports.buildProviderSetupPatch=cs,exports.buildRewindCommandSubcommands=el,exports.buildStatusLineCommandSubcommands=Ic,exports.cancelCommandBackgroundTask=_c,exports.checkForCliUpdate=_d,exports.checkSettingsDocument=vs,exports.checkSettingsFile=Cs,exports.clearCommandContextReferences=rc,exports.clearContextReferences=on,exports.clearConversationHistory=Gc,exports.closeCommandBackgroundTask=vc,exports.compactCommandContext=$s,exports.compareSemverVersions=cd,exports.createAgentRuntime=Md,exports.createAgentTool=Ft,exports.createBackgroundGroupExecutionEntryId=T,exports.createBackgroundProcessTool=Si,exports.createBackgroundTaskExecutionEntryId=w,exports.createBuiltinCommandModule=rs,exports.createCommandExecutionTool=Hu,exports.createCommandMemoryStores=pl,exports.createCommandPendingMemoryStore=fl,exports.createCommandProjectMemoryStore=dl,exports.createContextReferenceItem=nn,exports.createDefaultTools=Gr,exports.createExecutionOriginMetadata=E,exports.createExecutionWorkspaceSnapshot=de,exports.createExecutionWorkspaceTaskSpawner=Ne,exports.createInProcessSubagentRunner=Tt,exports.createInteractiveRuntime=Xu,exports.createLineDetailPage=Ae,exports.createMainThreadDetailPage=ke,exports.createMainThreadExecutionEntryId=C,exports.createModelCommandToolProjection=lt,exports.createPluginRegistryReloadRequestedEffect=Hc,exports.createPluginTuiRequestedEffect=Vc,exports.createProjectSessionStore=Ml,exports.createProjectedCommandExecutionTools=ft,exports.createPromptFileReferenceHistoryEntry=vn,exports.createProviderFromSettings=Hs,exports.createProviderSafeModelCommandToolName=ct,exports.createQuery=Kl,exports.createSessionExitRequestedEffect=Yc,exports.createSessionPickerRequestedEffect=Jc,exports.createSessionRenamedEffect=qc,exports.createStatelessRuntime=Nd,exports.createSubagentLogger=ga,exports.createSubagentSession=yt,exports.createSystemCommands=es,exports.createTestInteractiveSession=rd,exports.createUserSessionStore=Nl,exports.deleteProviderProfile=os,exports.deleteSettings=qi,exports.deleteUserLocalMemoryItem=Tu,exports.disableUserLocalMemoryItem=wu,exports.discoverTaskFiles=oo,exports.evaluateReversibleToolSafety=ta,exports.executeSkill=Sl,exports.formatCliUpdateCheckMessage=Cd,exports.formatCliUpdateNotice=Sd,exports.formatCommandBackgroundTask=uc,exports.formatCommandBackgroundTaskList=dc,exports.formatCommandHelpMessage=cc,exports.formatCommandPermissionsMessage=Nc,exports.formatCommandSessionReplayValidationReport=Qc,Object.defineProperty(exports,"formatEnvReference",{enumerable:!0,get:function(){return c.formatEnvReference}}),exports.formatInvalidPermissionModeMessage=Dc,exports.formatLanguageUsageMessage=Sc,exports.formatOrgPolicyViolationMessage=kl,exports.formatProjectedModelCommandToolPromptDescription=ut,exports.formatPromptFileReferenceDiagnostics=_n,exports.formatTaskContext=lo,exports.generateSessionName=Gl,exports.getBuiltInAgent=k,exports.getForkWorkerSuffix=rt,exports.getProviderSettingsPaths=As,exports.getStartupCliUpdateNotice=bd,exports.getSubagentSuffix=nt,exports.getUserSettingsPath=Ui,exports.getUserUpdateCheckCachePath=md,exports.hasBlockingPromptFileReferenceDiagnostics=gn,exports.hasSensitiveCommandMemoryContent=hl,Object.defineProperty(exports,"hasUsableSecretReference",{enumerable:!0,get:function(){return c.hasUsableSecretReference}}),exports.inspectCommandEditCheckpoint=nl,exports.inspectUserLocalMemoryItem=Cu,exports.inspectUserLocalStorage=ru,exports.isApiKeyPlaintext=Al,exports.isCommandMemoryType=ml,Object.defineProperty(exports,"isEnvReference",{enumerable:!0,get:function(){return c.isEnvReference}}),exports.isMemoryType=ho,exports.isNewerSemverVersion=ld,exports.isPermissionMode=Ec,exports.isSlashCommand=Uu,exports.isStatusLineCommandSettingsPatch=Lc,exports.listActiveContextReferences=sn,exports.listCommandBackgroundTasks=hc,exports.listCommandContextReferences=ec,exports.listCommandEditCheckpoints=tl,exports.listCommandSessionAllowedTools=jc,exports.listCommandUsedMemoryReferences=gl,exports.listResumableSessionSummaries=Pl,exports.listUserLocalMemoryItems=Su,exports.loadOrgPolicy=Ol,exports.loadTaskContext=uo,exports.mergeProviderPatch=us,exports.mergeProviders=Ds,exports.mergeSettings=Es,exports.normalizeModelCommandName=A,exports.parseCommandBackgroundLogCursor=fc,exports.parseExecutionWorkspaceEntryId=ue,exports.parseFrontmatter=Li,exports.parseInput=Gu,exports.parseLanguageArgument=xc,exports.parsePermissionModeArgument=Tc,exports.parsePromptFileReferences=Sn,exports.parseSessionNameArgument=Kc,exports.parseTaskFile=so,exports.planSelfHostingVerification=Pu,exports.preprocessShellCommands=yl,exports.probeProviderProfile=_s,exports.projectPaths=R,exports.promptForApproval=$u,exports.readAutoCompactThreshold=Js,exports.readAutoCompactThresholdSource=Ys,exports.readCommandBackgroundTaskLog=gc,exports.readCommandContextState=qs,exports.readCommandPermissionMode=kc,exports.readCommandPermissionsState=Mc,exports.readCommandSessionInfo=Xc,exports.readCurrentGitBranch=ao,exports.readEnabledUserLocalMemoryItem=Eu,exports.readMergedProviderSettings=zs,exports.readMergedProviderSettingsFromPaths=ws,exports.readPackageVersion=pd,exports.readProviderSettings=Vs,exports.readSettings=W,exports.readStatusLineSettings=Rc,exports.readUpdateCheckCache=hd,exports.recordCommandMemoryEvent=_l,exports.removeCommandContextReference=nc,exports.removeContextReference=an,exports.resetAutoCompactThresholdSetting=Qs,exports.resetUserConfig=id,exports.resolveActiveProvider=Os,exports.resolveEnvDefaultProvider=Bs,Object.defineProperty(exports,"resolveEnvReference",{enumerable:!0,get:function(){return c.resolveEnvReference}}),exports.resolveGitBranch=ad,exports.resolveLatestSessionId=Fl,exports.resolvePermissionModeAdapter=Oc,exports.resolvePluginCommandAdapter=Uc,exports.resolvePromptFileReferencePaths=kn,exports.resolvePromptFileReferences=On,exports.resolveProviderSettingsWriteTargetPath=js,exports.resolveSessionIdByIdOrName=Il,exports.resolveSettingsPathForScope=Wi,exports.resolveSubagentLogDir=_a,exports.resolveUserLocalStorageRoot=eu,exports.restoreCommandEditCheckpoint=rl,exports.retrieveAgentToolDeps=j,exports.rollbackCommandEditCheckpoint=il,exports.sanitizeProviderProfileName=oc,exports.selectRelevantTasks=co,exports.setCommandAutoCompactThreshold=Xs,exports.setCurrentProvider=as,exports.setUserLocalMemoryItem=xu,exports.shouldRunStartupCliUpdateCheck=xd,exports.storeAgentToolDeps=At,exports.substituteVariables=vl,exports.suggestProviderProfileName=ac,exports.summarizeBackgroundJobGroup=se,exports.testProviderProfileCommand=gs,exports.toContextReferenceRecords=cn,exports.toPromptFileReferenceRecords=F,exports.tokeniseSlashCommand=Wu,exports.transitionSelfHostingLoop=Fu,exports.updateModelInSettings=Gi,exports.updateTaskFileStatus=fo,exports.upsertContextReference=rn,exports.upsertProviderProfile=is,exports.userPaths=hr,exports.validateCommandSessionReplayLog=Zc,exports.validateProviderProfile=ss,exports.wrapEditCheckpointTools=Ai,exports.wrapReversibleExecutionTools=na,exports.writeAutoCompactThresholdSetting=Zs,exports.writeCommandPermissionMode=Ac,exports.writeSettings=G,exports.writeUpdateCheckCache=gd;
|