@xenosystem/agent-sdk 0.9.34 → 0.9.35

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.
@@ -48,7 +48,7 @@ ${this.stringify(e.data)}
48
48
  `)+`
49
49
  `;await k(this.transcriptPath,a);let l=this.buildMarkdownDocument(o,"session store");if(await k(this.markdownPath,l),!this.workspaceMirrorDisabled){let c=await this.resolveWorkspaceMarkdownPath();if(c)try{let u=this.buildMarkdownDocument(o,"workspace mirror");await k(c,u)}catch(u){this.workspaceMirrorDisabled=!0,L("Transcript workspace mirror disabled",u)}}}async truncateAfterMessageCount(e){let t=await x(this.transcriptPath);if(!t)return;let r=Z(t),s=Math.max(0,e),i=0,o=[];for(let c of r){if(c.type==="user_message"||c.type==="assistant_message"){if(i>=s)break;i+=1}o.push(c)}let a=o.length>0?o.map(c=>JSON.stringify(c)).join(`
50
50
  `)+`
51
- `:"";await k(this.transcriptPath,a);let l=this.buildMarkdownDocument(o,"session store");if(await k(this.markdownPath,l),!this.workspaceMirrorDisabled){let c=await this.resolveWorkspaceMarkdownPath();if(c)try{let u=this.buildMarkdownDocument(o,"workspace mirror");await k(c,u)}catch(u){this.workspaceMirrorDisabled=!0,L("Transcript workspace mirror disabled",u)}}}getSequence(){return this.sequence}async initialize(){try{let e=await x(this.transcriptPath);if(!e){this.sequence=0;return}let t=Z(e);if(t.length===0){this.sequence=0;return}let r=t[t.length-1];this.sequence=r.sequence+1}catch(e){let t=e instanceof Error?e.message:String(e);L(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};var ee=_(require("path"),1),lt=require("crypto"),ut=require("fs/promises");var qt={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit"};function fe(n){return qt[n]??n}var I=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=ee.join(e,"checkpoints"),this.autoInterval=t?.autoInterval??10}async initialize(){let e=await this.list();e.length>0&&(this.lastCheckpointMessageCount=e[0].messageCount)}async create(e){await N(this.checkpointsDir);let t=(0,lt.randomUUID)(),r={id:t,name:e.description,trigger:e.trigger,createdAt:new Date().toISOString(),messageCount:e.messages.length,tokenCount:this.estimateTokens(e.messages)},s={info:r,messages:e.messages},i=ee.join(this.checkpointsDir,`${t}.json`);return await k(i,JSON.stringify(s,null,2)),this.lastCheckpointMessageCount=e.messages.length,r}async list(){let e=await Ze(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await x(r);if(s){let i=E(s,null);if(i){let o=await(0,ut.stat)(r);t.push({info:i.info,modifiedAtMs:o.mtimeMs})}}}return t.sort((r,s)=>new Date(s.info.createdAt).getTime()-new Date(r.info.createdAt).getTime()||s.modifiedAtMs-r.modifiedAtMs).map(({info:r})=>r)}async restore(e){let t=ee.join(this.checkpointsDir,`${e}.json`),r;try{r=await x(t)}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to read checkpoint ${e}: ${o}`)}if(!r)throw new Error(`Checkpoint not found: ${e} (path: ${t})`);let s=E(r,null);if(!s)throw new Error(`Invalid checkpoint data for ${e}: JSON parse failed`);if(!s.messages||!Array.isArray(s.messages))throw new Error(`Invalid checkpoint data for ${e}: missing or invalid messages array`);if(!s.info)throw new Error(`Invalid checkpoint data for ${e}: missing info object`);return{messages:s.messages,info:s.info}}shouldAutoCheckpoint(e){return e-this.lastCheckpointMessageCount>=this.autoInterval}static isDangerousOperation(e,t){if(e=fe(e),e==="Write")return!0;if(e==="Bash"){let s=t.command?.toLowerCase()||"";return["rm ","del ","git push","git reset","drop ","truncate"].some(o=>s.includes(o))}return!1}async delete(e){let t=ee.join(this.checkpointsDir,`${e}.json`);await $(t)}estimateTokens(e){let t=0;for(let r of e)if(typeof r.content=="string")t+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let s of r.content)"text"in s&&(t+=Math.ceil(s.text.length/4));return t}};var F=_(require("path"),1),$e=_(require("os"),1),j=_(require("fs"),1);var Jt=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),Vt=globalThis,Oe=Vt[Jt]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},Ne=Oe.cleanups;function zt(){for(let n of Ne)try{n()}catch{}}function dt(n){return Ne.add(n),!Oe.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(Oe.exitHandlerRegistered=!0,process.on("exit",zt)),()=>{Ne.delete(n)}}var pt="0.9.34";var Xt=1e4,Kt=6e4,Yt="session.lock",Qt="lock.json",Q=new Map;function Be(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function Zt(){for(let[n,e]of Q)try{let t=E(j.readFileSync(n,"utf8"),null);Be(t,e)&&j.unlinkSync(n)}catch{}Q.clear()}dt(Zt);var U=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=F.join(e,Yt),this.legacyLockPath=F.join(e,Qt),this.sessionId=F.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:$e.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:pt,acquiredAt:e,updatedAt:e,heartbeat:e},r=F.dirname(this.lockPath);await j.promises.mkdir(r,{recursive:!0});let s=await this.findExistingLockPath();if(s){if(!await this.isStalePath(s)){let o=await this.readLockAt(s);throw new Error(`Session ${this.sessionId} is already locked by PID ${o?.pid} on ${o?.hostname}`)}await $(s)}try{await j.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,Q.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let l=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${l?.pid} on ${l?.hostname}`)}await $(this.lockPath);try{await j.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(l){throw l.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):l}this.acquiredOwner=t,Q.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;Q.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);Be(t,e)&&await $(this.lockPath)}async isLocked(){let e=await this.findExistingLockPath();return e?!await this.isStalePath(e):!1}async isStale(){let e=await this.findExistingLockPath();return e?this.isStalePath(e):!1}async isStalePath(e){let t=await this.readLockAt(e);if(!t)return!1;if(t.hostname===$e.hostname())try{return process.kill(t.pid,0),!1}catch(i){return i.code!=="EPERM"}let r=new Date(t.heartbeat).getTime();return Date.now()-r>Kt}startHeartbeat(e=Xt){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(t){let r=t instanceof Error?t.message:String(t);if(t?.code==="ENOENT"){W("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}W(`SessionLock: Failed to update heartbeat: ${r}`)}},e),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let e=await this.readLockAt(this.lockPath),t=this.acquiredOwner;if(!(!e||!t)){if(!Be(e,t)){this.acquiredOwner=void 0,Q.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await k(this.lockPath,JSON.stringify(e,null,2))}}async readLock(){let e=await this.findExistingLockPath();return e?this.readLockAt(e):null}async readLockAt(e){let t=await x(e);return t?E(t,null):null}async findExistingLockPath(){return await x(this.lockPath)?this.lockPath:await x(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let t=await le(e),r=[];for(let s of t){let i=new n(s);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await $(a),r.push(F.basename(s))}}return r}};var A=_(require("path"),1);var C=_(require("path"),1);function er(n,e){let t=C.resolve(n),r=C.resolve(n,e);return r===t?!0:t===C.parse(t).root?r.startsWith(t):r.startsWith(t+C.sep)}function q(n,e){if(C.isAbsolute(e))return C.resolve(e);if(!er(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return C.resolve(n,e)}function J(n){if(n!==void 0&&n!=="agent"&&n!=="chatOnly")throw new Error("Invalid session execution mode; expected agent or chatOnly.")}var T=_(require("path"),1),ye=_(require("os"),1),R=_(require("node:fs/promises"),1),we=require("node:crypto");var V=require("node:os");var Le=require("node:path"),Kr=(0,V.platform)();var Yr=(0,V.release)(),Qr=(0,V.homedir)();function me(){let n=process.env.XENO_AGENT_HOME?.trim();return n?(0,Le.resolve)(n):(0,Le.resolve)((0,V.homedir)(),".xeno-agent")}var gt=1,ft="recent.json",tr=".lock",ht=".entries",rr=3e4,je=6e4,yt=new Set(["EACCES","EBUSY","EPERM"]),nr=[5,10,20,40,80,160,320],he=new Map;function sr(n,e){let t=(0,we.createHash)("sha256").update(e).digest("hex");return T.join(`${n}${ht}`,`${t}.json`)}async function Fe(n,e,t){let r={schemaVersion:1,key:e,entry:t};await k(sr(n,e),JSON.stringify(r)+`
51
+ `:"";await k(this.transcriptPath,a);let l=this.buildMarkdownDocument(o,"session store");if(await k(this.markdownPath,l),!this.workspaceMirrorDisabled){let c=await this.resolveWorkspaceMarkdownPath();if(c)try{let u=this.buildMarkdownDocument(o,"workspace mirror");await k(c,u)}catch(u){this.workspaceMirrorDisabled=!0,L("Transcript workspace mirror disabled",u)}}}getSequence(){return this.sequence}async initialize(){try{let e=await x(this.transcriptPath);if(!e){this.sequence=0;return}let t=Z(e);if(t.length===0){this.sequence=0;return}let r=t[t.length-1];this.sequence=r.sequence+1}catch(e){let t=e instanceof Error?e.message:String(e);L(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};var ee=_(require("path"),1),lt=require("crypto"),ut=require("fs/promises");var qt={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit"};function fe(n){return qt[n]??n}var I=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=ee.join(e,"checkpoints"),this.autoInterval=t?.autoInterval??10}async initialize(){let e=await this.list();e.length>0&&(this.lastCheckpointMessageCount=e[0].messageCount)}async create(e){await N(this.checkpointsDir);let t=(0,lt.randomUUID)(),r={id:t,name:e.description,trigger:e.trigger,createdAt:new Date().toISOString(),messageCount:e.messages.length,tokenCount:this.estimateTokens(e.messages)},s={info:r,messages:e.messages},i=ee.join(this.checkpointsDir,`${t}.json`);return await k(i,JSON.stringify(s,null,2)),this.lastCheckpointMessageCount=e.messages.length,r}async list(){let e=await Ze(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await x(r);if(s){let i=E(s,null);if(i){let o=await(0,ut.stat)(r);t.push({info:i.info,modifiedAtMs:o.mtimeMs})}}}return t.sort((r,s)=>new Date(s.info.createdAt).getTime()-new Date(r.info.createdAt).getTime()||s.modifiedAtMs-r.modifiedAtMs).map(({info:r})=>r)}async restore(e){let t=ee.join(this.checkpointsDir,`${e}.json`),r;try{r=await x(t)}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to read checkpoint ${e}: ${o}`)}if(!r)throw new Error(`Checkpoint not found: ${e} (path: ${t})`);let s=E(r,null);if(!s)throw new Error(`Invalid checkpoint data for ${e}: JSON parse failed`);if(!s.messages||!Array.isArray(s.messages))throw new Error(`Invalid checkpoint data for ${e}: missing or invalid messages array`);if(!s.info)throw new Error(`Invalid checkpoint data for ${e}: missing info object`);return{messages:s.messages,info:s.info}}shouldAutoCheckpoint(e){return e-this.lastCheckpointMessageCount>=this.autoInterval}static isDangerousOperation(e,t){if(e=fe(e),e==="Write")return!0;if(e==="Bash"){let s=t.command?.toLowerCase()||"";return["rm ","del ","git push","git reset","drop ","truncate"].some(o=>s.includes(o))}return!1}async delete(e){let t=ee.join(this.checkpointsDir,`${e}.json`);await $(t)}estimateTokens(e){let t=0;for(let r of e)if(typeof r.content=="string")t+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let s of r.content)"text"in s&&(t+=Math.ceil(s.text.length/4));return t}};var F=_(require("path"),1),$e=_(require("os"),1),j=_(require("fs"),1);var Jt=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),Vt=globalThis,Oe=Vt[Jt]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},Ne=Oe.cleanups;function zt(){for(let n of Ne)try{n()}catch{}}function dt(n){return Ne.add(n),!Oe.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(Oe.exitHandlerRegistered=!0,process.on("exit",zt)),()=>{Ne.delete(n)}}var pt="0.9.35";var Xt=1e4,Kt=6e4,Yt="session.lock",Qt="lock.json",Q=new Map;function Be(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function Zt(){for(let[n,e]of Q)try{let t=E(j.readFileSync(n,"utf8"),null);Be(t,e)&&j.unlinkSync(n)}catch{}Q.clear()}dt(Zt);var U=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=F.join(e,Yt),this.legacyLockPath=F.join(e,Qt),this.sessionId=F.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:$e.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:pt,acquiredAt:e,updatedAt:e,heartbeat:e},r=F.dirname(this.lockPath);await j.promises.mkdir(r,{recursive:!0});let s=await this.findExistingLockPath();if(s){if(!await this.isStalePath(s)){let o=await this.readLockAt(s);throw new Error(`Session ${this.sessionId} is already locked by PID ${o?.pid} on ${o?.hostname}`)}await $(s)}try{await j.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,Q.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let l=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${l?.pid} on ${l?.hostname}`)}await $(this.lockPath);try{await j.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(l){throw l.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):l}this.acquiredOwner=t,Q.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;Q.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);Be(t,e)&&await $(this.lockPath)}async isLocked(){let e=await this.findExistingLockPath();return e?!await this.isStalePath(e):!1}async isStale(){let e=await this.findExistingLockPath();return e?this.isStalePath(e):!1}async isStalePath(e){let t=await this.readLockAt(e);if(!t)return!1;if(t.hostname===$e.hostname())try{return process.kill(t.pid,0),!1}catch(i){return i.code!=="EPERM"}let r=new Date(t.heartbeat).getTime();return Date.now()-r>Kt}startHeartbeat(e=Xt){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(t){let r=t instanceof Error?t.message:String(t);if(t?.code==="ENOENT"){W("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}W(`SessionLock: Failed to update heartbeat: ${r}`)}},e),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let e=await this.readLockAt(this.lockPath),t=this.acquiredOwner;if(!(!e||!t)){if(!Be(e,t)){this.acquiredOwner=void 0,Q.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await k(this.lockPath,JSON.stringify(e,null,2))}}async readLock(){let e=await this.findExistingLockPath();return e?this.readLockAt(e):null}async readLockAt(e){let t=await x(e);return t?E(t,null):null}async findExistingLockPath(){return await x(this.lockPath)?this.lockPath:await x(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let t=await le(e),r=[];for(let s of t){let i=new n(s);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await $(a),r.push(F.basename(s))}}return r}};var A=_(require("path"),1);var C=_(require("path"),1);function er(n,e){let t=C.resolve(n),r=C.resolve(n,e);return r===t?!0:t===C.parse(t).root?r.startsWith(t):r.startsWith(t+C.sep)}function q(n,e){if(C.isAbsolute(e))return C.resolve(e);if(!er(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return C.resolve(n,e)}function J(n){if(n!==void 0&&n!=="agent"&&n!=="chatOnly")throw new Error("Invalid session execution mode; expected agent or chatOnly.")}var T=_(require("path"),1),ye=_(require("os"),1),R=_(require("node:fs/promises"),1),we=require("node:crypto");var V=require("node:os");var Le=require("node:path"),Kr=(0,V.platform)();var Yr=(0,V.release)(),Qr=(0,V.homedir)();function me(){let n=process.env.XENO_AGENT_HOME?.trim();return n?(0,Le.resolve)(n):(0,Le.resolve)((0,V.homedir)(),".xeno-agent")}var gt=1,ft="recent.json",tr=".lock",ht=".entries",rr=3e4,je=6e4,yt=new Set(["EACCES","EBUSY","EPERM"]),nr=[5,10,20,40,80,160,320],he=new Map;function sr(n,e){let t=(0,we.createHash)("sha256").update(e).digest("hex");return T.join(`${n}${ht}`,`${t}.json`)}async function Fe(n,e,t){let r={schemaVersion:1,key:e,entry:t};await k(sr(n,e),JSON.stringify(r)+`
52
52
  `)}async function ir(n,e){let t=`${n}${ht}`,r;try{r=await R.readdir(t)}catch(s){if(s.code==="ENOENT")return;throw s}await Promise.all(r.filter(s=>s.endsWith(".json")).map(async s=>{let i=await R.readFile(T.join(t,s),"utf8").catch(()=>""),o=E(i,null);if(!(!o||o.schemaVersion!==1||typeof o.key!="string")){if(o.entry===null){delete e[o.key];return}typeof o.entry.sessionId!="string"||typeof o.entry.endedAt!="string"||(e[o.key]=o.entry)}}))}function mt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function or(n){try{let[e,t]=await Promise.all([R.readFile(T.join(n,"owner.json"),"utf8").catch(()=>""),R.stat(n)]),r=E(e,null);return r?.hostname===ye.hostname()&&mt(r.pid)?!1:r?.hostname&&r.hostname!==ye.hostname()||!r?Date.now()-t.mtimeMs>je:Date.now()-t.mtimeMs>je||!mt(r.pid)}catch{return!1}}async function wt(n){for(let e=0;;e+=1)try{await R.rm(n,{recursive:!0});return}catch(t){let r=t.code;if(r==="ENOENT")return;let s=nr[e];if(process.platform!=="win32"||!r||!yt.has(r)||s===void 0)throw t;await new Promise(i=>setTimeout(i,s))}}async function ar(n,e){try{let t=await R.readFile(T.join(n,"owner.json"),"utf8");E(t,null)?.token===e&&await wt(n)}catch(t){if(t.code!=="ENOENT")throw t}}async function He(n,e){let t=z(n),r=he.get(t)??Promise.resolve(),s,i=new Promise(o=>{s=o});he.set(t,i),await r;try{return await cr(t,e)}finally{s(),he.get(t)===i&&he.delete(t)}}async function cr(n,e){let t=`${n}${tr}`,r=(0,we.randomUUID)(),s=Date.now();await R.mkdir(T.dirname(n),{recursive:!0});for(let i=0;;i+=1){let o={schemaVersion:1,token:r,pid:process.pid,hostname:ye.hostname(),acquiredAt:new Date().toISOString()};try{await R.mkdir(t),await R.writeFile(T.join(t,"owner.json"),JSON.stringify(o),"utf8");break}catch(a){let l=a.code,c=process.platform==="win32"&&!!l&&yt.has(l);if(l!=="EEXIST"&&!c)throw a;if(await or(t)){await wt(t);continue}if(Date.now()-s>=rr)throw new Error(`Timed out waiting for recent-sessions index lock: ${t}`);let u=Math.min(100,5+i*5)+Math.floor(Math.random()*10);await new Promise(p=>setTimeout(p,u))}}try{return await e()}finally{await ar(t,r)}}function z(n){return n===void 0?T.join(me(),ft):T.join(n,".xeno-agent",ft)}function te(n){let e=T.normalize(n).replace(/[\\/]+$/,""),t=e.length>0?e:T.parse(T.normalize(n)).root;return process.platform==="win32"?t.toLowerCase():t}async function H(n){let e=z(n),t=ce(e)?await x(e):null,r=t?E(t,null):null,s=r&&typeof r=="object"?r:null,i={},o=s?.version===gt&&s.entries&&typeof s.entries=="object"?s.entries:{};for(let[a,l]of Object.entries(o)){if(!l||typeof l!="object")continue;let c=l;typeof c.sessionId!="string"||c.sessionId.length===0||typeof c.endedAt=="string"&&(i[a]={sessionId:c.sessionId,endedAt:c.endedAt,role:typeof c.role=="string"?c.role:void 0})}return await ir(e,i),{version:gt,entries:i}}async function Se(n,e={}){let t=await H(e.homeDir),r=te(n),s=t.entries[r];if(s&&!(e.role&&s.role&&s.role!==e.role))return s}async function ke(n,e={}){let t=te(n.cwd),r={sessionId:n.sessionId,role:n.role,endedAt:n.endedAt??new Date().toISOString()},s=z(e.homeDir);await Fe(s,t,r),await He(e.homeDir,async()=>{let i=await H(e.homeDir);i.entries[t]=r,await k(s,JSON.stringify(i,null,2)+`
53
53
  `)})}async function St(n,e={}){let t=te(n),r=z(e.homeDir);(await H(e.homeDir)).entries[t]&&(await Fe(r,t,null),await He(e.homeDir,async()=>{let i=await H(e.homeDir);delete i.entries[t],await k(r,JSON.stringify(i,null,2)+`
54
54
  `)}))}async function re(n,e={}){let t=await H(e.homeDir),r=Object.entries(t.entries).filter(([,i])=>i.sessionId===n).map(([i])=>i);if(r.length===0)return;let s=z(e.homeDir);await Promise.all(r.map(i=>Fe(s,i,null))),await He(e.homeDir,async()=>{let i=await H(e.homeDir);for(let[o,a]of Object.entries(i.entries))a.sessionId===n&&delete i.entries[o];await k(s,JSON.stringify(i,null,2)+`
@@ -48,7 +48,7 @@ ${this.stringify(e.data)}
48
48
  `)+`
49
49
  `;await S(this.transcriptPath,a);let l=this.buildMarkdownDocument(o,"session store");if(await S(this.markdownPath,l),!this.workspaceMirrorDisabled){let c=await this.resolveWorkspaceMarkdownPath();if(c)try{let u=this.buildMarkdownDocument(o,"workspace mirror");await S(c,u)}catch(u){this.workspaceMirrorDisabled=!0,$("Transcript workspace mirror disabled",u)}}}async truncateAfterMessageCount(e){let t=await k(this.transcriptPath);if(!t)return;let r=K(t),s=Math.max(0,e),i=0,o=[];for(let c of r){if(c.type==="user_message"||c.type==="assistant_message"){if(i>=s)break;i+=1}o.push(c)}let a=o.length>0?o.map(c=>JSON.stringify(c)).join(`
50
50
  `)+`
51
- `:"";await S(this.transcriptPath,a);let l=this.buildMarkdownDocument(o,"session store");if(await S(this.markdownPath,l),!this.workspaceMirrorDisabled){let c=await this.resolveWorkspaceMarkdownPath();if(c)try{let u=this.buildMarkdownDocument(o,"workspace mirror");await S(c,u)}catch(u){this.workspaceMirrorDisabled=!0,$("Transcript workspace mirror disabled",u)}}}getSequence(){return this.sequence}async initialize(){try{let e=await k(this.transcriptPath);if(!e){this.sequence=0;return}let t=K(e);if(t.length===0){this.sequence=0;return}let r=t[t.length-1];this.sequence=r.sequence+1}catch(e){let t=e instanceof Error?e.message:String(e);$(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};import*as Y from"path";import{randomUUID as Bt}from"crypto";import{stat as Lt}from"fs/promises";var $t={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit"};function ie(n){return $t[n]??n}var I=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=Y.join(e,"checkpoints"),this.autoInterval=t?.autoInterval??10}async initialize(){let e=await this.list();e.length>0&&(this.lastCheckpointMessageCount=e[0].messageCount)}async create(e){await A(this.checkpointsDir);let t=Bt(),r={id:t,name:e.description,trigger:e.trigger,createdAt:new Date().toISOString(),messageCount:e.messages.length,tokenCount:this.estimateTokens(e.messages)},s={info:r,messages:e.messages},i=Y.join(this.checkpointsDir,`${t}.json`);return await S(i,JSON.stringify(s,null,2)),this.lastCheckpointMessageCount=e.messages.length,r}async list(){let e=await We(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await k(r);if(s){let i=P(s,null);if(i){let o=await Lt(r);t.push({info:i.info,modifiedAtMs:o.mtimeMs})}}}return t.sort((r,s)=>new Date(s.info.createdAt).getTime()-new Date(r.info.createdAt).getTime()||s.modifiedAtMs-r.modifiedAtMs).map(({info:r})=>r)}async restore(e){let t=Y.join(this.checkpointsDir,`${e}.json`),r;try{r=await k(t)}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to read checkpoint ${e}: ${o}`)}if(!r)throw new Error(`Checkpoint not found: ${e} (path: ${t})`);let s=P(r,null);if(!s)throw new Error(`Invalid checkpoint data for ${e}: JSON parse failed`);if(!s.messages||!Array.isArray(s.messages))throw new Error(`Invalid checkpoint data for ${e}: missing or invalid messages array`);if(!s.info)throw new Error(`Invalid checkpoint data for ${e}: missing info object`);return{messages:s.messages,info:s.info}}shouldAutoCheckpoint(e){return e-this.lastCheckpointMessageCount>=this.autoInterval}static isDangerousOperation(e,t){if(e=ie(e),e==="Write")return!0;if(e==="Bash"){let s=t.command?.toLowerCase()||"";return["rm ","del ","git push","git reset","drop ","truncate"].some(o=>s.includes(o))}return!1}async delete(e){let t=Y.join(this.checkpointsDir,`${e}.json`);await O(t)}estimateTokens(e){let t=0;for(let r of e)if(typeof r.content=="string")t+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let s of r.content)"text"in s&&(t+=Math.ceil(s.text.length/4));return t}};import*as L from"path";import*as Pe from"os";import*as B from"fs";var jt=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),Ft=globalThis,xe=Ft[jt]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},ve=xe.cleanups;function Ht(){for(let n of ve)try{n()}catch{}}function Qe(n){return ve.add(n),!xe.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(xe.exitHandlerRegistered=!0,process.on("exit",Ht)),()=>{ve.delete(n)}}var Ze="0.9.34";var Wt=1e4,Gt=6e4,Ut="session.lock",qt="lock.json",q=new Map;function Ee(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function Jt(){for(let[n,e]of q)try{let t=P(B.readFileSync(n,"utf8"),null);Ee(t,e)&&B.unlinkSync(n)}catch{}q.clear()}Qe(Jt);var J=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=L.join(e,Ut),this.legacyLockPath=L.join(e,qt),this.sessionId=L.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:Pe.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:Ze,acquiredAt:e,updatedAt:e,heartbeat:e},r=L.dirname(this.lockPath);await B.promises.mkdir(r,{recursive:!0});let s=await this.findExistingLockPath();if(s){if(!await this.isStalePath(s)){let o=await this.readLockAt(s);throw new Error(`Session ${this.sessionId} is already locked by PID ${o?.pid} on ${o?.hostname}`)}await O(s)}try{await B.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,q.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let l=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${l?.pid} on ${l?.hostname}`)}await O(this.lockPath);try{await B.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(l){throw l.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):l}this.acquiredOwner=t,q.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;q.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);Ee(t,e)&&await O(this.lockPath)}async isLocked(){let e=await this.findExistingLockPath();return e?!await this.isStalePath(e):!1}async isStale(){let e=await this.findExistingLockPath();return e?this.isStalePath(e):!1}async isStalePath(e){let t=await this.readLockAt(e);if(!t)return!1;if(t.hostname===Pe.hostname())try{return process.kill(t.pid,0),!1}catch(i){return i.code!=="EPERM"}let r=new Date(t.heartbeat).getTime();return Date.now()-r>Gt}startHeartbeat(e=Wt){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(t){let r=t instanceof Error?t.message:String(t);if(t?.code==="ENOENT"){j("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}j(`SessionLock: Failed to update heartbeat: ${r}`)}},e),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let e=await this.readLockAt(this.lockPath),t=this.acquiredOwner;if(!(!e||!t)){if(!Ee(e,t)){this.acquiredOwner=void 0,q.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await S(this.lockPath,JSON.stringify(e,null,2))}}async readLock(){let e=await this.findExistingLockPath();return e?this.readLockAt(e):null}async readLockAt(e){let t=await k(e);return t?P(t,null):null}async findExistingLockPath(){return await k(this.lockPath)?this.lockPath:await k(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let t=await ne(e),r=[];for(let s of t){let i=new n(s);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await O(a),r.push(L.basename(s))}}return r}};import*as M from"path";import*as D from"path";function Vt(n,e){let t=D.resolve(n),r=D.resolve(n,e);return r===t?!0:t===D.parse(t).root?r.startsWith(t):r.startsWith(t+D.sep)}function H(n,e){if(D.isAbsolute(e))return D.resolve(e);if(!Vt(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return D.resolve(n,e)}function W(n){if(n!==void 0&&n!=="agent"&&n!=="chatOnly")throw new Error("Invalid session execution mode; expected agent or chatOnly.")}import*as b from"path";import*as ce from"os";import*as T from"node:fs/promises";import{createHash as Kt,randomUUID as Yt}from"node:crypto";import{homedir as tt,platform as zt,release as Xt}from"node:os";import{resolve as et}from"node:path";var cn=zt();var ln=Xt(),un=tt();function oe(){let n=process.env.XENO_AGENT_HOME?.trim();return n?et(n):et(tt(),".xeno-agent")}var rt=1,nt="recent.json",Qt=".lock",it=".entries",Zt=3e4,be=6e4,ot=new Set(["EACCES","EBUSY","EPERM"]),er=[5,10,20,40,80,160,320],ae=new Map;function tr(n,e){let t=Kt("sha256").update(e).digest("hex");return b.join(`${n}${it}`,`${t}.json`)}async function Te(n,e,t){let r={schemaVersion:1,key:e,entry:t};await S(tr(n,e),JSON.stringify(r)+`
51
+ `:"";await S(this.transcriptPath,a);let l=this.buildMarkdownDocument(o,"session store");if(await S(this.markdownPath,l),!this.workspaceMirrorDisabled){let c=await this.resolveWorkspaceMarkdownPath();if(c)try{let u=this.buildMarkdownDocument(o,"workspace mirror");await S(c,u)}catch(u){this.workspaceMirrorDisabled=!0,$("Transcript workspace mirror disabled",u)}}}getSequence(){return this.sequence}async initialize(){try{let e=await k(this.transcriptPath);if(!e){this.sequence=0;return}let t=K(e);if(t.length===0){this.sequence=0;return}let r=t[t.length-1];this.sequence=r.sequence+1}catch(e){let t=e instanceof Error?e.message:String(e);$(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};import*as Y from"path";import{randomUUID as Bt}from"crypto";import{stat as Lt}from"fs/promises";var $t={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit"};function ie(n){return $t[n]??n}var I=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=Y.join(e,"checkpoints"),this.autoInterval=t?.autoInterval??10}async initialize(){let e=await this.list();e.length>0&&(this.lastCheckpointMessageCount=e[0].messageCount)}async create(e){await A(this.checkpointsDir);let t=Bt(),r={id:t,name:e.description,trigger:e.trigger,createdAt:new Date().toISOString(),messageCount:e.messages.length,tokenCount:this.estimateTokens(e.messages)},s={info:r,messages:e.messages},i=Y.join(this.checkpointsDir,`${t}.json`);return await S(i,JSON.stringify(s,null,2)),this.lastCheckpointMessageCount=e.messages.length,r}async list(){let e=await We(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await k(r);if(s){let i=P(s,null);if(i){let o=await Lt(r);t.push({info:i.info,modifiedAtMs:o.mtimeMs})}}}return t.sort((r,s)=>new Date(s.info.createdAt).getTime()-new Date(r.info.createdAt).getTime()||s.modifiedAtMs-r.modifiedAtMs).map(({info:r})=>r)}async restore(e){let t=Y.join(this.checkpointsDir,`${e}.json`),r;try{r=await k(t)}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to read checkpoint ${e}: ${o}`)}if(!r)throw new Error(`Checkpoint not found: ${e} (path: ${t})`);let s=P(r,null);if(!s)throw new Error(`Invalid checkpoint data for ${e}: JSON parse failed`);if(!s.messages||!Array.isArray(s.messages))throw new Error(`Invalid checkpoint data for ${e}: missing or invalid messages array`);if(!s.info)throw new Error(`Invalid checkpoint data for ${e}: missing info object`);return{messages:s.messages,info:s.info}}shouldAutoCheckpoint(e){return e-this.lastCheckpointMessageCount>=this.autoInterval}static isDangerousOperation(e,t){if(e=ie(e),e==="Write")return!0;if(e==="Bash"){let s=t.command?.toLowerCase()||"";return["rm ","del ","git push","git reset","drop ","truncate"].some(o=>s.includes(o))}return!1}async delete(e){let t=Y.join(this.checkpointsDir,`${e}.json`);await O(t)}estimateTokens(e){let t=0;for(let r of e)if(typeof r.content=="string")t+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let s of r.content)"text"in s&&(t+=Math.ceil(s.text.length/4));return t}};import*as L from"path";import*as Pe from"os";import*as B from"fs";var jt=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),Ft=globalThis,xe=Ft[jt]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},ve=xe.cleanups;function Ht(){for(let n of ve)try{n()}catch{}}function Qe(n){return ve.add(n),!xe.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(xe.exitHandlerRegistered=!0,process.on("exit",Ht)),()=>{ve.delete(n)}}var Ze="0.9.35";var Wt=1e4,Gt=6e4,Ut="session.lock",qt="lock.json",q=new Map;function Ee(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function Jt(){for(let[n,e]of q)try{let t=P(B.readFileSync(n,"utf8"),null);Ee(t,e)&&B.unlinkSync(n)}catch{}q.clear()}Qe(Jt);var J=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=L.join(e,Ut),this.legacyLockPath=L.join(e,qt),this.sessionId=L.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:Pe.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:Ze,acquiredAt:e,updatedAt:e,heartbeat:e},r=L.dirname(this.lockPath);await B.promises.mkdir(r,{recursive:!0});let s=await this.findExistingLockPath();if(s){if(!await this.isStalePath(s)){let o=await this.readLockAt(s);throw new Error(`Session ${this.sessionId} is already locked by PID ${o?.pid} on ${o?.hostname}`)}await O(s)}try{await B.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,q.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let l=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${l?.pid} on ${l?.hostname}`)}await O(this.lockPath);try{await B.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(l){throw l.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):l}this.acquiredOwner=t,q.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;q.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);Ee(t,e)&&await O(this.lockPath)}async isLocked(){let e=await this.findExistingLockPath();return e?!await this.isStalePath(e):!1}async isStale(){let e=await this.findExistingLockPath();return e?this.isStalePath(e):!1}async isStalePath(e){let t=await this.readLockAt(e);if(!t)return!1;if(t.hostname===Pe.hostname())try{return process.kill(t.pid,0),!1}catch(i){return i.code!=="EPERM"}let r=new Date(t.heartbeat).getTime();return Date.now()-r>Gt}startHeartbeat(e=Wt){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(t){let r=t instanceof Error?t.message:String(t);if(t?.code==="ENOENT"){j("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}j(`SessionLock: Failed to update heartbeat: ${r}`)}},e),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let e=await this.readLockAt(this.lockPath),t=this.acquiredOwner;if(!(!e||!t)){if(!Ee(e,t)){this.acquiredOwner=void 0,q.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await S(this.lockPath,JSON.stringify(e,null,2))}}async readLock(){let e=await this.findExistingLockPath();return e?this.readLockAt(e):null}async readLockAt(e){let t=await k(e);return t?P(t,null):null}async findExistingLockPath(){return await k(this.lockPath)?this.lockPath:await k(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let t=await ne(e),r=[];for(let s of t){let i=new n(s);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await O(a),r.push(L.basename(s))}}return r}};import*as M from"path";import*as D from"path";function Vt(n,e){let t=D.resolve(n),r=D.resolve(n,e);return r===t?!0:t===D.parse(t).root?r.startsWith(t):r.startsWith(t+D.sep)}function H(n,e){if(D.isAbsolute(e))return D.resolve(e);if(!Vt(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return D.resolve(n,e)}function W(n){if(n!==void 0&&n!=="agent"&&n!=="chatOnly")throw new Error("Invalid session execution mode; expected agent or chatOnly.")}import*as b from"path";import*as ce from"os";import*as T from"node:fs/promises";import{createHash as Kt,randomUUID as Yt}from"node:crypto";import{homedir as tt,platform as zt,release as Xt}from"node:os";import{resolve as et}from"node:path";var cn=zt();var ln=Xt(),un=tt();function oe(){let n=process.env.XENO_AGENT_HOME?.trim();return n?et(n):et(tt(),".xeno-agent")}var rt=1,nt="recent.json",Qt=".lock",it=".entries",Zt=3e4,be=6e4,ot=new Set(["EACCES","EBUSY","EPERM"]),er=[5,10,20,40,80,160,320],ae=new Map;function tr(n,e){let t=Kt("sha256").update(e).digest("hex");return b.join(`${n}${it}`,`${t}.json`)}async function Te(n,e,t){let r={schemaVersion:1,key:e,entry:t};await S(tr(n,e),JSON.stringify(r)+`
52
52
  `)}async function rr(n,e){let t=`${n}${it}`,r;try{r=await T.readdir(t)}catch(s){if(s.code==="ENOENT")return;throw s}await Promise.all(r.filter(s=>s.endsWith(".json")).map(async s=>{let i=await T.readFile(b.join(t,s),"utf8").catch(()=>""),o=P(i,null);if(!(!o||o.schemaVersion!==1||typeof o.key!="string")){if(o.entry===null){delete e[o.key];return}typeof o.entry.sessionId!="string"||typeof o.entry.endedAt!="string"||(e[o.key]=o.entry)}}))}function st(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function nr(n){try{let[e,t]=await Promise.all([T.readFile(b.join(n,"owner.json"),"utf8").catch(()=>""),T.stat(n)]),r=P(e,null);return r?.hostname===ce.hostname()&&st(r.pid)?!1:r?.hostname&&r.hostname!==ce.hostname()||!r?Date.now()-t.mtimeMs>be:Date.now()-t.mtimeMs>be||!st(r.pid)}catch{return!1}}async function at(n){for(let e=0;;e+=1)try{await T.rm(n,{recursive:!0});return}catch(t){let r=t.code;if(r==="ENOENT")return;let s=er[e];if(process.platform!=="win32"||!r||!ot.has(r)||s===void 0)throw t;await new Promise(i=>setTimeout(i,s))}}async function sr(n,e){try{let t=await T.readFile(b.join(n,"owner.json"),"utf8");P(t,null)?.token===e&&await at(n)}catch(t){if(t.code!=="ENOENT")throw t}}async function Re(n,e){let t=V(n),r=ae.get(t)??Promise.resolve(),s,i=new Promise(o=>{s=o});ae.set(t,i),await r;try{return await ir(t,e)}finally{s(),ae.get(t)===i&&ae.delete(t)}}async function ir(n,e){let t=`${n}${Qt}`,r=Yt(),s=Date.now();await T.mkdir(b.dirname(n),{recursive:!0});for(let i=0;;i+=1){let o={schemaVersion:1,token:r,pid:process.pid,hostname:ce.hostname(),acquiredAt:new Date().toISOString()};try{await T.mkdir(t),await T.writeFile(b.join(t,"owner.json"),JSON.stringify(o),"utf8");break}catch(a){let l=a.code,c=process.platform==="win32"&&!!l&&ot.has(l);if(l!=="EEXIST"&&!c)throw a;if(await nr(t)){await at(t);continue}if(Date.now()-s>=Zt)throw new Error(`Timed out waiting for recent-sessions index lock: ${t}`);let u=Math.min(100,5+i*5)+Math.floor(Math.random()*10);await new Promise(p=>setTimeout(p,u))}}try{return await e()}finally{await sr(t,r)}}function V(n){return n===void 0?b.join(oe(),nt):b.join(n,".xeno-agent",nt)}function le(n){let e=b.normalize(n).replace(/[\\/]+$/,""),t=e.length>0?e:b.parse(b.normalize(n)).root;return process.platform==="win32"?t.toLowerCase():t}async function G(n){let e=V(n),t=re(e)?await k(e):null,r=t?P(t,null):null,s=r&&typeof r=="object"?r:null,i={},o=s?.version===rt&&s.entries&&typeof s.entries=="object"?s.entries:{};for(let[a,l]of Object.entries(o)){if(!l||typeof l!="object")continue;let c=l;typeof c.sessionId!="string"||c.sessionId.length===0||typeof c.endedAt=="string"&&(i[a]={sessionId:c.sessionId,endedAt:c.endedAt,role:typeof c.role=="string"?c.role:void 0})}return await rr(e,i),{version:rt,entries:i}}async function _e(n,e={}){let t=await G(e.homeDir),r=le(n),s=t.entries[r];if(s&&!(e.role&&s.role&&s.role!==e.role))return s}async function De(n,e={}){let t=le(n.cwd),r={sessionId:n.sessionId,role:n.role,endedAt:n.endedAt??new Date().toISOString()},s=V(e.homeDir);await Te(s,t,r),await Re(e.homeDir,async()=>{let i=await G(e.homeDir);i.entries[t]=r,await S(s,JSON.stringify(i,null,2)+`
53
53
  `)})}async function or(n,e={}){let t=le(n),r=V(e.homeDir);(await G(e.homeDir)).entries[t]&&(await Te(r,t,null),await Re(e.homeDir,async()=>{let i=await G(e.homeDir);delete i.entries[t],await S(r,JSON.stringify(i,null,2)+`
54
54
  `)}))}async function ue(n,e={}){let t=await G(e.homeDir),r=Object.entries(t.entries).filter(([,i])=>i.sessionId===n).map(([i])=>i);if(r.length===0)return;let s=V(e.homeDir);await Promise.all(r.map(i=>Te(s,i,null))),await Re(e.homeDir,async()=>{let i=await G(e.homeDir);for(let[o,a]of Object.entries(i.entries))a.sessionId===n&&delete i.entries[o];await S(s,JSON.stringify(i,null,2)+`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xenosystem/agent-sdk",
3
- "version": "0.9.34",
3
+ "version": "0.9.35",
4
4
  "description": "XENO Agent SDK built from the same engine as XENO CODE",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",