@xenosystem/agent-sdk 0.10.19 → 0.10.20

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.
@@ -1,24 +1,24 @@
1
- import{readdirSync as C,readFileSync as z}from"node:fs";import{existsSync as T,statSync as $}from"node:fs";import*as c from"node:fs/promises";import*as a from"node:path";function jt(t){try{return T(t)&&$(t).isFile()}catch{return!1}}function qt(t){try{return T(t)&&$(t).isDirectory()}catch{return!1}}function Ht(t,e=""){try{return z(t,"utf-8")}catch{return e}}async function k(t){await c.mkdir(t,{recursive:!0})}async function G(t,e){let n=a.dirname(t);await k(n);let r=Math.random().toString(36).substring(2,15),o=`${t}.tmp.${process.pid}.${r}`;try{await c.writeFile(o,e),await Q(o,t)}finally{try{await c.unlink(o)}catch{}}}var U=new Set(["EACCES","EBUSY","EPERM"]),K=[10,20,40,80,160,320,640];async function Q(t,e){for(let n=0;;n+=1)try{await c.rename(t,e);return}catch(r){let o=r.code,i=K[n];if(process.platform!=="win32"||!o||!U.has(o)||i===void 0)throw r;await new Promise(s=>setTimeout(s,i))}}async function Jt(t,e){let n=a.dirname(t);await k(n),await c.appendFile(t,e+`
2
- `,"utf-8")}async function Xt(t,e){let n=a.dirname(t);await k(n);let r=await c.open(t,"a");try{await r.writeFile(e+`
3
- `,"utf-8"),await r.sync()}finally{await r.close()}}function Z(t){return t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?"utf8-bom":t.length>=2&&t[0]===255&&t[1]===254?"utf16le":t.length>=2&&t[0]===254&&t[1]===255?"utf16be":"utf8"}function N(t){let e=Buffer.from(t);for(let n=0;n+1<e.length;n+=2){let r=e[n];e[n]=e[n+1],e[n+1]=r}return e}function V(t,e){switch(e){case"utf8-bom":return t.subarray(3).toString("utf8");case"utf16le":return t.subarray(2).toString("utf16le");case"utf16be":return N(t.subarray(2)).toString("utf16le");default:return t.toString("utf8")}}function tt(t,e){switch(e){case"utf8-bom":return Buffer.concat([Buffer.from([239,187,191]),Buffer.from(t,"utf8")]);case"utf16le":return Buffer.concat([Buffer.from([255,254]),Buffer.from(t,"utf16le")]);case"utf16be":return Buffer.concat([Buffer.from([254,255]),N(Buffer.from(t,"utf16le"))]);default:return Buffer.from(t,"utf8")}}function et(t){return t.includes(`\r
1
+ import{readdirSync as S,readFileSync as Y}from"node:fs";import{existsSync as T,statSync as $}from"node:fs";import*as c from"node:fs/promises";import*as a from"node:path";function zt(t){try{return T(t)&&$(t).isFile()}catch{return!1}}function Ht(t){try{return T(t)&&$(t).isDirectory()}catch{return!1}}function Jt(t,e=""){try{return Y(t,"utf-8")}catch{return e}}async function A(t){await c.mkdir(t,{recursive:!0})}async function U(t,e){let n=a.dirname(t);await A(n);let r=Math.random().toString(36).substring(2,15),o=`${t}.tmp.${process.pid}.${r}`;try{await c.writeFile(o,e),await Z(o,t)}finally{try{await c.unlink(o)}catch{}}}var G=new Set(["EACCES","EBUSY","EPERM"]),K=[10,20,40,80,160,320,640];async function Z(t,e){for(let n=0;;n+=1)try{await c.rename(t,e);return}catch(r){let o=r.code,i=K[n];if(process.platform!=="win32"||!o||!G.has(o)||i===void 0)throw r;await new Promise(s=>setTimeout(s,i))}}async function Yt(t,e){let n=a.dirname(t);await A(n),await c.appendFile(t,e+`
2
+ `,"utf-8")}async function Ut(t,e){let n=a.dirname(t);await A(n);let r=await c.open(t,"a");try{await r.writeFile(e+`
3
+ `,"utf-8"),await r.sync()}finally{await r.close()}}function Q(t){return t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?"utf8-bom":t.length>=2&&t[0]===255&&t[1]===254?"utf16le":t.length>=2&&t[0]===254&&t[1]===255?"utf16be":"utf8"}function N(t){let e=Buffer.from(t);for(let n=0;n+1<e.length;n+=2){let r=e[n];e[n]=e[n+1],e[n+1]=r}return e}function V(t,e){switch(e){case"utf8-bom":return t.subarray(3).toString("utf8");case"utf16le":return t.subarray(2).toString("utf16le");case"utf16be":return N(t.subarray(2)).toString("utf16le");default:return t.toString("utf8")}}function tt(t,e){switch(e){case"utf8-bom":return Buffer.concat([Buffer.from([239,187,191]),Buffer.from(t,"utf8")]);case"utf16le":return Buffer.concat([Buffer.from([255,254]),Buffer.from(t,"utf16le")]);case"utf16be":return Buffer.concat([Buffer.from([254,255]),N(Buffer.from(t,"utf16le"))]);default:return Buffer.from(t,"utf8")}}function et(t){return t.includes(`\r
4
4
  `)?"CRLF":"LF"}function nt(t,e){let n=t.replace(/\r\n/g,`
5
5
  `);return e==="CRLF"?n.replace(/\n/g,`\r
6
- `):n}async function rt(t){let e=await c.readFile(t),n=Z(e),r=V(e,n);return{content:r,encoding:n,lineEnding:et(r),sizeBytes:e.length}}async function Yt(t,e,n){let r=nt(e,n?.lineEnding??"LF");await G(t,tt(r,n?.encoding??"utf8"))}async function zt(t){let e=new Set,n=a.resolve(t);for(;!e.has(n);){e.add(n);try{let o=C(n,{withFileTypes:!0}).filter(i=>i.isFile()).map(i=>i.name).sort();for(let i of o){if(i.startsWith("."))continue;let s=a.extname(i).toLowerCase();if([".ts",".tsx",".js",".jsx",".json",".md",".txt",".yaml",".yml",".css",".html",".xml",".sh",".ps1"].includes(s))try{let u=a.join(n,i),l=await rt(u);if(l.content.length>0)return l.lineEnding}catch{}}}catch{}let r=a.dirname(n);if(r===n)break;n=r}return"LF"}function ot(t,e,n){let r=[],o=[{dir:t,depth:0}],i=new Set;for(;o.length>0&&r.length<n;){let s=o.shift();if(!i.has(s.dir)){i.add(s.dir);try{let u=C(s.dir,{withFileTypes:!0});for(let l of u){let d=a.join(s.dir,l.name);if(l.isFile()){if(r.push(d),r.length>=n)break;continue}l.isDirectory()&&s.depth<e&&!l.name.startsWith(".")&&l.name!=="node_modules"&&o.push({dir:d,depth:s.depth+1})}}catch{}}}return r}function Gt(t){try{let e=a.dirname(t),n=a.basename(t,a.extname(t)).toLowerCase(),r=a.basename(t).toLowerCase(),i=[e,a.dirname(e)].flatMap(u=>ot(u,2,500)),s=null;for(let u of i){let l=a.basename(u).toLowerCase(),d=a.basename(u,a.extname(u)).toLowerCase(),m=null;if(l===r?m=0:d===n?m=1:(l.includes(n)||n.includes(d))&&(m=2),m===null)continue;let R=a.relative(e,u).split(a.sep).length,_=m+R*.01;(!s||_<s.score)&&(s={filePath:u,score:_})}return s?.filePath??null}catch{}return null}async function Ut(t){try{return await c.readFile(t,"utf-8")}catch(e){if(e.code==="ENOENT")return null;throw e}}function Kt(t){return T(t)}async function Qt(t,e){try{let r=(await c.readdir(t,{withFileTypes:!0})).filter(o=>o.isFile()).map(o=>a.join(t,o.name));return e&&(r=r.filter(o=>e.test(a.basename(o)))),r}catch(n){if(n.code==="ENOENT")return[];throw n}}async function Zt(t){try{return(await c.readdir(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>a.join(t,n.name))}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Vt(t){try{await c.unlink(t)}catch(e){if(e.code!=="ENOENT")throw e}}async function te(t){try{await c.rm(t,{recursive:!0,force:!0})}catch(e){if(e.code!=="ENOENT")throw e}}function ne(t,e){try{return JSON.parse(t)}catch{return e}}function re(t,e="{}"){try{return JSON.stringify(t)}catch{return e}}function oe(t){let e=[];for(let n of t.split(`
7
- `)){let r=n.trim();if(r)try{e.push(JSON.parse(r))}catch{}}return e}function se(t){let e=it(t);return{frontmatter:e.frontmatter,content:e.content.trim()}}function ae(t,e){let n=Object.fromEntries(Object.entries(t).filter(([r,o])=>o!==void 0));return["---",B(n),"---","",e].join(`
8
- `)}function ue(t){return t.trimStart().startsWith("---")}function it(t){let e=t.replace(/^\uFEFF/,"");if(!e.startsWith("---"))return{frontmatter:{},content:t};let n=e.search(/\r?\n/);if(n<0||e.slice(0,n).trim()!=="---")return{frontmatter:{},content:t};let r=e.slice(n+(e[n]==="\r"?2:1)),o=r.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!o||o.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=r.slice(0,o.index),s=o[0],u=o.index+s.length;return{frontmatter:O(i),content:r.slice(u)}}function O(t){let e={},n=t.split(/\r?\n/);for(let r=0;r<n.length;r+=1){let o=n[r];if(!o.trim()||o.trimStart().startsWith("#"))continue;if(/^\s/.test(o))throw new Error(`Unexpected indentation at line ${r+1}.`);let i=at(o,r+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){e[i.key]=L(i.value,r+1);continue}let s=st(n,r+1);e[i.key]=s.value,r=s.nextIndex-1}return e}function st(t,e){let n=[],r=e;for(;r<t.length;r+=1){let i=t[r];if(!i.trim()){n.push(i);continue}if(!/^\s/.test(i))break;n.push(i.replace(/^ {2}/,""))}let o=n.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return o.length===0?{value:{},nextIndex:r}:o.every(i=>i.trimStart().startsWith("- "))?{value:o.map((i,s)=>L(i.trimStart().slice(2),e+s+1)),nextIndex:r}:{value:O(n.join(`
6
+ `):n}async function rt(t){let e=await c.readFile(t),n=Q(e),r=V(e,n);return{content:r,encoding:n,lineEnding:et(r),sizeBytes:e.length}}async function Gt(t,e,n){let r=nt(e,n?.lineEnding??"LF");await U(t,tt(r,n?.encoding??"utf8"))}async function Kt(t){let e=new Set,n=a.resolve(t);for(;!e.has(n);){e.add(n);try{let o=S(n,{withFileTypes:!0}).filter(i=>i.isFile()).map(i=>i.name).sort();for(let i of o){if(i.startsWith("."))continue;let s=a.extname(i).toLowerCase();if([".ts",".tsx",".js",".jsx",".json",".md",".txt",".yaml",".yml",".css",".html",".xml",".sh",".ps1"].includes(s))try{let u=a.join(n,i),f=await rt(u);if(f.content.length>0)return f.lineEnding}catch{}}}catch{}let r=a.dirname(n);if(r===n)break;n=r}return"LF"}function ot(t,e,n){let r=[],o=[{dir:t,depth:0}],i=new Set;for(;o.length>0&&r.length<n;){let s=o.shift();if(!i.has(s.dir)){i.add(s.dir);try{let u=S(s.dir,{withFileTypes:!0});for(let f of u){let d=a.join(s.dir,f.name);if(f.isFile()){if(r.push(d),r.length>=n)break;continue}f.isDirectory()&&s.depth<e&&!f.name.startsWith(".")&&f.name!=="node_modules"&&o.push({dir:d,depth:s.depth+1})}}catch{}}}return r}function Zt(t){try{let e=a.dirname(t),n=a.basename(t,a.extname(t)).toLowerCase(),r=a.basename(t).toLowerCase(),i=[e,a.dirname(e)].flatMap(u=>ot(u,2,500)),s=null;for(let u of i){let f=a.basename(u).toLowerCase(),d=a.basename(u,a.extname(u)).toLowerCase(),m=null;if(f===r?m=0:d===n?m=1:(f.includes(n)||n.includes(d))&&(m=2),m===null)continue;let R=a.relative(e,u).split(a.sep).length,_=m+R*.01;(!s||_<s.score)&&(s={filePath:u,score:_})}return s?.filePath??null}catch{}return null}async function Qt(t){try{return await c.readFile(t,"utf-8")}catch(e){if(e.code==="ENOENT")return null;throw e}}function Vt(t){return T(t)}async function te(t,e){try{let r=(await c.readdir(t,{withFileTypes:!0})).filter(o=>o.isFile()).map(o=>a.join(t,o.name));return e&&(r=r.filter(o=>e.test(a.basename(o)))),r}catch(n){if(n.code==="ENOENT")return[];throw n}}async function ee(t){try{return(await c.readdir(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>a.join(t,n.name))}catch(e){if(e.code==="ENOENT")return[];throw e}}async function ne(t){try{await c.unlink(t)}catch(e){if(e.code!=="ENOENT")throw e}}async function re(t){try{await c.rm(t,{recursive:!0,force:!0})}catch(e){if(e.code!=="ENOENT")throw e}}function ie(t,e){try{return JSON.parse(t)}catch{return e}}function se(t,e="{}"){try{return JSON.stringify(t)}catch{return e}}function ae(t){let e=[];for(let n of t.split(`
7
+ `)){let r=n.trim();if(r)try{e.push(JSON.parse(r))}catch{}}return e}function ce(t){let e=it(t);return{frontmatter:e.frontmatter,content:e.content.trim()}}function fe(t,e){let n=Object.fromEntries(Object.entries(t).filter(([r,o])=>o!==void 0));return["---",B(n),"---","",e].join(`
8
+ `)}function le(t){return t.trimStart().startsWith("---")}function it(t){let e=t.replace(/^\uFEFF/,"");if(!e.startsWith("---"))return{frontmatter:{},content:t};let n=e.search(/\r?\n/);if(n<0||e.slice(0,n).trim()!=="---")return{frontmatter:{},content:t};let r=e.slice(n+(e[n]==="\r"?2:1)),o=r.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!o||o.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=r.slice(0,o.index),s=o[0],u=o.index+s.length;return{frontmatter:O(i),content:r.slice(u)}}function O(t){let e={},n=t.split(/\r?\n/);for(let r=0;r<n.length;r+=1){let o=n[r];if(!o.trim()||o.trimStart().startsWith("#"))continue;if(/^\s/.test(o))throw new Error(`Unexpected indentation at line ${r+1}.`);let i=at(o,r+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){e[i.key]=L(i.value,r+1);continue}let s=st(n,r+1);e[i.key]=s.value,r=s.nextIndex-1}return e}function st(t,e){let n=[],r=e;for(;r<t.length;r+=1){let i=t[r];if(!i.trim()){n.push(i);continue}if(!/^\s/.test(i))break;n.push(i.replace(/^ {2}/,""))}let o=n.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return o.length===0?{value:{},nextIndex:r}:o.every(i=>i.trimStart().startsWith("- "))?{value:o.map((i,s)=>L(i.trimStart().slice(2),e+s+1)),nextIndex:r}:{value:O(n.join(`
9
9
  `)),nextIndex:r}}function at(t,e){let n=t.indexOf(":");if(n<=0)throw new Error(`Invalid YAML line ${e}.`);let r=t.slice(0,n).trim(),o=t.slice(n+1).trim();if(!r)throw new Error(`Invalid YAML key at line ${e}.`);return{key:r,value:o}}function L(t,e){if(t==="")return"";if(t==="[]")return[];if(t==="{}")return{};if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(t.startsWith('"'))return v(t,e);if(t.startsWith("'")){if(!t.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${e}.`);return t.slice(1,-1).replace(/''/g,"'")}if(t.startsWith("[")||t.startsWith("{"))return v(t,e);if(t.includes("[")||t.includes("]")||t.includes("{")||t.includes("}"))throw new Error(`Unsupported YAML scalar at line ${e}.`);return t}function v(t,e){try{return JSON.parse(t)}catch{throw new Error(`Invalid YAML scalar at line ${e}.`)}}function B(t,e=""){return Object.entries(t).map(([n,r])=>ut(n,r,e)).join(`
10
10
  `)}function ut(t,e,n){return Array.isArray(e)?`${n}${t}: ${JSON.stringify(e)}`:e&&typeof e=="object"?`${n}${t}:
11
- ${B(e,`${n} `)}`:`${n}${t}: ${JSON.stringify(e)}`}import*as f from"path";function ct(t,e){let n=f.resolve(t),r=f.resolve(t,e);return r===n?!0:n===f.parse(n).root?r.startsWith(n):r.startsWith(n+f.sep)}function le(t,e){if(f.isAbsolute(e))return f.resolve(e);if(!ct(t,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return f.resolve(t,e)}import{homedir as A,platform as lt,release as ft}from"node:os";import{execSync as dt}from"node:child_process";import{resolve as h}from"node:path";var M=lt(),pt=M==="win32",ge=M==="darwin",he=M==="linux",xe=ft(),ye=A();function we(){let t=process.env.XENO_AGENT_HOME?.trim();return t?h(t):h(A(),".xeno-agent")}function be(){let t=process.env.XENO_CONFIG_DIR?.trim();return t?h(t):h(A(),".xeno-code")}function Ee(t){return h(t,".xeno-code")}function Re(){return pt?"powershell":process.env.SHELL?.split("/").pop()??"bash"}function Te(t){try{return dt("git rev-parse --is-inside-work-tree",{cwd:t,stdio:"ignore"}),!0}catch{return!1}}function Ae(t,e){for(let n of e)if(t[n]===void 0||t[n]===null||t[n]==="")return`Missing required parameter: ${n}`;return null}function Me(t,e,n){let r=t[e];if(r==null){if(n!==void 0)return n;throw new Error(`Missing required parameter: ${e}`)}if(typeof r!="string")throw new Error(`Parameter ${e} must be a string, got ${typeof r}`);return r}function Se(t,e,n){let r=t[e];if(r==null){if(n!==void 0)return n;throw new Error(`Missing required parameter: ${e}`)}if(typeof r!="number")throw new Error(`Parameter ${e} must be a number, got ${typeof r}`);if(isNaN(r))throw new Error(`Parameter ${e} is NaN`);return r}function _e(t,e,n){let r=t[e];if(r==null){if(n!==void 0)return n;throw new Error(`Missing required parameter: ${e}`)}if(typeof r!="boolean")throw new Error(`Parameter ${e} must be a boolean, got ${typeof r}`);return r}function mt(t){if(t.length>5e3)return"Pattern too long (max 5000 characters)";let n=[/(\.\*){3,}/,/(\+\+|\*\*)/,/(.*\+.*\+.*\+)/];for(let r of n)if(r.test(t))return"Pattern contains potentially unsafe constructs that could cause excessive backtracking";return null}function Ce(t,e,n=5e3){let r=mt(t);if(r)throw new Error(r);try{return new RegExp(t,e)}catch(o){let i=o instanceof Error?o.message:String(o);throw new Error(`Invalid regex pattern: ${i}`)}}function $e(t,e,n=1e3){if(e.length>1e5)throw new Error(`Input too large for safe regex test (${e.length} chars, max 100000)`);return t.test(e)}var gt=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(gt||{}),g=1;function ve(t){g=t}function Oe(){return g}function p(){return new Date().toISOString()}function Le(t,e){g<=0&&(e!==void 0?process.stderr.write(`[${p()}] DEBUG: ${t} ${x(e)}
11
+ ${B(e,`${n} `)}`:`${n}${t}: ${JSON.stringify(e)}`}import*as l from"path";function ct(t,e){let n=l.resolve(t),r=l.resolve(t,e);return r===n?!0:n===l.parse(n).root?r.startsWith(n):r.startsWith(n+l.sep)}function pe(t,e){if(l.isAbsolute(e))return l.resolve(e);if(!ct(t,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return l.resolve(t,e)}import{homedir as C,platform as ft,release as lt}from"node:os";import{execSync as dt}from"node:child_process";import{resolve as h}from"node:path";var k=ft(),pt=k==="win32",ye=k==="darwin",we=k==="linux",be=lt(),Ee=C();function Re(){let t=process.env.XENO_AGENT_HOME?.trim();return t?h(t):h(C(),".xeno-agent")}function Te(){let t=process.env.XENO_CONFIG_DIR?.trim();return t?h(t):h(C(),".xeno-code")}function Ae(t){return h(t,".xeno-code")}function Ce(){return pt?"powershell":process.env.SHELL?.split("/").pop()??"bash"}function ke(t){try{return dt("git rev-parse --is-inside-work-tree",{cwd:t,stdio:"ignore"}),!0}catch{return!1}}function _e(t,e){for(let n of e)if(t[n]===void 0||t[n]===null||t[n]==="")return`Missing required parameter: ${n}`;return null}function Se(t,e,n){let r=t[e];if(r==null){if(n!==void 0)return n;throw new Error(`Missing required parameter: ${e}`)}if(typeof r!="string")throw new Error(`Parameter ${e} must be a string, got ${typeof r}`);return r}function $e(t,e,n){let r=t[e];if(r==null){if(n!==void 0)return n;throw new Error(`Missing required parameter: ${e}`)}if(typeof r!="number")throw new Error(`Parameter ${e} must be a number, got ${typeof r}`);if(isNaN(r))throw new Error(`Parameter ${e} is NaN`);return r}function Ne(t,e,n){let r=t[e];if(r==null){if(n!==void 0)return n;throw new Error(`Missing required parameter: ${e}`)}if(typeof r!="boolean")throw new Error(`Parameter ${e} must be a boolean, got ${typeof r}`);return r}function mt(t){if(t.length>5e3)return"Pattern too long (max 5000 characters)";let n=[/(\.\*){3,}/,/(\+\+|\*\*)/,/(.*\+.*\+.*\+)/];for(let r of n)if(r.test(t))return"Pattern contains potentially unsafe constructs that could cause excessive backtracking";return null}function ve(t,e,n=5e3){let r=mt(t);if(r)throw new Error(r);try{return new RegExp(t,e)}catch(o){let i=o instanceof Error?o.message:String(o);throw new Error(`Invalid regex pattern: ${i}`)}}function Oe(t,e,n=1e3){if(e.length>1e5)throw new Error(`Input too large for safe regex test (${e.length} chars, max 100000)`);return t.test(e)}var gt=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(gt||{}),g=1;function Be(t){g=t}function Pe(){return g}function p(){return new Date().toISOString()}function Ie(t,e){g<=0&&(e!==void 0?process.stderr.write(`[${p()}] DEBUG: ${t} ${x(e)}
12
12
  `):process.stderr.write(`[${p()}] DEBUG: ${t}
13
- `))}function Be(t,e){g<=1&&(e!==void 0?process.stderr.write(`[${p()}] INFO: ${t} ${x(e)}
13
+ `))}function De(t,e){g<=1&&(e!==void 0?process.stderr.write(`[${p()}] INFO: ${t} ${x(e)}
14
14
  `):process.stderr.write(`[${p()}] INFO: ${t}
15
- `))}function Pe(t,e){g<=2&&(e!==void 0?process.stderr.write(`[${p()}] WARN: ${t} ${x(e)}
15
+ `))}function Fe(t,e){g<=2&&(e!==void 0?process.stderr.write(`[${p()}] WARN: ${t} ${x(e)}
16
16
  `):process.stderr.write(`[${p()}] WARN: ${t}
17
- `))}function De(t,e){g<=3&&(e!==void 0?process.stderr.write(`[${p()}] ERROR: ${t} ${x(e)}
17
+ `))}function je(t,e){g<=3&&(e!==void 0?process.stderr.write(`[${p()}] ERROR: ${t} ${x(e)}
18
18
  `):process.stderr.write(`[${p()}] ERROR: ${t}
19
- `))}function x(t){if(t==null)return"";if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}var b=class extends Error{statusCode;body;retryAfterMs;requestId;cfRay;constructor(e,n={}){super(e),this.name="ApiTransientError",this.statusCode=n.statusCode,this.retryAfterMs=n.retryAfterMs,this.requestId=n.requestId,this.cfRay=n.cfRay}},y={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function w(t,e){let n=process.env[t],r=n?Number.parseInt(n,10):Number.NaN;return!Number.isFinite(r)||r<0?e:r}function ht(t={}){let e=Math.max(0,t.maxRetries??w("XENO_API_MAX_RETRIES",y.maxRetries)),n=Math.max(50,t.baseDelayMs??w("XENO_API_BASE_DELAY_MS",y.baseDelayMs)),r=Math.max(n,t.maxDelayMs??w("XENO_API_MAX_DELAY_MS",y.maxDelayMs)),o=Math.max(0,t.jitterMs??w("XENO_API_RETRY_JITTER_MS",y.jitterMs));return{maxRetries:e,baseDelayMs:n,maxDelayMs:r,jitterMs:o}}function xt(t,e,n){if(e.retryAfterMs&&e.retryAfterMs>0)return Math.min(e.retryAfterMs,n.maxDelayMs);let r=Math.min(n.baseDelayMs*Math.pow(2,t),n.maxDelayMs),o=Math.floor(Math.random()*n.jitterMs);return Math.min(r+o,n.maxDelayMs)}function P(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("too many requests")||e.includes("429")}function yt(t){let e=t.toLowerCase();return e.includes("network")||e.includes("timeout")||e.includes("fetch failed")||e.includes("socket hang up")||e.includes("econnreset")||e.includes("eai_again")||e.includes("enotfound")||e.includes("econnrefused")||e.includes("tls")||e.includes("temporarily unavailable")}function D(t){if(t instanceof b)return{statusCode:t.statusCode,retryAfterMs:t.retryAfterMs,requestId:t.requestId,cfRay:t.cfRay};if(!(t instanceof Error))return{};let e=t;if(e.statusCode!==void 0||e.retryAfterMs!==void 0||e.requestId!==void 0||e.cfRay!==void 0)return{statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId,cfRay:e.cfRay};let n=t.message.toLowerCase();return P(n)?{statusCode:429}:{}}var S="408|425|429|500|502|503|504";function wt(t){let e=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${S})\\b`,"i"),n=new RegExp(`\\b(?:${S})\\s+(?:internal|bad\\s+gateway|service\\s+unavailable|gateway\\s+time|request\\s+time|too\\s+early|too\\s+many)`,"i"),r=new RegExp(`^\\s*(?:${S})\\b`);return e.test(t)||n.test(t)||r.test(t)}function bt(t){if(t&&typeof t=="object"&&"retryable"in t)return t.retryable===!0;if(t instanceof b){let{statusCode:e}=D(t);if(e)return e===429||e>=500||e===408||e===409||e===425}if(t instanceof Error){let e=t.name?.toLowerCase()??"";return e==="aborterror"||e==="agentinterruptederror"||t.message.toLowerCase().includes("aborted")||t.message.toLowerCase().includes("interrupted")?!1:wt(t.message)?!0:P(t.message)||yt(t.message.toLowerCase())}return!1}function Et(t){if(t.onAbort)return t.onAbort();let e=new Error("The operation was aborted");return e.name="AbortError",e}async function Fe(t,e={}){let n=ht(e),r;for(let o=0;o<=n.maxRetries;o++)try{if(e.signal?.aborted)throw Et(e);return e.onBeforeAttempt?.(o),await t()}catch(i){if(r=i,!(e.shouldRetry?e.shouldRetry(i,o):bt(i))||o===n.maxRetries)throw i;let u=D(i),l=xt(o,u,n),d=e.getDelayMs?.(i,o,l),m=typeof d=="number"&&d>=0?d:l;await new Promise(R=>setTimeout(R,m))}throw r}var Rt=(t,e)=>{if(!t)return 0;let n=e.toLowerCase(),r=n.includes("claude")?3.5:n.includes("gemini")?3.8:(/(^|[/_-])(gpt|o\d)/.test(n),4),o=[...t].filter(s=>s.codePointAt(0)>127).length,i=Math.ceil(t.length/r);return Math.max(1,i+Math.ceil(o*.35))},Tt=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:Rt,countImage:({detail:t})=>t==="high"?2e3:t==="low"?512:1200,safetyMarginRatio:t=>{let e=t.toLowerCase();return e.includes("claude")?.12:e.includes("gemini")?.14:/(^|[/_-])(gpt|o\d)/.test(e)?.1:.18}});function je(t,e,n=Tt){return{tokens:Math.max(0,Math.ceil(n.countText(t,e))),source:n.source,adapterId:n.id}}function kt(t){return t?Math.ceil(t.length/4):0}function qe(t,e){if(!t||e<=0)return"";let n=e*4;if(t.length<=n)return t;let r=t.slice(0,n),o=r.lastIndexOf(" ");return o>n*.8&&(r=r.slice(0,o)),r+"..."}function He(t,e){return kt(t)<=e}function Je(t,e){return Math.max(0,e-t)}var At={"claude-opus-4-6-thinking":{input:15,output:75},"claude-opus-4-6":{input:15,output:75},"claude-opus-4-5-thinking":{input:15,output:75},"claude-sonnet-4-6":{input:3,output:15},"claude-sonnet-4-5-thinking":{input:3,output:15},"claude-sonnet-4-5":{input:3,output:15},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.5-flash-lite":{input:.075,output:.3},"gemini-3-flash":{input:.15,output:.6},"gemini-3-pro-high":{input:1.25,output:5},"gpt-5":{input:5,output:15},"gpt-5-codex":{input:5,output:15},"gpt-5.1":{input:5,output:15},"gpt-5.1-codex":{input:5,output:15},"gpt-5.2":{input:5,output:15},"gpt-5.2-codex":{input:5,output:15},"kimi-k2":{input:.6,output:2.4},"kimi-k2-thinking":{input:.6,output:2.4},"kimi-k2.5":{input:.6,output:2.4}};function Ye(t,e,n){let r=At[t];return r?e/1e6*r.input+n/1e6*r.output:0}function ze(t){return t<=0?"$0.00":t<.001?"<$0.001":t<.01?`$${t.toFixed(4)}`:t<1?`$${t.toFixed(3)}`:`$${t.toFixed(2)}`}import{spawnSync as Mt}from"node:child_process";function Ke(t){let e=process.platform==="win32"?[{command:"clip.exe",args:[]}]:process.platform==="darwin"?[{command:"pbcopy",args:[]}]:[{command:"wl-copy",args:[]},{command:"xclip",args:["-selection","clipboard"]},{command:"xsel",args:["--clipboard","--input"]}],n=null;for(let r of e)try{let o=Mt(r.command,r.args,{input:t,encoding:"utf8"});if(o.error){n=o.error.message;continue}if(o.status===0)return;n=o.stderr||o.stdout||`exit ${o.status}`}catch(o){n=o instanceof Error?o.message:String(o)}throw new Error(`Clipboard copy failed${n?`: ${n}`:""}`)}function F(t){return t.replace(/\\/g,"/").toLowerCase()}var St=["golden","solution","answer","expected"],_t=["expected","golden","reference","answer","answers"],Ct=new Set([";","&&","||","|"]);function W(t){return F(t).replace(/^\.\/+/,"").split("/").map(e=>e.trim()).filter(e=>e.length>0)}function $t(t){return St.some(e=>t.includes(e))}function I(t){return _t.some(e=>t.includes(e))}function j(t){return t.split("::",1)[0]?.split("?",1)[0]?.split("#",1)[0]??t}function E(t){let e=t.trim().replace(/^[({]+/,"").replace(/[),;]+$/,"");return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e}function Nt(t){return t.match(/"[^"]*"|'[^']*'|&&|\|\||[;|]|[^\s;|&]+/g)?.map(E).filter(e=>e.length>0)??[]}function q(t){let e=W(t),n=j(e.at(-1)??"");return I(n)||e.some(r=>I(r))}function H(t){let e=F(E(t));return!e||e==="/dev/null"||e.startsWith("/tmp/")||e.startsWith("tmp/")||e.startsWith("/var/tmp/")||e.startsWith("var/tmp/")?!1:e.startsWith("/app/")||e.startsWith("./")?!0:!e.startsWith("/")}function vt(t){return/[\\/]/.test(t)||/\.[A-Za-z0-9]{1,8}$/.test(t)}function Ot(t){let e=Nt(t);for(let n=0;n<e.length;n+=1){let r=e[n]?.toLowerCase();if(r!=="cp"&&r!=="mv"&&r!=="rsync"&&r!=="install")continue;let o=[];for(let s=n+1;s<e.length;s+=1){let u=e[s];if(!u||Ct.has(u))break;u!=="--"&&(u.startsWith("-")||o.push(u))}if(o.length<2)continue;let i=o.at(-1);if(H(i)){for(let s of o.slice(0,-1))if(vt(s)&&q(s))return{sourcePath:s,destinationPath:i,operation:r}}}return null}function Lt(t){let e=[/\bcat\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*>\s*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i,/\bdd\b[\s\S]*?\bif=(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))[\s\S]*?\bof=(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i];for(let n of e){let r=t.match(n);if(!r)continue;let o=E(r[1]??r[2]??r[3]??""),i=E(r[4]??r[5]??r[6]??"");if(!(!o||!i)&&q(o)&&H(i))return{sourcePath:o,destinationPath:i,operation:n.source.startsWith("\\bdd")?"dd":"redirect"}}return null}function J(){return process.env.XENO_BENCHMARK_MODE?.trim().toLowerCase()==="terminal-bench"}function X(t){let e=W(t);if(e.includes("solution")||e.includes("xeno-audit")||e.includes(".xeno")&&e.includes("audit"))return!0;let n=j(e.at(-1)??"");return e.includes("tests")&&$t(n)}function Ze(t){return J()?t.filter(e=>!X(e)):t}function Ve(t){return`Benchmark safety: access to verifier answer or benchmark trace artifacts is blocked (${t}). Use task inputs and verifier logic, not golden, solution, or agent audit files.`}function tn(t){return t.split(/[\s"'`;|&]+/).map(e=>e.trim()).filter(e=>e.length>0&&/[\\/]/.test(e)).some(e=>X(e))}function en(t){if(!J())return null;let e=Ot(t)??Lt(t);return e?["[xeno guidance]",`Benchmark safety blocked ${e.operation} from reference-like source ${e.sourcePath} to protected destination ${e.destinationPath}.`,"Do not copy expected, golden, reference, or answer files over task inputs or submission artifacts to make validation pass.","If a previous check polluted an input, restore/regenerate the original source input, then rerun the actual script or program under test."].join(`
20
- `):null}function Bt(t){return/^data:([^;,]+)[;,]/i.exec(t.trim())?.[1]}function Pt(t){let e=[];for(let n of t){if(n.type==="text"){e.push(n.text);continue}if(n.type==="image_url"){e.push(`[image ${Bt(n.image_url.url)??"unknown"}]`);continue}let r=n.text??n.data;if(r&&r.trim().length>0){e.push(r);continue}let o=n.uri??n.mimeType??"resource";e.push(`[resource ${o}]`)}return e.join(`
19
+ `))}function x(t){if(t==null)return"";if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}var ht=/^[A-Za-z0-9:._*-]{1,64}$/,xt=/^[A-Za-z0-9_-][A-Za-z0-9 _-]{0,30}[A-Za-z0-9_-]$/,yt=/^[0-9][0-9A-Za-z.+-]{0,40}$/;function qe(t){if(!t||typeof t!="object")throw new TypeError("requestContext must be an object");let e=Object.keys(t).filter(r=>r!=="surface"&&r!=="client");if(e.length>0)throw new TypeError(`requestContext does not accept: ${e.join(", ")}`);if(typeof t.surface!="string"||!ht.test(t.surface))throw new TypeError("requestContext.surface must match /^[A-Za-z0-9:._*-]{1,64}$/");if(t.client===void 0)return Object.freeze({surface:t.surface});let n=t.client;if(!n||typeof n!="object"||Object.keys(n).some(r=>r!=="name"&&r!=="version"))throw new TypeError("requestContext.client must be { name, version }");if(typeof n.name!="string"||!xt.test(n.name))throw new TypeError("requestContext.client.name must be 2-32 characters of letters, digits, space, _ or -");if(typeof n.version!="string"||!yt.test(n.version))throw new TypeError("requestContext.client.version must start with a digit, e.g. 1.2.3");return Object.freeze({surface:t.surface,client:Object.freeze({name:n.name,version:n.version})})}function Xe(t){return t?{"X-Xeno-Surface":t.surface,...t.client?{"X-Xeno-Client":`${t.client.name}/${t.client.version}`}:{}}:{}}var b=class extends Error{statusCode;body;retryAfterMs;requestId;cfRay;constructor(e,n={}){super(e),this.name="ApiTransientError",this.statusCode=n.statusCode,this.retryAfterMs=n.retryAfterMs,this.requestId=n.requestId,this.cfRay=n.cfRay}},y={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function w(t,e){let n=process.env[t],r=n?Number.parseInt(n,10):Number.NaN;return!Number.isFinite(r)||r<0?e:r}function wt(t={}){let e=Math.max(0,t.maxRetries??w("XENO_API_MAX_RETRIES",y.maxRetries)),n=Math.max(50,t.baseDelayMs??w("XENO_API_BASE_DELAY_MS",y.baseDelayMs)),r=Math.max(n,t.maxDelayMs??w("XENO_API_MAX_DELAY_MS",y.maxDelayMs)),o=Math.max(0,t.jitterMs??w("XENO_API_RETRY_JITTER_MS",y.jitterMs));return{maxRetries:e,baseDelayMs:n,maxDelayMs:r,jitterMs:o}}function bt(t,e,n){if(e.retryAfterMs&&e.retryAfterMs>0)return Math.min(e.retryAfterMs,n.maxDelayMs);let r=Math.min(n.baseDelayMs*Math.pow(2,t),n.maxDelayMs),o=Math.floor(Math.random()*n.jitterMs);return Math.min(r+o,n.maxDelayMs)}function P(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("too many requests")||e.includes("429")}function Et(t){let e=t.toLowerCase();return e.includes("network")||e.includes("timeout")||e.includes("fetch failed")||e.includes("socket hang up")||e.includes("econnreset")||e.includes("eai_again")||e.includes("enotfound")||e.includes("econnrefused")||e.includes("tls")||e.includes("temporarily unavailable")}function I(t){if(t instanceof b)return{statusCode:t.statusCode,retryAfterMs:t.retryAfterMs,requestId:t.requestId,cfRay:t.cfRay};if(!(t instanceof Error))return{};let e=t;if(e.statusCode!==void 0||e.retryAfterMs!==void 0||e.requestId!==void 0||e.cfRay!==void 0)return{statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId,cfRay:e.cfRay};let n=t.message.toLowerCase();return P(n)?{statusCode:429}:{}}var M="408|425|429|500|502|503|504";function Rt(t){let e=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${M})\\b`,"i"),n=new RegExp(`\\b(?:${M})\\s+(?:internal|bad\\s+gateway|service\\s+unavailable|gateway\\s+time|request\\s+time|too\\s+early|too\\s+many)`,"i"),r=new RegExp(`^\\s*(?:${M})\\b`);return e.test(t)||n.test(t)||r.test(t)}function Tt(t){if(t&&typeof t=="object"&&"retryable"in t)return t.retryable===!0;if(t instanceof b){let{statusCode:e}=I(t);if(e)return e===429||e>=500||e===408||e===409||e===425}if(t instanceof Error){let e=t.name?.toLowerCase()??"";return e==="aborterror"||e==="agentinterruptederror"||t.message.toLowerCase().includes("aborted")||t.message.toLowerCase().includes("interrupted")?!1:Rt(t.message)?!0:P(t.message)||Et(t.message.toLowerCase())}return!1}function At(t){if(t.onAbort)return t.onAbort();let e=new Error("The operation was aborted");return e.name="AbortError",e}async function He(t,e={}){let n=wt(e),r;for(let o=0;o<=n.maxRetries;o++)try{if(e.signal?.aborted)throw At(e);return e.onBeforeAttempt?.(o),await t()}catch(i){if(r=i,!(e.shouldRetry?e.shouldRetry(i,o):Tt(i))||o===n.maxRetries)throw i;let u=I(i),f=bt(o,u,n),d=e.getDelayMs?.(i,o,f),m=typeof d=="number"&&d>=0?d:f;await new Promise(R=>setTimeout(R,m))}throw r}var Ct=(t,e)=>{if(!t)return 0;let n=e.toLowerCase(),r=n.includes("claude")?3.5:n.includes("gemini")?3.8:(/(^|[/_-])(gpt|o\d)/.test(n),4),o=[...t].filter(s=>s.codePointAt(0)>127).length,i=Math.ceil(t.length/r);return Math.max(1,i+Math.ceil(o*.35))},kt=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:Ct,countImage:({detail:t})=>t==="high"?2e3:t==="low"?512:1200,safetyMarginRatio:t=>{let e=t.toLowerCase();return e.includes("claude")?.12:e.includes("gemini")?.14:/(^|[/_-])(gpt|o\d)/.test(e)?.1:.18}});function Ye(t,e,n=kt){return{tokens:Math.max(0,Math.ceil(n.countText(t,e))),source:n.source,adapterId:n.id}}function Mt(t){return t?Math.ceil(t.length/4):0}function Ue(t,e){if(!t||e<=0)return"";let n=e*4;if(t.length<=n)return t;let r=t.slice(0,n),o=r.lastIndexOf(" ");return o>n*.8&&(r=r.slice(0,o)),r+"..."}function Ge(t,e){return Mt(t)<=e}function Ke(t,e){return Math.max(0,e-t)}var _t={"claude-opus-4-6-thinking":{input:15,output:75},"claude-opus-4-6":{input:15,output:75},"claude-opus-4-5-thinking":{input:15,output:75},"claude-sonnet-4-6":{input:3,output:15},"claude-sonnet-4-5-thinking":{input:3,output:15},"claude-sonnet-4-5":{input:3,output:15},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.5-flash-lite":{input:.075,output:.3},"gemini-3-flash":{input:.15,output:.6},"gemini-3-pro-high":{input:1.25,output:5},"gpt-5":{input:5,output:15},"gpt-5-codex":{input:5,output:15},"gpt-5.1":{input:5,output:15},"gpt-5.1-codex":{input:5,output:15},"gpt-5.2":{input:5,output:15},"gpt-5.2-codex":{input:5,output:15},"kimi-k2":{input:.6,output:2.4},"kimi-k2-thinking":{input:.6,output:2.4},"kimi-k2.5":{input:.6,output:2.4}};function Qe(t,e,n){let r=_t[t];return r?e/1e6*r.input+n/1e6*r.output:0}function Ve(t){return t<=0?"$0.00":t<.001?"<$0.001":t<.01?`$${t.toFixed(4)}`:t<1?`$${t.toFixed(3)}`:`$${t.toFixed(2)}`}import{spawnSync as St}from"node:child_process";function nn(t){let e=process.platform==="win32"?[{command:"clip.exe",args:[]}]:process.platform==="darwin"?[{command:"pbcopy",args:[]}]:[{command:"wl-copy",args:[]},{command:"xclip",args:["-selection","clipboard"]},{command:"xsel",args:["--clipboard","--input"]}],n=null;for(let r of e)try{let o=St(r.command,r.args,{input:t,encoding:"utf8"});if(o.error){n=o.error.message;continue}if(o.status===0)return;n=o.stderr||o.stdout||`exit ${o.status}`}catch(o){n=o instanceof Error?o.message:String(o)}throw new Error(`Clipboard copy failed${n?`: ${n}`:""}`)}function F(t){return t.replace(/\\/g,"/").toLowerCase()}var $t=["golden","solution","answer","expected"],Nt=["expected","golden","reference","answer","answers"],vt=new Set([";","&&","||","|"]);function j(t){return F(t).replace(/^\.\/+/,"").split("/").map(e=>e.trim()).filter(e=>e.length>0)}function Ot(t){return $t.some(e=>t.includes(e))}function D(t){return Nt.some(e=>t.includes(e))}function W(t){return t.split("::",1)[0]?.split("?",1)[0]?.split("#",1)[0]??t}function E(t){let e=t.trim().replace(/^[({]+/,"").replace(/[),;]+$/,"");return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e}function Lt(t){return t.match(/"[^"]*"|'[^']*'|&&|\|\||[;|]|[^\s;|&]+/g)?.map(E).filter(e=>e.length>0)??[]}function q(t){let e=j(t),n=W(e.at(-1)??"");return D(n)||e.some(r=>D(r))}function X(t){let e=F(E(t));return!e||e==="/dev/null"||e.startsWith("/tmp/")||e.startsWith("tmp/")||e.startsWith("/var/tmp/")||e.startsWith("var/tmp/")?!1:e.startsWith("/app/")||e.startsWith("./")?!0:!e.startsWith("/")}function Bt(t){return/[\\/]/.test(t)||/\.[A-Za-z0-9]{1,8}$/.test(t)}function Pt(t){let e=Lt(t);for(let n=0;n<e.length;n+=1){let r=e[n]?.toLowerCase();if(r!=="cp"&&r!=="mv"&&r!=="rsync"&&r!=="install")continue;let o=[];for(let s=n+1;s<e.length;s+=1){let u=e[s];if(!u||vt.has(u))break;u!=="--"&&(u.startsWith("-")||o.push(u))}if(o.length<2)continue;let i=o.at(-1);if(X(i)){for(let s of o.slice(0,-1))if(Bt(s)&&q(s))return{sourcePath:s,destinationPath:i,operation:r}}}return null}function It(t){let e=[/\bcat\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*>\s*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i,/\bdd\b[\s\S]*?\bif=(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))[\s\S]*?\bof=(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i];for(let n of e){let r=t.match(n);if(!r)continue;let o=E(r[1]??r[2]??r[3]??""),i=E(r[4]??r[5]??r[6]??"");if(!(!o||!i)&&q(o)&&X(i))return{sourcePath:o,destinationPath:i,operation:n.source.startsWith("\\bdd")?"dd":"redirect"}}return null}function z(){return process.env.XENO_BENCHMARK_MODE?.trim().toLowerCase()==="terminal-bench"}function H(t){let e=j(t);if(e.includes("solution")||e.includes("xeno-audit")||e.includes(".xeno")&&e.includes("audit"))return!0;let n=W(e.at(-1)??"");return e.includes("tests")&&Ot(n)}function on(t){return z()?t.filter(e=>!H(e)):t}function sn(t){return`Benchmark safety: access to verifier answer or benchmark trace artifacts is blocked (${t}). Use task inputs and verifier logic, not golden, solution, or agent audit files.`}function an(t){return t.split(/[\s"'`;|&]+/).map(e=>e.trim()).filter(e=>e.length>0&&/[\\/]/.test(e)).some(e=>H(e))}function un(t){if(!z())return null;let e=Pt(t)??It(t);return e?["[xeno guidance]",`Benchmark safety blocked ${e.operation} from reference-like source ${e.sourcePath} to protected destination ${e.destinationPath}.`,"Do not copy expected, golden, reference, or answer files over task inputs or submission artifacts to make validation pass.","If a previous check polluted an input, restore/regenerate the original source input, then rerun the actual script or program under test."].join(`
20
+ `):null}function Dt(t){return/^data:([^;,]+)[;,]/i.exec(t.trim())?.[1]}function Ft(t){let e=[];for(let n of t){if(n.type==="text"){e.push(n.text);continue}if(n.type==="image_url"){e.push(`[image ${Dt(n.image_url.url)??"unknown"}]`);continue}let r=n.text??n.data;if(r&&r.trim().length>0){e.push(r);continue}let o=n.uri??n.mimeType??"resource";e.push(`[resource ${o}]`)}return e.join(`
21
21
 
22
- `).trim()}function Y(t){let e=t.trim();return e.length>0?[{type:"text",text:e}]:[]}function rn(t){return typeof t=="string"?t:Pt(t)}function Dt(t){if(t.success)return t.output;let e=[`Error: ${t.error??"Tool execution failed"}`];return t.output.trim().length>0&&e.push(t.output),e.join(`
23
- `)}function on(t){let e=t.assistant_content&&t.assistant_content.length>0?t.assistant_content:typeof t.content=="string"?Y(t.content):t.content,n=t.assistant_only_content??[],r=It(t),o=[...e,...n,...r?[r]:[]];return o.length>0?o:t.content}function It(t){let e=t.operation;if(!e)return null;let n=t.evidence??e.evidence??[],r=n.filter(i=>i.status==="verified").length,o=n.filter(i=>i.status==="failed").length;return{type:"text",text:["[xeno_operation]",`operation_id: ${e.operationId}`,`state: ${e.state}`,`terminal: ${e.terminal?"yes":"no"}`,`completion_policy: ${e.completionPolicy}`,e.taskId?`task_id: ${e.taskId}`:null,e.completionReason?`completion_reason: ${e.completionReason}`:null,`evidence: ${r} verified, ${o} failed`,t.retryable===void 0?null:`retryable: ${t.retryable?"yes":"no"}`,"[/xeno_operation]"].filter(i=>!!i).join(`
24
- `)}}function sn(t){return Array.isArray(t)&&t.some(e=>e.type!=="text")}function an(t){return typeof t=="string"?Y(t):t}function un(t,e){return{type:"tool_result",tool_use_id:t,content:Dt(e),...e.assistantContent&&e.assistantContent.length>0?{assistant_content:e.assistantContent}:{},...e.assistantOnlyContent&&e.assistantOnlyContent.length>0?{assistant_only_content:e.assistantOnlyContent}:{},is_error:!e.success,...e.operation?{operation:e.operation}:{},...e.evidence&&e.evidence.length>0?{evidence:e.evidence}:{},...e.webContext?{web_context:e.webContext}:{},...e.retryable!==void 0?{retryable:e.retryable}:{}}}function ln(t,e={}){for(let n of t){let r=n.codePointAt(0);if(r===127)return!0;if(!(r>31)&&!(r===9&&e.allowTab===!0)&&!((r===10||r===13)&&e.allowLineBreaks===!0))return!0}return!1}export{b as ApiTransientError,ye as HOME_DIR,he as IS_LINUX,ge as IS_MAC,pt as IS_WINDOWS,gt as LogLevel,xe as OS_VERSION,M as PLATFORM,je as accountTextTokens,Xt as appendDurableLine,Jt as appendLine,Ve as benchmarkLeakError,un as buildToolResultBlock,Dt as buildToolResultText,Ye as calculateCost,tn as commandMentionsBenchmarkLeak,Tt as conservativeTokenAccountingAdapter,Ke as copyTextToClipboard,Ce as createSafeRegex,Le as debug,V as decodeTextBuffer,te as deleteDir,Vt as deleteFile,et as detectLineEnding,zt as detectPreferredLineEnding,Z as detectTextEncoding,tt as encodeTextBuffer,k as ensureDir,De as error,kt as estimateTokens,Rt as estimateTokensForModel,Kt as existsSync,Ze as filterBenchmarkLeakPaths,Gt as findSimilarFile,He as fitsInBudget,ze as formatCost,we as getAgentHome,en as getBenchmarkReferenceOverwriteHint,_e as getBoolean,be as getConfigDir,Oe as getLogLevel,Se as getNumber,Ee as getProjectConfigDir,D as getRetryErrorContext,Re as getShellName,Me as getString,on as getToolResultTransportContent,qt as hasDir,ln as hasDisallowedAsciiControlCharacter,jt as hasFile,ue as hasFrontmatter,sn as hasNonTextToolResultContent,wt as hasTransientStatusMention,Be as info,X as isBenchmarkLeakPath,J as isBenchmarkMode,Te as isGitRepo,ct as isPathSafe,bt as isRetryableError,Zt as listDirs,Qt as listFiles,nt as normalizeLineEndings,se as parseDocument,oe as parseJsonLines,Ht as readFileSafe,Ut as readIfExists,rt as readTextFile,Je as remainingBudget,Q as renameReplacingWithRetry,ne as safeJsonParse,re as safeJsonStringify,$e as safeRegexTest,le as safeResolvePath,ve as setLogLevel,ae as stringifyDocument,an as toTransportAssistantBlocks,Pt as toolAssistantContentToText,rn as toolResultContentToText,qe as truncateToTokens,mt as validateRegexPattern,Ae as validateRequired,Pe as warn,Fe as withRetry,G as writeAtomic,Yt as writeTextFile};
22
+ `).trim()}function J(t){let e=t.trim();return e.length>0?[{type:"text",text:e}]:[]}function fn(t){return typeof t=="string"?t:Ft(t)}function jt(t){if(t.success)return t.output;let e=[`Error: ${t.error??"Tool execution failed"}`];return t.output.trim().length>0&&e.push(t.output),e.join(`
23
+ `)}function ln(t){let e=t.assistant_content&&t.assistant_content.length>0?t.assistant_content:typeof t.content=="string"?J(t.content):t.content,n=t.assistant_only_content??[],r=Wt(t),o=[...e,...n,...r?[r]:[]];return o.length>0?o:t.content}function Wt(t){let e=t.operation;if(!e)return null;let n=t.evidence??e.evidence??[],r=n.filter(i=>i.status==="verified").length,o=n.filter(i=>i.status==="failed").length;return{type:"text",text:["[xeno_operation]",`operation_id: ${e.operationId}`,`state: ${e.state}`,`terminal: ${e.terminal?"yes":"no"}`,`completion_policy: ${e.completionPolicy}`,e.taskId?`task_id: ${e.taskId}`:null,e.completionReason?`completion_reason: ${e.completionReason}`:null,`evidence: ${r} verified, ${o} failed`,t.retryable===void 0?null:`retryable: ${t.retryable?"yes":"no"}`,"[/xeno_operation]"].filter(i=>!!i).join(`
24
+ `)}}function dn(t){return Array.isArray(t)&&t.some(e=>e.type!=="text")}function pn(t){return typeof t=="string"?J(t):t}function mn(t,e){return{type:"tool_result",tool_use_id:t,content:jt(e),...e.assistantContent&&e.assistantContent.length>0?{assistant_content:e.assistantContent}:{},...e.assistantOnlyContent&&e.assistantOnlyContent.length>0?{assistant_only_content:e.assistantOnlyContent}:{},is_error:!e.success,...e.operation?{operation:e.operation}:{},...e.evidence&&e.evidence.length>0?{evidence:e.evidence}:{},...e.webContext?{web_context:e.webContext}:{},...e.retryable!==void 0?{retryable:e.retryable}:{}}}function hn(t,e={}){for(let n of t){let r=n.codePointAt(0);if(r===127)return!0;if(!(r>31)&&!(r===9&&e.allowTab===!0)&&!((r===10||r===13)&&e.allowLineBreaks===!0))return!0}return!1}export{b as ApiTransientError,Ee as HOME_DIR,we as IS_LINUX,ye as IS_MAC,pt as IS_WINDOWS,gt as LogLevel,be as OS_VERSION,k as PLATFORM,Ye as accountTextTokens,Ut as appendDurableLine,Yt as appendLine,sn as benchmarkLeakError,mn as buildToolResultBlock,jt as buildToolResultText,Qe as calculateCost,an as commandMentionsBenchmarkLeak,kt as conservativeTokenAccountingAdapter,nn as copyTextToClipboard,ve as createSafeRegex,Ie as debug,V as decodeTextBuffer,re as deleteDir,ne as deleteFile,et as detectLineEnding,Kt as detectPreferredLineEnding,Q as detectTextEncoding,tt as encodeTextBuffer,A as ensureDir,je as error,Mt as estimateTokens,Ct as estimateTokensForModel,Vt as existsSync,on as filterBenchmarkLeakPaths,Zt as findSimilarFile,Ge as fitsInBudget,Ve as formatCost,Re as getAgentHome,un as getBenchmarkReferenceOverwriteHint,Ne as getBoolean,Te as getConfigDir,Pe as getLogLevel,$e as getNumber,Ae as getProjectConfigDir,I as getRetryErrorContext,Ce as getShellName,Se as getString,ln as getToolResultTransportContent,Ht as hasDir,hn as hasDisallowedAsciiControlCharacter,zt as hasFile,le as hasFrontmatter,dn as hasNonTextToolResultContent,Rt as hasTransientStatusMention,De as info,H as isBenchmarkLeakPath,z as isBenchmarkMode,ke as isGitRepo,ct as isPathSafe,Tt as isRetryableError,ee as listDirs,te as listFiles,nt as normalizeLineEndings,qe as normalizeXenoRequestContext,ce as parseDocument,ae as parseJsonLines,Jt as readFileSafe,Qt as readIfExists,rt as readTextFile,Ke as remainingBudget,Z as renameReplacingWithRetry,ie as safeJsonParse,se as safeJsonStringify,Oe as safeRegexTest,pe as safeResolvePath,Be as setLogLevel,fe as stringifyDocument,pn as toTransportAssistantBlocks,Ft as toolAssistantContentToText,fn as toolResultContentToText,Ue as truncateToTokens,mt as validateRegexPattern,_e as validateRequired,Fe as warn,He as withRetry,U as writeAtomic,Gt as writeTextFile,Xe as xenoRequestContextHeaders};
@@ -1 +1 @@
1
- {"inputs":{"src/utils/fs.ts":{"bytes":11685,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/json.ts":{"bytes":804,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/utils/path-security.ts":{"bytes":993,"imports":[{"path":"path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/platform.ts":{"bytes":5600,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/validation.ts":{"bytes":5336,"imports":[],"format":"esm"},"src/utils/logger.ts":{"bytes":3719,"imports":[],"format":"esm"},"src/utils/retry.ts":{"bytes":11711,"imports":[],"format":"esm"},"src/utils/tokens.ts":{"bytes":3207,"imports":[],"format":"esm"},"src/utils/cost.ts":{"bytes":1826,"imports":[],"format":"esm"},"src/utils/clipboard.ts":{"bytes":1156,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/utils/benchmark-safety.ts":{"bytes":6542,"imports":[],"format":"esm"},"src/utils/tool-result-content.ts":{"bytes":4820,"imports":[],"format":"esm"},"src/utils/text-security.ts":{"bytes":809,"imports":[],"format":"esm"},"src/utils/index.ts":{"bytes":1453,"imports":[{"path":"src/utils/fs.ts","kind":"import-statement","original":"./fs.js"},{"path":"src/utils/json.ts","kind":"import-statement","original":"./json.js"},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"./yaml.js"},{"path":"src/utils/path-security.ts","kind":"import-statement","original":"./path-security.js"},{"path":"src/utils/platform.ts","kind":"import-statement","original":"./platform.js"},{"path":"src/utils/validation.ts","kind":"import-statement","original":"./validation.js"},{"path":"src/utils/logger.ts","kind":"import-statement","original":"./logger.js"},{"path":"src/utils/retry.ts","kind":"import-statement","original":"./retry.js"},{"path":"src/utils/tokens.ts","kind":"import-statement","original":"./tokens.js"},{"path":"src/utils/cost.ts","kind":"import-statement","original":"./cost.js"},{"path":"src/utils/clipboard.ts","kind":"import-statement","original":"./clipboard.js"},{"path":"src/utils/benchmark-safety.ts","kind":"import-statement","original":"./benchmark-safety.js"},{"path":"src/utils/tool-result-content.ts","kind":"import-statement","original":"./tool-result-content.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"./text-security.js"}],"format":"esm"}},"outputs":{"dist/utils/index.cjs":{"imports":[{"path":"node:fs","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"path","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/utils/index.ts","inputs":{"src/utils/index.ts":{"bytesInOutput":1976},"src/utils/fs.ts":{"bytesInOutput":4478},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2639},"src/utils/path-security.ts":{"bytesInOutput":313},"src/utils/platform.ts":{"bytesInOutput":687},"src/utils/validation.ts":{"bytesInOutput":1423},"src/utils/logger.ts":{"bytesInOutput":913},"src/utils/retry.ts":{"bytesInOutput":3188},"src/utils/tokens.ts":{"bytesInOutput":904},"src/utils/cost.ts":{"bytesInOutput":933},"src/utils/clipboard.ts":{"bytesInOutput":604},"src/utils/benchmark-safety.ts":{"bytesInOutput":3108},"src/utils/tool-result-content.ts":{"bytesInOutput":2118},"src/utils/text-security.ts":{"bytesInOutput":180}},"bytes":25666}}}
1
+ {"inputs":{"src/utils/fs.ts":{"bytes":11685,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/json.ts":{"bytes":804,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/utils/path-security.ts":{"bytes":993,"imports":[{"path":"path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/platform.ts":{"bytes":5600,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/validation.ts":{"bytes":5336,"imports":[],"format":"esm"},"src/utils/logger.ts":{"bytes":3719,"imports":[],"format":"esm"},"src/utils/request-context.ts":{"bytes":3679,"imports":[],"format":"esm"},"src/utils/retry.ts":{"bytes":11711,"imports":[],"format":"esm"},"src/utils/tokens.ts":{"bytes":3207,"imports":[],"format":"esm"},"src/utils/cost.ts":{"bytes":1826,"imports":[],"format":"esm"},"src/utils/clipboard.ts":{"bytes":1156,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/utils/benchmark-safety.ts":{"bytes":6542,"imports":[],"format":"esm"},"src/utils/tool-result-content.ts":{"bytes":4820,"imports":[],"format":"esm"},"src/utils/text-security.ts":{"bytes":809,"imports":[],"format":"esm"},"src/utils/index.ts":{"bytes":1491,"imports":[{"path":"src/utils/fs.ts","kind":"import-statement","original":"./fs.js"},{"path":"src/utils/json.ts","kind":"import-statement","original":"./json.js"},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"./yaml.js"},{"path":"src/utils/path-security.ts","kind":"import-statement","original":"./path-security.js"},{"path":"src/utils/platform.ts","kind":"import-statement","original":"./platform.js"},{"path":"src/utils/validation.ts","kind":"import-statement","original":"./validation.js"},{"path":"src/utils/logger.ts","kind":"import-statement","original":"./logger.js"},{"path":"src/utils/request-context.ts","kind":"import-statement","original":"./request-context.js"},{"path":"src/utils/retry.ts","kind":"import-statement","original":"./retry.js"},{"path":"src/utils/tokens.ts","kind":"import-statement","original":"./tokens.js"},{"path":"src/utils/cost.ts","kind":"import-statement","original":"./cost.js"},{"path":"src/utils/clipboard.ts","kind":"import-statement","original":"./clipboard.js"},{"path":"src/utils/benchmark-safety.ts","kind":"import-statement","original":"./benchmark-safety.js"},{"path":"src/utils/tool-result-content.ts","kind":"import-statement","original":"./tool-result-content.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"./text-security.js"}],"format":"esm"}},"outputs":{"dist/utils/index.cjs":{"imports":[{"path":"node:fs","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"path","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/utils/index.ts","inputs":{"src/utils/index.ts":{"bytesInOutput":2044},"src/utils/fs.ts":{"bytesInOutput":4478},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2639},"src/utils/path-security.ts":{"bytesInOutput":313},"src/utils/platform.ts":{"bytesInOutput":687},"src/utils/validation.ts":{"bytesInOutput":1423},"src/utils/logger.ts":{"bytesInOutput":913},"src/utils/request-context.ts":{"bytesInOutput":1241},"src/utils/retry.ts":{"bytesInOutput":3188},"src/utils/tokens.ts":{"bytesInOutput":904},"src/utils/cost.ts":{"bytesInOutput":933},"src/utils/clipboard.ts":{"bytesInOutput":604},"src/utils/benchmark-safety.ts":{"bytesInOutput":3108},"src/utils/tool-result-content.ts":{"bytesInOutput":2118},"src/utils/text-security.ts":{"bytesInOutput":180}},"bytes":27029}}}
@@ -1 +1 @@
1
- {"inputs":{"src/utils/fs.ts":{"bytes":11685,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/json.ts":{"bytes":804,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/utils/path-security.ts":{"bytes":993,"imports":[{"path":"path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/platform.ts":{"bytes":5600,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/validation.ts":{"bytes":5336,"imports":[],"format":"esm"},"src/utils/logger.ts":{"bytes":3719,"imports":[],"format":"esm"},"src/utils/retry.ts":{"bytes":11711,"imports":[],"format":"esm"},"src/utils/tokens.ts":{"bytes":3207,"imports":[],"format":"esm"},"src/utils/cost.ts":{"bytes":1826,"imports":[],"format":"esm"},"src/utils/clipboard.ts":{"bytes":1156,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/utils/benchmark-safety.ts":{"bytes":6542,"imports":[],"format":"esm"},"src/utils/tool-result-content.ts":{"bytes":4820,"imports":[],"format":"esm"},"src/utils/text-security.ts":{"bytes":809,"imports":[],"format":"esm"},"src/utils/index.ts":{"bytes":1453,"imports":[{"path":"src/utils/fs.ts","kind":"import-statement","original":"./fs.js"},{"path":"src/utils/json.ts","kind":"import-statement","original":"./json.js"},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"./yaml.js"},{"path":"src/utils/path-security.ts","kind":"import-statement","original":"./path-security.js"},{"path":"src/utils/platform.ts","kind":"import-statement","original":"./platform.js"},{"path":"src/utils/validation.ts","kind":"import-statement","original":"./validation.js"},{"path":"src/utils/logger.ts","kind":"import-statement","original":"./logger.js"},{"path":"src/utils/retry.ts","kind":"import-statement","original":"./retry.js"},{"path":"src/utils/tokens.ts","kind":"import-statement","original":"./tokens.js"},{"path":"src/utils/cost.ts","kind":"import-statement","original":"./cost.js"},{"path":"src/utils/clipboard.ts","kind":"import-statement","original":"./clipboard.js"},{"path":"src/utils/benchmark-safety.ts","kind":"import-statement","original":"./benchmark-safety.js"},{"path":"src/utils/tool-result-content.ts","kind":"import-statement","original":"./tool-result-content.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"./text-security.js"}],"format":"esm"}},"outputs":{"dist/utils/index.js":{"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"path","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true}],"exports":["ApiTransientError","HOME_DIR","IS_LINUX","IS_MAC","IS_WINDOWS","LogLevel","OS_VERSION","PLATFORM","accountTextTokens","appendDurableLine","appendLine","benchmarkLeakError","buildToolResultBlock","buildToolResultText","calculateCost","commandMentionsBenchmarkLeak","conservativeTokenAccountingAdapter","copyTextToClipboard","createSafeRegex","debug","decodeTextBuffer","deleteDir","deleteFile","detectLineEnding","detectPreferredLineEnding","detectTextEncoding","encodeTextBuffer","ensureDir","error","estimateTokens","estimateTokensForModel","existsSync","filterBenchmarkLeakPaths","findSimilarFile","fitsInBudget","formatCost","getAgentHome","getBenchmarkReferenceOverwriteHint","getBoolean","getConfigDir","getLogLevel","getNumber","getProjectConfigDir","getRetryErrorContext","getShellName","getString","getToolResultTransportContent","hasDir","hasDisallowedAsciiControlCharacter","hasFile","hasFrontmatter","hasNonTextToolResultContent","hasTransientStatusMention","info","isBenchmarkLeakPath","isBenchmarkMode","isGitRepo","isPathSafe","isRetryableError","listDirs","listFiles","normalizeLineEndings","parseDocument","parseJsonLines","readFileSafe","readIfExists","readTextFile","remainingBudget","renameReplacingWithRetry","safeJsonParse","safeJsonStringify","safeRegexTest","safeResolvePath","setLogLevel","stringifyDocument","toTransportAssistantBlocks","toolAssistantContentToText","toolResultContentToText","truncateToTokens","validateRegexPattern","validateRequired","warn","withRetry","writeAtomic","writeTextFile"],"entryPoint":"src/utils/index.ts","inputs":{"src/utils/fs.ts":{"bytesInOutput":4427},"src/utils/index.ts":{"bytesInOutput":0},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2639},"src/utils/path-security.ts":{"bytesInOutput":311},"src/utils/platform.ts":{"bytesInOutput":630},"src/utils/validation.ts":{"bytesInOutput":1425},"src/utils/logger.ts":{"bytesInOutput":915},"src/utils/retry.ts":{"bytesInOutput":3185},"src/utils/tokens.ts":{"bytesInOutput":904},"src/utils/cost.ts":{"bytesInOutput":933},"src/utils/clipboard.ts":{"bytesInOutput":601},"src/utils/benchmark-safety.ts":{"bytesInOutput":3090},"src/utils/tool-result-content.ts":{"bytesInOutput":2115},"src/utils/text-security.ts":{"bytesInOutput":180}},"bytes":23461}}}
1
+ {"inputs":{"src/utils/fs.ts":{"bytes":11685,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/json.ts":{"bytes":804,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/utils/path-security.ts":{"bytes":993,"imports":[{"path":"path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/platform.ts":{"bytes":5600,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/validation.ts":{"bytes":5336,"imports":[],"format":"esm"},"src/utils/logger.ts":{"bytes":3719,"imports":[],"format":"esm"},"src/utils/request-context.ts":{"bytes":3679,"imports":[],"format":"esm"},"src/utils/retry.ts":{"bytes":11711,"imports":[],"format":"esm"},"src/utils/tokens.ts":{"bytes":3207,"imports":[],"format":"esm"},"src/utils/cost.ts":{"bytes":1826,"imports":[],"format":"esm"},"src/utils/clipboard.ts":{"bytes":1156,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/utils/benchmark-safety.ts":{"bytes":6542,"imports":[],"format":"esm"},"src/utils/tool-result-content.ts":{"bytes":4820,"imports":[],"format":"esm"},"src/utils/text-security.ts":{"bytes":809,"imports":[],"format":"esm"},"src/utils/index.ts":{"bytes":1491,"imports":[{"path":"src/utils/fs.ts","kind":"import-statement","original":"./fs.js"},{"path":"src/utils/json.ts","kind":"import-statement","original":"./json.js"},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"./yaml.js"},{"path":"src/utils/path-security.ts","kind":"import-statement","original":"./path-security.js"},{"path":"src/utils/platform.ts","kind":"import-statement","original":"./platform.js"},{"path":"src/utils/validation.ts","kind":"import-statement","original":"./validation.js"},{"path":"src/utils/logger.ts","kind":"import-statement","original":"./logger.js"},{"path":"src/utils/request-context.ts","kind":"import-statement","original":"./request-context.js"},{"path":"src/utils/retry.ts","kind":"import-statement","original":"./retry.js"},{"path":"src/utils/tokens.ts","kind":"import-statement","original":"./tokens.js"},{"path":"src/utils/cost.ts","kind":"import-statement","original":"./cost.js"},{"path":"src/utils/clipboard.ts","kind":"import-statement","original":"./clipboard.js"},{"path":"src/utils/benchmark-safety.ts","kind":"import-statement","original":"./benchmark-safety.js"},{"path":"src/utils/tool-result-content.ts","kind":"import-statement","original":"./tool-result-content.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"./text-security.js"}],"format":"esm"}},"outputs":{"dist/utils/index.js":{"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"path","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true}],"exports":["ApiTransientError","HOME_DIR","IS_LINUX","IS_MAC","IS_WINDOWS","LogLevel","OS_VERSION","PLATFORM","accountTextTokens","appendDurableLine","appendLine","benchmarkLeakError","buildToolResultBlock","buildToolResultText","calculateCost","commandMentionsBenchmarkLeak","conservativeTokenAccountingAdapter","copyTextToClipboard","createSafeRegex","debug","decodeTextBuffer","deleteDir","deleteFile","detectLineEnding","detectPreferredLineEnding","detectTextEncoding","encodeTextBuffer","ensureDir","error","estimateTokens","estimateTokensForModel","existsSync","filterBenchmarkLeakPaths","findSimilarFile","fitsInBudget","formatCost","getAgentHome","getBenchmarkReferenceOverwriteHint","getBoolean","getConfigDir","getLogLevel","getNumber","getProjectConfigDir","getRetryErrorContext","getShellName","getString","getToolResultTransportContent","hasDir","hasDisallowedAsciiControlCharacter","hasFile","hasFrontmatter","hasNonTextToolResultContent","hasTransientStatusMention","info","isBenchmarkLeakPath","isBenchmarkMode","isGitRepo","isPathSafe","isRetryableError","listDirs","listFiles","normalizeLineEndings","normalizeXenoRequestContext","parseDocument","parseJsonLines","readFileSafe","readIfExists","readTextFile","remainingBudget","renameReplacingWithRetry","safeJsonParse","safeJsonStringify","safeRegexTest","safeResolvePath","setLogLevel","stringifyDocument","toTransportAssistantBlocks","toolAssistantContentToText","toolResultContentToText","truncateToTokens","validateRegexPattern","validateRequired","warn","withRetry","writeAtomic","writeTextFile","xenoRequestContextHeaders"],"entryPoint":"src/utils/index.ts","inputs":{"src/utils/fs.ts":{"bytesInOutput":4427},"src/utils/index.ts":{"bytesInOutput":0},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2639},"src/utils/path-security.ts":{"bytesInOutput":311},"src/utils/platform.ts":{"bytesInOutput":630},"src/utils/validation.ts":{"bytesInOutput":1425},"src/utils/logger.ts":{"bytesInOutput":915},"src/utils/request-context.ts":{"bytesInOutput":1241},"src/utils/retry.ts":{"bytesInOutput":3185},"src/utils/tokens.ts":{"bytesInOutput":904},"src/utils/cost.ts":{"bytesInOutput":933},"src/utils/clipboard.ts":{"bytesInOutput":601},"src/utils/benchmark-safety.ts":{"bytesInOutput":3090},"src/utils/tool-result-content.ts":{"bytesInOutput":2115},"src/utils/text-security.ts":{"bytesInOutput":180}},"bytes":24768}}}
@@ -1 +1 @@
1
- "use strict";var O=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var D=(e,r)=>{for(var n in r)O(e,n,{get:r[n],enumerable:!0})},J=(e,r,n,c)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of H(r))!V.call(e,o)&&o!==n&&O(e,o,{get:()=>r[o],enumerable:!(c=z(r,o))||c.enumerable});return e};var K=e=>J(O({},"__esModule",{value:!0}),e);var le={};D(le,{RUN_LEASE_MAX_SECONDS:()=>N,RUN_LEASE_SKEW_SECONDS:()=>C,RunAuthorityRefusedError:()=>P,RunStepRefused:()=>w,WorkforceAdmissionRefused:()=>m,createWorkforceRunAdmissionClient:()=>ce,createWorkforceRunAuthority:()=>X,verifyWorkforceRunLease:()=>W});module.exports=K(le);var L=require("node:crypto"),q="/api/workforce/run-admissions/authorize-step",B="/api/oauth2/jwks",N=60,C=5,Y="xeno-run-lease+jwt",Z=1e4,j=65536,w=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,r){let n=s=>({valid:!1,reason:s}),c=typeof e=="string"?e.split("."):[];if(c.length!==3)return n("malformed");let o,l;try{o=JSON.parse(Buffer.from(c[0],"base64url").toString("utf8")),l=JSON.parse(Buffer.from(c[1],"base64url").toString("utf8"))}catch{return n("malformed")}if(o.alg!=="ES256"||o.typ!==Y)return n("wrong_type");if(!r.publicKey)return n("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 n("bad_signature");if(l.iss!=="xeno-platform"||l.aud!=="xeno-run-runtime"||l.sub!==r.admissionId)return n("wrong_subject");if(!Number.isSafeInteger(l.iat)||!Number.isSafeInteger(l.exp)||l.exp<=l.iat||l.exp-l.iat>N)return n("unbounded");if(!Array.isArray(l.caps)||!l.caps.every(s=>typeof s=="string"))return n("malformed");let d;try{d=BigInt(l.seq)}catch{return n("malformed")}if(d<r.minSequence)return n("superseded");if(r.nowWallMs/1e3>=l.exp-C)return n("expired");if(r.receivedAtMono===null)return n("requires_online_reauthorization");let i=(r.nowMono-r.receivedAtMono)/1e3;return i<0?n("requires_online_reauthorization"):i>=l.exp-l.iat-C?n("expired"):{valid:!0,sequence:d,claims:l}}async function F(e,r){let n=e.headers.get("content-length");if(n!==null&&(!/^\d+$/.test(n)||Number(n)>j))throw new Error("response too large");if(!e.body)return null;let c=e.body.getReader(),o=[],l=0;try{for(;;){let{done:i,value:s}=await c.read();if(r.aborted)throw new Error("response did not complete before the deadline");if(i)break;if(l+=s.byteLength,l>j)throw new Error("response too large");o.push(s)}}finally{try{c.releaseLock()}catch{}}let t=new Uint8Array(l),d=0;for(let i of o)t.set(i,d),d+=i.byteLength;return t.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t)):null}function X(e){let r=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 o;try{o=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(o.protocol!=="https:"||o.pathname!=="/"||o.username||o.password||o.search||o.hash)throw new Error("invalid issuer");let l=o.origin,t=new Map,d=new Map,i=null,s=async(a,f,u)=>{let p=`${l}${f}`,R=new AbortController,b=setTimeout(()=>R.abort(),Z);b.unref?.();try{let I=null;if(a==="POST"&&(I=await e.authorizeRequest({method:a,url:p}),!I))throw new w("authority_unavailable");let M=await r(p,{method:a,redirect:"error",signal:R.signal,headers:{accept:"application/json",...u?{"content-type":"application/json"}:{},...I?{authorization:I.authorization,...I.dpop?{dpop:I.dpop}:{}}:{}},...u?{body:JSON.stringify(u)}:{}});return{status:M.status,json:await F(M,R.signal)}}finally{clearTimeout(b)}},h=async a=>{if(t.has(a))return t.get(a);let{status:f,json:u}=await s("GET",B);if(f!==200||!u||typeof u!="object"||!Array.isArray(u.keys))return null;for(let p of u.keys)if(!(typeof p.kid!="string"||p.kty!=="EC"||p.crv!=="P-256"))try{t.set(p.kid,(0,L.createPublicKey)({key:{kty:"EC",crv:"P-256",x:p.x,y:p.y},format:"jwk"}))}catch{}return t.get(a)??null},A=()=>e.sequenceStore.read(c)??0n,y=(a,f)=>`${a}:${f??""}`,_=async a=>{let f=JSON.parse(Buffer.from(a.token.split(".")[0],"base64url").toString("utf8")).kid;return W(a.token,{publicKey:await h(f),admissionId:c,receivedAtMono:a.receivedAtMono,nowMono:n.monoMs(),nowWallMs:n.wallMs(),minSequence:A()}).valid},k=async(a,f,u)=>{if(u.throwIfAborted(),i)throw new w(i);let p=d.get(y(a,f));if(p&&await _(p).catch(()=>!1))return;let R;try{R=await s("POST",q,{admissionId:c,operation:a,...f?{capability:f}:{}})}catch(T){throw T instanceof w?T:new w("authority_unavailable")}let b=R.json;if(R.status!==200||b?.success!==!0||typeof b.token!="string"){let T=typeof b?.details?.reason=="string"&&/^[a-z_]{1,64}$/.test(b.details.reason)?b.details.reason:"authority_unavailable";throw T==="admission_revoked"&&(i=T),new w(T)}let I=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 w("authority_unavailable");let v=W(b.token,{publicKey:await h(M.kid).catch(()=>null),admissionId:c,receivedAtMono:I,nowMono:n.monoMs(),nowWallMs:n.wallMs(),minSequence:A()});if(!v.valid)throw new w("authority_unavailable");if(a==="privileged_call"&&v.claims.cap!==f)throw new w("authority_unavailable");await e.sequenceStore.write(c,v.sequence),d.set(y(a,f),{token:b.token,sequence:v.sequence,operation:a,capability:f,capabilities:v.claims.caps,iat:v.claims.iat,exp:v.claims.exp,receivedAtMono:I})};return{authorizeDispatch:(a,f)=>k("provider_dispatch",null,f),authorizeToolCall:(a,f)=>{let u=e.capabilityForTool(a.toolName);return u===null||!/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/.test(u)?Promise.reject(new w("capability_not_admitted")):k("privileged_call",u,f)}}}var Q="/api/workforce/run-admissions",G="/api/workforce/run-admissions/revoke",ee="/api/workforce/run-admissions/authority",te="/api/workforce/run-admissions/pin";var S=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ne=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,$=/^[a-z_]{1,64}$/,re=new Set(["bad_input","denied","not_found","needs_approval","conflict","rate_limited","unavailable","timeout","internal"]),m=class extends Error{constructor(n,c,o={}){super(`workforce admission refused: ${n}/${c}`);this.code=n;this.reason=c;this.name="WorkforceAdmissionRefused",this.details={reason:c,...o}}code;reason;details},E=()=>new m("unavailable","authority_unavailable"),g=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),x=e=>Array.isArray(e)&&e.length<=64&&e.every(r=>typeof r=="string"&&ne.test(r));function oe(e){if(!g(e)||e.schemaVersion!==1||typeof e.admissionId!="string"||!S.test(e.admissionId)||typeof e.operationId!="string"||!S.test(e.operationId))return null;let r=e.agent;if(!g(r)||typeof r.resourceId!="string"||!S.test(r.resourceId)||!Number.isSafeInteger(r.version)||typeof r.contentHash!="string")return null;let n=e.capabilities;if(!g(n)||!x(n.effective)||!x(n.requested))return null;let c=e.payer;if(!g(c)||typeof c.kind!="string")return null;let o=e.budget;return!g(o)||typeof o.ceilingMicro!="string"||!/^[1-9][0-9]{0,17}$/.test(o.ceilingMicro)||!g(e.target)||typeof e.admittedAt!="string"||!Number.isFinite(Date.parse(e.admittedAt))?null:e}var ie=/^[0-9a-f]{64}$/;function se(e,r,n,c){if(!g(e)||e.schemaVersion!==1)return null;let o=e.agent;if(!g(o)||typeof o.resourceId!="string"||o.resourceId.toLowerCase()!==r||!Number.isSafeInteger(o.version)||o.version<1||typeof o.contentHash!="string"||!ie.test(o.contentHash)||!g(e.target)||JSON.stringify(Object.entries(e.target).map(([d,i])=>[d,typeof i=="string"?i.toLowerCase():i]).sort())!==JSON.stringify(Object.entries(n).map(([d,i])=>[d,typeof i=="string"?i.toLowerCase():i]).sort()))return null;let l=e.team;if(c?!g(l)||typeof l.teamId!="string"||l.teamId.toLowerCase()!==c:l!==null)return null;let t=e.terms;return!g(t)||!x(t.definition)||!x(t.target)?null:{schemaVersion:1,agent:{resourceId:r,version:o.version,contentHash:o.contentHash},target:{...n},team:c?{teamId:c}:null,terms:{definition:[...t.definition],target:[...t.target]}}}function U(e,r){return!g(e)||e.schemaVersion!==1||e.admissionId!==r||typeof e.revoked!="boolean"?null:{schemaVersion:1,admissionId:r,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 ae(e,r){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(),o=[],l=0;try{for(;;){let{done:i,value:s}=await c.read();if(r.aborted)throw new Error("response did not complete before the deadline");if(i)break;if(l+=s.byteLength,l>65536)throw new Error("response too large");o.push(s)}}finally{try{c.releaseLock()}catch{}}let t=new Uint8Array(l),d=0;for(let i of o)t.set(i,d),d+=i.byteLength;return t.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t)):null}function ce(e){let r=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,o=async(t,d,i)=>{let s=`${c}${t}`,h=new AbortController,A=()=>h.abort();i?.addEventListener("abort",A,{once:!0});let y=setTimeout(A,15e3);y.unref?.();try{i?.throwIfAborted();let _=await e.authorizeRequest({method:"POST",url:s});if(!_)throw E();let k,a;try{k=await r(s,{method:"POST",redirect:"error",signal:h.signal,headers:{accept:"application/json","content-type":"application/json",authorization:_.authorization,..._.dpop?{dpop:_.dpop}:{}},body:JSON.stringify(d)}),a=await ae(k,h.signal)}catch(p){throw i?.aborted?p:E()}if(k.status===200&&g(a)&&a.success===!0)return a;let f=g(a)&&typeof a.code=="string"&&re.has(a.code)?a.code:null,u=g(a)&&g(a.details)?a.details:null;throw f&&u&&u.schemaVersion===1&&typeof u.reason=="string"&&$.test(u.reason)?new m(f,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}:{}}):f?new m(f,f==="denied"&&k.status===403&&g(a)&&typeof a.required_scope=="string"?"insufficient_scope":f):E()}finally{clearTimeout(y),i?.removeEventListener("abort",A)}},l=t=>{if(typeof t!="string"||!S.test(t))throw new m("bad_input","invalid_admission");return t.toLowerCase()};return{async admit(t,d){if(!S.test(t.operationId))throw new m("bad_input","invalid_operation");if(!x(t.capabilities))throw new m("bad_input","invalid_capabilities");if(t.runtimeCapabilities!==void 0&&!x(t.runtimeCapabilities))throw new m("bad_input","invalid_runtime_capabilities");if(!/^[1-9][0-9]{0,17}$/.test(t.budget?.ceilingMicro??""))throw new m("bad_input","invalid_budget_ceiling");let i={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]}:{}},s=await o(Q,i,d),h=oe(s.admission);if(!h||h.operationId.toLowerCase()!==t.operationId.toLowerCase())throw E();return{admission:h,replayed:s.replayed===!0}},async revoke(t,d){let i=l(t),s=U(await o(G,{admissionId:i},d),i);if(!s||!s.revoked)throw E();return s},async pin(t,d){let i=t?.agent?.resourceId;if(typeof i!="string"||!S.test(i))throw new m("bad_input","invalid_agent_resource");let s=t.target,h=g(s)?s.kind==="personal"?[s.ownerUserId]:s.kind==="workspace"?[s.assignmentId]:s.kind==="project"?[s.projectId,s.participationId]:null:null;if(!h||!h.every(a=>typeof a=="string"&&S.test(a)))throw new m("bad_input","invalid_target");let A=s.kind==="personal"?{kind:"personal",ownerUserId:s.ownerUserId}:s.kind==="workspace"?{kind:"workspace",assignmentId:s.assignmentId}:{kind:"project",projectId:s.projectId,participationId:s.participationId},y=t.team?t.team.teamId:null;if(y!==null&&(typeof y!="string"||!S.test(y)))throw new m("bad_input","invalid_team");let _={agent:{resourceId:i},target:A,...y?{team:{teamId:y}}:{},...t.expectedActorAccountId?{expectedActorAccountId:t.expectedActorAccountId}:{}},k=se(await o(te,_,d),i.toLowerCase(),A,y?y.toLowerCase():null);if(!k)throw E();return k},async authority(t,d){let i=l(t),s=U(await o(ee,{admissionId:i},d),i);if(!s)throw E();return s}}}var P=class extends Error{code="RUN_AUTHORITY_REFUSED";retryable=!1;reason;step;constructor(r,n,c){super(`Run authority refused the ${r==="dispatch"?"provider dispatch":"tool call"}: ${n}`,c),this.name="RunAuthorityRefusedError",this.reason=n,this.step=r}};0&&(module.exports={RUN_LEASE_MAX_SECONDS,RUN_LEASE_SKEW_SECONDS,RunAuthorityRefusedError,RunStepRefused,WorkforceAdmissionRefused,createWorkforceRunAdmissionClient,createWorkforceRunAuthority,verifyWorkforceRunLease});
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});
@@ -201,6 +201,20 @@ interface WorkforceRunAdmissionClient {
201
201
  }>;
202
202
  revoke(admissionId: string, signal?: AbortSignal): Promise<WorkforceRunAuthorityState>;
203
203
  authority(admissionId: string, signal?: AbortSignal): Promise<WorkforceRunAuthorityState>;
204
+ read(admissionId: string, options?: {
205
+ expectedActorAccountId?: string;
206
+ }, signal?: AbortSignal): Promise<WorkforceAdmission>;
207
+ readOperation(operationId: string, options: {
208
+ expectedActorAccountId: string;
209
+ }, signal?: AbortSignal): Promise<{
210
+ state: "not-observed";
211
+ operationId: string;
212
+ admission: null;
213
+ } | {
214
+ state: "committed";
215
+ operationId: string;
216
+ admission: WorkforceAdmission;
217
+ }>;
204
218
  pin(request: {
205
219
  agent: {
206
220
  resourceId: string;
@@ -201,6 +201,20 @@ interface WorkforceRunAdmissionClient {
201
201
  }>;
202
202
  revoke(admissionId: string, signal?: AbortSignal): Promise<WorkforceRunAuthorityState>;
203
203
  authority(admissionId: string, signal?: AbortSignal): Promise<WorkforceRunAuthorityState>;
204
+ read(admissionId: string, options?: {
205
+ expectedActorAccountId?: string;
206
+ }, signal?: AbortSignal): Promise<WorkforceAdmission>;
207
+ readOperation(operationId: string, options: {
208
+ expectedActorAccountId: string;
209
+ }, signal?: AbortSignal): Promise<{
210
+ state: "not-observed";
211
+ operationId: string;
212
+ admission: null;
213
+ } | {
214
+ state: "committed";
215
+ operationId: string;
216
+ admission: WorkforceAdmission;
217
+ }>;
204
218
  pin(request: {
205
219
  agent: {
206
220
  resourceId: string;
@@ -1 +1 @@
1
- import{createPublicKey as N,verify as U}from"node:crypto";var $="/api/workforce/run-admissions/authorize-step",z="/api/oauth2/jwks",H=60,P=5,V="xeno-run-lease+jwt",D=1e4,O=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 C(e,a){let n=o=>({valid:!1,reason:o}),l=typeof e=="string"?e.split("."):[];if(l.length!==3)return n("malformed");let i,c;try{i=JSON.parse(Buffer.from(l[0],"base64url").toString("utf8")),c=JSON.parse(Buffer.from(l[1],"base64url").toString("utf8"))}catch{return n("malformed")}if(i.alg!=="ES256"||i.typ!==V)return n("wrong_type");if(!a.publicKey)return n("unknown_key");if(!U("sha256",Buffer.from(`${l[0]}.${l[1]}`),{key:a.publicKey,dsaEncoding:"ieee-p1363"},Buffer.from(l[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>H)return n("unbounded");if(!Array.isArray(c.caps)||!c.caps.every(o=>typeof o=="string"))return n("malformed");let d;try{d=BigInt(c.seq)}catch{return n("malformed")}if(d<a.minSequence)return n("superseded");if(a.nowWallMs/1e3>=c.exp-P)return n("expired");if(a.receivedAtMono===null)return n("requires_online_reauthorization");let r=(a.nowMono-a.receivedAtMono)/1e3;return r<0?n("requires_online_reauthorization"):r>=c.exp-c.iat-P?n("expired"):{valid:!0,sequence:d,claims:c}}async function J(e,a){let n=e.headers.get("content-length");if(n!==null&&(!/^\d+$/.test(n)||Number(n)>O))throw new Error("response too large");if(!e.body)return null;let l=e.body.getReader(),i=[],c=0;try{for(;;){let{done:r,value:o}=await l.read();if(a.aborted)throw new Error("response did not complete before the deadline");if(r)break;if(c+=o.byteLength,c>O)throw new Error("response too large");i.push(o)}}finally{try{l.releaseLock()}catch{}}let t=new Uint8Array(c),d=0;for(let r of i)t.set(r,d),d+=r.byteLength;return t.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t)):null}function ne(e){let a=e.fetchImpl??globalThis.fetch,n=e.clock??{wallMs:()=>Date.now(),monoMs:()=>performance.now()},l=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(l))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,d=new Map,r=null,o=async(s,f,u)=>{let p=`${c}${f}`,R=new AbortController,w=setTimeout(()=>R.abort(),D);w.unref?.();try{let I=null;if(s==="POST"&&(I=await e.authorizeRequest({method:s,url:p}),!I))throw new b("authority_unavailable");let M=await a(p,{method:s,redirect:"error",signal:R.signal,headers:{accept:"application/json",...u?{"content-type":"application/json"}:{},...I?{authorization:I.authorization,...I.dpop?{dpop:I.dpop}:{}}:{}},...u?{body:JSON.stringify(u)}:{}});return{status:M.status,json:await J(M,R.signal)}}finally{clearTimeout(w)}},m=async s=>{if(t.has(s))return t.get(s);let{status:f,json:u}=await o("GET",z);if(f!==200||!u||typeof u!="object"||!Array.isArray(u.keys))return null;for(let p of u.keys)if(!(typeof p.kid!="string"||p.kty!=="EC"||p.crv!=="P-256"))try{t.set(p.kid,N({key:{kty:"EC",crv:"P-256",x:p.x,y:p.y},format:"jwk"}))}catch{}return t.get(s)??null},A=()=>e.sequenceStore.read(l)??0n,h=(s,f)=>`${s}:${f??""}`,_=async s=>{let f=JSON.parse(Buffer.from(s.token.split(".")[0],"base64url").toString("utf8")).kid;return C(s.token,{publicKey:await m(f),admissionId:l,receivedAtMono:s.receivedAtMono,nowMono:n.monoMs(),nowWallMs:n.wallMs(),minSequence:A()}).valid},k=async(s,f,u)=>{if(u.throwIfAborted(),r)throw new b(r);let p=d.get(h(s,f));if(p&&await _(p).catch(()=>!1))return;let R;try{R=await o("POST",$,{admissionId:l,operation:s,...f?{capability:f}:{}})}catch(T){throw T instanceof b?T:new b("authority_unavailable")}let w=R.json;if(R.status!==200||w?.success!==!0||typeof w.token!="string"){let T=typeof w?.details?.reason=="string"&&/^[a-z_]{1,64}$/.test(w.details.reason)?w.details.reason:"authority_unavailable";throw T==="admission_revoked"&&(r=T),new b(T)}let I=n.monoMs(),M=(()=>{try{return JSON.parse(Buffer.from(w.token.split(".")[0],"base64url").toString("utf8"))}catch{return null}})();if(typeof M?.kid!="string")throw new b("authority_unavailable");let v=C(w.token,{publicKey:await m(M.kid).catch(()=>null),admissionId:l,receivedAtMono:I,nowMono:n.monoMs(),nowWallMs:n.wallMs(),minSequence:A()});if(!v.valid)throw new b("authority_unavailable");if(s==="privileged_call"&&v.claims.cap!==f)throw new b("authority_unavailable");await e.sequenceStore.write(l,v.sequence),d.set(h(s,f),{token:w.token,sequence:v.sequence,operation:s,capability:f,capabilities:v.claims.caps,iat:v.claims.iat,exp:v.claims.exp,receivedAtMono:I})};return{authorizeDispatch:(s,f)=>k("provider_dispatch",null,f),authorizeToolCall:(s,f)=>{let u=e.capabilityForTool(s.toolName);return u===null||!/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/.test(u)?Promise.reject(new b("capability_not_admitted")):k("privileged_call",u,f)}}}var K="/api/workforce/run-admissions",q="/api/workforce/run-admissions/revoke",B="/api/workforce/run-admissions/authority",Y="/api/workforce/run-admissions/pin";var S=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Z=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,j=/^[a-z_]{1,64}$/,F=new Set(["bad_input","denied","not_found","needs_approval","conflict","rate_limited","unavailable","timeout","internal"]),y=class extends Error{constructor(n,l,i={}){super(`workforce admission refused: ${n}/${l}`);this.code=n;this.reason=l;this.name="WorkforceAdmissionRefused",this.details={reason:l,...i}}code;reason;details},E=()=>new y("unavailable","authority_unavailable"),g=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),x=e=>Array.isArray(e)&&e.length<=64&&e.every(a=>typeof a=="string"&&Z.test(a));function X(e){if(!g(e)||e.schemaVersion!==1||typeof e.admissionId!="string"||!S.test(e.admissionId)||typeof e.operationId!="string"||!S.test(e.operationId))return null;let a=e.agent;if(!g(a)||typeof a.resourceId!="string"||!S.test(a.resourceId)||!Number.isSafeInteger(a.version)||typeof a.contentHash!="string")return null;let n=e.capabilities;if(!g(n)||!x(n.effective)||!x(n.requested))return null;let l=e.payer;if(!g(l)||typeof l.kind!="string")return null;let i=e.budget;return!g(i)||typeof i.ceilingMicro!="string"||!/^[1-9][0-9]{0,17}$/.test(i.ceilingMicro)||!g(e.target)||typeof e.admittedAt!="string"||!Number.isFinite(Date.parse(e.admittedAt))?null:e}var Q=/^[0-9a-f]{64}$/;function G(e,a,n,l){if(!g(e)||e.schemaVersion!==1)return null;let i=e.agent;if(!g(i)||typeof i.resourceId!="string"||i.resourceId.toLowerCase()!==a||!Number.isSafeInteger(i.version)||i.version<1||typeof i.contentHash!="string"||!Q.test(i.contentHash)||!g(e.target)||JSON.stringify(Object.entries(e.target).map(([d,r])=>[d,typeof r=="string"?r.toLowerCase():r]).sort())!==JSON.stringify(Object.entries(n).map(([d,r])=>[d,typeof r=="string"?r.toLowerCase():r]).sort()))return null;let c=e.team;if(l?!g(c)||typeof c.teamId!="string"||c.teamId.toLowerCase()!==l:c!==null)return null;let t=e.terms;return!g(t)||!x(t.definition)||!x(t.target)?null:{schemaVersion:1,agent:{resourceId:a,version:i.version,contentHash:i.contentHash},target:{...n},team:l?{teamId:l}:null,terms:{definition:[...t.definition],target:[...t.target]}}}function W(e,a){return!g(e)||e.schemaVersion!==1||e.admissionId!==a||typeof e.revoked!="boolean"?null:{schemaVersion:1,admissionId:a,revoked:e.revoked,reason:typeof e.reason=="string"&&j.test(e.reason)?e.reason:null,revokedAt:typeof e.revokedAt=="string"?e.revokedAt:null,latestLeaseSequence:typeof e.latestLeaseSequence=="string"?e.latestLeaseSequence:null}}async function ee(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 l=e.body.getReader(),i=[],c=0;try{for(;;){let{done:r,value:o}=await l.read();if(a.aborted)throw new Error("response did not complete before the deadline");if(r)break;if(c+=o.byteLength,c>65536)throw new Error("response too large");i.push(o)}}finally{try{l.releaseLock()}catch{}}let t=new Uint8Array(c),d=0;for(let r of i)t.set(r,d),d+=r.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;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 l=n.origin,i=async(t,d,r)=>{let o=`${l}${t}`,m=new AbortController,A=()=>m.abort();r?.addEventListener("abort",A,{once:!0});let h=setTimeout(A,15e3);h.unref?.();try{r?.throwIfAborted();let _=await e.authorizeRequest({method:"POST",url:o});if(!_)throw E();let k,s;try{k=await a(o,{method:"POST",redirect:"error",signal:m.signal,headers:{accept:"application/json","content-type":"application/json",authorization:_.authorization,..._.dpop?{dpop:_.dpop}:{}},body:JSON.stringify(d)}),s=await ee(k,m.signal)}catch(p){throw r?.aborted?p:E()}if(k.status===200&&g(s)&&s.success===!0)return s;let f=g(s)&&typeof s.code=="string"&&F.has(s.code)?s.code:null,u=g(s)&&g(s.details)?s.details:null;throw f&&u&&u.schemaVersion===1&&typeof u.reason=="string"&&j.test(u.reason)?new y(f,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}:{}}):f?new y(f,f==="denied"&&k.status===403&&g(s)&&typeof s.required_scope=="string"?"insufficient_scope":f):E()}finally{clearTimeout(h),r?.removeEventListener("abort",A)}},c=t=>{if(typeof t!="string"||!S.test(t))throw new y("bad_input","invalid_admission");return t.toLowerCase()};return{async admit(t,d){if(!S.test(t.operationId))throw new y("bad_input","invalid_operation");if(!x(t.capabilities))throw new y("bad_input","invalid_capabilities");if(t.runtimeCapabilities!==void 0&&!x(t.runtimeCapabilities))throw new y("bad_input","invalid_runtime_capabilities");if(!/^[1-9][0-9]{0,17}$/.test(t.budget?.ceilingMicro??""))throw new y("bad_input","invalid_budget_ceiling");let r={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 i(K,r,d),m=X(o.admission);if(!m||m.operationId.toLowerCase()!==t.operationId.toLowerCase())throw E();return{admission:m,replayed:o.replayed===!0}},async revoke(t,d){let r=c(t),o=W(await i(q,{admissionId:r},d),r);if(!o||!o.revoked)throw E();return o},async pin(t,d){let r=t?.agent?.resourceId;if(typeof r!="string"||!S.test(r))throw new y("bad_input","invalid_agent_resource");let o=t.target,m=g(o)?o.kind==="personal"?[o.ownerUserId]:o.kind==="workspace"?[o.assignmentId]:o.kind==="project"?[o.projectId,o.participationId]:null:null;if(!m||!m.every(s=>typeof s=="string"&&S.test(s)))throw new y("bad_input","invalid_target");let A=o.kind==="personal"?{kind:"personal",ownerUserId:o.ownerUserId}:o.kind==="workspace"?{kind:"workspace",assignmentId:o.assignmentId}:{kind:"project",projectId:o.projectId,participationId:o.participationId},h=t.team?t.team.teamId:null;if(h!==null&&(typeof h!="string"||!S.test(h)))throw new y("bad_input","invalid_team");let _={agent:{resourceId:r},target:A,...h?{team:{teamId:h}}:{},...t.expectedActorAccountId?{expectedActorAccountId:t.expectedActorAccountId}:{}},k=G(await i(Y,_,d),r.toLowerCase(),A,h?h.toLowerCase():null);if(!k)throw E();return k},async authority(t,d){let r=c(t),o=W(await i(B,{admissionId:r},d),r);if(!o)throw E();return o}}}var L=class extends Error{code="RUN_AUTHORITY_REFUSED";retryable=!1;reason;step;constructor(a,n,l){super(`Run authority refused the ${a==="dispatch"?"provider dispatch":"tool call"}: ${n}`,l),this.name="RunAuthorityRefusedError",this.reason=n,this.step=a}};export{H as RUN_LEASE_MAX_SECONDS,P as RUN_LEASE_SKEW_SECONDS,L as RunAuthorityRefusedError,b as RunStepRefused,y as WorkforceAdmissionRefused,oe as createWorkforceRunAdmissionClient,ne as createWorkforceRunAuthority,C as verifyWorkforceRunLease};
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 +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":20292,"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":7112},"src/core/agent-loop/run-authority.ts":{"bytesInOutput":257}},"bytes":13511}}}
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 +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":20292,"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":7098},"src/core/agent-loop/run-authority.ts":{"bytesInOutput":257}},"bytes":12818}}}
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}}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xenosystem/agent-sdk",
3
- "version": "0.10.19",
3
+ "version": "0.10.20",
4
4
  "description": "XENO Agent SDK built from the same engine as XENO CODE",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",