@xenosystem/agent-sdk 0.10.26 → 0.10.29

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.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)+`
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.29";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.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)+`
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.29";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)+`
@@ -1 +1 @@
1
- "use strict";var O=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var J=(e,i)=>{for(var n in i)O(e,n,{get:i[n],enumerable:!0})},K=(e,i,n,c)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of V(i))!D.call(e,r)&&r!==n&&O(e,r,{get:()=>i[r],enumerable:!(c=z(i,r))||c.enumerable});return e};var q=e=>K(O({},"__esModule",{value:!0}),e);var ue={};J(ue,{RUN_LEASE_MAX_SECONDS:()=>H,RUN_LEASE_SKEW_SECONDS:()=>C,RunAuthorityRefusedError:()=>P,RunStepRefused:()=>b,WorkforceAdmissionRefused:()=>w,createWorkforceRunAdmissionClient:()=>le,createWorkforceRunAuthority:()=>Q,verifyWorkforceRunLease:()=>W});module.exports=q(ue);var L=require("node:crypto"),B="/api/workforce/run-admissions/authorize-step",Y="/api/oauth2/jwks",H=60,C=5,Z="xeno-run-lease+jwt",F=1e4,N=65536,b=class extends Error{constructor(n){super(`run step refused: ${n}`);this.reason=n;this.name="RunStepRefused",this.details={reason:n}}reason;details};function W(e,i){let n=o=>({valid:!1,reason:o}),c=typeof e=="string"?e.split("."):[];if(c.length!==3)return n("malformed");let r,d;try{r=JSON.parse(Buffer.from(c[0],"base64url").toString("utf8")),d=JSON.parse(Buffer.from(c[1],"base64url").toString("utf8"))}catch{return n("malformed")}if(r.alg!=="ES256"||r.typ!==Z)return n("wrong_type");if(!i.publicKey)return n("unknown_key");if(!(0,L.verify)("sha256",Buffer.from(`${c[0]}.${c[1]}`),{key:i.publicKey,dsaEncoding:"ieee-p1363"},Buffer.from(c[2],"base64url")))return n("bad_signature");if(d.iss!=="xeno-platform"||d.aud!=="xeno-run-runtime"||d.sub!==i.admissionId)return n("wrong_subject");if(!Number.isSafeInteger(d.iat)||!Number.isSafeInteger(d.exp)||d.exp<=d.iat||d.exp-d.iat>H)return n("unbounded");if(!Array.isArray(d.caps)||!d.caps.every(o=>typeof o=="string"))return n("malformed");let l;try{l=BigInt(d.seq)}catch{return n("malformed")}if(l<i.minSequence)return n("superseded");if(i.nowWallMs/1e3>=d.exp-C)return n("expired");if(i.receivedAtMono===null)return n("requires_online_reauthorization");let s=(i.nowMono-i.receivedAtMono)/1e3;return s<0?n("requires_online_reauthorization"):s>=d.exp-d.iat-C?n("expired"):{valid:!0,sequence:l,claims:d}}async function X(e,i){let n=e.headers.get("content-length");if(n!==null&&(!/^\d+$/.test(n)||Number(n)>N))throw new Error("response too large");if(!e.body)return null;let c=e.body.getReader(),r=[],d=0;try{for(;;){let{done:s,value:o}=await c.read();if(i.aborted)throw new Error("response did not complete before the deadline");if(s)break;if(d+=o.byteLength,d>N)throw new Error("response too large");r.push(o)}}finally{try{c.releaseLock()}catch{}}let t=new Uint8Array(d),l=0;for(let s of r)t.set(s,l),l+=s.byteLength;return t.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t)):null}function Q(e){let i=e.fetchImpl??globalThis.fetch,n=e.clock??{wallMs:()=>Date.now(),monoMs:()=>performance.now()},c=e.admissionId;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c))throw new Error("invalid admission id");let r;try{r=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(r.protocol!=="https:"||r.pathname!=="/"||r.username||r.password||r.search||r.hash)throw new Error("invalid issuer");let d=r.origin,t=new Map,l=new Map,s=null,o=async(a,p,u)=>{let y=`${d}${p}`,v=new AbortController,A=setTimeout(()=>v.abort(),F);A.unref?.();try{let S=null;if(a==="POST"&&(S=await e.authorizeRequest({method:a,url:y}),!S))throw new b("authority_unavailable");let M=await i(y,{method:a,redirect:"error",signal:v.signal,headers:{accept:"application/json",...u?{"content-type":"application/json"}:{},...S?{authorization:S.authorization,...S.dpop?{dpop:S.dpop}:{}}:{}},...u?{body:JSON.stringify(u)}:{}});return{status:M.status,json:await X(M,v.signal)}}finally{clearTimeout(A)}},f=async a=>{if(t.has(a))return t.get(a);let{status:p,json:u}=await o("GET",Y);if(p!==200||!u||typeof u!="object"||!Array.isArray(u.keys))return null;for(let y of u.keys)if(!(typeof y.kid!="string"||y.kty!=="EC"||y.crv!=="P-256"))try{t.set(y.kid,(0,L.createPublicKey)({key:{kty:"EC",crv:"P-256",x:y.x,y:y.y},format:"jwk"}))}catch{}return t.get(a)??null},m=()=>e.sequenceStore.read(c)??0n,g=(a,p)=>`${a}:${p??""}`,R=async a=>{let p=JSON.parse(Buffer.from(a.token.split(".")[0],"base64url").toString("utf8")).kid;return W(a.token,{publicKey:await f(p),admissionId:c,receivedAtMono:a.receivedAtMono,nowMono:n.monoMs(),nowWallMs:n.wallMs(),minSequence:m()}).valid},_=async(a,p,u)=>{if(u.throwIfAborted(),s)throw new b(s);let y=l.get(g(a,p));if(y&&await R(y).catch(()=>!1))return;let v;try{v=await o("POST",B,{admissionId:c,operation:a,...p?{capability:p}:{}})}catch(E){throw E instanceof b?E:new b("authority_unavailable")}let A=v.json;if(v.status!==200||A?.success!==!0||typeof A.token!="string"){let E=typeof A?.details?.reason=="string"&&/^[a-z_]{1,64}$/.test(A.details.reason)?A.details.reason:"authority_unavailable";throw E==="admission_revoked"&&(s=E),new b(E)}let S=n.monoMs(),M=(()=>{try{return JSON.parse(Buffer.from(A.token.split(".")[0],"base64url").toString("utf8"))}catch{return null}})();if(typeof M?.kid!="string")throw new b("authority_unavailable");let x=W(A.token,{publicKey:await f(M.kid).catch(()=>null),admissionId:c,receivedAtMono:S,nowMono:n.monoMs(),nowWallMs:n.wallMs(),minSequence:m()});if(!x.valid)throw new b("authority_unavailable");if(a==="privileged_call"&&x.claims.cap!==p)throw new b("authority_unavailable");await e.sequenceStore.write(c,x.sequence),l.set(g(a,p),{token:A.token,sequence:x.sequence,operation:a,capability:p,capabilities:x.claims.caps,iat:x.claims.iat,exp:x.claims.exp,receivedAtMono:S})};return{authorizeDispatch:(a,p)=>_("provider_dispatch",null,p),authorizeToolCall:(a,p)=>{let u=e.capabilityForTool(a.toolName);return u===null||!/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/.test(u)?Promise.reject(new b("capability_not_admitted")):_("privileged_call",u,p)}}}var G="/api/workforce/run-admissions",ee="/api/workforce/run-admissions/revoke",te="/api/workforce/run-admissions/authority",ne="/api/workforce/run-admissions/pin",re="/api/workforce/run-admissions/read",oe="/api/workforce/run-admissions/operations/read";var I=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ie=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,$=/^[a-z_]{1,64}$/,se=new Set(["bad_input","denied","not_found","needs_approval","conflict","rate_limited","unavailable","timeout","internal"]),w=class extends Error{constructor(n,c,r={}){super(`workforce admission refused: ${n}/${c}`);this.code=n;this.reason=c;this.name="WorkforceAdmissionRefused",this.details={reason:c,...r}}code;reason;details},k=()=>new w("unavailable","authority_unavailable"),h=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),T=e=>Array.isArray(e)&&e.length<=64&&e.every(i=>typeof i=="string"&&ie.test(i));function j(e){if(!h(e)||e.schemaVersion!==1||typeof e.admissionId!="string"||!I.test(e.admissionId)||typeof e.operationId!="string"||!I.test(e.operationId))return null;let i=e.agent;if(!h(i)||typeof i.resourceId!="string"||!I.test(i.resourceId)||!Number.isSafeInteger(i.version)||typeof i.contentHash!="string")return null;let n=e.capabilities;if(!h(n)||!T(n.effective)||!T(n.requested))return null;let c=e.payer;if(!h(c)||typeof c.kind!="string")return null;let r=e.budget;return!h(r)||typeof r.ceilingMicro!="string"||!/^[1-9][0-9]{0,17}$/.test(r.ceilingMicro)||!h(e.target)||typeof e.admittedAt!="string"||!Number.isFinite(Date.parse(e.admittedAt))?null:e}var ae=/^[0-9a-f]{64}$/;function ce(e,i,n,c){if(!h(e)||e.schemaVersion!==1)return null;let r=e.agent;if(!h(r)||typeof r.resourceId!="string"||r.resourceId.toLowerCase()!==i||!Number.isSafeInteger(r.version)||r.version<1||typeof r.contentHash!="string"||!ae.test(r.contentHash)||!h(e.target)||JSON.stringify(Object.entries(e.target).map(([l,s])=>[l,typeof s=="string"?s.toLowerCase():s]).sort())!==JSON.stringify(Object.entries(n).map(([l,s])=>[l,typeof s=="string"?s.toLowerCase():s]).sort()))return null;let d=e.team;if(c?!h(d)||typeof d.teamId!="string"||d.teamId.toLowerCase()!==c:d!==null)return null;let t=e.terms;return!h(t)||!T(t.definition)||!T(t.target)?null:{schemaVersion:1,agent:{resourceId:i,version:r.version,contentHash:r.contentHash},target:{...n},team:c?{teamId:c}:null,terms:{definition:[...t.definition],target:[...t.target]}}}function U(e,i){return!h(e)||e.schemaVersion!==1||e.admissionId!==i||typeof e.revoked!="boolean"?null:{schemaVersion:1,admissionId:i,revoked:e.revoked,reason:typeof e.reason=="string"&&$.test(e.reason)?e.reason:null,revokedAt:typeof e.revokedAt=="string"?e.revokedAt:null,latestLeaseSequence:typeof e.latestLeaseSequence=="string"?e.latestLeaseSequence:null}}async function de(e,i){let n=e.headers.get("content-length");if(n!==null&&(!/^\d+$/.test(n)||Number(n)>65536))throw new Error("response too large");if(!e.body)return null;let c=e.body.getReader(),r=[],d=0;try{for(;;){let{done:s,value:o}=await c.read();if(i.aborted)throw new Error("response did not complete before the deadline");if(s)break;if(d+=o.byteLength,d>65536)throw new Error("response too large");r.push(o)}}finally{try{c.releaseLock()}catch{}}let t=new Uint8Array(d),l=0;for(let s of r)t.set(s,l),l+=s.byteLength;return t.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t)):null}function le(e){let i=e.fetchImpl??globalThis.fetch,n;try{n=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(n.protocol!=="https:"||n.pathname!=="/"||n.username||n.password||n.search||n.hash)throw new Error("invalid issuer");let c=n.origin,r=async(t,l,s)=>{let o=`${c}${t}`,f=new AbortController,m=()=>f.abort();s?.addEventListener("abort",m,{once:!0});let g=setTimeout(m,15e3);g.unref?.();try{s?.throwIfAborted();let R=await e.authorizeRequest({method:"POST",url:o});if(!R)throw k();let _,a;try{_=await i(o,{method:"POST",redirect:"error",signal:f.signal,headers:{accept:"application/json","content-type":"application/json",authorization:R.authorization,...R.dpop?{dpop:R.dpop}:{}},body:JSON.stringify(l)}),a=await de(_,f.signal)}catch(y){throw s?.aborted?y:k()}if(_.status===200&&h(a)&&a.success===!0)return a;let p=h(a)&&typeof a.code=="string"&&se.has(a.code)?a.code:null,u=h(a)&&h(a.details)?a.details:null;throw p&&u&&u.schemaVersion===1&&typeof u.reason=="string"&&$.test(u.reason)?new w(p,u.reason,{...Number.isSafeInteger(u.currentVersion)?{currentVersion:u.currentVersion}:{},...typeof u.availableMicro=="string"&&/^[0-9]{1,20}$/.test(u.availableMicro)?{availableMicro:u.availableMicro}:{},...typeof u.field=="string"&&/^[a-zA-Z.]{1,64}$/.test(u.field)?{field:u.field}:{}}):p?new w(p,p==="denied"&&_.status===403&&h(a)&&typeof a.required_scope=="string"?"insufficient_scope":p):k()}finally{clearTimeout(g),s?.removeEventListener("abort",m)}},d=t=>{if(typeof t!="string"||!I.test(t))throw new w("bad_input","invalid_admission");return t.toLowerCase()};return{async admit(t,l){if(!I.test(t.operationId))throw new w("bad_input","invalid_operation");if(!T(t.capabilities))throw new w("bad_input","invalid_capabilities");if(t.runtimeCapabilities!==void 0&&!T(t.runtimeCapabilities))throw new w("bad_input","invalid_runtime_capabilities");if(!/^[1-9][0-9]{0,17}$/.test(t.budget?.ceilingMicro??""))throw new w("bad_input","invalid_budget_ceiling");let s={operationId:t.operationId,agent:{resourceId:t.agent.resourceId,version:t.agent.version,contentHash:t.agent.contentHash},target:{...t.target},capabilities:[...t.capabilities],budget:{ceilingMicro:t.budget.ceilingMicro},...t.expectedActorAccountId?{expectedActorAccountId:t.expectedActorAccountId}:{},...t.team?{team:{teamId:t.team.teamId}}:{},...t.conversationId?{conversationId:t.conversationId}:{},...t.root?{root:{bindingId:t.root.bindingId,installationId:t.root.installationId}}:{},...t.runtimeCapabilities?{runtimeCapabilities:[...t.runtimeCapabilities]}:{}},o=await r(G,s,l),f=j(o.admission);if(!f||f.operationId.toLowerCase()!==t.operationId.toLowerCase())throw k();return{admission:f,replayed:o.replayed===!0}},async revoke(t,l){let s=d(t),o=U(await r(ee,{admissionId:s},l),s);if(!o||!o.revoked)throw k();return o},async pin(t,l){let s=t?.agent?.resourceId;if(typeof s!="string"||!I.test(s))throw new w("bad_input","invalid_agent_resource");let o=t.target,f=h(o)?o.kind==="personal"?[o.ownerUserId]:o.kind==="workspace"?[o.assignmentId]:o.kind==="project"?[o.projectId,o.participationId]:null:null;if(!f||!f.every(a=>typeof a=="string"&&I.test(a)))throw new w("bad_input","invalid_target");let m=o.kind==="personal"?{kind:"personal",ownerUserId:o.ownerUserId}:o.kind==="workspace"?{kind:"workspace",assignmentId:o.assignmentId}:{kind:"project",projectId:o.projectId,participationId:o.participationId},g=t.team?t.team.teamId:null;if(g!==null&&(typeof g!="string"||!I.test(g)))throw new w("bad_input","invalid_team");let R={agent:{resourceId:s},target:m,...g?{team:{teamId:g}}:{},...t.expectedActorAccountId?{expectedActorAccountId:t.expectedActorAccountId}:{}},_=ce(await r(ne,R,l),s.toLowerCase(),m,g?g.toLowerCase():null);if(!_)throw k();return _},async read(t,l,s){let o=d(t),f=l?.expectedActorAccountId;if(f!==void 0&&(typeof f!="string"||!I.test(f)))throw new w("bad_input","invalid_expected_actor");let m=await r(re,{admissionId:o,...f?{expectedActorAccountId:f}:{}},s),g=j(m.admission);if(!g||g.admissionId.toLowerCase()!==o)throw k();return g},async readOperation(t,l,s){if(typeof t!="string"||!I.test(t))throw new w("bad_input","invalid_operation");let o=l?.expectedActorAccountId;if(typeof o!="string"||!I.test(o))throw new w("bad_input","invalid_expected_actor");let f=t.toLowerCase(),m=await r(oe,{operationId:f,expectedActorAccountId:o.toLowerCase()},s);if(m.schemaVersion!==1||typeof m.operationId!="string"||m.operationId.toLowerCase()!==f)throw k();if(m.state==="not-observed"&&m.admission===null)return{state:"not-observed",operationId:f,admission:null};if(m.state!=="committed")throw k();let g=j(m.admission);if(!g||g.operationId.toLowerCase()!==f)throw k();return{state:"committed",operationId:f,admission:g}},async authority(t,l){let s=d(t),o=U(await r(te,{admissionId:s},l),s);if(!o)throw k();return o}}}var P=class extends Error{code="RUN_AUTHORITY_REFUSED";retryable=!1;reason;step;constructor(i,n,c){super(`Run authority refused the ${i==="dispatch"?"provider dispatch":"tool call"}: ${n}`,c),this.name="RunAuthorityRefusedError",this.reason=n,this.step=i}};0&&(module.exports={RUN_LEASE_MAX_SECONDS,RUN_LEASE_SKEW_SECONDS,RunAuthorityRefusedError,RunStepRefused,WorkforceAdmissionRefused,createWorkforceRunAdmissionClient,createWorkforceRunAuthority,verifyWorkforceRunLease});
1
+ "use strict";var M=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var G=(e,r)=>{for(var t in r)M(e,t,{get:r[t],enumerable:!0})},Q=(e,r,t,c)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Y(r))!X.call(e,i)&&i!==t&&M(e,i,{get:()=>r[i],enumerable:!(c=F(r,i))||c.enumerable});return e};var ee=e=>Q(M({},"__esModule",{value:!0}),e);var Re={};G(Re,{RUN_LEASE_MAX_SECONDS:()=>$,RUN_LEASE_SKEW_SECONDS:()=>P,RunAuthorityRefusedError:()=>O,RunStepRefused:()=>A,WorkforceAdmissionRefused:()=>w,createWorkforceRunAdmissionClient:()=>ve,createWorkforceRunAuthority:()=>se,verifyWorkforceRunLease:()=>N,workforceDefinitionContentHash:()=>Z});module.exports=ee(Re);var L=require("node:crypto"),te="/api/workforce/run-admissions/authorize-step",ne="/api/oauth2/jwks",$=60,P=5,re="xeno-run-lease+jwt",oe=1e4,V=65536,A=class extends Error{constructor(t){super(`run step refused: ${t}`);this.reason=t;this.name="RunStepRefused",this.details={reason:t}}reason;details};function N(e,r){let t=s=>({valid:!1,reason:s}),c=typeof e=="string"?e.split("."):[];if(c.length!==3)return t("malformed");let i,o;try{i=JSON.parse(Buffer.from(c[0],"base64url").toString("utf8")),o=JSON.parse(Buffer.from(c[1],"base64url").toString("utf8"))}catch{return t("malformed")}if(i.alg!=="ES256"||i.typ!==re)return t("wrong_type");if(!r.publicKey)return t("unknown_key");if(!(0,L.verify)("sha256",Buffer.from(`${c[0]}.${c[1]}`),{key:r.publicKey,dsaEncoding:"ieee-p1363"},Buffer.from(c[2],"base64url")))return t("bad_signature");if(o.iss!=="xeno-platform"||o.aud!=="xeno-run-runtime"||o.sub!==r.admissionId)return t("wrong_subject");if(!Number.isSafeInteger(o.iat)||!Number.isSafeInteger(o.exp)||o.exp<=o.iat||o.exp-o.iat>$)return t("unbounded");if(!Array.isArray(o.caps)||!o.caps.every(s=>typeof s=="string"))return t("malformed");let d;try{d=BigInt(o.seq)}catch{return t("malformed")}if(d<r.minSequence)return t("superseded");if(r.nowWallMs/1e3>=o.exp-P)return t("expired");if(r.receivedAtMono===null)return t("requires_online_reauthorization");let a=(r.nowMono-r.receivedAtMono)/1e3;return a<0?t("requires_online_reauthorization"):a>=o.exp-o.iat-P?t("expired"):{valid:!0,sequence:d,claims:o}}async function ie(e,r){let t=e.headers.get("content-length");if(t!==null&&(!/^\d+$/.test(t)||Number(t)>V))throw new Error("response too large");if(!e.body)return null;let c=e.body.getReader(),i=[],o=0;try{for(;;){let{done:a,value:s}=await c.read();if(r.aborted)throw new Error("response did not complete before the deadline");if(a)break;if(o+=s.byteLength,o>V)throw new Error("response too large");i.push(s)}}finally{try{c.releaseLock()}catch{}}let n=new Uint8Array(o),d=0;for(let a of i)n.set(a,d),d+=a.byteLength;return n.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)):null}function se(e){let r=e.fetchImpl??globalThis.fetch,t=e.clock??{wallMs:()=>Date.now(),monoMs:()=>performance.now()},c=e.admissionId;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c))throw new Error("invalid admission id");let i;try{i=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(i.protocol!=="https:"||i.pathname!=="/"||i.username||i.password||i.search||i.hash)throw new Error("invalid issuer");let o=i.origin,n=new Map,d=new Map,a=null,s=async(f,u,h)=>{let g=`${o}${u}`,v=new AbortController,I=setTimeout(()=>v.abort(),oe);I.unref?.();try{let R=null;if(f==="POST"&&(R=await e.authorizeRequest({method:f,url:g}),!R))throw new A("authority_unavailable");let C=await r(g,{method:f,redirect:"error",signal:v.signal,headers:{accept:"application/json",...h?{"content-type":"application/json"}:{},...R?{authorization:R.authorization,...R.dpop?{dpop:R.dpop}:{}}:{}},...h?{body:JSON.stringify(h)}:{}});return{status:C.status,json:await ie(C,v.signal)}}finally{clearTimeout(I)}},l=async f=>{if(n.has(f))return n.get(f);let{status:u,json:h}=await s("GET",ne);if(u!==200||!h||typeof h!="object"||!Array.isArray(h.keys))return null;for(let g of h.keys)if(!(typeof g.kid!="string"||g.kty!=="EC"||g.crv!=="P-256"))try{n.set(g.kid,(0,L.createPublicKey)({key:{kty:"EC",crv:"P-256",x:g.x,y:g.y},format:"jwk"}))}catch{}return n.get(f)??null},y=()=>e.sequenceStore.read(c)??0n,m=(f,u)=>`${f}:${u??""}`,x=async f=>{let u=JSON.parse(Buffer.from(f.token.split(".")[0],"base64url").toString("utf8")).kid;return N(f.token,{publicKey:await l(u),admissionId:c,receivedAtMono:f.receivedAtMono,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()}).valid},_=async(f,u,h)=>{if(h.throwIfAborted(),a)throw new A(a);let g=d.get(m(f,u));if(g&&await x(g).catch(()=>!1))return;let v;try{v=await s("POST",te,{admissionId:c,operation:f,...u?{capability:u}:{}})}catch(E){throw E instanceof A?E:new A("authority_unavailable")}let I=v.json;if(v.status!==200||I?.success!==!0||typeof I.token!="string"){let E=typeof I?.details?.reason=="string"&&/^[a-z_]{1,64}$/.test(I.details.reason)?I.details.reason:"authority_unavailable";throw E==="admission_revoked"&&(a=E),new A(E)}let R=t.monoMs(),C=(()=>{try{return JSON.parse(Buffer.from(I.token.split(".")[0],"base64url").toString("utf8"))}catch{return null}})();if(typeof C?.kid!="string")throw new A("authority_unavailable");let S=N(I.token,{publicKey:await l(C.kid).catch(()=>null),admissionId:c,receivedAtMono:R,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()});if(!S.valid)throw new A("authority_unavailable");if(f==="privileged_call"&&S.claims.cap!==u)throw new A("authority_unavailable");await e.sequenceStore.write(c,S.sequence),d.set(m(f,u),{token:I.token,sequence:S.sequence,operation:f,capability:u,capabilities:S.claims.caps,iat:S.claims.iat,exp:S.claims.exp,receivedAtMono:R})};return{authorizeDispatch:(f,u)=>_("provider_dispatch",null,u),authorizeToolCall:(f,u)=>{let h=e.capabilityForTool(f.toolName);return h===null||!/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/.test(h)?Promise.reject(new A("capability_not_admitted")):_("privileged_call",h,u)}}}var J=require("node:crypto"),ae="/api/workforce/run-admissions",ce="/api/workforce/run-admissions/revoke",de="/api/workforce/run-admissions/authority",ue="/api/workforce/run-admissions/pin",le="/api/workforce/run-admissions/read",fe="/api/workforce/run-admissions/operations/read",ge="/api/workforce/resources/definition/read",pe=15e3,K=65536,me=256*1024,he=32768,H=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,ye=/^[A-Z][A-Z0-9_]{0,63}$/,b=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,we=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,q=/^[a-z_]{1,64}$/,be=new Set(["bad_input","denied","not_found","needs_approval","conflict","rate_limited","unavailable","timeout","internal"]),w=class extends Error{constructor(t,c,i={}){super(`workforce admission refused: ${t}/${c}`);this.code=t;this.reason=c;this.name="WorkforceAdmissionRefused",this.details={reason:c,...i}}code;reason;details},k=()=>new w("unavailable","authority_unavailable"),p=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),T=e=>Array.isArray(e)&&e.length<=64&&e.every(r=>typeof r=="string"&&we.test(r));function W(e){if(!p(e)||e.schemaVersion!==1||typeof e.admissionId!="string"||!b.test(e.admissionId)||typeof e.operationId!="string"||!b.test(e.operationId))return null;let r=e.agent;if(!p(r)||typeof r.resourceId!="string"||!b.test(r.resourceId)||!Number.isSafeInteger(r.version)||typeof r.contentHash!="string")return null;let t=e.capabilities;if(!p(t)||!T(t.effective)||!T(t.requested))return null;let c=e.payer;if(!p(c)||typeof c.kind!="string")return null;let i=e.budget;return!p(i)||typeof i.ceilingMicro!="string"||!/^[1-9][0-9]{0,17}$/.test(i.ceilingMicro)||!p(e.target)||typeof e.admittedAt!="string"||!Number.isFinite(Date.parse(e.admittedAt))?null:e}var z=/^[0-9a-f]{64}$/;function Ae(e,r,t,c){if(!p(e)||e.schemaVersion!==1)return null;let i=e.agent;if(!p(i)||typeof i.resourceId!="string"||i.resourceId.toLowerCase()!==r||!Number.isSafeInteger(i.version)||i.version<1||typeof i.contentHash!="string"||!z.test(i.contentHash)||!p(e.target)||JSON.stringify(Object.entries(e.target).map(([d,a])=>[d,typeof a=="string"?a.toLowerCase():a]).sort())!==JSON.stringify(Object.entries(t).map(([d,a])=>[d,typeof a=="string"?a.toLowerCase():a]).sort()))return null;let o=e.team;if(c?!p(o)||typeof o.teamId!="string"||o.teamId.toLowerCase()!==c:o!==null)return null;let n=e.terms;return!p(n)||!T(n.definition)||!T(n.target)?null:{schemaVersion:1,agent:{resourceId:r,version:i.version,contentHash:i.contentHash},target:{...t},team:c?{teamId:c}:null,terms:{definition:[...n.definition],target:[...n.target]}}}function B(e,r){return!p(e)||e.schemaVersion!==1||e.admissionId!==r||typeof e.revoked!="boolean"?null:{schemaVersion:1,admissionId:r,revoked:e.revoked,reason:typeof e.reason=="string"&&q.test(e.reason)?e.reason:null,revokedAt:typeof e.revokedAt=="string"?e.revokedAt:null,latestLeaseSequence:typeof e.latestLeaseSequence=="string"?e.latestLeaseSequence:null}}function U(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(U):Object.fromEntries(Object.keys(e).sort().map(r=>[r,U(e[r])]))}function Z(e){return(0,J.createHash)("sha256").update(JSON.stringify(U({schemaVersion:1,content:e.content,provenance:e.provenance,license:e.license}))).digest("hex")}var j=(e,r)=>Object.keys(e).every(t=>r.includes(t)),D=(e,r)=>new Set(e.map(r)).size===e.length;function ke(e){if(!p(e)||!j(e,["instructions","skills","requestedCapabilities","secretReferences"]))return null;let{instructions:r,skills:t,requestedCapabilities:c,secretReferences:i}=e;return typeof r!="string"||r.includes("\0")||new TextEncoder().encode(r).byteLength>he||!Array.isArray(t)||t.length>64||!t.every(o=>p(o)&&j(o,["id","version","hash"])&&typeof o.id=="string"&&H.test(o.id)&&typeof o.version=="string"&&H.test(o.version)&&typeof o.hash=="string"&&z.test(o.hash))||!D(t,o=>o.id)||!Array.isArray(c)||c.length>64||!c.every(o=>typeof o=="string"&&H.test(o))||!D(c,o=>o)||!Array.isArray(i)||i.length>32||!i.every(o=>p(o)&&j(o,["name","ref"])&&typeof o.name=="string"&&ye.test(o.name)&&typeof o.ref=="string"&&b.test(o.ref))||!D(i,o=>o.name)?null:{instructions:r,skills:t.map(({id:o,version:n,hash:d})=>({id:o,version:n,hash:d})),requestedCapabilities:[...c],secretReferences:i.map(({name:o,ref:n})=>({name:o,ref:n}))}}function Ie(e,r){if(!p(e)||e.schemaVersion!==1||!p(e.access)||e.access.allowed!==!0)return null;let t=e.version;if(!p(t)||t.schemaVersion!==1||typeof t.resourceId!="string"||t.resourceId.toLowerCase()!==r.resourceId||t.version!==r.version||t.contentHash!==r.contentHash)return null;let c=ke(t.content);return!c||!p(t.provenance)||!p(t.license)||t.createdByUserId!==null&&(typeof t.createdByUserId!="string"||!b.test(t.createdByUserId))||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||Z({content:t.content,provenance:t.provenance,license:t.license})!==r.contentHash?null:{resourceId:r.resourceId,version:r.version,schemaVersion:1,content:c,contentHash:r.contentHash,provenance:t.provenance,license:t.license,createdByUserId:t.createdByUserId,createdAt:t.createdAt}}async function _e(e,r,t=K){let c=e.headers.get("content-length");if(c!==null&&(!/^\d+$/.test(c)||Number(c)>t))throw new Error("response too large");if(!e.body)return null;let i=e.body.getReader(),o=[],n=0;try{for(;;){let{done:s,value:l}=await i.read();if(r.aborted)throw new Error("response did not complete before the deadline");if(s)break;if(n+=l.byteLength,n>t)throw new Error("response too large");o.push(l)}}finally{try{i.releaseLock()}catch{}}let d=new Uint8Array(n),a=0;for(let s of o)d.set(s,a),a+=s.byteLength;return d.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)):null}function ve(e){let r=e.fetchImpl??globalThis.fetch,t;try{t=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(t.protocol!=="https:"||t.pathname!=="/"||t.username||t.password||t.search||t.hash)throw new Error("invalid issuer");let c=t.origin,i=async(n,d,a,s=K)=>{let l=`${c}${n}`,y=new AbortController,m=()=>y.abort();a?.addEventListener("abort",m,{once:!0});let x=setTimeout(m,pe);x.unref?.();try{a?.throwIfAborted();let _=await e.authorizeRequest({method:"POST",url:l});if(!_)throw k();let f,u;try{f=await r(l,{method:"POST",redirect:"error",signal:y.signal,headers:{accept:"application/json","content-type":"application/json",authorization:_.authorization,..._.dpop?{dpop:_.dpop}:{}},body:JSON.stringify(d)}),u=await _e(f,y.signal,s)}catch(v){throw a?.aborted?v:k()}if(f.status===200&&p(u)&&u.success===!0)return u;let h=p(u)&&typeof u.code=="string"&&be.has(u.code)?u.code:null,g=p(u)&&p(u.details)?u.details:null;throw h&&g&&g.schemaVersion===1&&typeof g.reason=="string"&&q.test(g.reason)?new w(h,g.reason,{...Number.isSafeInteger(g.currentVersion)?{currentVersion:g.currentVersion}:{},...typeof g.availableMicro=="string"&&/^[0-9]{1,20}$/.test(g.availableMicro)?{availableMicro:g.availableMicro}:{},...typeof g.field=="string"&&/^[a-zA-Z.]{1,64}$/.test(g.field)?{field:g.field}:{}}):h?new w(h,h==="denied"&&f.status===403&&p(u)&&typeof u.required_scope=="string"?"insufficient_scope":h):k()}finally{clearTimeout(x),a?.removeEventListener("abort",m)}},o=n=>{if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_admission");return n.toLowerCase()};return{async admit(n,d){if(!b.test(n.operationId))throw new w("bad_input","invalid_operation");if(!T(n.capabilities))throw new w("bad_input","invalid_capabilities");if(n.runtimeCapabilities!==void 0&&!T(n.runtimeCapabilities))throw new w("bad_input","invalid_runtime_capabilities");if(!/^[1-9][0-9]{0,17}$/.test(n.budget?.ceilingMicro??""))throw new w("bad_input","invalid_budget_ceiling");let a={operationId:n.operationId,agent:{resourceId:n.agent.resourceId,version:n.agent.version,contentHash:n.agent.contentHash},target:{...n.target},capabilities:[...n.capabilities],budget:{ceilingMicro:n.budget.ceilingMicro},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{},...n.team?{team:{teamId:n.team.teamId}}:{},...n.conversationId?{conversationId:n.conversationId}:{},...n.root?{root:{bindingId:n.root.bindingId,installationId:n.root.installationId}}:{},...n.runtimeCapabilities?{runtimeCapabilities:[...n.runtimeCapabilities]}:{}},s=await i(ae,a,d),l=W(s.admission);if(!l||l.operationId.toLowerCase()!==n.operationId.toLowerCase())throw k();return{admission:l,replayed:s.replayed===!0}},async revoke(n,d){let a=o(n),s=B(await i(ce,{admissionId:a},d),a);if(!s||!s.revoked)throw k();return s},async pin(n,d){let a=n?.agent?.resourceId;if(typeof a!="string"||!b.test(a))throw new w("bad_input","invalid_agent_resource");let s=n.target,l=p(s)?s.kind==="personal"?[s.ownerUserId]:s.kind==="workspace"?[s.assignmentId]:s.kind==="project"?[s.projectId,s.participationId]:null:null;if(!l||!l.every(f=>typeof f=="string"&&b.test(f)))throw new w("bad_input","invalid_target");let y=s.kind==="personal"?{kind:"personal",ownerUserId:s.ownerUserId}:s.kind==="workspace"?{kind:"workspace",assignmentId:s.assignmentId}:{kind:"project",projectId:s.projectId,participationId:s.participationId},m=n.team?n.team.teamId:null;if(m!==null&&(typeof m!="string"||!b.test(m)))throw new w("bad_input","invalid_team");let x={agent:{resourceId:a},target:y,...m?{team:{teamId:m}}:{},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{}},_=Ae(await i(ue,x,d),a.toLowerCase(),y,m?m.toLowerCase():null);if(!_)throw k();return _},async read(n,d,a){let s=o(n),l=d?.expectedActorAccountId;if(l!==void 0&&(typeof l!="string"||!b.test(l)))throw new w("bad_input","invalid_expected_actor");let y=await i(le,{admissionId:s,...l?{expectedActorAccountId:l}:{}},a),m=W(y.admission);if(!m||m.admissionId.toLowerCase()!==s)throw k();return m},async readOperation(n,d,a){if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_operation");let s=d?.expectedActorAccountId;if(typeof s!="string"||!b.test(s))throw new w("bad_input","invalid_expected_actor");let l=n.toLowerCase(),y=await i(fe,{operationId:l,expectedActorAccountId:s.toLowerCase()},a);if(y.schemaVersion!==1||typeof y.operationId!="string"||y.operationId.toLowerCase()!==l)throw k();if(y.state==="not-observed"&&y.admission===null)return{state:"not-observed",operationId:l,admission:null};if(y.state!=="committed")throw k();let m=W(y.admission);if(!m||m.operationId.toLowerCase()!==l)throw k();return{state:"committed",operationId:l,admission:m}},async readDefinition(n,d){let a=n?.resourceId;if(typeof a!="string"||!b.test(a))throw new w("bad_input","invalid_agent_resource");if(!Number.isSafeInteger(n.version)||n.version<1)throw new w("bad_input","invalid_version");if(typeof n.contentHash!="string"||!z.test(n.contentHash))throw new w("bad_input","invalid_content_hash");let s=n.expectedActorAccountId;if(typeof s!="string"||!b.test(s))throw new w("bad_input","invalid_expected_actor");let l={resourceId:a.toLowerCase(),version:n.version,contentHash:n.contentHash},y=await i(ge,{...l,expectedActorAccountId:s.toLowerCase()},d,me),m=Ie(y,l);if(!m)throw k();return m},async authority(n,d){let a=o(n),s=B(await i(de,{admissionId:a},d),a);if(!s)throw k();return s}}}var O=class extends Error{code="RUN_AUTHORITY_REFUSED";retryable=!1;reason;step;constructor(r,t,c){super(`Run authority refused the ${r==="dispatch"?"provider dispatch":"tool call"}: ${t}`,c),this.name="RunAuthorityRefusedError",this.reason=t,this.step=r}};0&&(module.exports={RUN_LEASE_MAX_SECONDS,RUN_LEASE_SKEW_SECONDS,RunAuthorityRefusedError,RunStepRefused,WorkforceAdmissionRefused,createWorkforceRunAdmissionClient,createWorkforceRunAuthority,verifyWorkforceRunLease,workforceDefinitionContentHash});
@@ -168,6 +168,30 @@ interface WorkforceRunAuthorityState {
168
168
  revokedAt: string | null;
169
169
  latestLeaseSequence: string | null;
170
170
  }
