@xenosystem/agent-sdk 0.10.7 → 0.10.9
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/artifacts/index.cjs +10 -10
- package/dist/artifacts/index.js +10 -10
- package/dist/artifacts/metafile-cjs.json +1 -1
- package/dist/artifacts/metafile-esm.json +1 -1
- package/dist/automation/index.cjs +15 -15
- package/dist/automation/index.js +16 -16
- package/dist/automation/metafile-cjs.json +1 -1
- package/dist/automation/metafile-esm.json +1 -1
- package/dist/control-plane/index.cjs +1 -1
- package/dist/control-plane/index.js +1 -1
- package/dist/electron/index.cjs +2 -2
- package/dist/electron/index.js +2 -2
- package/dist/electron/metafile-cjs.json +1 -1
- package/dist/electron/metafile-esm.json +1 -1
- package/dist/index.cjs +306 -306
- package/dist/index.js +326 -326
- package/dist/intelligence/index.cjs +10 -10
- package/dist/intelligence/index.js +10 -10
- package/dist/intelligence/metafile-cjs.json +1 -1
- package/dist/intelligence/metafile-esm.json +1 -1
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/providers/index.cjs +10 -10
- package/dist/providers/index.js +10 -10
- package/dist/providers/metafile-cjs.json +1 -1
- package/dist/providers/metafile-esm.json +1 -1
- package/dist/recipes/index.cjs +2 -2
- package/dist/recipes/index.js +2 -2
- package/dist/recipes/metafile-cjs.json +1 -1
- package/dist/recipes/metafile-esm.json +1 -1
- package/dist/research/index.cjs +3 -3
- package/dist/research/index.js +3 -3
- package/dist/research/metafile-cjs.json +1 -1
- package/dist/research/metafile-esm.json +1 -1
- package/dist/session/index.cjs +1 -1
- package/dist/session/index.js +1 -1
- package/dist/session/metafile-cjs.json +1 -1
- package/dist/session/metafile-esm.json +1 -1
- package/dist/sharing/index.cjs +4 -4
- package/dist/sharing/index.js +4 -4
- package/dist/sharing/metafile-cjs.json +1 -1
- package/dist/sharing/metafile-esm.json +1 -1
- package/dist/ui/index.cjs +2 -2
- package/dist/ui/index.js +2 -2
- package/dist/ui/metafile-cjs.json +1 -1
- package/dist/ui/metafile-esm.json +1 -1
- package/dist/utils/index.cjs +13 -13
- package/dist/utils/index.d.cts +2 -1
- package/dist/utils/index.d.ts +2 -1
- package/dist/utils/index.js +1 -1
- package/dist/utils/metafile-cjs.json +1 -1
- package/dist/utils/metafile-esm.json +1 -1
- package/package.json +1 -1
package/dist/electron/index.js
CHANGED
|
@@ -56,7 +56,7 @@ ${this.stringify(e.data)}
|
|
|
56
56
|
`)+`
|
|
57
57
|
`;await ue(this.transcriptPath,a);let c=this.buildMarkdownDocument(i,"session store");if(await ue(this.markdownPath,c),!this.workspaceMirrorDisabled){let l=await this.resolveWorkspaceMarkdownPath();if(l)try{let u=this.buildMarkdownDocument(i,"workspace mirror");await ue(l,u)}catch(u){this.workspaceMirrorDisabled=!0,St("Transcript workspace mirror disabled",u)}}}async truncateAfterMessageCount(e){let n=await ie(this.transcriptPath);if(!n)return;let r=Kn(n),o=Math.max(0,e),s=0,i=[];for(let l of r){if(l.type==="user_message"||l.type==="assistant_message"){if(s>=o)break;s+=1}i.push(l)}let a=i.length>0?i.map(l=>JSON.stringify(l)).join(`
|
|
58
58
|
`)+`
|
|
59
|
-
`:"";await ue(this.transcriptPath,a);let c=this.buildMarkdownDocument(i,"session store");if(await ue(this.markdownPath,c),!this.workspaceMirrorDisabled){let l=await this.resolveWorkspaceMarkdownPath();if(l)try{let u=this.buildMarkdownDocument(i,"workspace mirror");await ue(l,u)}catch(u){this.workspaceMirrorDisabled=!0,St("Transcript workspace mirror disabled",u)}}}getSequence(){return this.sequence}async initialize(){try{let e=await ie(this.transcriptPath);if(!e){this.sequence=0;return}let n=Kn(e);if(n.length===0){this.sequence=0;return}let r=n[n.length-1];this.sequence=r.sequence+1}catch(e){let n=e instanceof Error?e.message:String(e);St(`Transcript initialization warning: ${n}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};import*as Qn from"path";import{randomUUID as Ww}from"crypto";import{stat as Hw}from"fs/promises";var jw={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function W(t){return jw[t]??t}var Xw=new Set(["Read","Glob","Grep","LS","Think","dispatch_agent","ElfAnalyze","Receive","ListAgents","ListSessions","CoordinationQuery"]),Gw=new Set(["Write","Edit","Send","CoordinationSend"]),zw=new Set(["Bash"]);function lo(t){let e=W(t);return zw.has(e)?"high":Xw.has(e)?"low":(Gw.has(e),"medium")}function ot(t,e,n){return{definition:{...e.definition,name:t,...n?{description:n}:{}},execute:e.execute}}var uo=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,n){this.sessionDir=e,this.checkpointsDir=Qn.join(e,"checkpoints"),this.autoInterval=n?.autoInterval??10}async initialize(){let e=await this.list();e.length>0&&(this.lastCheckpointMessageCount=e[0].messageCount)}async create(e){await rt(this.checkpointsDir);let n=Ww(),r={id:n,name:e.description,trigger:e.trigger,createdAt:new Date().toISOString(),messageCount:e.messages.length,tokenCount:this.estimateTokens(e.messages)},o={info:r,messages:e.messages},s=Qn.join(this.checkpointsDir,`${n}.json`);return await ue(s,JSON.stringify(o,null,2)),this.lastCheckpointMessageCount=e.messages.length,r}async list(){let e=await Bu(this.checkpointsDir,/\.json$/),n=[];for(let r of e){let o=await ie(r);if(o){let s=we(o,null);if(s){let i=await Hw(r);n.push({info:s.info,modifiedAtMs:i.mtimeMs})}}}return n.sort((r,o)=>new Date(o.info.createdAt).getTime()-new Date(r.info.createdAt).getTime()||o.modifiedAtMs-r.modifiedAtMs).map(({info:r})=>r)}async restore(e){let n=Qn.join(this.checkpointsDir,`${e}.json`),r;try{r=await ie(n)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Failed to read checkpoint ${e}: ${i}`)}if(!r)throw new Error(`Checkpoint not found: ${e} (path: ${n})`);let o=we(r,null);if(!o)throw new Error(`Invalid checkpoint data for ${e}: JSON parse failed`);if(!o.messages||!Array.isArray(o.messages))throw new Error(`Invalid checkpoint data for ${e}: missing or invalid messages array`);if(!o.info)throw new Error(`Invalid checkpoint data for ${e}: missing info object`);return{messages:o.messages,info:o.info}}shouldAutoCheckpoint(e){return e-this.lastCheckpointMessageCount>=this.autoInterval}static isDangerousOperation(e,n){if(e=W(e),e==="Write")return!0;if(e==="Bash"){let o=n.command?.toLowerCase()||"";return["rm ","del ","git push","git reset","drop ","truncate"].some(i=>o.includes(i))}return!1}async delete(e){let n=Qn.join(this.checkpointsDir,`${e}.json`);await oo(n)}estimateTokens(e){let n=0;for(let r of e)if(typeof r.content=="string")n+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let o of r.content)"text"in o&&(n+=Math.ceil(o.text.length/4));return n}};var Zn=class{static async fork(e,n){let r=await this.find(e);if(!r)throw new Error(`Session not found: ${e}`);let o=this.getSessionDir(e),s=new Yn(o),i=n?.checkpointId?await new uo(o).restore(n.checkpointId):null,a=i?.messages??await s.getMessages(),c=await s.read(),l=0,u=!1,d=c.filter(b=>{if(b.type==="session_start"||b.type==="session_end"||b.type==="checkpoint"||u)return!1;if(b.type==="user_message"||b.type==="assistant_message"){if(i&&l>=i.info.messageCount)return u=!0,!1;l+=1}return!0}),m=Zu(r.role),p=this.getSessionDir(m);await rt(p);let g=new Date().toISOString(),f={...r,id:m,name:n?.name??(r.name?`${r.name} (fork)`:void 0),status:"completed",parentSession:r.id,createdAt:g,updatedAt:g,lastActivity:g,checkpoints:[],messageCount:a.length,tokenUsage:{...r.tokenUsage}};await ue(Ue.join(p,"meta.json"),JSON.stringify(f,null,2));let h=new Yn(p);await h.append({type:"session_start",data:{sessionId:m,role:r.role,workingDirectory:r.workingDirectory,model:r.model,formatVersion:r.formatVersion,forkedFrom:r.id,...n?.checkpointId?{checkpointId:n.checkpointId}:{}}});for(let b of d)await h.append({type:b.type,data:b.data});return await h.flush(),f}static async setTitle(e,n){let r=typeof n=="string"?n.replace(/\s+/g," ").trim().slice(0,200):"";return this.updateMeta(e,{name:r||void 0})}static async setPinned(e,n){return this.updateMeta(e,n?{pinned:!0,pinnedAt:new Date().toISOString()}:{pinned:void 0,pinnedAt:void 0})}static async setArchived(e,n){let r=await this.find(e);if(!r)throw new Error(`Session not found: ${e}`);return n?this.updateMeta(e,{status:"archived"}):r.status!=="archived"?r:this.updateMeta(e,{status:"completed"})}static getSessionsDir(){let e=Le();return Ue.join(e,"sessions")}static async list(e){let n=this.getSessionsDir(),r=typeof e?.limit=="number"&&Number.isFinite(e.limit)?Math.max(0,Math.floor(e.limit)):void 0;if(r===0)return[];let o=e?.workingDirectory?this.normalizeWorkingDirectory(e.workingDirectory):void 0;if(!ro(n))return[];let s=await $u(n),i=[];for(let a of s){let c=await this.loadMeta(a);c&&(e?.status&&!e.status.includes(c.status)||c.status==="archived"&&!e?.includeArchived&&!e?.status?.includes("archived")||e?.role&&c.role!==e.role||o&&this.normalizeWorkingDirectory(c.workingDirectory)!==o||i.push(c))}return i.sort((a,c)=>{if(!!a.pinned!=!!c.pinned)return a.pinned?-1:1;if(a.pinned&&c.pinned){let l=new Date(c.pinnedAt??0).getTime()-new Date(a.pinnedAt??0).getTime();if(l!==0)return l}return new Date(c.lastActivity).getTime()-new Date(a.lastActivity).getTime()}),r!==void 0?i.slice(0,r):i}static async find(e){let n=this.getSessionsDir(),r=D(n,e);return await this.loadMeta(r)}static async findMostRecent(e){let n=typeof e=="string"?{role:e}:e??{};if(n.workingDirectory){let s=await Yu(n.workingDirectory,{...n.role!==void 0?{role:n.role}:{}});if(s){let i=await this.find(s.sessionId);if(i){if(!(n.role&&i.role!==n.role)){if(this.normalizeWorkingDirectory(i.workingDirectory)===this.normalizeWorkingDirectory(n.workingDirectory))return i}}else await Ni(s.sessionId)}}let o=(await this.list({...n.role!==void 0?{role:n.role}:{},...n.workingDirectory!==void 0?{workingDirectory:n.workingDirectory}:{},limit:1}))[0]??null;if(o&&n.workingDirectory)try{await Qu({cwd:o.workingDirectory,sessionId:o.id,role:o.role,endedAt:o.lastActivity})}catch{}return o}static async delete(e){let n=this.getSessionsDir(),r=D(n,e);await Uu(r),await Ni(e)}static async purgeWorkingDirectory(e,n){let r=new Set(n?.excludeSessionIds??[]),o=await this.list({workingDirectory:e}),s=[],i=[];for(let a of o){if(r.has(a.id)){i.push(a.id);continue}await this.delete(a.id),await this.deleteWorkspaceMirror(e,a.id),s.push(a.id)}return{deletedIds:s,skippedIds:i}}static async updateMeta(e,n){let r=this.getSessionsDir(),o=D(r,e),s=Ue.join(o,"meta.json"),i=await ie(s);if(!i)throw new Error(`Session not found: ${e}`);let a=we(i,null);if(!a)throw new Error(`Invalid session metadata: ${e}`);let c={...a,...n,updatedAt:new Date().toISOString()};return Oi(c.executionMode),await ue(s,JSON.stringify(c,null,2)),c}static async loadMeta(e){let n=Ue.join(e,"meta.json"),r=await ie(n);if(!r)return null;let o=we(r,null);if(!o)return null;Oi(o.executionMode);let s=o.formatVersion;return{...o,formatVersion:typeof s=="number"&&Number.isFinite(s)&&s>0?s:1}}static getSessionDir(e){return D(this.getSessionsDir(),e)}static normalizeWorkingDirectory(e){let n=Ue.normalize(e).replace(/[\\/]+$/,""),r=n.length>0?n:Ue.parse(Ue.normalize(e)).root;return process.platform==="win32"?r.toLowerCase():r}static async deleteWorkspaceMirror(e,n){let r=Ue.join(e,".xeno","sessions",`${n}.md`);await oo(r)}};var mo=class{cwd;globalDir;role;sessionDir;scope;budgets;projectSessionContextDefaults;constructor(e){this.cwd=e.cwd,this.globalDir=e.globalDir||Le(),this.role=e.role,this.sessionDir=e.sessionDir,this.scope=e.scope??"user",this.budgets={...Mu,...e.budgets},this.projectSessionContextDefaults={limit:e.projectSessionContext?.limit??3,maxTokens:e.projectSessionContext?.maxTokens??700,maxCharsPerSession:e.projectSessionContext?.maxCharsPerSession??2400}}get accessScope(){return this.scope}canAccessLevel(e){return this.scope==="none"?!1:this.scope==="session"?e==="session":this.scope==="project"?e==="project"||e==="role"||e==="session":!0}assertLevelAccess(e){if(!this.canAccessLevel(e))throw new Error(`MemoryManager: Memory level '${e}' exceeds active '${this.scope}' memory scope`)}getProjectSessionContextDefaults(){return{...this.projectSessionContextDefaults}}getPath(e){this.assertLevelAccess(e);let n=Ou[e];switch(e){case"global":return D(st.join(this.globalDir,"memory"),n);case"project":return D(st.join(this.cwd,".xeno","memory"),n);case"role":if(!this.role)throw new Error("MemoryManager: Role configuration required but not provided");return D(st.join(this.cwd,".xeno","roles",this.role),n);case"session":if(!this.sessionDir)throw new Error("MemoryManager: Session directory configuration required but not provided");return D(this.sessionDir,n);default:throw new Error(`MemoryManager: Unknown memory level: ${e}`)}}async loadForPrompt(){let e=[];this.canAccessLevel("global")&&e.push("global"),this.canAccessLevel("project")&&e.push("project"),this.role&&this.canAccessLevel("role")&&e.push("role"),this.sessionDir&&this.canAccessLevel("session")&&e.push("session");let n=[],r={global:"",project:"",role:"",session:""},o=0,s=!1;for(let i of e)try{let a=this.getPath(i),c=await ie(a);if(c){let l=this.budgets[i],u=ce(c),d=c;u>l&&(d=this.truncateContent(c,l),s=!0);let m=ce(d);n.push({level:i,path:a,content:d,tokenCount:m}),r[i]=d,o+=m}}catch(a){xe(`Failed to load ${i} memory`,a)}if(o>this.budgets.total){let i=this.budgets.total/o;for(let a of n){let c=Math.max(1,Math.floor(a.tokenCount*i));a.content=Be(a.content,c),a.tokenCount=ce(a.content),r[a.level]=a.content}o=n.reduce((a,c)=>a+c.tokenCount,0),s=!0}return{files:n,byLevel:r,totalTokens:o,truncated:s}}async loadProjectSessionContext(e){if(!this.canAccessLevel("project"))return{entries:[],totalTokens:0,truncated:!1,content:""};let n=Math.max(1,Math.min(e?.limit??this.projectSessionContextDefaults.limit,10)),r=Math.max(n*20,120),o=Math.max(120,e?.maxTokens??this.projectSessionContextDefaults.maxTokens),s=Math.max(200,e?.maxCharsPerSession??this.projectSessionContextDefaults.maxCharsPerSession),i=e?.excludeSessionId,a={entries:[],totalTokens:0,truncated:!1,content:""};try{let c=await Zn.list({limit:r}),l=this.filterProjectSessions(c,i),u=[],d=[],m=0,p=!1;for(let f of l){if(u.length>=n)break;let h=st.join(Zn.getSessionDir(f.id),"transcript.md"),b=await ie(h);if(!b)continue;let y=this.extractRecentTranscriptExcerpt(b,s);if(!y)continue;let x={sessionId:f.id,model:f.model,lastActivity:f.lastActivity,messageCount:f.messageCount,excerpt:y},w=this.formatProjectSessionEntry(x),S=ce(w);if(m+S>o){if(u.length===0){let E=Be(w,o);E.trim().length>0&&(u.push(x),d.push(E),m+=ce(E))}p=!0;break}u.push(x),d.push(w),m+=S}if(u.length===0)return a;let g=["# Project Session History","",...d].join(`
|
|
59
|
+
`:"";await ue(this.transcriptPath,a);let c=this.buildMarkdownDocument(i,"session store");if(await ue(this.markdownPath,c),!this.workspaceMirrorDisabled){let l=await this.resolveWorkspaceMarkdownPath();if(l)try{let u=this.buildMarkdownDocument(i,"workspace mirror");await ue(l,u)}catch(u){this.workspaceMirrorDisabled=!0,St("Transcript workspace mirror disabled",u)}}}getSequence(){return this.sequence}async initialize(){try{let e=await ie(this.transcriptPath);if(!e){this.sequence=0;return}let n=Kn(e);if(n.length===0){this.sequence=0;return}let r=n[n.length-1];this.sequence=r.sequence+1}catch(e){let n=e instanceof Error?e.message:String(e);St(`Transcript initialization warning: ${n}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};import*as Qn from"path";import{randomUUID as Ww}from"crypto";import{stat as Hw}from"fs/promises";var jw={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function W(t){return jw[t]??t}var Xw=new Set(["Read","Glob","Grep","LS","MemoryRead","Think","dispatch_agent","ElfAnalyze","Receive","ListAgents","ListSessions","CoordinationQuery"]),Gw=new Set(["Write","Edit","MemoryWrite","Send","CoordinationSend"]),zw=new Set(["Bash"]);function lo(t){let e=W(t);return zw.has(e)?"high":Xw.has(e)?"low":(Gw.has(e),"medium")}function ot(t,e,n){return{definition:{...e.definition,name:t,...n?{description:n}:{}},execute:e.execute}}var uo=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,n){this.sessionDir=e,this.checkpointsDir=Qn.join(e,"checkpoints"),this.autoInterval=n?.autoInterval??10}async initialize(){let e=await this.list();e.length>0&&(this.lastCheckpointMessageCount=e[0].messageCount)}async create(e){await rt(this.checkpointsDir);let n=Ww(),r={id:n,name:e.description,trigger:e.trigger,createdAt:new Date().toISOString(),messageCount:e.messages.length,tokenCount:this.estimateTokens(e.messages)},o={info:r,messages:e.messages},s=Qn.join(this.checkpointsDir,`${n}.json`);return await ue(s,JSON.stringify(o,null,2)),this.lastCheckpointMessageCount=e.messages.length,r}async list(){let e=await Bu(this.checkpointsDir,/\.json$/),n=[];for(let r of e){let o=await ie(r);if(o){let s=we(o,null);if(s){let i=await Hw(r);n.push({info:s.info,modifiedAtMs:i.mtimeMs})}}}return n.sort((r,o)=>new Date(o.info.createdAt).getTime()-new Date(r.info.createdAt).getTime()||o.modifiedAtMs-r.modifiedAtMs).map(({info:r})=>r)}async restore(e){let n=Qn.join(this.checkpointsDir,`${e}.json`),r;try{r=await ie(n)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Failed to read checkpoint ${e}: ${i}`)}if(!r)throw new Error(`Checkpoint not found: ${e} (path: ${n})`);let o=we(r,null);if(!o)throw new Error(`Invalid checkpoint data for ${e}: JSON parse failed`);if(!o.messages||!Array.isArray(o.messages))throw new Error(`Invalid checkpoint data for ${e}: missing or invalid messages array`);if(!o.info)throw new Error(`Invalid checkpoint data for ${e}: missing info object`);return{messages:o.messages,info:o.info}}shouldAutoCheckpoint(e){return e-this.lastCheckpointMessageCount>=this.autoInterval}static isDangerousOperation(e,n){if(e=W(e),e==="Write")return!0;if(e==="Bash"){let o=n.command?.toLowerCase()||"";return["rm ","del ","git push","git reset","drop ","truncate"].some(i=>o.includes(i))}return!1}async delete(e){let n=Qn.join(this.checkpointsDir,`${e}.json`);await oo(n)}estimateTokens(e){let n=0;for(let r of e)if(typeof r.content=="string")n+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let o of r.content)"text"in o&&(n+=Math.ceil(o.text.length/4));return n}};var Zn=class{static async fork(e,n){let r=await this.find(e);if(!r)throw new Error(`Session not found: ${e}`);let o=this.getSessionDir(e),s=new Yn(o),i=n?.checkpointId?await new uo(o).restore(n.checkpointId):null,a=i?.messages??await s.getMessages(),c=await s.read(),l=0,u=!1,d=c.filter(b=>{if(b.type==="session_start"||b.type==="session_end"||b.type==="checkpoint"||u)return!1;if(b.type==="user_message"||b.type==="assistant_message"){if(i&&l>=i.info.messageCount)return u=!0,!1;l+=1}return!0}),m=Zu(r.role),p=this.getSessionDir(m);await rt(p);let g=new Date().toISOString(),f={...r,id:m,name:n?.name??(r.name?`${r.name} (fork)`:void 0),status:"completed",parentSession:r.id,createdAt:g,updatedAt:g,lastActivity:g,checkpoints:[],messageCount:a.length,tokenUsage:{...r.tokenUsage}};await ue(Ue.join(p,"meta.json"),JSON.stringify(f,null,2));let h=new Yn(p);await h.append({type:"session_start",data:{sessionId:m,role:r.role,workingDirectory:r.workingDirectory,model:r.model,formatVersion:r.formatVersion,forkedFrom:r.id,...n?.checkpointId?{checkpointId:n.checkpointId}:{}}});for(let b of d)await h.append({type:b.type,data:b.data});return await h.flush(),f}static async setTitle(e,n){let r=typeof n=="string"?n.replace(/\s+/g," ").trim().slice(0,200):"";return this.updateMeta(e,{name:r||void 0})}static async setPinned(e,n){return this.updateMeta(e,n?{pinned:!0,pinnedAt:new Date().toISOString()}:{pinned:void 0,pinnedAt:void 0})}static async setArchived(e,n){let r=await this.find(e);if(!r)throw new Error(`Session not found: ${e}`);return n?this.updateMeta(e,{status:"archived"}):r.status!=="archived"?r:this.updateMeta(e,{status:"completed"})}static getSessionsDir(){let e=Le();return Ue.join(e,"sessions")}static async list(e){let n=this.getSessionsDir(),r=typeof e?.limit=="number"&&Number.isFinite(e.limit)?Math.max(0,Math.floor(e.limit)):void 0;if(r===0)return[];let o=e?.workingDirectory?this.normalizeWorkingDirectory(e.workingDirectory):void 0;if(!ro(n))return[];let s=await $u(n),i=[];for(let a of s){let c=await this.loadMeta(a);c&&(e?.status&&!e.status.includes(c.status)||c.status==="archived"&&!e?.includeArchived&&!e?.status?.includes("archived")||e?.role&&c.role!==e.role||o&&this.normalizeWorkingDirectory(c.workingDirectory)!==o||i.push(c))}return i.sort((a,c)=>{if(!!a.pinned!=!!c.pinned)return a.pinned?-1:1;if(a.pinned&&c.pinned){let l=new Date(c.pinnedAt??0).getTime()-new Date(a.pinnedAt??0).getTime();if(l!==0)return l}return new Date(c.lastActivity).getTime()-new Date(a.lastActivity).getTime()}),r!==void 0?i.slice(0,r):i}static async find(e){let n=this.getSessionsDir(),r=D(n,e);return await this.loadMeta(r)}static async findMostRecent(e){let n=typeof e=="string"?{role:e}:e??{};if(n.workingDirectory){let s=await Yu(n.workingDirectory,{...n.role!==void 0?{role:n.role}:{}});if(s){let i=await this.find(s.sessionId);if(i){if(!(n.role&&i.role!==n.role)){if(this.normalizeWorkingDirectory(i.workingDirectory)===this.normalizeWorkingDirectory(n.workingDirectory))return i}}else await Ni(s.sessionId)}}let o=(await this.list({...n.role!==void 0?{role:n.role}:{},...n.workingDirectory!==void 0?{workingDirectory:n.workingDirectory}:{},limit:1}))[0]??null;if(o&&n.workingDirectory)try{await Qu({cwd:o.workingDirectory,sessionId:o.id,role:o.role,endedAt:o.lastActivity})}catch{}return o}static async delete(e){let n=this.getSessionsDir(),r=D(n,e);await Uu(r),await Ni(e)}static async purgeWorkingDirectory(e,n){let r=new Set(n?.excludeSessionIds??[]),o=await this.list({workingDirectory:e}),s=[],i=[];for(let a of o){if(r.has(a.id)){i.push(a.id);continue}await this.delete(a.id),await this.deleteWorkspaceMirror(e,a.id),s.push(a.id)}return{deletedIds:s,skippedIds:i}}static async updateMeta(e,n){let r=this.getSessionsDir(),o=D(r,e),s=Ue.join(o,"meta.json"),i=await ie(s);if(!i)throw new Error(`Session not found: ${e}`);let a=we(i,null);if(!a)throw new Error(`Invalid session metadata: ${e}`);let c={...a,...n,updatedAt:new Date().toISOString()};return Oi(c.executionMode),await ue(s,JSON.stringify(c,null,2)),c}static async loadMeta(e){let n=Ue.join(e,"meta.json"),r=await ie(n);if(!r)return null;let o=we(r,null);if(!o)return null;Oi(o.executionMode);let s=o.formatVersion;return{...o,formatVersion:typeof s=="number"&&Number.isFinite(s)&&s>0?s:1}}static getSessionDir(e){return D(this.getSessionsDir(),e)}static normalizeWorkingDirectory(e){let n=Ue.normalize(e).replace(/[\\/]+$/,""),r=n.length>0?n:Ue.parse(Ue.normalize(e)).root;return process.platform==="win32"?r.toLowerCase():r}static async deleteWorkspaceMirror(e,n){let r=Ue.join(e,".xeno","sessions",`${n}.md`);await oo(r)}};var mo=class{cwd;globalDir;role;sessionDir;scope;budgets;projectSessionContextDefaults;constructor(e){this.cwd=e.cwd,this.globalDir=e.globalDir||Le(),this.role=e.role,this.sessionDir=e.sessionDir,this.scope=e.scope??"user",this.budgets={...Mu,...e.budgets},this.projectSessionContextDefaults={limit:e.projectSessionContext?.limit??3,maxTokens:e.projectSessionContext?.maxTokens??700,maxCharsPerSession:e.projectSessionContext?.maxCharsPerSession??2400}}get accessScope(){return this.scope}canAccessLevel(e){return this.scope==="none"?!1:this.scope==="session"?e==="session":this.scope==="project"?e==="project"||e==="role"||e==="session":!0}assertLevelAccess(e){if(!this.canAccessLevel(e))throw new Error(`MemoryManager: Memory level '${e}' exceeds active '${this.scope}' memory scope`)}getProjectSessionContextDefaults(){return{...this.projectSessionContextDefaults}}getPath(e){this.assertLevelAccess(e);let n=Ou[e];switch(e){case"global":return D(st.join(this.globalDir,"memory"),n);case"project":return D(st.join(this.cwd,".xeno","memory"),n);case"role":if(!this.role)throw new Error("MemoryManager: Role configuration required but not provided");return D(st.join(this.cwd,".xeno","roles",this.role),n);case"session":if(!this.sessionDir)throw new Error("MemoryManager: Session directory configuration required but not provided");return D(this.sessionDir,n);default:throw new Error(`MemoryManager: Unknown memory level: ${e}`)}}async loadForPrompt(){let e=[];this.canAccessLevel("global")&&e.push("global"),this.canAccessLevel("project")&&e.push("project"),this.role&&this.canAccessLevel("role")&&e.push("role"),this.sessionDir&&this.canAccessLevel("session")&&e.push("session");let n=[],r={global:"",project:"",role:"",session:""},o=0,s=!1;for(let i of e)try{let a=this.getPath(i),c=await ie(a);if(c){let l=this.budgets[i],u=ce(c),d=c;u>l&&(d=this.truncateContent(c,l),s=!0);let m=ce(d);n.push({level:i,path:a,content:d,tokenCount:m}),r[i]=d,o+=m}}catch(a){xe(`Failed to load ${i} memory`,a)}if(o>this.budgets.total){let i=this.budgets.total/o;for(let a of n){let c=Math.max(1,Math.floor(a.tokenCount*i));a.content=Be(a.content,c),a.tokenCount=ce(a.content),r[a.level]=a.content}o=n.reduce((a,c)=>a+c.tokenCount,0),s=!0}return{files:n,byLevel:r,totalTokens:o,truncated:s}}async loadProjectSessionContext(e){if(!this.canAccessLevel("project"))return{entries:[],totalTokens:0,truncated:!1,content:""};let n=Math.max(1,Math.min(e?.limit??this.projectSessionContextDefaults.limit,10)),r=Math.max(n*20,120),o=Math.max(120,e?.maxTokens??this.projectSessionContextDefaults.maxTokens),s=Math.max(200,e?.maxCharsPerSession??this.projectSessionContextDefaults.maxCharsPerSession),i=e?.excludeSessionId,a={entries:[],totalTokens:0,truncated:!1,content:""};try{let c=await Zn.list({limit:r}),l=this.filterProjectSessions(c,i),u=[],d=[],m=0,p=!1;for(let f of l){if(u.length>=n)break;let h=st.join(Zn.getSessionDir(f.id),"transcript.md"),b=await ie(h);if(!b)continue;let y=this.extractRecentTranscriptExcerpt(b,s);if(!y)continue;let x={sessionId:f.id,model:f.model,lastActivity:f.lastActivity,messageCount:f.messageCount,excerpt:y},w=this.formatProjectSessionEntry(x),S=ce(w);if(m+S>o){if(u.length===0){let E=Be(w,o);E.trim().length>0&&(u.push(x),d.push(E),m+=ce(E))}p=!0;break}u.push(x),d.push(w),m+=S}if(u.length===0)return a;let g=["# Project Session History","",...d].join(`
|
|
60
60
|
`);return p&&(g+=`
|
|
61
61
|
|
|
62
62
|
*Note: Some prior session history was omitted to fit token budget.*`),{entries:u,totalTokens:ce(g),truncated:p,content:g}}catch(c){return xe("Failed to load project session context",c),a}}filterProjectSessions(e,n){let r=this.normalizePath(this.cwd);return e.filter(o=>n&&o.id===n||!o.workingDirectory?!1:this.normalizePath(o.workingDirectory)===r)}normalizePath(e){return st.resolve(e).replace(/[\\/]+/g,st.sep).toLowerCase()}extractRecentTranscriptExcerpt(e,n){let r=e.replace(/\r\n/g,`
|
|
@@ -1990,7 +1990,7 @@ ${s.content}`:s.content;await this.appendSyntheticUserMessage(i,"context_injecti
|
|
|
1990
1990
|
`),await this.appendSyntheticAssistantMessage(y,"budget_continuation_suspended_assistant_message"),this.handleTextDelta(`
|
|
1991
1991
|
|
|
1992
1992
|
${y}`,n,i),this.lastRunTerminationInfo={status:"suspended",reason:b.continuationTurns>=b.maxContinuationTurns?"continuation_exhausted":"max_iterations",iteration:i,maxIterations:c,finalStateVerified:!1,message:y},this.queryLifecycle?.transition("suspended",i),this.emitRuntimeEvent({type:"turn.continuation_enqueued",turnId:n,continuationId:b.continuationId,pendingOperationIds:[],message:y}),this.emitRuntimeEvent({type:"turn.suspended",turnId:n,continuationId:b.continuationId,pendingOperationIds:[],message:y})}return a}clearHistory(){this._messages=[],this.totalInputTokens=0,this.totalOutputTokens=0,this.modelWorkAttemptedRequests=0,this.modelWorkMeteredRequests=0,this.lastRequestInputTokens=void 0,this.messageFlow.reset()}};import{createInterface as UC}from"node:readline";import{createHash as FC}from"node:crypto";import{dirname as qC,resolve as jC,normalize as wt,sep as Oy}from"node:path";var CC={color:"auto"},Ti={...CC};function bu(t){return Number.isFinite(t)?Math.max(0,Math.min(255,Math.round(t))):0}function Ee(t,e){return{open:`\x1B[${t}m`,close:`\x1B[${e}m`}}function MC(){if(Ti.colorDepth)return Ti.colorDepth;let t=Number(process.env.XENO_COLOR_DEPTH??"");return t===1||t===4||t===8||t===24?t:/^(?:truecolor|24bit)$/i.test(process.env.COLORTERM??"")||process.platform==="win32"?24:/256color/i.test(process.env.TERM??"")?8:4}function OC(){return Ti.color==="always"?!0:Ti.color==="never"||process.env.NO_COLOR!==void 0||process.env.FORCE_COLOR==="0"?!1:process.env.FORCE_COLOR!==void 0?!0:process.env.TERM==="dumb"?!1:!!process.stdout?.isTTY}function _y(t){let e=t.trim().replace(/^#/,""),n=e.length===3?e.split("").map(r=>r+r).join(""):e;if(!/^[0-9a-f]{6}$/i.test(n))throw new Error(`Invalid terminal color: ${t}`);return[Number.parseInt(n.slice(0,2),16),Number.parseInt(n.slice(2,4),16),Number.parseInt(n.slice(4,6),16)]}function LC(t,e,n){if(t===e&&e===n)return t<8?16:t>248?231:Math.round((t-8)/10)+232;let r=o=>Math.round(o/255*5);return 16+36*r(t)+6*r(e)+r(n)}var ky=[[0,0,0],[205,49,49],[13,188,121],[229,229,16],[36,114,200],[188,63,188],[17,168,205],[229,229,229]];function NC(t,e,n){let r=0,o=Number.POSITIVE_INFINITY;for(let s=0;s<ky.length;s+=1){let i=ky[s],a=(t-i[0])**2+(e-i[1])**2+(n-i[2])**2;a<o&&(r=s,o=a)}return r}function vi(t,e,n,r){let o=bu(t),s=bu(e),i=bu(n),a=MC();return Ee(a===24?`${r?48:38};2;${o};${s};${i}`:a===8?`${r?48:38};5;${LC(o,s,i)}`:String((r?40:30)+NC(o,s,i)),r?"49":"39")}function Iy(t,e){let n=String(t??"");if(!n||e.length===0||!OC())return n;let r=e.map(i=>i.open).join(""),o=[...e].reverse().map(i=>i.close).join(""),s=n.replaceAll("\x1B[0m",`\x1B[0m${r}`);for(let i of e)s=s.replaceAll(i.close,`${i.close}${r}`);return`${r}${s}${o}`}function ye(...t){let e=(n=>Iy(n,t));return Object.defineProperty(e,"styles",{value:Object.freeze([...t]),enumerable:!0}),e}var Oe={bold:Ee("1","22"),dim:Ee("2","22"),italic:Ee("3","23"),strikethrough:Ee("9","29"),black:Ee("30","39"),red:Ee("31","39"),green:Ee("32","39"),yellow:Ee("33","39"),blue:Ee("34","39"),magenta:Ee("35","39"),cyan:Ee("36","39"),white:Ee("37","39"),gray:Ee("90","39")},Vr=Object.freeze({bold:ye(Oe.bold),dim:ye(Oe.dim),italic:ye(Oe.italic),strikethrough:ye(Oe.strikethrough),black:ye(Oe.black),red:ye(Oe.red),green:ye(Oe.green),yellow:ye(Oe.yellow),blue:ye(Oe.blue),magenta:ye(Oe.magenta),cyan:ye(Oe.cyan),white:ye(Oe.white),gray:ye(Oe.gray),rgb:(t,e,n)=>ye(vi(t,e,n,!1)),bgRgb:(t,e,n)=>ye(vi(t,e,n,!0)),hex:t=>ye(vi(..._y(t),!1)),bgHex:t=>ye(vi(..._y(t),!0)),compose:(...t)=>ye(...t.flatMap(e=>e.styles)),format:(t,...e)=>Iy(t,e)});var t4=new Intl.Segmenter(void 0,{granularity:"grapheme"}),n4=new RegExp("\\p{Extended_Pictographic}","u"),r4=new RegExp("\\p{Regional_Indicator}","u");import{existsSync as Ay}from"node:fs";var Py=2,Si=10;function Ei(t){return t.split(`
|
|
1993
|
-
`).map(e=>e.endsWith("\r")?e.slice(0,-1):e)}function Jr(t,e){let n=e.length>180?`${e.slice(0,177)}...`:e;return`${String(t).padStart(4)} | ${n.length>0?n:"(blank)"}`}function Ry(t,e,n,r){let o=Ei(e),s=Ei(n),i=0,a=Math.min(o.length,s.length);for(;i<a&&o[i]===s[i];)i+=1;let c=o.length-1,l=s.length-1;for(;c>=i&&l>=i&&o[c]===s[l];)c-=1,l-=1;let u=Math.max(0,i-Py),d=Math.min(s.length,l+1+Py),m=[];for(let p=u;p<i;p+=1)m.push({kind:"context",text:Jr(p+1,s[p]??"")});for(let p=i;p<=c;p+=1)m.push({kind:"remove",text:Jr(p+1,o[p]??"")});for(let p=i;p<=l;p+=1)m.push({kind:"add",text:Jr(p+1,s[p]??"")});for(let p=l+1;p<d;p+=1)m.push({kind:"context",text:Jr(p+1,s[p]??"")});return m.length===0&&m.push({kind:"meta",text:"No textual changes detected."}),{title:t,summary:r,lines:m.slice(0,Si),truncated:m.length>Si}}function Cy(t,e,n){let r=Ei(e).map((o,s)=>({kind:"add",text:Jr(s+1,o)}));return{title:t,summary:n,lines:r.slice(0,Si),truncated:r.length>Si}}function DC(t){let e=[],n=t.toLowerCase();/\bsudo\b|\bsu\b|\bdoas\b/.test(n)&&e.push("Requests elevated privileges."),/rm\s+-rf\b|remove-item\b.+-recurse/.test(n)&&e.push("Contains recursive deletion semantics."),/curl\b|wget\b|invoke-webrequest\b|invoke-restmethod\b/.test(n)&&e.push("Fetches data from the network.");let r=[{kind:"meta",text:t.length>220?`${t.slice(0,217)}...`:t},...e.map(o=>({kind:"meta",text:o}))];return{title:"Command preview",summary:e.length>0?`${e.length} warning${e.length===1?"":"s"}`:"No immediate danger markers detected",lines:r}}function yu(t,e){let n=typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:typeof e.notebook_path=="string"?e.notebook_path:typeof e.filePath=="string"?e.filePath:null;if(!n||n.trim().length===0)return null;try{return D(t,n)}catch{return null}}async function BC(t,e){let n=typeof e.file_path=="string"?e.file_path:"",r=typeof e.content=="string"?e.content:"",o=yu(t,e),s=`${Ei(r).length} line(s)`;if(!o||n.length===0)return{operation:"write"};if(!Ay(o))return{operation:"write",preview:Cy(`Create ${n}`,r,s)};try{let i=await Te(o);return{operation:"write",preview:Ry(`Overwrite ${n}`,i.content,r,s)}}catch{return{operation:"write"}}}async function $C(t,e){let n=typeof e.file_path=="string"?e.file_path:"",r=typeof e.old_string=="string"?e.old_string:"",o=typeof e.new_string=="string"?e.new_string:"",s=e.replace_all===!0,i=yu(t,e);if(!i||n.length===0)return{operation:"edit"};if(!Ay(i))return r.length===0?{operation:"edit",preview:Cy(`Create ${n} via Edit`,o)}:{operation:"edit",preview:{title:`Edit ${n}`,lines:[{kind:"meta",text:"Target file does not exist yet."}]}};try{let c=(await Te(i)).content;if(r.length===0)return{operation:"edit",preview:{title:`Edit ${n}`,lines:[{kind:"meta",text:"old_string is empty for an existing file; the edit tool will reject this."}]}};if(!c.includes(r))return{operation:"edit",preview:{title:`Edit ${n}`,lines:[{kind:"meta",text:"old_string was not found in the current file contents."}]}};if(!s){let u=c.indexOf(r);if(c.indexOf(r,u+r.length)!==-1)return{operation:"edit",preview:{title:`Edit ${n}`,lines:[{kind:"meta",text:"old_string is not unique in the file; the edit tool will require more context or replace_all."}]}}}let l=s?c.replaceAll(r,o):c.replace(r,o);return{operation:"edit",preview:Ry(`Edit ${n}`,c,l,s?"replace_all=true":"single replacement")}}catch{return{operation:"edit"}}}async function My(t,e,n){let r=W(e);if(r==="Write")return BC(t,n);if(r==="Edit")return $C(t,n);if(r==="Bash")return{operation:"bash",preview:DC(typeof n.command=="string"?n.command:"")};if(r==="Read"||r==="ReadImage"||r==="Glob"||r==="Grep"||r==="LS"||r==="ElfAnalyze"||r==="LspDefinition"||r==="LspDiagnostics"||r==="LspHover"||r==="LspReferences"||r==="NotebookRead"||r==="NotebookEdit"){let o=yu(t,n);return{operation:"filesystem",...o?{preview:{title:r==="LS"?"Filesystem target":"File target",lines:[{kind:"meta",text:o}]}}:{}}}return{operation:"generic"}}var nn=new Set(["Read","ReadImage","Write","Edit","Glob","Grep","LS","ElfAnalyze","NotebookRead","NotebookEdit","LspDefinition","LspDiagnostics","LspHover","LspReferences"]),XC=3,Ly=new Set(["Write","Edit","NotebookEdit","MemoryWrite"]),GC=/(?:&&|\|\||;|\||>|<|`|\$\()/,Ny=new Set(["BackgroundAgent","BackgroundAgentSession","BackgroundAgentSend","BackgroundAgentList","BackgroundAgentPeek","BackgroundAgentJoin","BackgroundAgentStop","BackgroundAgentEvents"]),Dy={Read:"allow",ReadImage:"allow",LS:"allow",Glob:"allow",Grep:"allow",ElfAnalyze:"allow",MemoryRead:"allow",dispatch_agent:"allow",Think:"allow",GitStatus:"allow",GitDiff:"allow",GitLog:"allow",GitBranch:"allow",WebSearch:"allow",WebFetch:"allow",AskUser:"allow",NotebookRead:"allow",LspDefinition:"ask",LspDiagnostics:"ask",LspHover:"ask",LspReferences:"ask",Write:"ask",Edit:"ask",MemoryWrite:"ask",NotebookEdit:"ask",Bash:"ask",GitCommit:"ask",TaskOutput:"allow",TaskStop:"ask",CoordinationQuery:"allow",CoordinationSend:"allow",Send:"allow",Receive:"allow",ListAgents:"allow",ListSessions:"allow",Artifact:"allow",ToolSearch:"allow"},zC=new Set(["Send","CoordinationSend"]),_i=class t{config;workingDirectory=process.cwd();sessionAllowed=new Set;sessionAllowedDirectories=new Set;persistentAllowed=new Set;persistentAllowedDirectories=new Set;promptFn;decisionHook;constructor(e,n,r){this.config={mode:e?.mode??"default",rules:e?.rules??[],...e?.profile?{profile:e.profile}:{}},this.promptFn=n,this.decisionHook=r}fork(e=this.promptFn){let n=new t({mode:this.config.mode,rules:[...this.config.rules],...this.config.profile?{profile:this.config.profile}:{}},e,this.decisionHook);return n.workingDirectory=this.workingDirectory,n.sessionAllowed=new Set(this.sessionAllowed),n.sessionAllowedDirectories=new Set(this.sessionAllowedDirectories),n.persistentAllowed=new Set(this.persistentAllowed),n.persistentAllowedDirectories=new Set(this.persistentAllowedDirectories),n}get mode(){return this.config.mode}setMode(e){this.config.mode!==e&&(this.config.mode=e,this.sessionAllowed.clear(),this.sessionAllowedDirectories.clear())}setWorkingDirectory(e){this.workingDirectory=e}setRules(e){this.config.rules=[...e]}loadPersistentState(e){this.persistentAllowed.clear(),this.persistentAllowedDirectories.clear();for(let n of e.allowedTools??[]){let r=this.normalizePersistentApprovalKey(n.trim());r.length>0&&this.persistentAllowed.add(r)}for(let n of e.allowedDirectories??[]){let r=n.trim();r.length>0&&this.persistentAllowedDirectories.add(this.normalizeDirectory(r))}}allowDirectory(e){let n=this.normalizeDirectory(e);this.sessionAllowedDirectories.add(n)}isPathInAllowedDirectory(e){if(this.sessionAllowedDirectories.size===0&&this.persistentAllowedDirectories.size===0)return!1;let n=wt(this.resolveTargetPath(e));for(let r of this.persistentAllowedDirectories)if(n.startsWith(r))return!0;for(let r of this.sessionAllowedDirectories)if(n.startsWith(r))return!0;return!1}async check(e,n,r){let o=W(e);if(o==="WebFetch"&&this.config.profile&&typeof n.url=="string"){let c=Vo(this.config.profile,n.url);if(!c.allowed)return this.finalizeDecision(e,n,!1,`profile network deny: ${c.reason}`,r?.traceId,r?.requesterLabel)}if(this.config.mode==="bypassPermissions")return this.finalizeDecision(e,n,!0,"bypass mode",r?.traceId,r?.requesterLabel);if(this.config.mode==="plan"&&((Dy[o]??"ask")!=="allow"||zC.has(o)))return this.finalizeDecision(e,n,!1,"plan mode",r?.traceId,r?.requesterLabel);for(let c of this.config.rules)if(this.matchesRule(c.tool,c.pattern,e,n)){if(c.decision==="allow"){if(o==="Bash"&&this.hasShellComposition(typeof n.command=="string"?n.command:""))continue;return this.finalizeDecision(e,n,!0,`rule: allow ${c.tool}`,r?.traceId,r?.requesterLabel)}if(c.decision==="deny")return this.finalizeDecision(e,n,!1,`rule: deny ${c.tool}`,r?.traceId,r?.requesterLabel)}if(this.config.mode==="auto"){let c=this.classifyAutoPermission(o,n);if(c.decision==="allow")return this.finalizeDecision(e,n,!0,`auto allow: ${c.reason}`,r?.traceId,r?.requesterLabel);if(c.decision==="deny")return this.finalizeDecision(e,n,!1,`auto deny: ${c.reason}`,r?.traceId,r?.requesterLabel);r?.onWaitStart?.();let l=await this.promptUser(e,n,r?.requesterLabel,r?.ephemeralInputPreview).finally(()=>r?.onWaitEnd?.());return l.persist&&!l.directoryCached&&this.sessionAllowed.add(this.getCacheKey(o,n)),this.finalizeDecision(e,n,l.allowed,l.allowed?`auto ask: user approved (${c.reason})`:`auto ask: user denied (${c.reason})`,r?.traceId,r?.requesterLabel)}let s=Dy[o]??"ask";if(s==="allow")return this.finalizeDecision(e,n,!0,"default allow",r?.traceId,r?.requesterLabel);if(s==="deny")return this.finalizeDecision(e,n,!1,"default deny",r?.traceId,r?.requesterLabel);if(this.config.mode==="acceptEdits"&&(o==="Write"||o==="Edit"))return this.finalizeDecision(e,n,!0,"acceptEdits mode",r?.traceId,r?.requesterLabel);if(nn.has(o)){let c=this.extractFilePath(o,n);if(c&&this.isPathInAllowedDirectory(c)){let l=this.isPathInPersistentAllowedDirectory(c)?"persistent directory approval":"directory auto-grant";return this.finalizeDecision(e,n,!0,l,r?.traceId,r?.requesterLabel)}}let i=this.getCacheKey(o,n);if(this.persistentAllowed.has(i))return this.finalizeDecision(e,n,!0,"persistent approval",r?.traceId,r?.requesterLabel);if(o==="Bash"&&this.hasBashApproval(this.persistentAllowed,n))return this.finalizeDecision(e,n,!0,"persistent approval",r?.traceId,r?.requesterLabel);if(this.sessionAllowed.has(i))return this.finalizeDecision(e,n,!0,"session approved",r?.traceId,r?.requesterLabel);if(o==="Bash"&&this.hasBashApproval(this.sessionAllowed,n))return this.finalizeDecision(e,n,!0,"session approved",r?.traceId,r?.requesterLabel);r?.onWaitStart?.();let a=await this.promptUser(e,n,r?.requesterLabel,r?.ephemeralInputPreview).finally(()=>r?.onWaitEnd?.());return a.persist&&!a.directoryCached&&this.sessionAllowed.add(i),this.finalizeDecision(e,n,a.allowed,a.allowed?"user approved":"user denied",r?.traceId,r?.requesterLabel)}async finalizeDecision(e,n,r,o,s,i){if(this.decisionHook)try{await this.decisionHook({traceId:s,toolName:e,input:n,allowed:r,reason:o,mode:this.config.mode,requesterLabel:i})}catch(a){xe("[PermissionEngine] decision hook failed",a)}return{allowed:r,reason:o}}classifyAutoPermission(e,n){let r=W(e);if(r==="Read"||r==="ReadImage"||r==="NotebookRead"){let o=this.extractFilePath(r,n);return o&&this.isCredentialLikePath(o)?{decision:"deny",confidence:"high",reason:"credential-like file read",risk:"critical",matchedRules:["auto:credential-read-deny"]}:{decision:"allow",confidence:"high",reason:"read-only file inspection",risk:"low",matchedRules:["auto:read-only-allow"]}}if(r==="Glob"||r==="Grep"||r==="LS"||r==="MemoryRead"||r==="GitStatus"||r==="GitDiff"||r==="GitLog"||r==="GitBranch"||r==="TaskOutput"||r==="TaskCreate"||r==="TaskGet"||r==="TaskList"||r==="TaskUpdate"||r==="CronCreate"||r==="CronDelete"||r==="CronList"||r==="ScheduleWakeup"||r==="CoordinationQuery"||r==="CoordinationSend"||r==="Send"||r==="Receive"||r==="ListAgents"||r==="ListSessions"||r==="Artifact"||r==="Think"||r==="dispatch_agent"||r==="AskUser"||r==="WebSearch")return{decision:"allow",confidence:"high",reason:"read-only or conversational tool",risk:"low",matchedRules:["auto:read-only-tool-allow"]};if(r==="PushNotification"||r==="RemoteTrigger"||r==="EnterWorktree"||r==="ExitWorktree")return{decision:"ask",confidence:"high",reason:r==="PushNotification"?"notification delivery is an outward-facing action":r==="RemoteTrigger"?"remote trigger operations read or mutate an external control plane":"interactive worktree lifecycle mutates repository and process workspace state",risk:"high",matchedRules:["auto:harness-side-effect-ask"]};if(r==="Bash"){let o=typeof n.command=="string"?n.command:"";return this.isDangerousAutoBashCommand(o)?{decision:"deny",confidence:"high",reason:"destructive, publishing, deployment, or remote mutation shell command",risk:"critical",matchedRules:["auto:bash-danger-deny"]}:this.isLowRiskAutoBashCommand(o)?{decision:"allow",confidence:"medium",reason:"low-risk local inspection/test command",risk:"low",matchedRules:["auto:bash-safe-allow"]}:{decision:"ask",confidence:"medium",reason:"shell command requires confirmation",risk:"high",matchedRules:["auto:bash-ask"]}}return r==="WebFetch"?{decision:"ask",confidence:"medium",reason:"network fetch requires confirmation in auto mode",risk:"medium",matchedRules:["auto:network-ask"]}:r==="Write"||r==="Edit"||r==="NotebookEdit"||r==="MemoryWrite"||r==="GitCommit"||r==="TaskStop"?{decision:"ask",confidence:"medium",reason:"mutating tool requires confirmation",risk:"medium",matchedRules:["auto:mutation-ask"]}:{decision:"ask",confidence:"low",reason:"unknown tool requires confirmation",risk:"medium",matchedRules:["auto:unknown-ask"]}}contentDigest(e){let n=JSON.stringify(Object.keys(e).sort().map(r=>[r,e[r]]));return FC("sha256").update(n).digest("hex").slice(0,16)}hasShellComposition(e){return GC.test(e)}getCacheKey(e,n){let r=W(e);if(r==="Bash"){let s=typeof n.command=="string"?n.command:"";if(this.hasShellComposition(s))return`${r}!${this.normalizeCommandText(s)}`;let i=this.getCommandPrefix(e,n);return`${r}:${i||"*"}`}if(Ny.has(r))return`${r}:*`;if(r==="MemoryRead"||r==="MemoryWrite"){let s=Ly.has(r)?`#${this.contentDigest(n)}`:"";if(typeof n.file_path=="string"&&n.file_path.trim().length>0)return`${r}:${wt(this.resolveTargetPath(n.file_path))}${s}`;let i=typeof n.level=="string"&&n.level.trim().length>0?n.level.trim().toLowerCase():r==="MemoryRead"?"all":"*";return`${r}:${i}${s}`}if(nn.has(r)){let s=this.extractFilePath(r,n);if(s){let i=`${r}:${wt(this.resolveTargetPath(s))}`;return Ly.has(r)?`${i}#${this.contentDigest(n)}`:i}}let o=Object.entries(n).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>typeof i=="string"?`${s}=${i}`:`${s}=${JSON.stringify(i)}`).join("&");return o.length===0?`${r}:*`:`${r}:${o}`}isPathInPersistentAllowedDirectory(e){if(this.persistentAllowedDirectories.size===0)return!1;let n=wt(this.resolveTargetPath(e));for(let r of this.persistentAllowedDirectories)if(n.startsWith(r))return!0;return!1}normalizePersistentApprovalKey(e){let n=e.indexOf(":"),r=n>=0?e.slice(0,n):e,o=W(r);return Ny.has(o)?`${o}:*`:e}extractFilePath(e,n){return typeof n.file_path=="string"&&n.file_path.length>0?n.file_path:typeof n.path=="string"&&n.path.length>0?n.path:typeof n.filePath=="string"&&n.filePath.length>0?n.filePath:typeof n.notebook_path=="string"&&n.notebook_path.length>0?n.notebook_path:null}extractDirectory(e,n){let r=this.extractFilePath(e,n);if(!r)return null;let o=W(e);return o==="Glob"||o==="Grep"||o==="LS"?wt(this.resolveTargetPath(r)):qC(wt(this.resolveTargetPath(r)))}normalizeDirectory(e){let n=wt(this.resolveTargetPath(e));return n.endsWith(Oy)||(n+=Oy),n}async promptUser(e,n,r,o){let s=this.getToolDetail(e,n),i=r?`${r} requests permission to use ${e}`:void 0,a=W(e);if(this.promptFn){let m=n.description!==void 0&&n.description!==null?String(n.description):void 0,p=nn.has(a)?this.extractFilePath(a,n):void 0,g=nn.has(a)?this.extractDirectory(a,n):void 0,f=await My(this.workingDirectory,e,n),b={toolName:e,detail:s,description:m,...o!==void 0?{operation:"generic",preview:{title:"Terminal input preview",summary:"Ephemeral preview; not written to audit or session history.",lines:[{kind:"context",text:o}]}}:f,commandPrefix:this.getCommandPrefix(e,n),approvalKey:this.getCacheKey(e,n),requesterLabel:r,requesterSummary:i,directory:g??void 0,filePath:p??void 0},y=await this.promptFn(b);if(y==="always"){if(g&&nn.has(a))return this.allowDirectory(g),{allowed:!0,directoryCached:!0,persist:!0};let x=this.getCacheKey(e,n);return this.sessionAllowed.add(x),{allowed:!0,directoryCached:!1,persist:!0}}return{allowed:y==="allow",directoryCached:!1,persist:!1}}if(!process.stdin.isTTY)return{allowed:!1,directoryCached:!1,persist:!1};let c=s.length>60?s.slice(0,60)+"...":s,l=r?`${r} \xB7 `:"",u=`${Vr.bold(`${l}${e}`)}: ${c} Allow? ${Vr.dim("[y/N/a]")}`,d=UC({input:process.stdin,output:process.stderr});return new Promise(m=>{let p=!1,g=h=>{p||(p=!0,m(h))},f=()=>g({allowed:!1,directoryCached:!1,persist:!1});d.once("close",f),d.question(`
|
|
1993
|
+
`).map(e=>e.endsWith("\r")?e.slice(0,-1):e)}function Jr(t,e){let n=e.length>180?`${e.slice(0,177)}...`:e;return`${String(t).padStart(4)} | ${n.length>0?n:"(blank)"}`}function Ry(t,e,n,r){let o=Ei(e),s=Ei(n),i=0,a=Math.min(o.length,s.length);for(;i<a&&o[i]===s[i];)i+=1;let c=o.length-1,l=s.length-1;for(;c>=i&&l>=i&&o[c]===s[l];)c-=1,l-=1;let u=Math.max(0,i-Py),d=Math.min(s.length,l+1+Py),m=[];for(let p=u;p<i;p+=1)m.push({kind:"context",text:Jr(p+1,s[p]??"")});for(let p=i;p<=c;p+=1)m.push({kind:"remove",text:Jr(p+1,o[p]??"")});for(let p=i;p<=l;p+=1)m.push({kind:"add",text:Jr(p+1,s[p]??"")});for(let p=l+1;p<d;p+=1)m.push({kind:"context",text:Jr(p+1,s[p]??"")});return m.length===0&&m.push({kind:"meta",text:"No textual changes detected."}),{title:t,summary:r,lines:m.slice(0,Si),truncated:m.length>Si}}function Cy(t,e,n){let r=Ei(e).map((o,s)=>({kind:"add",text:Jr(s+1,o)}));return{title:t,summary:n,lines:r.slice(0,Si),truncated:r.length>Si}}function DC(t){let e=[],n=t.toLowerCase();/\bsudo\b|\bsu\b|\bdoas\b/.test(n)&&e.push("Requests elevated privileges."),/rm\s+-rf\b|remove-item\b.+-recurse/.test(n)&&e.push("Contains recursive deletion semantics."),/curl\b|wget\b|invoke-webrequest\b|invoke-restmethod\b/.test(n)&&e.push("Fetches data from the network.");let r=[{kind:"meta",text:t.length>220?`${t.slice(0,217)}...`:t},...e.map(o=>({kind:"meta",text:o}))];return{title:"Command preview",summary:e.length>0?`${e.length} warning${e.length===1?"":"s"}`:"No immediate danger markers detected",lines:r}}function yu(t,e){let n=typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:typeof e.notebook_path=="string"?e.notebook_path:typeof e.filePath=="string"?e.filePath:null;if(!n||n.trim().length===0)return null;try{return D(t,n)}catch{return null}}async function BC(t,e){let n=typeof e.file_path=="string"?e.file_path:"",r=typeof e.content=="string"?e.content:"",o=yu(t,e),s=`${Ei(r).length} line(s)`;if(!o||n.length===0)return{operation:"write"};if(!Ay(o))return{operation:"write",preview:Cy(`Create ${n}`,r,s)};try{let i=await Te(o);return{operation:"write",preview:Ry(`Overwrite ${n}`,i.content,r,s)}}catch{return{operation:"write"}}}async function $C(t,e){let n=typeof e.file_path=="string"?e.file_path:"",r=typeof e.old_string=="string"?e.old_string:"",o=typeof e.new_string=="string"?e.new_string:"",s=e.replace_all===!0,i=yu(t,e);if(!i||n.length===0)return{operation:"edit"};if(!Ay(i))return r.length===0?{operation:"edit",preview:Cy(`Create ${n} via Edit`,o)}:{operation:"edit",preview:{title:`Edit ${n}`,lines:[{kind:"meta",text:"Target file does not exist yet."}]}};try{let c=(await Te(i)).content;if(r.length===0)return{operation:"edit",preview:{title:`Edit ${n}`,lines:[{kind:"meta",text:"old_string is empty for an existing file; the edit tool will reject this."}]}};if(!c.includes(r))return{operation:"edit",preview:{title:`Edit ${n}`,lines:[{kind:"meta",text:"old_string was not found in the current file contents."}]}};if(!s){let u=c.indexOf(r);if(c.indexOf(r,u+r.length)!==-1)return{operation:"edit",preview:{title:`Edit ${n}`,lines:[{kind:"meta",text:"old_string is not unique in the file; the edit tool will require more context or replace_all."}]}}}let l=s?c.replaceAll(r,o):c.replace(r,o);return{operation:"edit",preview:Ry(`Edit ${n}`,c,l,s?"replace_all=true":"single replacement")}}catch{return{operation:"edit"}}}async function My(t,e,n){let r=W(e);if(r==="Write")return BC(t,n);if(r==="Edit")return $C(t,n);if(r==="Bash")return{operation:"bash",preview:DC(typeof n.command=="string"?n.command:"")};if(r==="Read"||r==="ReadImage"||r==="Glob"||r==="Grep"||r==="LS"||r==="ElfAnalyze"||r==="LspDefinition"||r==="LspDiagnostics"||r==="LspHover"||r==="LspReferences"||r==="NotebookRead"||r==="NotebookEdit"){let o=yu(t,n);return{operation:"filesystem",...o?{preview:{title:r==="LS"?"Filesystem target":"File target",lines:[{kind:"meta",text:o}]}}:{}}}return{operation:"generic"}}var nn=new Set(["Read","ReadImage","Write","Edit","Glob","Grep","LS","ElfAnalyze","NotebookRead","NotebookEdit","LspDefinition","LspDiagnostics","LspHover","LspReferences"]),XC=3,Ly=new Set(["Write","Edit","NotebookEdit","MemoryWrite"]),GC=/(?:&&|\|\||;|\||>|<|`|\$\()/,Ny=new Set(["BackgroundAgent","BackgroundAgentSession","BackgroundAgentSend","BackgroundAgentList","BackgroundAgentPeek","BackgroundAgentJoin","BackgroundAgentStop","BackgroundAgentEvents"]),Dy={Read:"allow",ReadImage:"allow",LS:"allow",Glob:"allow",Grep:"allow",ElfAnalyze:"allow",MemoryRead:"allow",dispatch_agent:"allow",Think:"allow",GitStatus:"allow",GitDiff:"allow",GitLog:"allow",GitBranch:"allow",WebSearch:"allow",WebFetch:"allow",AskUser:"allow",NotebookRead:"allow",LspDefinition:"ask",LspDiagnostics:"ask",LspHover:"ask",LspReferences:"ask",Write:"ask",Edit:"ask",MemoryWrite:"ask",NotebookEdit:"ask",Bash:"ask",GitCommit:"ask",TaskOutput:"allow",TaskStop:"ask",CoordinationQuery:"allow",CoordinationSend:"allow",Send:"allow",Receive:"allow",ListAgents:"allow",ListSessions:"allow",Artifact:"allow",ToolSearch:"allow"},zC=new Set(["Send","CoordinationSend"]),_i=class t{config;workingDirectory=process.cwd();sessionAllowed=new Set;sessionAllowedDirectories=new Set;persistentAllowed=new Set;persistentAllowedDirectories=new Set;promptFn;decisionHook;constructor(e,n,r){this.config={mode:e?.mode??"default",rules:e?.rules??[],...e?.profile?{profile:e.profile}:{}},this.promptFn=n,this.decisionHook=r}fork(e=this.promptFn){let n=new t({mode:this.config.mode,rules:[...this.config.rules],...this.config.profile?{profile:this.config.profile}:{}},e,this.decisionHook);return n.workingDirectory=this.workingDirectory,n.sessionAllowed=new Set(this.sessionAllowed),n.sessionAllowedDirectories=new Set(this.sessionAllowedDirectories),n.persistentAllowed=new Set(this.persistentAllowed),n.persistentAllowedDirectories=new Set(this.persistentAllowedDirectories),n}get mode(){return this.config.mode}setMode(e){this.config.mode!==e&&(this.config.mode=e,this.sessionAllowed.clear(),this.sessionAllowedDirectories.clear())}setWorkingDirectory(e){this.workingDirectory=e}setRules(e){this.config.rules=[...e]}loadPersistentState(e){this.persistentAllowed.clear(),this.persistentAllowedDirectories.clear();for(let n of e.allowedTools??[]){let r=this.normalizePersistentApprovalKey(n.trim());r.length>0&&this.persistentAllowed.add(r)}for(let n of e.allowedDirectories??[]){let r=n.trim();r.length>0&&this.persistentAllowedDirectories.add(this.normalizeDirectory(r))}}allowDirectory(e){let n=this.normalizeDirectory(e);this.sessionAllowedDirectories.add(n)}isPathInAllowedDirectory(e){if(this.sessionAllowedDirectories.size===0&&this.persistentAllowedDirectories.size===0)return!1;let n=wt(this.resolveTargetPath(e));for(let r of this.persistentAllowedDirectories)if(n.startsWith(r))return!0;for(let r of this.sessionAllowedDirectories)if(n.startsWith(r))return!0;return!1}async check(e,n,r){let o=W(e);if(o==="WebFetch"&&this.config.profile&&typeof n.url=="string"){let c=Vo(this.config.profile,n.url);if(!c.allowed)return this.finalizeDecision(e,n,!1,`profile network deny: ${c.reason}`,r?.traceId,r?.requesterLabel)}if(this.config.mode==="bypassPermissions")return this.finalizeDecision(e,n,!0,"bypass mode",r?.traceId,r?.requesterLabel);if(this.config.mode==="plan"&&((Dy[o]??"ask")!=="allow"||zC.has(o)))return this.finalizeDecision(e,n,!1,"plan mode",r?.traceId,r?.requesterLabel);for(let c of this.config.rules)if(this.matchesRule(c.tool,c.pattern,e,n)){if(c.decision==="allow"){if(o==="Bash"&&this.hasShellComposition(typeof n.command=="string"?n.command:""))continue;return this.finalizeDecision(e,n,!0,`rule: allow ${c.tool}`,r?.traceId,r?.requesterLabel)}if(c.decision==="deny")return this.finalizeDecision(e,n,!1,`rule: deny ${c.tool}`,r?.traceId,r?.requesterLabel)}if(this.config.mode==="auto"){let c=this.classifyAutoPermission(o,n);if(c.decision==="allow")return this.finalizeDecision(e,n,!0,`auto allow: ${c.reason}`,r?.traceId,r?.requesterLabel);if(c.decision==="deny")return this.finalizeDecision(e,n,!1,`auto deny: ${c.reason}`,r?.traceId,r?.requesterLabel);r?.onWaitStart?.();let l=await this.promptUser(e,n,r?.requesterLabel,r?.ephemeralInputPreview).finally(()=>r?.onWaitEnd?.());return l.persist&&!l.directoryCached&&this.sessionAllowed.add(this.getCacheKey(o,n)),this.finalizeDecision(e,n,l.allowed,l.allowed?`auto ask: user approved (${c.reason})`:`auto ask: user denied (${c.reason})`,r?.traceId,r?.requesterLabel)}let s=Dy[o]??"ask";if(s==="allow")return this.finalizeDecision(e,n,!0,"default allow",r?.traceId,r?.requesterLabel);if(s==="deny")return this.finalizeDecision(e,n,!1,"default deny",r?.traceId,r?.requesterLabel);if(this.config.mode==="acceptEdits"&&(o==="Write"||o==="Edit"))return this.finalizeDecision(e,n,!0,"acceptEdits mode",r?.traceId,r?.requesterLabel);if(nn.has(o)){let c=this.extractFilePath(o,n);if(c&&this.isPathInAllowedDirectory(c)){let l=this.isPathInPersistentAllowedDirectory(c)?"persistent directory approval":"directory auto-grant";return this.finalizeDecision(e,n,!0,l,r?.traceId,r?.requesterLabel)}}let i=this.getCacheKey(o,n);if(this.persistentAllowed.has(i))return this.finalizeDecision(e,n,!0,"persistent approval",r?.traceId,r?.requesterLabel);if(o==="Bash"&&this.hasBashApproval(this.persistentAllowed,n))return this.finalizeDecision(e,n,!0,"persistent approval",r?.traceId,r?.requesterLabel);if(this.sessionAllowed.has(i))return this.finalizeDecision(e,n,!0,"session approved",r?.traceId,r?.requesterLabel);if(o==="Bash"&&this.hasBashApproval(this.sessionAllowed,n))return this.finalizeDecision(e,n,!0,"session approved",r?.traceId,r?.requesterLabel);r?.onWaitStart?.();let a=await this.promptUser(e,n,r?.requesterLabel,r?.ephemeralInputPreview).finally(()=>r?.onWaitEnd?.());return a.persist&&!a.directoryCached&&this.sessionAllowed.add(i),this.finalizeDecision(e,n,a.allowed,a.allowed?"user approved":"user denied",r?.traceId,r?.requesterLabel)}async finalizeDecision(e,n,r,o,s,i){if(this.decisionHook)try{await this.decisionHook({traceId:s,toolName:e,input:n,allowed:r,reason:o,mode:this.config.mode,requesterLabel:i})}catch(a){xe("[PermissionEngine] decision hook failed",a)}return{allowed:r,reason:o}}classifyAutoPermission(e,n){let r=W(e);if(r==="Read"||r==="ReadImage"||r==="NotebookRead"){let o=this.extractFilePath(r,n);return o&&this.isCredentialLikePath(o)?{decision:"deny",confidence:"high",reason:"credential-like file read",risk:"critical",matchedRules:["auto:credential-read-deny"]}:{decision:"allow",confidence:"high",reason:"read-only file inspection",risk:"low",matchedRules:["auto:read-only-allow"]}}if(r==="Glob"||r==="Grep"||r==="LS"||r==="ElfAnalyze"||r==="ToolSearch"||r==="MemoryRead"||r==="GitStatus"||r==="GitDiff"||r==="GitLog"||r==="GitBranch"||r==="TaskOutput"||r==="TaskCreate"||r==="TaskGet"||r==="TaskList"||r==="TaskUpdate"||r==="CronCreate"||r==="CronDelete"||r==="CronList"||r==="ScheduleWakeup"||r==="CoordinationQuery"||r==="CoordinationSend"||r==="Send"||r==="Receive"||r==="ListAgents"||r==="ListSessions"||r==="Artifact"||r==="Think"||r==="dispatch_agent"||r==="AskUser"||r==="WebSearch")return{decision:"allow",confidence:"high",reason:"read-only or conversational tool",risk:"low",matchedRules:["auto:read-only-tool-allow"]};if(r==="PushNotification"||r==="RemoteTrigger"||r==="EnterWorktree"||r==="ExitWorktree")return{decision:"ask",confidence:"high",reason:r==="PushNotification"?"notification delivery is an outward-facing action":r==="RemoteTrigger"?"remote trigger operations read or mutate an external control plane":"interactive worktree lifecycle mutates repository and process workspace state",risk:"high",matchedRules:["auto:harness-side-effect-ask"]};if(r==="Bash"){let o=typeof n.command=="string"?n.command:"";return this.isDangerousAutoBashCommand(o)?{decision:"deny",confidence:"high",reason:"destructive, publishing, deployment, or remote mutation shell command",risk:"critical",matchedRules:["auto:bash-danger-deny"]}:this.isLowRiskAutoBashCommand(o)?{decision:"allow",confidence:"medium",reason:"low-risk local inspection/test command",risk:"low",matchedRules:["auto:bash-safe-allow"]}:{decision:"ask",confidence:"medium",reason:"shell command requires confirmation",risk:"high",matchedRules:["auto:bash-ask"]}}return r==="WebFetch"?{decision:"ask",confidence:"medium",reason:"network fetch requires confirmation in auto mode",risk:"medium",matchedRules:["auto:network-ask"]}:r==="Write"||r==="Edit"||r==="NotebookEdit"||r==="MemoryWrite"||r==="GitCommit"||r==="TaskStop"?{decision:"ask",confidence:"medium",reason:"mutating tool requires confirmation",risk:"medium",matchedRules:["auto:mutation-ask"]}:{decision:"ask",confidence:"low",reason:"unknown tool requires confirmation",risk:"medium",matchedRules:["auto:unknown-ask"]}}contentDigest(e){let n=JSON.stringify(Object.keys(e).sort().map(r=>[r,e[r]]));return FC("sha256").update(n).digest("hex").slice(0,16)}hasShellComposition(e){return GC.test(e)}getCacheKey(e,n){let r=W(e);if(r==="Bash"){let s=typeof n.command=="string"?n.command:"";if(this.hasShellComposition(s))return`${r}!${this.normalizeCommandText(s)}`;let i=this.getCommandPrefix(e,n);return`${r}:${i||"*"}`}if(Ny.has(r))return`${r}:*`;if(r==="MemoryRead"||r==="MemoryWrite"){let s=Ly.has(r)?`#${this.contentDigest(n)}`:"";if(typeof n.file_path=="string"&&n.file_path.trim().length>0)return`${r}:${wt(this.resolveTargetPath(n.file_path))}${s}`;let i=typeof n.level=="string"&&n.level.trim().length>0?n.level.trim().toLowerCase():r==="MemoryRead"?"all":"*";return`${r}:${i}${s}`}if(nn.has(r)){let s=this.extractFilePath(r,n);if(s){let i=`${r}:${wt(this.resolveTargetPath(s))}`;return Ly.has(r)?`${i}#${this.contentDigest(n)}`:i}}let o=Object.entries(n).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>typeof i=="string"?`${s}=${i}`:`${s}=${JSON.stringify(i)}`).join("&");return o.length===0?`${r}:*`:`${r}:${o}`}isPathInPersistentAllowedDirectory(e){if(this.persistentAllowedDirectories.size===0)return!1;let n=wt(this.resolveTargetPath(e));for(let r of this.persistentAllowedDirectories)if(n.startsWith(r))return!0;return!1}normalizePersistentApprovalKey(e){let n=e.indexOf(":"),r=n>=0?e.slice(0,n):e,o=W(r);return Ny.has(o)?`${o}:*`:e}extractFilePath(e,n){return typeof n.file_path=="string"&&n.file_path.length>0?n.file_path:typeof n.path=="string"&&n.path.length>0?n.path:typeof n.filePath=="string"&&n.filePath.length>0?n.filePath:typeof n.notebook_path=="string"&&n.notebook_path.length>0?n.notebook_path:null}extractDirectory(e,n){let r=this.extractFilePath(e,n);if(!r)return null;let o=W(e);return o==="Glob"||o==="Grep"||o==="LS"?wt(this.resolveTargetPath(r)):qC(wt(this.resolveTargetPath(r)))}normalizeDirectory(e){let n=wt(this.resolveTargetPath(e));return n.endsWith(Oy)||(n+=Oy),n}async promptUser(e,n,r,o){let s=this.getToolDetail(e,n),i=r?`${r} requests permission to use ${e}`:void 0,a=W(e);if(this.promptFn){let m=n.description!==void 0&&n.description!==null?String(n.description):void 0,p=nn.has(a)?this.extractFilePath(a,n):void 0,g=nn.has(a)?this.extractDirectory(a,n):void 0,f=await My(this.workingDirectory,e,n),b={toolName:e,detail:s,description:m,...o!==void 0?{operation:"generic",preview:{title:"Terminal input preview",summary:"Ephemeral preview; not written to audit or session history.",lines:[{kind:"context",text:o}]}}:f,commandPrefix:this.getCommandPrefix(e,n),approvalKey:this.getCacheKey(e,n),requesterLabel:r,requesterSummary:i,directory:g??void 0,filePath:p??void 0},y=await this.promptFn(b);if(y==="always"){if(g&&nn.has(a))return this.allowDirectory(g),{allowed:!0,directoryCached:!0,persist:!0};let x=this.getCacheKey(e,n);return this.sessionAllowed.add(x),{allowed:!0,directoryCached:!1,persist:!0}}return{allowed:y==="allow",directoryCached:!1,persist:!1}}if(!process.stdin.isTTY)return{allowed:!1,directoryCached:!1,persist:!1};let c=s.length>60?s.slice(0,60)+"...":s,l=r?`${r} \xB7 `:"",u=`${Vr.bold(`${l}${e}`)}: ${c} Allow? ${Vr.dim("[y/N/a]")}`,d=UC({input:process.stdin,output:process.stderr});return new Promise(m=>{let p=!1,g=h=>{p||(p=!0,m(h))},f=()=>g({allowed:!1,directoryCached:!1,persist:!1});d.once("close",f),d.question(`
|
|
1994
1994
|
${Vr.yellow("\u26A0")} ${u} `,h=>{d.close();let b=h.trim().toLowerCase();if(b==="a"||b==="always"){let y=nn.has(a)?this.extractDirectory(a,n):null;y?(this.allowDirectory(y),g({allowed:!0,directoryCached:!0,persist:!0})):(this.sessionAllowed.add(this.getCacheKey(e,n)),g({allowed:!0,directoryCached:!1,persist:!0}))}else g({allowed:b==="y"||b==="yes",directoryCached:!1,persist:!1})})})}getToolDetail(e,n){switch(W(e)){case"Bash":return String(n.command??"");case"Write":case"Edit":case"ElfAnalyze":return String(n.file_path??"");case"ReadImage":return String(n.path??"");case"NotebookRead":case"NotebookEdit":return String(n.notebook_path??"");case"LspDefinition":case"LspDiagnostics":case"LspHover":case"LspReferences":return String(n.file_path??"");case"LS":case"Glob":case"Grep":return String(n.path??"");case"AskUser":return String(n.question??"");case"dispatch_agent":return String(n.prompt??"");case"MemoryRead":case"MemoryWrite":return String(n.file_path??n.level??"");default:return""}}getCommandPrefix(e,n){if(e==="Bash"){let r=typeof n.command=="string"?n.command:"";return this.extractBashCommandPrefix(r)}return e}matchesRule(e,n,r,o){let s=W(r),i=e==="*"?e:W(e);if(i!=="*"&&i!==s)return!1;if(!n||n.trim().length===0)return!0;let a=n.trim();if(s==="Bash"){let c=typeof o.command=="string"?o.command:"";return this.matchesBashPattern(c,a)}if(nn.has(s)){let c=this.extractFilePath(s,o);if(!c)return!1;let l=wt(this.resolveTargetPath(c)),u=wt(this.resolveTargetPath(a));return l===u||l.startsWith(this.normalizeDirectory(u))}return this.getToolDetail(r,o).includes(a)}matchesBashPattern(e,n){let r=this.normalizeCommandText(n),o=this.normalizeCommandText(e),s=this.extractBashCommandPrefix(e);return r.includes("*")?this.matchesWildcard(o,r):o===r||o.startsWith(`${r} `)||s===r||s.startsWith(`${r} `)}matchesWildcard(e,n){let r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}isCredentialLikePath(e){let n=e.replace(/\\/g,"/").toLowerCase(),r=n.split("/").filter(s=>s.length>0),o=r.at(-1)??n;return o===".env"||o.startsWith(".env.")||o===".npmrc"||o===".pypirc"||o===".netrc"||o==="id_rsa"||o==="id_dsa"||o==="id_ecdsa"||o==="id_ed25519"||o.endsWith(".pem")||o.endsWith(".key")||o.endsWith(".p12")||o.endsWith(".pfx")?!0:r.includes(".ssh")||r.includes(".gnupg")}isDangerousAutoBashCommand(e){let n=this.normalizeCommandText(e).toLowerCase();return n?[/\brm\s+(-[^\s]*r[^\s]*f|-rf|-fr)\s+(\/|~|[a-z]:\\?)/i,/\b(git\s+push|git\s+reset\s+--hard|git\s+clean\s+-[^\s]*f)/i,/\b(npm|pnpm|yarn)\s+publish\b/i,/\bnpx\s+.*\s+publish\b/i,/\b(vercel|netlify|firebase)\s+deploy\b/i,/\b(terraform|tofu)\s+(apply|destroy)\b/i,/\bkubectl\s+(apply|delete|replace|scale|rollout)\b/i,/\bdocker\s+(push|rm|rmi|system\s+prune)\b/i,/\bchmod\s+-r\b/i,/\bchown\s+-r\b/i,/\b(curl|wget)\b.*\|\s*(sh|bash|pwsh|powershell)\b/i,/\bsetx\b.*(token|secret|key|password)/i].some(o=>o.test(n)):!0}isLowRiskAutoBashCommand(e){let n=this.normalizeCommandText(e);return!n||/[;&|`>$]/.test(n)?!1:[/^git (status|diff|log|show|branch)(\s|$)/i,/^(npm|pnpm|yarn) (test|run test|run lint|run typecheck|run build)(\s|$)/i,/^(node|npm|pnpm|yarn) (--version|-v)$/i,/^(pwd|dir|ls)(\s|$)/i].some(r=>r.test(n))}hasBashApproval(e,n){let r=typeof n.command=="string"?n.command:"";if(this.hasShellComposition(r))return!1;let o=this.normalizeCommandText(r),s=this.extractBashCommandPrefix(r);for(let i of e){if(!i.startsWith("Bash:"))continue;let a=this.normalizeCommandText(i.slice(5));if(!a||a==="*"||o===a||o.startsWith(`${a} `)||s===a||s.startsWith(`${a} `))return!0}return!1}extractBashCommandPrefix(e){let n=this.normalizeCommandText(e);if(!n)return"";let o=(n.split(/(?:&&|\|\||;|\|)/,1)[0]?.trim()??n).split(" ").filter(i=>i.length>0);return o.length===0?"":o.slice(0,XC).join(" ").trim()}normalizeCommandText(e){return e.trim().replace(/\s+/g," ")}resolveTargetPath(e){return jC(this.workingDirectory,e)}};var WC={pixel:"XENO Pixel (Image Editor)",motion:"XENO Motion (Video Editor)",sound:"XENO Sound (Audio Editor / DAW)"},ki=class{provider;setProvider(e){this.provider=e}getContext(){return this.provider?this.provider():{app:"pixel"}}formatForPrompt(){if(!this.provider)return"";let e=this.provider(),n=[];if(n.push("[Current Context]"),n.push(`App: ${WC[e.app]??e.app}`),e.document){let r=e.document.modified?" (unsaved changes)":"";n.push(`Document: ${e.document.name}${r}`),e.document.path&&n.push(`Path: ${e.document.path}`)}return e.app==="pixel"&&(e.activeLayer&&n.push(`Active Layer: "${e.activeLayer.name}" (${e.activeLayer.type}, id: ${e.activeLayer.id})`),e.selectedTool&&n.push(`Selected Tool: ${e.selectedTool}`),e.canvasSize&&n.push(`Canvas: ${e.canvasSize.width} x ${e.canvasSize.height}px`)),e.app==="motion"&&(e.currentFrame!==void 0&&n.push(`Playhead: frame ${e.currentFrame}`),e.selectedClip&&n.push(`Selected Clip: "${e.selectedClip.name}" (${e.selectedClip.type}, id: ${e.selectedClip.id})`),e.timelineLength!==void 0&&n.push(`Timeline Length: ${e.timelineLength} frames`)),e.app==="sound"&&(e.bpm!==void 0&&n.push(`BPM: ${e.bpm}`),e.currentPosition!==void 0&&n.push(`Position: ${e.currentPosition.toFixed(2)}s`),e.selectedTrack&&n.push(`Selected Track: "${e.selectedTrack.name}" (id: ${e.selectedTrack.id})`),e.isRecording&&n.push("Status: RECORDING")),n.join(`
|
|
1995
1995
|
`)}};var HC=`You are an AI assistant embedded in XENO Pixel, a professional image editor.
|
|
1996
1996
|
|