@xenosystem/agent-sdk 0.10.24 → 0.10.26

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 c=this.buildMarkdownDocument(o,"session store");if(await k(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await k(u,l)}catch(l){this.workspaceMirrorDisabled=!0,F("Transcript workspace mirror disabled",l)}}}async truncateAfterMessageCount(e){let t=await x(this.transcriptPath);if(!t)return;let r=ee(t),s=Math.max(0,e),i=0,o=[];for(let u of r){if(u.type==="user_message"||u.type==="assistant_message"){if(i>=s)break;i+=1}o.push(u)}let a=o.length>0?o.map(u=>JSON.stringify(u)).join(`
50
50
  `)+`
51
- `:"";await k(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await k(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await k(u,l)}catch(l){this.workspaceMirrorDisabled=!0,F("Transcript workspace mirror disabled",l)}}}getSequence(){return this.sequence}async initialize(){try{let e=await x(this.transcriptPath);if(!e){this.sequence=0;return}let t=ee(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);F(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};var te=_(require("path"),1),gt=require("crypto"),ft=require("fs/promises");var Zt={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function he(n){return Zt[n]??n}var I=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=te.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,gt.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=te.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 nt(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await x(r);if(s){let i=b(s,null);if(i){let o=await(0,ft.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=te.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=b(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=he(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=te.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 j=_(require("path"),1),Fe=_(require("os"),1),B=_(require("fs"),1);var er=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),tr=globalThis,$e=tr[er]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},Le=$e.cleanups;function rr(){for(let n of Le)try{n()}catch{}}function mt(n){return Le.add(n),!$e.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&($e.exitHandlerRegistered=!0,process.on("exit",rr)),()=>{Le.delete(n)}}var ht="0.10.24";var nr=1e4,sr=6e4,ir="session.lock",or="lock.json",Y=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 ar(){for(let[n,e]of Y)try{let t=b(B.readFileSync(n,"utf8"),null);Be(t,e)&&B.unlinkSync(n)}catch{}Y.clear()}mt(ar);var G=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=j.join(e,ir),this.legacyLockPath=j.join(e,or),this.sessionId=j.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:Fe.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:ht,acquiredAt:e,updatedAt:e,heartbeat:e},r=j.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 $(s)}try{await B.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,Y.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let c=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${c?.pid} on ${c?.hostname}`)}await $(this.lockPath);try{await B.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(c){throw c.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):c}this.acquiredOwner=t,Y.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;Y.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===Fe.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>sr}startHeartbeat(e=nr){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"){H("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}H(`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,Y.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?b(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 de(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(j.basename(s))}}return r}};var C=_(require("path"),1);var re=1;var A=_(require("path"),1);function cr(n,e){let t=A.resolve(n),r=A.resolve(n,e);return r===t?!0:t===A.parse(t).root?r.startsWith(t):r.startsWith(t+A.sep)}function W(n,e){if(A.isAbsolute(e))return A.resolve(e);if(!cr(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return A.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 P=_(require("path"),1),Se=_(require("os"),1),R=_(require("node:fs/promises"),1),ke=require("node:crypto");var z=require("node:os");var je=require("node:path"),pn=(0,z.platform)();var gn=(0,z.release)(),fn=(0,z.homedir)();function ye(){let n=process.env.XENO_AGENT_HOME?.trim();return n?(0,je.resolve)(n):(0,je.resolve)((0,z.homedir)(),".xeno-agent")}var yt=1,wt="recent.json",ur=".lock",kt=".entries",lr=3e4,Ue=6e4,xt=new Set(["EACCES","EBUSY","EPERM"]),dr=[5,10,20,40,80,160,320],we=new Map;function pr(n,e){let t=(0,ke.createHash)("sha256").update(e).digest("hex");return P.join(`${n}${kt}`,`${t}.json`)}async function He(n,e,t){let r={schemaVersion:1,key:e,entry:t};await k(pr(n,e),JSON.stringify(r)+`
51
+ `:"";await k(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await k(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await k(u,l)}catch(l){this.workspaceMirrorDisabled=!0,F("Transcript workspace mirror disabled",l)}}}getSequence(){return this.sequence}async initialize(){try{let e=await x(this.transcriptPath);if(!e){this.sequence=0;return}let t=ee(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);F(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};var te=_(require("path"),1),gt=require("crypto"),ft=require("fs/promises");var Zt={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function he(n){return Zt[n]??n}var I=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=te.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,gt.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=te.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 nt(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await x(r);if(s){let i=b(s,null);if(i){let o=await(0,ft.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=te.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=b(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=he(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=te.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 j=_(require("path"),1),Fe=_(require("os"),1),B=_(require("fs"),1);var er=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),tr=globalThis,$e=tr[er]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},Le=$e.cleanups;function rr(){for(let n of Le)try{n()}catch{}}function mt(n){return Le.add(n),!$e.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&($e.exitHandlerRegistered=!0,process.on("exit",rr)),()=>{Le.delete(n)}}var ht="0.10.26";var nr=1e4,sr=6e4,ir="session.lock",or="lock.json",Y=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 ar(){for(let[n,e]of Y)try{let t=b(B.readFileSync(n,"utf8"),null);Be(t,e)&&B.unlinkSync(n)}catch{}Y.clear()}mt(ar);var G=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=j.join(e,ir),this.legacyLockPath=j.join(e,or),this.sessionId=j.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:Fe.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:ht,acquiredAt:e,updatedAt:e,heartbeat:e},r=j.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 $(s)}try{await B.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,Y.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let c=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${c?.pid} on ${c?.hostname}`)}await $(this.lockPath);try{await B.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(c){throw c.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):c}this.acquiredOwner=t,Y.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;Y.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===Fe.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>sr}startHeartbeat(e=nr){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"){H("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}H(`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,Y.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?b(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 de(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(j.basename(s))}}return r}};var C=_(require("path"),1);var re=1;var A=_(require("path"),1);function cr(n,e){let t=A.resolve(n),r=A.resolve(n,e);return r===t?!0:t===A.parse(t).root?r.startsWith(t):r.startsWith(t+A.sep)}function W(n,e){if(A.isAbsolute(e))return A.resolve(e);if(!cr(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return A.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 P=_(require("path"),1),Se=_(require("os"),1),R=_(require("node:fs/promises"),1),ke=require("node:crypto");var z=require("node:os");var je=require("node:path"),pn=(0,z.platform)();var gn=(0,z.release)(),fn=(0,z.homedir)();function ye(){let n=process.env.XENO_AGENT_HOME?.trim();return n?(0,je.resolve)(n):(0,je.resolve)((0,z.homedir)(),".xeno-agent")}var yt=1,wt="recent.json",ur=".lock",kt=".entries",lr=3e4,Ue=6e4,xt=new Set(["EACCES","EBUSY","EPERM"]),dr=[5,10,20,40,80,160,320],we=new Map;function pr(n,e){let t=(0,ke.createHash)("sha256").update(e).digest("hex");return P.join(`${n}${kt}`,`${t}.json`)}async function He(n,e,t){let r={schemaVersion:1,key:e,entry:t};await k(pr(n,e),JSON.stringify(r)+`
52
52
  `)}async function gr(n,e){let t=`${n}${kt}`,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(P.join(t,s),"utf8").catch(()=>""),o=b(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 fr(n){try{let[e,t]=await Promise.all([R.readFile(P.join(n,"owner.json"),"utf8").catch(()=>""),R.stat(n)]),r=b(e,null);return r?.hostname===Se.hostname()&&St(r.pid)?!1:r?.hostname&&r.hostname!==Se.hostname()||!r?Date.now()-t.mtimeMs>Ue:Date.now()-t.mtimeMs>Ue||!St(r.pid)}catch{return!1}}async function vt(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=dr[e];if(process.platform!=="win32"||!r||!xt.has(r)||s===void 0)throw t;await new Promise(i=>setTimeout(i,s))}}async function mr(n,e){try{let t=await R.readFile(P.join(n,"owner.json"),"utf8");b(t,null)?.token===e&&await vt(n)}catch(t){if(t.code!=="ENOENT")throw t}}async function qe(n,e){let t=V(n),r=we.get(t)??Promise.resolve(),s,i=new Promise(o=>{s=o});we.set(t,i),await r;try{return await hr(t,e)}finally{s(),we.get(t)===i&&we.delete(t)}}async function hr(n,e){let t=`${n}${ur}`,r=(0,ke.randomUUID)(),s=Date.now();await R.mkdir(P.dirname(n),{recursive:!0});for(let i=0;;i+=1){let o={schemaVersion:1,token:r,pid:process.pid,hostname:Se.hostname(),acquiredAt:new Date().toISOString()};try{await R.mkdir(t),await R.writeFile(P.join(t,"owner.json"),JSON.stringify(o),"utf8");break}catch(a){let c=a.code,u=process.platform==="win32"&&!!c&&xt.has(c);if(c!=="EEXIST"&&!u)throw a;if(await fr(t)){await vt(t);continue}if(Date.now()-s>=lr)throw new Error(`Timed out waiting for recent-sessions index lock: ${t}`);let l=Math.min(100,5+i*5)+Math.floor(Math.random()*10);await new Promise(d=>setTimeout(d,l))}}try{return await e()}finally{await mr(t,r)}}function V(n){return n===void 0?P.join(ye(),wt):P.join(n,".xeno-agent",wt)}function ne(n){let e=P.normalize(n).replace(/[\\/]+$/,""),t=e.length>0?e:P.parse(P.normalize(n)).root;return process.platform==="win32"?t.toLowerCase():t}async function U(n){let e=V(n),t=le(e)?await x(e):null,r=t?b(t,null):null,s=r&&typeof r=="object"?r:null,i={},o=s?.version===yt&&s.entries&&typeof s.entries=="object"?s.entries:{};for(let[a,c]of Object.entries(o)){if(!c||typeof c!="object")continue;let u=c;typeof u.sessionId!="string"||u.sessionId.length===0||typeof u.endedAt=="string"&&(i[a]={sessionId:u.sessionId,endedAt:u.endedAt,role:typeof u.role=="string"?u.role:void 0})}return await gr(e,i),{version:yt,entries:i}}async function xe(n,e={}){let t=await U(e.homeDir),r=ne(n),s=t.entries[r];if(s&&!(e.role&&s.role&&s.role!==e.role))return s}async function ve(n,e={}){let t=ne(n.cwd),r={sessionId:n.sessionId,role:n.role,endedAt:n.endedAt??new Date().toISOString()},s=V(e.homeDir);await He(s,t,r),await qe(e.homeDir,async()=>{let i=await U(e.homeDir);i.entries[t]=r,await k(s,JSON.stringify(i,null,2)+`
53
53
  `)})}async function Et(n,e={}){let t=ne(n),r=V(e.homeDir);(await U(e.homeDir)).entries[t]&&(await He(r,t,null),await qe(e.homeDir,async()=>{let i=await U(e.homeDir);delete i.entries[t],await k(r,JSON.stringify(i,null,2)+`
54
54
  `)}))}async function se(n,e={}){let t=await U(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=>He(s,i,null))),await qe(e.homeDir,async()=>{let i=await U(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 c=this.buildMarkdownDocument(o,"session store");if(await S(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await S(u,l)}catch(l){this.workspaceMirrorDisabled=!0,$("Transcript workspace mirror disabled",l)}}}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 u of r){if(u.type==="user_message"||u.type==="assistant_message"){if(i>=s)break;i+=1}o.push(u)}let a=o.length>0?o.map(u=>JSON.stringify(u)).join(`
50
50
  `)+`
51
- `:"";await S(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await S(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await S(u,l)}catch(l){this.workspaceMirrorDisabled=!0,$("Transcript workspace mirror disabled",l)}}}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 Q from"path";import{randomUUID as Wt}from"crypto";import{stat as Jt}from"fs/promises";var Gt={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function ae(n){return Gt[n]??n}var I=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=Q.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 C(this.checkpointsDir);let t=Wt(),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=Q.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 Je(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await k(r);if(s){let i=E(s,null);if(i){let o=await Jt(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=Q.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=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=ae(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=Q.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 F from"path";import*as Te from"os";import*as L from"fs";var zt=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),Vt=globalThis,Ee=Vt[zt]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},be=Ee.cleanups;function Xt(){for(let n of be)try{n()}catch{}}function rt(n){return be.add(n),!Ee.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(Ee.exitHandlerRegistered=!0,process.on("exit",Xt)),()=>{be.delete(n)}}var nt="0.10.24";var Kt=1e4,Qt=6e4,Yt="session.lock",Zt="lock.json",W=new Map;function Pe(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function er(){for(let[n,e]of W)try{let t=E(L.readFileSync(n,"utf8"),null);Pe(t,e)&&L.unlinkSync(n)}catch{}W.clear()}rt(er);var J=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=F.join(e,Yt),this.legacyLockPath=F.join(e,Zt),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:Te.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:nt,acquiredAt:e,updatedAt:e,heartbeat:e},r=F.dirname(this.lockPath);await L.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 L.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,W.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let c=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${c?.pid} on ${c?.hostname}`)}await O(this.lockPath);try{await L.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(c){throw c.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):c}this.acquiredOwner=t,W.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;W.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);Pe(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===Te.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>Qt}startHeartbeat(e=Kt){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"){B("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}B(`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(!Pe(e,t)){this.acquiredOwner=void 0,W.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?E(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 ie(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(F.basename(s))}}return r}};import*as D from"path";var Y=1;import*as M from"path";function tr(n,e){let t=M.resolve(n),r=M.resolve(n,e);return r===t?!0:t===M.parse(t).root?r.startsWith(t):r.startsWith(t+M.sep)}function U(n,e){if(M.isAbsolute(e))return M.resolve(e);if(!tr(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return M.resolve(n,e)}function H(n){if(n!==void 0&&n!=="agent"&&n!=="chatOnly")throw new Error("Invalid session execution mode; expected agent or chatOnly.")}import*as T from"path";import*as le from"os";import*as P from"node:fs/promises";import{createHash as sr,randomUUID as ir}from"node:crypto";import{homedir as it,platform as rr,release as nr}from"node:os";import{resolve as st}from"node:path";var En=rr();var bn=nr(),Tn=it();function ce(){let n=process.env.XENO_AGENT_HOME?.trim();return n?st(n):st(it(),".xeno-agent")}var ot=1,at="recent.json",or=".lock",ut=".entries",ar=3e4,Re=6e4,lt=new Set(["EACCES","EBUSY","EPERM"]),cr=[5,10,20,40,80,160,320],ue=new Map;function ur(n,e){let t=sr("sha256").update(e).digest("hex");return T.join(`${n}${ut}`,`${t}.json`)}async function _e(n,e,t){let r={schemaVersion:1,key:e,entry:t};await S(ur(n,e),JSON.stringify(r)+`
51
+ `:"";await S(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await S(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await S(u,l)}catch(l){this.workspaceMirrorDisabled=!0,$("Transcript workspace mirror disabled",l)}}}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 Q from"path";import{randomUUID as Wt}from"crypto";import{stat as Jt}from"fs/promises";var Gt={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function ae(n){return Gt[n]??n}var I=class{sessionDir;checkpointsDir;autoInterval;lastCheckpointMessageCount=0;constructor(e,t){this.sessionDir=e,this.checkpointsDir=Q.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 C(this.checkpointsDir);let t=Wt(),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=Q.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 Je(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await k(r);if(s){let i=E(s,null);if(i){let o=await Jt(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=Q.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=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=ae(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=Q.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 F from"path";import*as Te from"os";import*as L from"fs";var zt=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),Vt=globalThis,Ee=Vt[zt]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},be=Ee.cleanups;function Xt(){for(let n of be)try{n()}catch{}}function rt(n){return be.add(n),!Ee.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(Ee.exitHandlerRegistered=!0,process.on("exit",Xt)),()=>{be.delete(n)}}var nt="0.10.26";var Kt=1e4,Qt=6e4,Yt="session.lock",Zt="lock.json",W=new Map;function Pe(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function er(){for(let[n,e]of W)try{let t=E(L.readFileSync(n,"utf8"),null);Pe(t,e)&&L.unlinkSync(n)}catch{}W.clear()}rt(er);var J=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=F.join(e,Yt),this.legacyLockPath=F.join(e,Zt),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:Te.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:nt,acquiredAt:e,updatedAt:e,heartbeat:e},r=F.dirname(this.lockPath);await L.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 L.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,W.set(this.lockPath,t)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let c=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${c?.pid} on ${c?.hostname}`)}await O(this.lockPath);try{await L.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"})}catch(c){throw c.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):c}this.acquiredOwner=t,W.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;W.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);Pe(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===Te.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>Qt}startHeartbeat(e=Kt){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"){B("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}B(`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(!Pe(e,t)){this.acquiredOwner=void 0,W.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?E(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 ie(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(F.basename(s))}}return r}};import*as D from"path";var Y=1;import*as M from"path";function tr(n,e){let t=M.resolve(n),r=M.resolve(n,e);return r===t?!0:t===M.parse(t).root?r.startsWith(t):r.startsWith(t+M.sep)}function U(n,e){if(M.isAbsolute(e))return M.resolve(e);if(!tr(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return M.resolve(n,e)}function H(n){if(n!==void 0&&n!=="agent"&&n!=="chatOnly")throw new Error("Invalid session execution mode; expected agent or chatOnly.")}import*as T from"path";import*as le from"os";import*as P from"node:fs/promises";import{createHash as sr,randomUUID as ir}from"node:crypto";import{homedir as it,platform as rr,release as nr}from"node:os";import{resolve as st}from"node:path";var En=rr();var bn=nr(),Tn=it();function ce(){let n=process.env.XENO_AGENT_HOME?.trim();return n?st(n):st(it(),".xeno-agent")}var ot=1,at="recent.json",or=".lock",ut=".entries",ar=3e4,Re=6e4,lt=new Set(["EACCES","EBUSY","EPERM"]),cr=[5,10,20,40,80,160,320],ue=new Map;function ur(n,e){let t=sr("sha256").update(e).digest("hex");return T.join(`${n}${ut}`,`${t}.json`)}async function _e(n,e,t){let r={schemaVersion:1,key:e,entry:t};await S(ur(n,e),JSON.stringify(r)+`
52
52
  `)}async function lr(n,e){let t=`${n}${ut}`,r;try{r=await P.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 P.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 ct(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function dr(n){try{let[e,t]=await Promise.all([P.readFile(T.join(n,"owner.json"),"utf8").catch(()=>""),P.stat(n)]),r=E(e,null);return r?.hostname===le.hostname()&&ct(r.pid)?!1:r?.hostname&&r.hostname!==le.hostname()||!r?Date.now()-t.mtimeMs>Re:Date.now()-t.mtimeMs>Re||!ct(r.pid)}catch{return!1}}async function dt(n){for(let e=0;;e+=1)try{await P.rm(n,{recursive:!0});return}catch(t){let r=t.code;if(r==="ENOENT")return;let s=cr[e];if(process.platform!=="win32"||!r||!lt.has(r)||s===void 0)throw t;await new Promise(i=>setTimeout(i,s))}}async function pr(n,e){try{let t=await P.readFile(T.join(n,"owner.json"),"utf8");E(t,null)?.token===e&&await dt(n)}catch(t){if(t.code!=="ENOENT")throw t}}async function Me(n,e){let t=z(n),r=ue.get(t)??Promise.resolve(),s,i=new Promise(o=>{s=o});ue.set(t,i),await r;try{return await gr(t,e)}finally{s(),ue.get(t)===i&&ue.delete(t)}}async function gr(n,e){let t=`${n}${or}`,r=ir(),s=Date.now();await P.mkdir(T.dirname(n),{recursive:!0});for(let i=0;;i+=1){let o={schemaVersion:1,token:r,pid:process.pid,hostname:le.hostname(),acquiredAt:new Date().toISOString()};try{await P.mkdir(t),await P.writeFile(T.join(t,"owner.json"),JSON.stringify(o),"utf8");break}catch(a){let c=a.code,u=process.platform==="win32"&&!!c&&lt.has(c);if(c!=="EEXIST"&&!u)throw a;if(await dr(t)){await dt(t);continue}if(Date.now()-s>=ar)throw new Error(`Timed out waiting for recent-sessions index lock: ${t}`);let l=Math.min(100,5+i*5)+Math.floor(Math.random()*10);await new Promise(d=>setTimeout(d,l))}}try{return await e()}finally{await pr(t,r)}}function z(n){return n===void 0?T.join(ce(),at):T.join(n,".xeno-agent",at)}function de(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 q(n){let e=z(n),t=se(e)?await k(e):null,r=t?E(t,null):null,s=r&&typeof r=="object"?r:null,i={},o=s?.version===ot&&s.entries&&typeof s.entries=="object"?s.entries:{};for(let[a,c]of Object.entries(o)){if(!c||typeof c!="object")continue;let u=c;typeof u.sessionId!="string"||u.sessionId.length===0||typeof u.endedAt=="string"&&(i[a]={sessionId:u.sessionId,endedAt:u.endedAt,role:typeof u.role=="string"?u.role:void 0})}return await lr(e,i),{version:ot,entries:i}}async function De(n,e={}){let t=await q(e.homeDir),r=de(n),s=t.entries[r];if(s&&!(e.role&&s.role&&s.role!==e.role))return s}async function Ie(n,e={}){let t=de(n.cwd),r={sessionId:n.sessionId,role:n.role,endedAt:n.endedAt??new Date().toISOString()},s=z(e.homeDir);await _e(s,t,r),await Me(e.homeDir,async()=>{let i=await q(e.homeDir);i.entries[t]=r,await S(s,JSON.stringify(i,null,2)+`
53
53
  `)})}async function fr(n,e={}){let t=de(n),r=z(e.homeDir);(await q(e.homeDir)).entries[t]&&(await _e(r,t,null),await Me(e.homeDir,async()=>{let i=await q(e.homeDir);delete i.entries[t],await S(r,JSON.stringify(i,null,2)+`
54
54
  `)}))}async function pe(n,e={}){let t=await q(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=>_e(s,i,null))),await Me(e.homeDir,async()=>{let i=await q(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.10.24",
3
+ "version": "0.10.26",
4
4
  "description": "XENO Agent SDK built from the same engine as XENO CODE",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",