171
+ interface WorkforceAgentDefinitionContent {
172
+ instructions: string;
173
+ skills: Array<{
174
+ id: string;
175
+ version: string;
176
+ hash: string;
177
+ }>;
178
+ requestedCapabilities: string[];
179
+ secretReferences: Array<{
180
+ name: string;
181
+ ref: string;
182
+ }>;
183
+ }
184
+ interface WorkforceAgentDefinitionVersion {
185
+ resourceId: string;
186
+ version: number;
187
+ schemaVersion: 1;
188
+ content: WorkforceAgentDefinitionContent;
189
+ contentHash: string;
190
+ provenance: Record<string, unknown>;
191
+ license: Record<string, unknown>;
192
+ createdByUserId: string | null;
193
+ createdAt: string;
194
+ }
171
195
  declare class WorkforceAdmissionRefused extends Error {
172
196
  readonly code: string;
173
197
  readonly reason: string;
@@ -215,6 +239,12 @@ interface WorkforceRunAdmissionClient {
215
239
  operationId: string;
216
240
  admission: WorkforceAdmission;
217
241
  }>;
242
+ readDefinition(request: {
243
+ resourceId: string;
244
+ version: number;
245
+ contentHash: string;
246
+ expectedActorAccountId: string;
247
+ }, signal?: AbortSignal): Promise<WorkforceAgentDefinitionVersion>;
218
248
  pin(request: {
219
249
  agent: {
220
250
  resourceId: string;
@@ -226,5 +256,10 @@ interface WorkforceRunAdmissionClient {
226
256
  expectedActorAccountId?: string;
227
257
  }, signal?: AbortSignal): Promise<WorkforceRunnablePin>;
228
258
  }
259
+ declare function workforceDefinitionContentHash(definition: {
260
+ content: unknown;
261
+ provenance: unknown;
262
+ license: unknown;
263
+ }): string;
229
264
  declare function createWorkforceRunAdmissionClient(options: WorkforceRunAdmissionClientOptions): WorkforceRunAdmissionClient;
230
- export { RUN_LEASE_MAX_SECONDS, RUN_LEASE_SKEW_SECONDS, type RunAuthority, type RunAuthorityDispatch, RunAuthorityRefusedError, type RunAuthorityToolCall, type RunLeaseSequenceStore, RunStepRefused, type WorkforceAdmission, WorkforceAdmissionRefused, type WorkforceAdmissionRequest, type WorkforceAdmissionTarget, type WorkforceRunAdmissionClient, type WorkforceRunAdmissionClientOptions, type WorkforceRunAuthorityOptions, type WorkforceRunAuthorityState, type WorkforceRunnablePin, createWorkforceRunAdmissionClient, createWorkforceRunAuthority, verifyWorkforceRunLease };
265
+ export { RUN_LEASE_MAX_SECONDS, RUN_LEASE_SKEW_SECONDS, type RunAuthority, type RunAuthorityDispatch, RunAuthorityRefusedError, type RunAuthorityToolCall, type RunLeaseSequenceStore, RunStepRefused, type WorkforceAdmission, WorkforceAdmissionRefused, type WorkforceAdmissionRequest, type WorkforceAdmissionTarget, type WorkforceAgentDefinitionContent, type WorkforceAgentDefinitionVersion, type WorkforceRunAdmissionClient, type WorkforceRunAdmissionClientOptions, type WorkforceRunAuthorityOptions, type WorkforceRunAuthorityState, type WorkforceRunnablePin, createWorkforceRunAdmissionClient, createWorkforceRunAuthority, verifyWorkforceRunLease, workforceDefinitionContentHash };
@@ -168,6 +168,30 @@ interface WorkforceRunAuthorityState {
168
168
  revokedAt: string | null;
169
169
  latestLeaseSequence: string | null;
170
170
  }
171
+ interface WorkforceAgentDefinitionContent {
172
+ instructions: string;
173
+ skills: Array<{
174
+ id: string;
175
+ version: string;
176
+ hash: string;
177
+ }>;
178
+ requestedCapabilities: string[];
179
+ secretReferences: Array<{
180
+ name: string;
181
+ ref: string;
182
+ }>;
183
+ }
184
+ interface WorkforceAgentDefinitionVersion {
185
+ resourceId: string;
186
+ version: number;
187
+ schemaVersion: 1;
188
+ content: WorkforceAgentDefinitionContent;
189
+ contentHash: string;
190
+ provenance: Record<string, unknown>;
191
+ license: Record<string, unknown>;
192
+ createdByUserId: string | null;
193
+ createdAt: string;
194
+ }
171
195
  declare class WorkforceAdmissionRefused extends Error {
172
196
  readonly code: string;
173
197
  readonly reason: string;
@@ -215,6 +239,12 @@ interface WorkforceRunAdmissionClient {
215
239
  operationId: string;
216
240
  admission: WorkforceAdmission;
217
241
  }>;
242
+ readDefinition(request: {
243
+ resourceId: string;
244
+ version: number;
245
+ contentHash: string;
246
+ expectedActorAccountId: string;
247
+ }, signal?: AbortSignal): Promise<WorkforceAgentDefinitionVersion>;
218
248
  pin(request: {
219
249
  agent: {
220
250
  resourceId: string;
@@ -226,5 +256,10 @@ interface WorkforceRunAdmissionClient {
226
256
  expectedActorAccountId?: string;
227
257
  }, signal?: AbortSignal): Promise<WorkforceRunnablePin>;
228
258
  }
259
+ declare function workforceDefinitionContentHash(definition: {
260
+ content: unknown;
261
+ provenance: unknown;
262
+ license: unknown;
263
+ }): string;
229
264
  declare function createWorkforceRunAdmissionClient(options: WorkforceRunAdmissionClientOptions): WorkforceRunAdmissionClient;
230
- export { RUN_LEASE_MAX_SECONDS, RUN_LEASE_SKEW_SECONDS, type RunAuthority, type RunAuthorityDispatch, RunAuthorityRefusedError, type RunAuthorityToolCall, type RunLeaseSequenceStore, RunStepRefused, type WorkforceAdmission, WorkforceAdmissionRefused, type WorkforceAdmissionRequest, type WorkforceAdmissionTarget, type WorkforceRunAdmissionClient, type WorkforceRunAdmissionClientOptions, type WorkforceRunAuthorityOptions, type WorkforceRunAuthorityState, type WorkforceRunnablePin, createWorkforceRunAdmissionClient, createWorkforceRunAuthority, verifyWorkforceRunLease };
265
+ export { RUN_LEASE_MAX_SECONDS, RUN_LEASE_SKEW_SECONDS, type RunAuthority, type RunAuthorityDispatch, RunAuthorityRefusedError, type RunAuthorityToolCall, type RunLeaseSequenceStore, RunStepRefused, type WorkforceAdmission, WorkforceAdmissionRefused, type WorkforceAdmissionRequest, type WorkforceAdmissionTarget, type WorkforceAgentDefinitionContent, type WorkforceAgentDefinitionVersion, type WorkforceRunAdmissionClient, type WorkforceRunAdmissionClientOptions, type WorkforceRunAuthorityOptions, type WorkforceRunAuthorityState, type WorkforceRunnablePin, createWorkforceRunAdmissionClient, createWorkforceRunAuthority, verifyWorkforceRunLease, workforceDefinitionContentHash };
@@ -1 +1 @@
1
- import{createPublicKey as H,verify as U}from"node:crypto";var $="/api/workforce/run-admissions/authorize-step",z="/api/oauth2/jwks",V=60,O=5,D="xeno-run-lease+jwt",J=1e4,C=65536,A=class extends Error{constructor(n){super(`run step refused: ${n}`);this.reason=n;this.name="RunStepRefused",this.details={reason:n}}reason;details};function W(e,a){let n=r=>({valid:!1,reason:r}),d=typeof e=="string"?e.split("."):[];if(d.length!==3)return n("malformed");let i,c;try{i=JSON.parse(Buffer.from(d[0],"base64url").toString("utf8")),c=JSON.parse(Buffer.from(d[1],"base64url").toString("utf8"))}catch{return n("malformed")}if(i.alg!=="ES256"||i.typ!==D)return n("wrong_type");if(!a.publicKey)return n("unknown_key");if(!U("sha256",Buffer.from(`${d[0]}.${d[1]}`),{key:a.publicKey,dsaEncoding:"ieee-p1363"},Buffer.from(d[2],"base64url")))return n("bad_signature");if(c.iss!=="xeno-platform"||c.aud!=="xeno-run-runtime"||c.sub!==a.admissionId)return n("wrong_subject");if(!Number.isSafeInteger(c.iat)||!Number.isSafeInteger(c.exp)||c.exp<=c.iat||c.exp-c.iat>V)return n("unbounded");if(!Array.isArray(c.caps)||!c.caps.every(r=>typeof r=="string"))return n("malformed");let l;try{l=BigInt(c.seq)}catch{return n("malformed")}if(l<a.minSequence)return n("superseded");if(a.nowWallMs/1e3>=c.exp-O)return n("expired");if(a.receivedAtMono===null)return n("requires_online_reauthorization");let o=(a.nowMono-a.receivedAtMono)/1e3;return o<0?n("requires_online_reauthorization"):o>=c.exp-c.iat-O?n("expired"):{valid:!0,sequence:l,claims:c}}async function K(e,a){let n=e.headers.get("content-length");if(n!==null&&(!/^\d+$/.test(n)||Number(n)>C))throw new Error("response too large");if(!e.body)return null;let d=e.body.getReader(),i=[],c=0;try{for(;;){let{done:o,value:r}=await d.read();if(a.aborted)throw new Error("response did not complete before the deadline");if(o)break;if(c+=r.byteLength,c>C)throw new Error("response too large");i.push(r)}}finally{try{d.releaseLock()}catch{}}let t=new Uint8Array(c),l=0;for(let o of i)t.set(o,l),l+=o.byteLength;return t.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t)):null}function oe(e){let a=e.fetchImpl??globalThis.fetch,n=e.clock??{wallMs:()=>Date.now(),monoMs:()=>performance.now()},d=e.admissionId;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(d))throw new Error("invalid admission id");let i;try{i=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(i.protocol!=="https:"||i.pathname!=="/"||i.username||i.password||i.search||i.hash)throw new Error("invalid issuer");let c=i.origin,t=new Map,l=new Map,o=null,r=async(s,p,u)=>{let y=`${c}${p}`,v=new AbortController,b=setTimeout(()=>v.abort(),J);b.unref?.();try{let S=null;if(s==="POST"&&(S=await e.authorizeRequest({method:s,url:y}),!S))throw new A("authority_unavailable");let M=await a(y,{method:s,redirect:"error",signal:v.signal,headers:{accept:"application/json",...u?{"content-type":"application/json"}:{},...S?{authorization:S.authorization,...S.dpop?{dpop:S.dpop}:{}}:{}},...u?{body:JSON.stringify(u)}:{}});return{status:M.status,json:await K(M,v.signal)}}finally{clearTimeout(b)}},f=async s=>{if(t.has(s))return t.get(s);let{status:p,json:u}=await r("GET",z);if(p!==200||!u||typeof u!="object"||!Array.isArray(u.keys))return null;for(let y of u.keys)if(!(typeof y.kid!="string"||y.kty!=="EC"||y.crv!=="P-256"))try{t.set(y.kid,H({key:{kty:"EC",crv:"P-256",x:y.x,y:y.y},format:"jwk"}))}catch{}return t.get(s)??null},m=()=>e.sequenceStore.read(d)??0n,g=(s,p)=>`${s}:${p??""}`,R=async s=>{let p=JSON.parse(Buffer.from(s.token.split(".")[0],"base64url").toString("utf8")).kid;return W(s.token,{publicKey:await f(p),admissionId:d,receivedAtMono:s.receivedAtMono,nowMono:n.monoMs(),nowWallMs:n.wallMs(),minSequence:m()}).valid},_=async(s,p,u)=>{if(u.throwIfAborted(),o)throw new A(o);let y=l.get(g(s,p));if(y&&await R(y).catch(()=>!1))return;let v;try{v=await r("POST",$,{admissionId:d,operation:s,...p?{capability:p}:{}})}catch(E){throw E instanceof A?E:new A("authority_unavailable")}let b=v.json;if(v.status!==200||b?.success!==!0||typeof b.token!="string"){let E=typeof b?.details?.reason=="string"&&/^[a-z_]{1,64}$/.test(b.details.reason)?b.details.reason:"authority_unavailable";throw E==="admission_revoked"&&(o=E),new A(E)}let S=n.monoMs(),M=(()=>{try{return JSON.parse(Buffer.from(b.token.split(".")[0],"base64url").toString("utf8"))}catch{return null}})();if(typeof M?.kid!="string")throw new A("authority_unavailable");let x=W(b.token,{publicKey:await f(M.kid).catch(()=>null),admissionId:d,receivedAtMono:S,nowMono:n.monoMs(),nowWallMs:n.wallMs(),minSequence:m()});if(!x.valid)throw new A("authority_unavailable");if(s==="privileged_call"&&x.claims.cap!==p)throw new A("authority_unavailable");await e.sequenceStore.write(d,x.sequence),l.set(g(s,p),{token:b.token,sequence:x.sequence,operation:s,capability:p,capabilities:x.claims.caps,iat:x.claims.iat,exp:x.claims.exp,receivedAtMono:S})};return{authorizeDispatch:(s,p)=>_("provider_dispatch",null,p),authorizeToolCall:(s,p)=>{let u=e.capabilityForTool(s.toolName);return u===null||!/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/.test(u)?Promise.reject(new A("capability_not_admitted")):_("privileged_call",u,p)}}}var q="/api/workforce/run-admissions",B="/api/workforce/run-admissions/revoke",Y="/api/workforce/run-admissions/authority",Z="/api/workforce/run-admissions/pin",F="/api/workforce/run-admissions/read",X="/api/workforce/run-admissions/operations/read";var I=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Q=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,N=/^[a-z_]{1,64}$/,G=new Set(["bad_input","denied","not_found","needs_approval","conflict","rate_limited","unavailable","timeout","internal"]),w=class extends Error{constructor(n,d,i={}){super(`workforce admission refused: ${n}/${d}`);this.code=n;this.reason=d;this.name="WorkforceAdmissionRefused",this.details={reason:d,...i}}code;reason;details},k=()=>new w("unavailable","authority_unavailable"),h=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),T=e=>Array.isArray(e)&&e.length<=64&&e.every(a=>typeof a=="string"&&Q.test(a));function L(e){if(!h(e)||e.schemaVersion!==1||typeof e.admissionId!="string"||!I.test(e.admissionId)||typeof e.operationId!="string"||!I.test(e.operationId))return null;let a=e.agent;if(!h(a)||typeof a.resourceId!="string"||!I.test(a.resourceId)||!Number.isSafeInteger(a.version)||typeof a.contentHash!="string")return null;let n=e.capabilities;if(!h(n)||!T(n.effective)||!T(n.requested))return null;let d=e.payer;if(!h(d)||typeof d.kind!="string")return null;let i=e.budget;return!h(i)||typeof i.ceilingMicro!="string"||!/^[1-9][0-9]{0,17}$/.test(i.ceilingMicro)||!h(e.target)||typeof e.admittedAt!="string"||!Number.isFinite(Date.parse(e.admittedAt))?null:e}var ee=/^[0-9a-f]{64}$/;function te(e,a,n,d){if(!h(e)||e.schemaVersion!==1)return null;let i=e.agent;if(!h(i)||typeof i.resourceId!="string"||i.resourceId.toLowerCase()!==a||!Number.isSafeInteger(i.version)||i.version<1||typeof i.contentHash!="string"||!ee.test(i.contentHash)||!h(e.target)||JSON.stringify(Object.entries(e.target).map(([l,o])=>[l,typeof o=="string"?o.toLowerCase():o]).sort())!==JSON.stringify(Object.entries(n).map(([l,o])=>[l,typeof o=="string"?o.toLowerCase():o]).sort()))return null;let c=e.team;if(d?!h(c)||typeof c.teamId!="string"||c.teamId.toLowerCase()!==d:c!==null)return null;let t=e.terms;return!h(t)||!T(t.definition)||!T(t.target)?null:{schemaVersion:1,agent:{resourceId:a,version:i.version,contentHash:i.contentHash},target:{...n},team:d?{teamId:d}:null,terms:{definition:[...t.definition],target:[...t.target]}}}function j(e,a){return!h(e)||e.schemaVersion!==1||e.admissionId!==a||typeof e.revoked!="boolean"?null:{schemaVersion:1,admissionId:a,revoked:e.revoked,reason:typeof e.reason=="string"&&N.test(e.reason)?e.reason:null,revokedAt:typeof e.revokedAt=="string"?e.revokedAt:null,latestLeaseSequence:typeof e.latestLeaseSequence=="string"?e.latestLeaseSequence:null}}async function ne(e,a){let n=e.headers.get("content-length");if(n!==null&&(!/^\d+$/.test(n)||Number(n)>65536))throw new Error("response too large");if(!e.body)return null;let d=e.body.getReader(),i=[],c=0;try{for(;;){let{done:o,value:r}=await d.read();if(a.aborted)throw new Error("response did not complete before the deadline");if(o)break;if(c+=r.byteLength,c>65536)throw new Error("response too large");i.push(r)}}finally{try{d.releaseLock()}catch{}}let t=new Uint8Array(c),l=0;for(let o of i)t.set(o,l),l+=o.byteLength;return t.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t)):null}function se(e){let a=e.fetchImpl??globalThis.fetch,n;try{n=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(n.protocol!=="https:"||n.pathname!=="/"||n.username||n.password||n.search||n.hash)throw new Error("invalid issuer");let d=n.origin,i=async(t,l,o)=>{let r=`${d}${t}`,f=new AbortController,m=()=>f.abort();o?.addEventListener("abort",m,{once:!0});let g=setTimeout(m,15e3);g.unref?.();try{o?.throwIfAborted();let R=await e.authorizeRequest({method:"POST",url:r});if(!R)throw k();let _,s;try{_=await a(r,{method:"POST",redirect:"error",signal:f.signal,headers:{accept:"application/json","content-type":"application/json",authorization:R.authorization,...R.dpop?{dpop:R.dpop}:{}},body:JSON.stringify(l)}),s=await ne(_,f.signal)}catch(y){throw o?.aborted?y:k()}if(_.status===200&&h(s)&&s.success===!0)return s;let p=h(s)&&typeof s.code=="string"&&G.has(s.code)?s.code:null,u=h(s)&&h(s.details)?s.details:null;throw p&&u&&u.schemaVersion===1&&typeof u.reason=="string"&&N.test(u.reason)?new w(p,u.reason,{...Number.isSafeInteger(u.currentVersion)?{currentVersion:u.currentVersion}:{},...typeof u.availableMicro=="string"&&/^[0-9]{1,20}$/.test(u.availableMicro)?{availableMicro:u.availableMicro}:{},...typeof u.field=="string"&&/^[a-zA-Z.]{1,64}$/.test(u.field)?{field:u.field}:{}}):p?new w(p,p==="denied"&&_.status===403&&h(s)&&typeof s.required_scope=="string"?"insufficient_scope":p):k()}finally{clearTimeout(g),o?.removeEventListener("abort",m)}},c=t=>{if(typeof t!="string"||!I.test(t))throw new w("bad_input","invalid_admission");return t.toLowerCase()};return{async admit(t,l){if(!I.test(t.operationId))throw new w("bad_input","invalid_operation");if(!T(t.capabilities))throw new w("bad_input","invalid_capabilities");if(t.runtimeCapabilities!==void 0&&!T(t.runtimeCapabilities))throw new w("bad_input","invalid_runtime_capabilities");if(!/^[1-9][0-9]{0,17}$/.test(t.budget?.ceilingMicro??""))throw new w("bad_input","invalid_budget_ceiling");let o={operationId:t.operationId,agent:{resourceId:t.agent.resourceId,version:t.agent.version,contentHash:t.agent.contentHash},target:{...t.target},capabilities:[...t.capabilities],budget:{ceilingMicro:t.budget.ceilingMicro},...t.expectedActorAccountId?{expectedActorAccountId:t.expectedActorAccountId}:{},...t.team?{team:{teamId:t.team.teamId}}:{},...t.conversationId?{conversationId:t.conversationId}:{},...t.root?{root:{bindingId:t.root.bindingId,installationId:t.root.installationId}}:{},...t.runtimeCapabilities?{runtimeCapabilities:[...t.runtimeCapabilities]}:{}},r=await i(q,o,l),f=L(r.admission);if(!f||f.operationId.toLowerCase()!==t.operationId.toLowerCase())throw k();return{admission:f,replayed:r.replayed===!0}},async revoke(t,l){let o=c(t),r=j(await i(B,{admissionId:o},l),o);if(!r||!r.revoked)throw k();return r},async pin(t,l){let o=t?.agent?.resourceId;if(typeof o!="string"||!I.test(o))throw new w("bad_input","invalid_agent_resource");let r=t.target,f=h(r)?r.kind==="personal"?[r.ownerUserId]:r.kind==="workspace"?[r.assignmentId]:r.kind==="project"?[r.projectId,r.participationId]:null:null;if(!f||!f.every(s=>typeof s=="string"&&I.test(s)))throw new w("bad_input","invalid_target");let m=r.kind==="personal"?{kind:"personal",ownerUserId:r.ownerUserId}:r.kind==="workspace"?{kind:"workspace",assignmentId:r.assignmentId}:{kind:"project",projectId:r.projectId,participationId:r.participationId},g=t.team?t.team.teamId:null;if(g!==null&&(typeof g!="string"||!I.test(g)))throw new w("bad_input","invalid_team");let R={agent:{resourceId:o},target:m,...g?{team:{teamId:g}}:{},...t.expectedActorAccountId?{expectedActorAccountId:t.expectedActorAccountId}:{}},_=te(await i(Z,R,l),o.toLowerCase(),m,g?g.toLowerCase():null);if(!_)throw k();return _},async read(t,l,o){let r=c(t),f=l?.expectedActorAccountId;if(f!==void 0&&(typeof f!="string"||!I.test(f)))throw new w("bad_input","invalid_expected_actor");let m=await i(F,{admissionId:r,...f?{expectedActorAccountId:f}:{}},o),g=L(m.admission);if(!g||g.admissionId.toLowerCase()!==r)throw k();return g},async readOperation(t,l,o){if(typeof t!="string"||!I.test(t))throw new w("bad_input","invalid_operation");let r=l?.expectedActorAccountId;if(typeof r!="string"||!I.test(r))throw new w("bad_input","invalid_expected_actor");let f=t.toLowerCase(),m=await i(X,{operationId:f,expectedActorAccountId:r.toLowerCase()},o);if(m.schemaVersion!==1||typeof m.operationId!="string"||m.operationId.toLowerCase()!==f)throw k();if(m.state==="not-observed"&&m.admission===null)return{state:"not-observed",operationId:f,admission:null};if(m.state!=="committed")throw k();let g=L(m.admission);if(!g||g.operationId.toLowerCase()!==f)throw k();return{state:"committed",operationId:f,admission:g}},async authority(t,l){let o=c(t),r=j(await i(Y,{admissionId:o},l),o);if(!r)throw k();return r}}}var P=class extends Error{code="RUN_AUTHORITY_REFUSED";retryable=!1;reason;step;constructor(a,n,d){super(`Run authority refused the ${a==="dispatch"?"provider dispatch":"tool call"}: ${n}`,d),this.name="RunAuthorityRefusedError",this.reason=n,this.step=a}};export{V as RUN_LEASE_MAX_SECONDS,O as RUN_LEASE_SKEW_SECONDS,P as RunAuthorityRefusedError,A as RunStepRefused,w as WorkforceAdmissionRefused,se as createWorkforceRunAdmissionClient,oe as createWorkforceRunAuthority,W as verifyWorkforceRunLease};
1
+ import{createPublicKey as B,verify as J}from"node:crypto";var K="/api/workforce/run-admissions/authorize-step",q="/api/oauth2/jwks",Z=60,j=5,F="xeno-run-lease+jwt",Y=1e4,D=65536,I=class extends Error{constructor(t){super(`run step refused: ${t}`);this.reason=t;this.name="RunStepRefused",this.details={reason:t}}reason;details};function U(e,o){let t=i=>({valid:!1,reason:i}),c=typeof e=="string"?e.split("."):[];if(c.length!==3)return t("malformed");let s,r;try{s=JSON.parse(Buffer.from(c[0],"base64url").toString("utf8")),r=JSON.parse(Buffer.from(c[1],"base64url").toString("utf8"))}catch{return t("malformed")}if(s.alg!=="ES256"||s.typ!==F)return t("wrong_type");if(!o.publicKey)return t("unknown_key");if(!J("sha256",Buffer.from(`${c[0]}.${c[1]}`),{key:o.publicKey,dsaEncoding:"ieee-p1363"},Buffer.from(c[2],"base64url")))return t("bad_signature");if(r.iss!=="xeno-platform"||r.aud!=="xeno-run-runtime"||r.sub!==o.admissionId)return t("wrong_subject");if(!Number.isSafeInteger(r.iat)||!Number.isSafeInteger(r.exp)||r.exp<=r.iat||r.exp-r.iat>Z)return t("unbounded");if(!Array.isArray(r.caps)||!r.caps.every(i=>typeof i=="string"))return t("malformed");let d;try{d=BigInt(r.seq)}catch{return t("malformed")}if(d<o.minSequence)return t("superseded");if(o.nowWallMs/1e3>=r.exp-j)return t("expired");if(o.receivedAtMono===null)return t("requires_online_reauthorization");let a=(o.nowMono-o.receivedAtMono)/1e3;return a<0?t("requires_online_reauthorization"):a>=r.exp-r.iat-j?t("expired"):{valid:!0,sequence:d,claims:r}}async function X(e,o){let t=e.headers.get("content-length");if(t!==null&&(!/^\d+$/.test(t)||Number(t)>D))throw new Error("response too large");if(!e.body)return null;let c=e.body.getReader(),s=[],r=0;try{for(;;){let{done:a,value:i}=await c.read();if(o.aborted)throw new Error("response did not complete before the deadline");if(a)break;if(r+=i.byteLength,r>D)throw new Error("response too large");s.push(i)}}finally{try{c.releaseLock()}catch{}}let n=new Uint8Array(r),d=0;for(let a of s)n.set(a,d),d+=a.byteLength;return n.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)):null}function we(e){let o=e.fetchImpl??globalThis.fetch,t=e.clock??{wallMs:()=>Date.now(),monoMs:()=>performance.now()},c=e.admissionId;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c))throw new Error("invalid admission id");let s;try{s=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(s.protocol!=="https:"||s.pathname!=="/"||s.username||s.password||s.search||s.hash)throw new Error("invalid issuer");let r=s.origin,n=new Map,d=new Map,a=null,i=async(f,u,h)=>{let g=`${r}${u}`,v=new AbortController,k=setTimeout(()=>v.abort(),Y);k.unref?.();try{let R=null;if(f==="POST"&&(R=await e.authorizeRequest({method:f,url:g}),!R))throw new I("authority_unavailable");let C=await o(g,{method:f,redirect:"error",signal:v.signal,headers:{accept:"application/json",...h?{"content-type":"application/json"}:{},...R?{authorization:R.authorization,...R.dpop?{dpop:R.dpop}:{}}:{}},...h?{body:JSON.stringify(h)}:{}});return{status:C.status,json:await X(C,v.signal)}}finally{clearTimeout(k)}},l=async f=>{if(n.has(f))return n.get(f);let{status:u,json:h}=await i("GET",q);if(u!==200||!h||typeof h!="object"||!Array.isArray(h.keys))return null;for(let g of h.keys)if(!(typeof g.kid!="string"||g.kty!=="EC"||g.crv!=="P-256"))try{n.set(g.kid,B({key:{kty:"EC",crv:"P-256",x:g.x,y:g.y},format:"jwk"}))}catch{}return n.get(f)??null},y=()=>e.sequenceStore.read(c)??0n,m=(f,u)=>`${f}:${u??""}`,x=async f=>{let u=JSON.parse(Buffer.from(f.token.split(".")[0],"base64url").toString("utf8")).kid;return U(f.token,{publicKey:await l(u),admissionId:c,receivedAtMono:f.receivedAtMono,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()}).valid},_=async(f,u,h)=>{if(h.throwIfAborted(),a)throw new I(a);let g=d.get(m(f,u));if(g&&await x(g).catch(()=>!1))return;let v;try{v=await i("POST",K,{admissionId:c,operation:f,...u?{capability:u}:{}})}catch(E){throw E instanceof I?E:new I("authority_unavailable")}let k=v.json;if(v.status!==200||k?.success!==!0||typeof k.token!="string"){let E=typeof k?.details?.reason=="string"&&/^[a-z_]{1,64}$/.test(k.details.reason)?k.details.reason:"authority_unavailable";throw E==="admission_revoked"&&(a=E),new I(E)}let R=t.monoMs(),C=(()=>{try{return JSON.parse(Buffer.from(k.token.split(".")[0],"base64url").toString("utf8"))}catch{return null}})();if(typeof C?.kid!="string")throw new I("authority_unavailable");let S=U(k.token,{publicKey:await l(C.kid).catch(()=>null),admissionId:c,receivedAtMono:R,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()});if(!S.valid)throw new I("authority_unavailable");if(f==="privileged_call"&&S.claims.cap!==u)throw new I("authority_unavailable");await e.sequenceStore.write(c,S.sequence),d.set(m(f,u),{token:k.token,sequence:S.sequence,operation:f,capability:u,capabilities:S.claims.caps,iat:S.claims.iat,exp:S.claims.exp,receivedAtMono:R})};return{authorizeDispatch:(f,u)=>_("provider_dispatch",null,u),authorizeToolCall:(f,u)=>{let h=e.capabilityForTool(f.toolName);return h===null||!/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/.test(h)?Promise.reject(new I("capability_not_admitted")):_("privileged_call",h,u)}}}import{createHash as G}from"node:crypto";var Q="/api/workforce/run-admissions",ee="/api/workforce/run-admissions/revoke",te="/api/workforce/run-admissions/authority",ne="/api/workforce/run-admissions/pin",re="/api/workforce/run-admissions/read",oe="/api/workforce/run-admissions/operations/read",ie="/api/workforce/resources/definition/read",se=15e3,V=65536,ae=256*1024,ce=32768,L=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,de=/^[A-Z][A-Z0-9_]{0,63}$/,b=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ue=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,$=/^[a-z_]{1,64}$/,le=new Set(["bad_input","denied","not_found","needs_approval","conflict","rate_limited","unavailable","timeout","internal"]),w=class extends Error{constructor(t,c,s={}){super(`workforce admission refused: ${t}/${c}`);this.code=t;this.reason=c;this.name="WorkforceAdmissionRefused",this.details={reason:c,...s}}code;reason;details},A=()=>new w("unavailable","authority_unavailable"),p=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),T=e=>Array.isArray(e)&&e.length<=64&&e.every(o=>typeof o=="string"&&ue.test(o));function O(e){if(!p(e)||e.schemaVersion!==1||typeof e.admissionId!="string"||!b.test(e.admissionId)||typeof e.operationId!="string"||!b.test(e.operationId))return null;let o=e.agent;if(!p(o)||typeof o.resourceId!="string"||!b.test(o.resourceId)||!Number.isSafeInteger(o.version)||typeof o.contentHash!="string")return null;let t=e.capabilities;if(!p(t)||!T(t.effective)||!T(t.requested))return null;let c=e.payer;if(!p(c)||typeof c.kind!="string")return null;let s=e.budget;return!p(s)||typeof s.ceilingMicro!="string"||!/^[1-9][0-9]{0,17}$/.test(s.ceilingMicro)||!p(e.target)||typeof e.admittedAt!="string"||!Number.isFinite(Date.parse(e.admittedAt))?null:e}var H=/^[0-9a-f]{64}$/;function fe(e,o,t,c){if(!p(e)||e.schemaVersion!==1)return null;let s=e.agent;if(!p(s)||typeof s.resourceId!="string"||s.resourceId.toLowerCase()!==o||!Number.isSafeInteger(s.version)||s.version<1||typeof s.contentHash!="string"||!H.test(s.contentHash)||!p(e.target)||JSON.stringify(Object.entries(e.target).map(([d,a])=>[d,typeof a=="string"?a.toLowerCase():a]).sort())!==JSON.stringify(Object.entries(t).map(([d,a])=>[d,typeof a=="string"?a.toLowerCase():a]).sort()))return null;let r=e.team;if(c?!p(r)||typeof r.teamId!="string"||r.teamId.toLowerCase()!==c:r!==null)return null;let n=e.terms;return!p(n)||!T(n.definition)||!T(n.target)?null:{schemaVersion:1,agent:{resourceId:o,version:s.version,contentHash:s.contentHash},target:{...t},team:c?{teamId:c}:null,terms:{definition:[...n.definition],target:[...n.target]}}}function z(e,o){return!p(e)||e.schemaVersion!==1||e.admissionId!==o||typeof e.revoked!="boolean"?null:{schemaVersion:1,admissionId:o,revoked:e.revoked,reason:typeof e.reason=="string"&&$.test(e.reason)?e.reason:null,revokedAt:typeof e.revokedAt=="string"?e.revokedAt:null,latestLeaseSequence:typeof e.latestLeaseSequence=="string"?e.latestLeaseSequence:null}}function N(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(N):Object.fromEntries(Object.keys(e).sort().map(o=>[o,N(e[o])]))}function ge(e){return G("sha256").update(JSON.stringify(N({schemaVersion:1,content:e.content,provenance:e.provenance,license:e.license}))).digest("hex")}var M=(e,o)=>Object.keys(e).every(t=>o.includes(t)),P=(e,o)=>new Set(e.map(o)).size===e.length;function pe(e){if(!p(e)||!M(e,["instructions","skills","requestedCapabilities","secretReferences"]))return null;let{instructions:o,skills:t,requestedCapabilities:c,secretReferences:s}=e;return typeof o!="string"||o.includes("\0")||new TextEncoder().encode(o).byteLength>ce||!Array.isArray(t)||t.length>64||!t.every(r=>p(r)&&M(r,["id","version","hash"])&&typeof r.id=="string"&&L.test(r.id)&&typeof r.version=="string"&&L.test(r.version)&&typeof r.hash=="string"&&H.test(r.hash))||!P(t,r=>r.id)||!Array.isArray(c)||c.length>64||!c.every(r=>typeof r=="string"&&L.test(r))||!P(c,r=>r)||!Array.isArray(s)||s.length>32||!s.every(r=>p(r)&&M(r,["name","ref"])&&typeof r.name=="string"&&de.test(r.name)&&typeof r.ref=="string"&&b.test(r.ref))||!P(s,r=>r.name)?null:{instructions:o,skills:t.map(({id:r,version:n,hash:d})=>({id:r,version:n,hash:d})),requestedCapabilities:[...c],secretReferences:s.map(({name:r,ref:n})=>({name:r,ref:n}))}}function me(e,o){if(!p(e)||e.schemaVersion!==1||!p(e.access)||e.access.allowed!==!0)return null;let t=e.version;if(!p(t)||t.schemaVersion!==1||typeof t.resourceId!="string"||t.resourceId.toLowerCase()!==o.resourceId||t.version!==o.version||t.contentHash!==o.contentHash)return null;let c=pe(t.content);return!c||!p(t.provenance)||!p(t.license)||t.createdByUserId!==null&&(typeof t.createdByUserId!="string"||!b.test(t.createdByUserId))||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||ge({content:t.content,provenance:t.provenance,license:t.license})!==o.contentHash?null:{resourceId:o.resourceId,version:o.version,schemaVersion:1,content:c,contentHash:o.contentHash,provenance:t.provenance,license:t.license,createdByUserId:t.createdByUserId,createdAt:t.createdAt}}async function he(e,o,t=V){let c=e.headers.get("content-length");if(c!==null&&(!/^\d+$/.test(c)||Number(c)>t))throw new Error("response too large");if(!e.body)return null;let s=e.body.getReader(),r=[],n=0;try{for(;;){let{done:i,value:l}=await s.read();if(o.aborted)throw new Error("response did not complete before the deadline");if(i)break;if(n+=l.byteLength,n>t)throw new Error("response too large");r.push(l)}}finally{try{s.releaseLock()}catch{}}let d=new Uint8Array(n),a=0;for(let i of r)d.set(i,a),a+=i.byteLength;return d.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)):null}function ke(e){let o=e.fetchImpl??globalThis.fetch,t;try{t=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(t.protocol!=="https:"||t.pathname!=="/"||t.username||t.password||t.search||t.hash)throw new Error("invalid issuer");let c=t.origin,s=async(n,d,a,i=V)=>{let l=`${c}${n}`,y=new AbortController,m=()=>y.abort();a?.addEventListener("abort",m,{once:!0});let x=setTimeout(m,se);x.unref?.();try{a?.throwIfAborted();let _=await e.authorizeRequest({method:"POST",url:l});if(!_)throw A();let f,u;try{f=await o(l,{method:"POST",redirect:"error",signal:y.signal,headers:{accept:"application/json","content-type":"application/json",authorization:_.authorization,..._.dpop?{dpop:_.dpop}:{}},body:JSON.stringify(d)}),u=await he(f,y.signal,i)}catch(v){throw a?.aborted?v:A()}if(f.status===200&&p(u)&&u.success===!0)return u;let h=p(u)&&typeof u.code=="string"&&le.has(u.code)?u.code:null,g=p(u)&&p(u.details)?u.details:null;throw h&&g&&g.schemaVersion===1&&typeof g.reason=="string"&&$.test(g.reason)?new w(h,g.reason,{...Number.isSafeInteger(g.currentVersion)?{currentVersion:g.currentVersion}:{},...typeof g.availableMicro=="string"&&/^[0-9]{1,20}$/.test(g.availableMicro)?{availableMicro:g.availableMicro}:{},...typeof g.field=="string"&&/^[a-zA-Z.]{1,64}$/.test(g.field)?{field:g.field}:{}}):h?new w(h,h==="denied"&&f.status===403&&p(u)&&typeof u.required_scope=="string"?"insufficient_scope":h):A()}finally{clearTimeout(x),a?.removeEventListener("abort",m)}},r=n=>{if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_admission");return n.toLowerCase()};return{async admit(n,d){if(!b.test(n.operationId))throw new w("bad_input","invalid_operation");if(!T(n.capabilities))throw new w("bad_input","invalid_capabilities");if(n.runtimeCapabilities!==void 0&&!T(n.runtimeCapabilities))throw new w("bad_input","invalid_runtime_capabilities");if(!/^[1-9][0-9]{0,17}$/.test(n.budget?.ceilingMicro??""))throw new w("bad_input","invalid_budget_ceiling");let a={operationId:n.operationId,agent:{resourceId:n.agent.resourceId,version:n.agent.version,contentHash:n.agent.contentHash},target:{...n.target},capabilities:[...n.capabilities],budget:{ceilingMicro:n.budget.ceilingMicro},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{},...n.team?{team:{teamId:n.team.teamId}}:{},...n.conversationId?{conversationId:n.conversationId}:{},...n.root?{root:{bindingId:n.root.bindingId,installationId:n.root.installationId}}:{},...n.runtimeCapabilities?{runtimeCapabilities:[...n.runtimeCapabilities]}:{}},i=await s(Q,a,d),l=O(i.admission);if(!l||l.operationId.toLowerCase()!==n.operationId.toLowerCase())throw A();return{admission:l,replayed:i.replayed===!0}},async revoke(n,d){let a=r(n),i=z(await s(ee,{admissionId:a},d),a);if(!i||!i.revoked)throw A();return i},async pin(n,d){let a=n?.agent?.resourceId;if(typeof a!="string"||!b.test(a))throw new w("bad_input","invalid_agent_resource");let i=n.target,l=p(i)?i.kind==="personal"?[i.ownerUserId]:i.kind==="workspace"?[i.assignmentId]:i.kind==="project"?[i.projectId,i.participationId]:null:null;if(!l||!l.every(f=>typeof f=="string"&&b.test(f)))throw new w("bad_input","invalid_target");let y=i.kind==="personal"?{kind:"personal",ownerUserId:i.ownerUserId}:i.kind==="workspace"?{kind:"workspace",assignmentId:i.assignmentId}:{kind:"project",projectId:i.projectId,participationId:i.participationId},m=n.team?n.team.teamId:null;if(m!==null&&(typeof m!="string"||!b.test(m)))throw new w("bad_input","invalid_team");let x={agent:{resourceId:a},target:y,...m?{team:{teamId:m}}:{},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{}},_=fe(await s(ne,x,d),a.toLowerCase(),y,m?m.toLowerCase():null);if(!_)throw A();return _},async read(n,d,a){let i=r(n),l=d?.expectedActorAccountId;if(l!==void 0&&(typeof l!="string"||!b.test(l)))throw new w("bad_input","invalid_expected_actor");let y=await s(re,{admissionId:i,...l?{expectedActorAccountId:l}:{}},a),m=O(y.admission);if(!m||m.admissionId.toLowerCase()!==i)throw A();return m},async readOperation(n,d,a){if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_operation");let i=d?.expectedActorAccountId;if(typeof i!="string"||!b.test(i))throw new w("bad_input","invalid_expected_actor");let l=n.toLowerCase(),y=await s(oe,{operationId:l,expectedActorAccountId:i.toLowerCase()},a);if(y.schemaVersion!==1||typeof y.operationId!="string"||y.operationId.toLowerCase()!==l)throw A();if(y.state==="not-observed"&&y.admission===null)return{state:"not-observed",operationId:l,admission:null};if(y.state!=="committed")throw A();let m=O(y.admission);if(!m||m.operationId.toLowerCase()!==l)throw A();return{state:"committed",operationId:l,admission:m}},async readDefinition(n,d){let a=n?.resourceId;if(typeof a!="string"||!b.test(a))throw new w("bad_input","invalid_agent_resource");if(!Number.isSafeInteger(n.version)||n.version<1)throw new w("bad_input","invalid_version");if(typeof n.contentHash!="string"||!H.test(n.contentHash))throw new w("bad_input","invalid_content_hash");let i=n.expectedActorAccountId;if(typeof i!="string"||!b.test(i))throw new w("bad_input","invalid_expected_actor");let l={resourceId:a.toLowerCase(),version:n.version,contentHash:n.contentHash},y=await s(ie,{...l,expectedActorAccountId:i.toLowerCase()},d,ae),m=me(y,l);if(!m)throw A();return m},async authority(n,d){let a=r(n),i=z(await s(te,{admissionId:a},d),a);if(!i)throw A();return i}}}var W=class extends Error{code="RUN_AUTHORITY_REFUSED";retryable=!1;reason;step;constructor(o,t,c){super(`Run authority refused the ${o==="dispatch"?"provider dispatch":"tool call"}: ${t}`,c),this.name="RunAuthorityRefusedError",this.reason=t,this.step=o}};export{Z as RUN_LEASE_MAX_SECONDS,j as RUN_LEASE_SKEW_SECONDS,W as RunAuthorityRefusedError,I as RunStepRefused,w as WorkforceAdmissionRefused,ke as createWorkforceRunAdmissionClient,we as createWorkforceRunAuthority,U as verifyWorkforceRunLease,ge as workforceDefinitionContentHash};
@@ -1 +1 @@
1
- {"inputs":{"src/workforce/run-authority-client.ts":{"bytes":15410,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/workforce/run-admission-client.ts":{"bytes":24384,"imports":[],"format":"esm"},"src/core/agent-loop/run-authority.ts":{"bytes":4631,"imports":[],"format":"esm"},"src/workforce/index.ts":{"bytes":745,"imports":[{"path":"src/workforce/run-authority-client.ts","kind":"import-statement","original":"./run-authority-client.js"},{"path":"src/workforce/run-admission-client.ts","kind":"import-statement","original":"./run-admission-client.js"},{"path":"src/core/agent-loop/run-authority.ts","kind":"import-statement","original":"../core/agent-loop/run-authority.js"}],"format":"esm"}},"outputs":{"dist/workforce/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/workforce/index.ts","inputs":{"src/workforce/index.ts":{"bytesInOutput":285},"src/workforce/run-authority-client.ts":{"bytesInOutput":5212},"src/workforce/run-admission-client.ts":{"bytesInOutput":8182},"src/core/agent-loop/run-authority.ts":{"bytesInOutput":257}},"bytes":14581}}}
1
+ {"inputs":{"src/workforce/run-authority-client.ts":{"bytes":15410,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/workforce/run-admission-client.ts":{"bytes":32982,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/core/agent-loop/run-authority.ts":{"bytes":4631,"imports":[],"format":"esm"},"src/workforce/index.ts":{"bytes":745,"imports":[{"path":"src/workforce/run-authority-client.ts","kind":"import-statement","original":"./run-authority-client.js"},{"path":"src/workforce/run-admission-client.ts","kind":"import-statement","original":"./run-admission-client.js"},{"path":"src/core/agent-loop/run-authority.ts","kind":"import-statement","original":"../core/agent-loop/run-authority.js"}],"format":"esm"}},"outputs":{"dist/workforce/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/workforce/index.ts","inputs":{"src/workforce/index.ts":{"bytesInOutput":324},"src/workforce/run-authority-client.ts":{"bytesInOutput":5223},"src/workforce/run-admission-client.ts":{"bytesInOutput":11100},"src/core/agent-loop/run-authority.ts":{"bytesInOutput":257}},"bytes":17581}}}
@@ -1 +1 @@
1
- {"inputs":{"src/workforce/run-authority-client.ts":{"bytes":15410,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/workforce/run-admission-client.ts":{"bytes":24384,"imports":[],"format":"esm"},"src/core/agent-loop/run-authority.ts":{"bytes":4631,"imports":[],"format":"esm"},"src/workforce/index.ts":{"bytes":745,"imports":[{"path":"src/workforce/run-authority-client.ts","kind":"import-statement","original":"./run-authority-client.js"},{"path":"src/workforce/run-admission-client.ts","kind":"import-statement","original":"./run-admission-client.js"},{"path":"src/core/agent-loop/run-authority.ts","kind":"import-statement","original":"../core/agent-loop/run-authority.js"}],"format":"esm"}},"outputs":{"dist/workforce/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["RUN_LEASE_MAX_SECONDS","RUN_LEASE_SKEW_SECONDS","RunAuthorityRefusedError","RunStepRefused","WorkforceAdmissionRefused","createWorkforceRunAdmissionClient","createWorkforceRunAuthority","verifyWorkforceRunLease"],"entryPoint":"src/workforce/index.ts","inputs":{"src/workforce/run-authority-client.ts":{"bytesInOutput":5215},"src/workforce/index.ts":{"bytesInOutput":0},"src/workforce/run-admission-client.ts":{"bytesInOutput":8168},"src/core/agent-loop/run-authority.ts":{"bytesInOutput":257}},"bytes":13888}}}
1
+ {"inputs":{"src/workforce/run-authority-client.ts":{"bytes":15410,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/workforce/run-admission-client.ts":{"bytes":32982,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/core/agent-loop/run-authority.ts":{"bytes":4631,"imports":[],"format":"esm"},"src/workforce/index.ts":{"bytes":745,"imports":[{"path":"src/workforce/run-authority-client.ts","kind":"import-statement","original":"./run-authority-client.js"},{"path":"src/workforce/run-admission-client.ts","kind":"import-statement","original":"./run-admission-client.js"},{"path":"src/core/agent-loop/run-authority.ts","kind":"import-statement","original":"../core/agent-loop/run-authority.js"}],"format":"esm"}},"outputs":{"dist/workforce/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["RUN_LEASE_MAX_SECONDS","RUN_LEASE_SKEW_SECONDS","RunAuthorityRefusedError","RunStepRefused","WorkforceAdmissionRefused","createWorkforceRunAdmissionClient","createWorkforceRunAuthority","verifyWorkforceRunLease","workforceDefinitionContentHash"],"entryPoint":"src/workforce/index.ts","inputs":{"src/workforce/run-authority-client.ts":{"bytesInOutput":5215},"src/workforce/index.ts":{"bytesInOutput":0},"src/workforce/run-admission-client.ts":{"bytesInOutput":11102},"src/core/agent-loop/run-authority.ts":{"bytesInOutput":257}},"bytes":16859}}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xenosystem/agent-sdk",
3
- "version": "0.10.26",
3
+ "version": "0.10.29",
4
4
  "description": "XENO Agent SDK built from the same engine as XENO CODE",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",