@xenosystem/agent-sdk 0.10.35 → 0.10.36
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/README.md +1 -1
- package/dist/artifacts/index.cjs +1 -1
- package/dist/artifacts/index.js +1 -1
- package/dist/automation/index.cjs +1 -1
- package/dist/automation/index.js +1 -1
- package/dist/control-plane/index.cjs +1 -1
- package/dist/control-plane/index.js +1 -1
- package/dist/electron/index.cjs +197 -189
- package/dist/electron/index.d.cts +40 -0
- package/dist/electron/index.d.ts +40 -0
- package/dist/electron/index.js +196 -188
- package/dist/electron/metafile-cjs.json +1 -1
- package/dist/electron/metafile-esm.json +1 -1
- package/dist/index.cjs +358 -358
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +351 -351
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/session/index.cjs +1 -1
- package/dist/session/index.js +1 -1
- package/ownership/ownership-policy.json +2 -2
- package/package.json +1 -1
package/dist/session/index.cjs
CHANGED
|
@@ -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,B("Transcript workspace mirror disabled",l)}}}async truncateAfterMessageCount(e){let t=await S(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,B("Transcript workspace mirror disabled",l)}}}getSequence(){return this.sequence}async initialize(){try{let e=await S(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);B(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};var te=_(require("path"),1),mt=require("crypto"),ht=require("fs/promises");var tr={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function he(n){return tr[n]??n}var D=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,mt.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 it(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await S(r);if(s){let i=E(s,null);if(i){let o=await(0,ht.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 S(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=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 U=_(require("path"),1),je=_(require("os"),1),j=_(require("fs"),1);var rr=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),nr=globalThis,Fe=nr[rr]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},Be=Fe.cleanups;function sr(){for(let n of Be)try{n()}catch{}}function wt(n){return Be.add(n),!Fe.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(Fe.exitHandlerRegistered=!0,process.on("exit",sr)),()=>{Be.delete(n)}}var yt="0.10.
|
|
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,B("Transcript workspace mirror disabled",l)}}}getSequence(){return this.sequence}async initialize(){try{let e=await S(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);B(`Transcript initialization warning: ${t}. Starting with empty transcript.`),this.sequence=0}}async flush(){await this.writeQueue}};var te=_(require("path"),1),mt=require("crypto"),ht=require("fs/promises");var tr={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function he(n){return tr[n]??n}var D=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,mt.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 it(this.checkpointsDir,/\.json$/),t=[];for(let r of e){let s=await S(r);if(s){let i=E(s,null);if(i){let o=await(0,ht.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 S(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=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 U=_(require("path"),1),je=_(require("os"),1),j=_(require("fs"),1);var rr=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),nr=globalThis,Fe=nr[rr]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},Be=Fe.cleanups;function sr(){for(let n of Be)try{n()}catch{}}function wt(n){return Be.add(n),!Fe.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(Fe.exitHandlerRegistered=!0,process.on("exit",sr)),()=>{Be.delete(n)}}var yt="0.10.36";var ir=1e4,or=6e4,ar="session.lock",cr="lock.json",Z=new Map;function Ue(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function ur(){for(let[n,e]of Z)try{let t=E(j.readFileSync(n,"utf8"),null);Ue(t,e)&&j.unlinkSync(n)}catch{}Z.clear()}wt(ur);var G=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=U.join(e,ar),this.legacyLockPath=U.join(e,cr),this.sessionId=U.basename(e)}async acquire(){let e=new Date().toISOString(),t={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:je.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:yt,acquiredAt:e,updatedAt:e,heartbeat:e},r=U.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,Z.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 j.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,Z.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;Z.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);Ue(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===je.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>or}startHeartbeat(e=ir){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"){q("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}q(`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(!Ue(e,t)){this.acquiredOwner=void 0,Z.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 S(e);return t?E(t,null):null}async findExistingLockPath(){return await S(this.lockPath)?this.lockPath:await S(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(U.basename(s))}}return r}};var C=_(require("path"),1);var re=1;var A=_(require("path"),1);function lr(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 J(n,e){if(A.isAbsolute(e))return A.resolve(e);if(!lr(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return A.resolve(n,e)}function we(n,e=process.platform){let t=A.resolve(n);return e==="win32"?t.toLowerCase():t}function V(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),xe=require("node:crypto");var z=require("node:os");var He=require("node:path"),fn=(0,z.platform)();var mn=(0,z.release)(),hn=(0,z.homedir)();function ye(){let n=process.env.XENO_AGENT_HOME?.trim();return n?(0,He.resolve)(n):(0,He.resolve)((0,z.homedir)(),".xeno-agent")}var kt=1,St="recent.json",dr=".lock",vt=".entries",pr=3e4,qe=6e4,bt=new Set(["EACCES","EBUSY","EPERM"]),gr=[5,10,20,40,80,160,320],ke=new Map;function fr(n,e){let t=(0,xe.createHash)("sha256").update(e).digest("hex");return P.join(`${n}${vt}`,`${t}.json`)}async function We(n,e,t){let r={schemaVersion:1,key:e,entry:t};await k(fr(n,e),JSON.stringify(r)+`
|
|
52
52
|
`)}async function mr(n,e){let t=`${n}${vt}`,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=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 xt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function hr(n){try{let[e,t]=await Promise.all([R.readFile(P.join(n,"owner.json"),"utf8").catch(()=>""),R.stat(n)]),r=E(e,null);return r?.hostname===Se.hostname()&&xt(r.pid)?!1:r?.hostname&&r.hostname!==Se.hostname()||!r?Date.now()-t.mtimeMs>qe:Date.now()-t.mtimeMs>qe||!xt(r.pid)}catch{return!1}}async function Et(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=gr[e];if(process.platform!=="win32"||!r||!bt.has(r)||s===void 0)throw t;await new Promise(i=>setTimeout(i,s))}}async function wr(n,e){try{let t=await R.readFile(P.join(n,"owner.json"),"utf8");E(t,null)?.token===e&&await Et(n)}catch(t){if(t.code!=="ENOENT")throw t}}async function Ge(n,e){let t=X(n),r=ke.get(t)??Promise.resolve(),s,i=new Promise(o=>{s=o});ke.set(t,i),await r;try{return await yr(t,e)}finally{s(),ke.get(t)===i&&ke.delete(t)}}async function yr(n,e){let t=`${n}${dr}`,r=(0,xe.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&&bt.has(c);if(c!=="EEXIST"&&!u)throw a;if(await hr(t)){await Et(t);continue}if(Date.now()-s>=pr)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(p=>setTimeout(p,l))}}try{return await e()}finally{await wr(t,r)}}function X(n){return n===void 0?P.join(ye(),St):P.join(n,".xeno-agent",St)}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 H(n){let e=X(n),t=le(e)?await S(e):null,r=t?E(t,null):null,s=r&&typeof r=="object"?r:null,i={},o=s?.version===kt&&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 mr(e,i),{version:kt,entries:i}}async function ve(n,e={}){let t=await H(e.homeDir),r=ne(n),s=t.entries[r];if(s&&!(e.role&&s.role&&s.role!==e.role))return s}async function be(n,e={}){let t=ne(n.cwd),r={sessionId:n.sessionId,role:n.role,endedAt:n.endedAt??new Date().toISOString()},s=X(e.homeDir);await We(s,t,r),await Ge(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 Tt(n,e={}){let t=ne(n),r=X(e.homeDir);(await H(e.homeDir)).entries[t]&&(await We(r,t,null),await Ge(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 se(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=X(e.homeDir);await Promise.all(r.map(i=>We(s,i,null))),await Ge(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)+`
|
package/dist/session/index.js
CHANGED
|
@@ -48,7 +48,7 @@ ${this.stringify(e.data)}
|
|
|
48
48
|
`)+`
|
|
49
49
|
`;await y(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await y(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await y(u,l)}catch(l){this.workspaceMirrorDisabled=!0,L("Transcript workspace mirror disabled",l)}}}async truncateAfterMessageCount(e){let t=await k(this.transcriptPath);if(!t)return;let r=Q(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 y(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await y(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await y(u,l)}catch(l){this.workspaceMirrorDisabled=!0,L("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=Q(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}};import*as Y from"path";import{randomUUID as Vt}from"crypto";import{stat as zt}from"fs/promises";var Jt={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function ae(n){return Jt[n]??n}var A=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 C(this.checkpointsDir);let t=Vt(),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 y(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 k(r);if(s){let i=b(s,null);if(i){let o=await zt(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=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=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=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 B from"path";import*as Pe from"os";import*as F from"fs";var Xt=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),Kt=globalThis,Ee=Kt[Xt]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},Te=Ee.cleanups;function Qt(){for(let n of Te)try{n()}catch{}}function st(n){return Te.add(n),!Ee.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(Ee.exitHandlerRegistered=!0,process.on("exit",Qt)),()=>{Te.delete(n)}}var it="0.10.
|
|
51
|
+
`:"";await y(this.transcriptPath,a);let c=this.buildMarkdownDocument(o,"session store");if(await y(this.markdownPath,c),!this.workspaceMirrorDisabled){let u=await this.resolveWorkspaceMarkdownPath();if(u)try{let l=this.buildMarkdownDocument(o,"workspace mirror");await y(u,l)}catch(l){this.workspaceMirrorDisabled=!0,L("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=Q(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}};import*as Y from"path";import{randomUUID as Vt}from"crypto";import{stat as zt}from"fs/promises";var Jt={View:"Read",Replace:"Write",GlobTool:"Glob",GrepTool:"Grep",SQLiteAnalyze:"SqliteAnalyze",ReadNotebook:"NotebookRead",NotebookEditCell:"NotebookEdit",CoordinationSend:"Send",CoordinationQuery:"Receive"};function ae(n){return Jt[n]??n}var A=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 C(this.checkpointsDir);let t=Vt(),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 y(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 k(r);if(s){let i=b(s,null);if(i){let o=await zt(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=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=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=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 B from"path";import*as Pe from"os";import*as F from"fs";var Xt=Symbol.for("@xenosystem/agent-sdk/shutdown-registry"),Kt=globalThis,Ee=Kt[Xt]??={cleanups:new Set,exitHandlerRegistered:!1,signalHandlersInstalled:!1},Te=Ee.cleanups;function Qt(){for(let n of Te)try{n()}catch{}}function st(n){return Te.add(n),!Ee.exitHandlerRegistered&&typeof process<"u"&&typeof process.on=="function"&&(Ee.exitHandlerRegistered=!0,process.on("exit",Qt)),()=>{Te.delete(n)}}var it="0.10.36";var Yt=1e4,Zt=6e4,er="session.lock",tr="lock.json",J=new Map;function Re(n,e){return n!=null&&n.pid===e.pid&&n.hostname===e.hostname&&n.processStartedAt===e.processStartedAt&&n.acquiredAt===e.acquiredAt}function rr(){for(let[n,e]of J)try{let t=b(F.readFileSync(n,"utf8"),null);Re(t,e)&&F.unlinkSync(n)}catch{}J.clear()}st(rr);var V=class n{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=B.join(e,er),this.legacyLockPath=B.join(e,tr),this.sessionId=B.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:it,acquiredAt:e,updatedAt:e,heartbeat:e},r=B.dirname(this.lockPath);await F.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 F.promises.writeFile(this.lockPath,JSON.stringify(t,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=t,J.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 F.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,J.set(this.lockPath,t)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;J.delete(this.lockPath);let t=await this.readLockAt(this.lockPath);Re(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>Zt}startHeartbeat(e=Yt){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(!Re(e,t)){this.acquiredOwner=void 0,J.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await y(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?b(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(B.basename(s))}}return r}};import*as I from"path";var Z=1;import*as _ from"path";function nr(n,e){let t=_.resolve(n),r=_.resolve(n,e);return r===t?!0:t===_.parse(t).root?r.startsWith(t):r.startsWith(t+_.sep)}function H(n,e){if(_.isAbsolute(e))return _.resolve(e);if(!nr(n,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return _.resolve(n,e)}function ce(n,e=process.platform){let t=_.resolve(n);return e==="win32"?t.toLowerCase():t}function q(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 de from"os";import*as P from"node:fs/promises";import{createHash as or,randomUUID as ar}from"node:crypto";import{homedir as at,platform as sr,release as ir}from"node:os";import{resolve as ot}from"node:path";var Tn=sr();var Pn=ir(),Rn=at();function ue(){let n=process.env.XENO_AGENT_HOME?.trim();return n?ot(n):ot(at(),".xeno-agent")}var ct=1,ut="recent.json",cr=".lock",dt=".entries",ur=3e4,_e=6e4,pt=new Set(["EACCES","EBUSY","EPERM"]),lr=[5,10,20,40,80,160,320],le=new Map;function dr(n,e){let t=or("sha256").update(e).digest("hex");return T.join(`${n}${dt}`,`${t}.json`)}async function Me(n,e,t){let r={schemaVersion:1,key:e,entry:t};await y(dr(n,e),JSON.stringify(r)+`
|
|
52
52
|
`)}async function pr(n,e){let t=`${n}${dt}`,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=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 lt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function gr(n){try{let[e,t]=await Promise.all([P.readFile(T.join(n,"owner.json"),"utf8").catch(()=>""),P.stat(n)]),r=b(e,null);return r?.hostname===de.hostname()&<(r.pid)?!1:r?.hostname&&r.hostname!==de.hostname()||!r?Date.now()-t.mtimeMs>_e:Date.now()-t.mtimeMs>_e||!lt(r.pid)}catch{return!1}}async function gt(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=lr[e];if(process.platform!=="win32"||!r||!pt.has(r)||s===void 0)throw t;await new Promise(i=>setTimeout(i,s))}}async function fr(n,e){try{let t=await P.readFile(T.join(n,"owner.json"),"utf8");b(t,null)?.token===e&&await gt(n)}catch(t){if(t.code!=="ENOENT")throw t}}async function Ie(n,e){let t=z(n),r=le.get(t)??Promise.resolve(),s,i=new Promise(o=>{s=o});le.set(t,i),await r;try{return await mr(t,e)}finally{s(),le.get(t)===i&&le.delete(t)}}async function mr(n,e){let t=`${n}${cr}`,r=ar(),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:de.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&&pt.has(c);if(c!=="EEXIST"&&!u)throw a;if(await gr(t)){await gt(t);continue}if(Date.now()-s>=ur)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(p=>setTimeout(p,l))}}try{return await e()}finally{await fr(t,r)}}function z(n){return n===void 0?T.join(ue(),ut):T.join(n,".xeno-agent",ut)}function pe(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 W(n){let e=z(n),t=se(e)?await k(e):null,r=t?b(t,null):null,s=r&&typeof r=="object"?r:null,i={},o=s?.version===ct&&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 pr(e,i),{version:ct,entries:i}}async function Ae(n,e={}){let t=await W(e.homeDir),r=pe(n),s=t.entries[r];if(s&&!(e.role&&s.role&&s.role!==e.role))return s}async function De(n,e={}){let t=pe(n.cwd),r={sessionId:n.sessionId,role:n.role,endedAt:n.endedAt??new Date().toISOString()},s=z(e.homeDir);await Me(s,t,r),await Ie(e.homeDir,async()=>{let i=await W(e.homeDir);i.entries[t]=r,await y(s,JSON.stringify(i,null,2)+`
|
|
53
53
|
`)})}async function hr(n,e={}){let t=pe(n),r=z(e.homeDir);(await W(e.homeDir)).entries[t]&&(await Me(r,t,null),await Ie(e.homeDir,async()=>{let i=await W(e.homeDir);delete i.entries[t],await y(r,JSON.stringify(i,null,2)+`
|
|
54
54
|
`)}))}async function ge(n,e={}){let t=await W(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=>Me(s,i,null))),await Ie(e.homeDir,async()=>{let i=await W(e.homeDir);for(let[o,a]of Object.entries(i.entries))a.sessionId===n&&delete i.entries[o];await y(s,JSON.stringify(i,null,2)+`
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"sourceRoots": [
|
|
23
23
|
"src"
|
|
24
24
|
],
|
|
25
|
-
"reportDirectory": "docs/compliance"
|
|
25
|
+
"reportDirectory": "docs/compliance/memos"
|
|
26
26
|
},
|
|
27
27
|
"cli": {
|
|
28
28
|
"label": "@xenosystem/agent-cli",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"additionalOwnedSourceRoots": [
|
|
38
38
|
"../xeno-agent-sdk/src"
|
|
39
39
|
],
|
|
40
|
-
"reportDirectory": "docs/compliance"
|
|
40
|
+
"reportDirectory": "docs/compliance/memos"
|
|
41
41
|
}
|
|
42
42
|
},
|
|
43
43
|
"runtimeComponents": [
|