@xenosystem/agent-sdk 0.10.34 → 0.10.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +34 -1
  2. package/dist/artifacts/index.cjs +1 -1
  3. package/dist/artifacts/index.js +1 -1
  4. package/dist/automation/index.cjs +1 -1
  5. package/dist/automation/index.js +1 -1
  6. package/dist/control-plane/index.cjs +1 -1
  7. package/dist/control-plane/index.js +1 -1
  8. package/dist/coordination/index.cjs +2 -2
  9. package/dist/coordination/index.js +2 -2
  10. package/dist/coordination/metafile-cjs.json +1 -1
  11. package/dist/coordination/metafile-esm.json +1 -1
  12. package/dist/electron/index.cjs +215 -201
  13. package/dist/electron/index.d.cts +67 -1
  14. package/dist/electron/index.d.ts +67 -1
  15. package/dist/electron/index.js +215 -201
  16. package/dist/electron/metafile-cjs.json +1 -1
  17. package/dist/electron/metafile-esm.json +1 -1
  18. package/dist/index.cjs +384 -379
  19. package/dist/index.d.cts +118 -36
  20. package/dist/index.d.ts +118 -36
  21. package/dist/index.js +384 -379
  22. package/dist/metafile-cjs.json +1 -1
  23. package/dist/metafile-esm.json +1 -1
  24. package/dist/providers/index.cjs +10 -10
  25. package/dist/providers/index.d.cts +49 -33
  26. package/dist/providers/index.d.ts +49 -33
  27. package/dist/providers/index.js +10 -10
  28. package/dist/providers/metafile-cjs.json +1 -1
  29. package/dist/providers/metafile-esm.json +1 -1
  30. package/dist/session/index.cjs +1 -1
  31. package/dist/session/index.js +1 -1
  32. package/dist/utils/index.cjs +15 -15
  33. package/dist/utils/index.d.cts +15 -2
  34. package/dist/utils/index.d.ts +15 -2
  35. package/dist/utils/index.js +14 -14
  36. package/dist/utils/metafile-cjs.json +1 -1
  37. package/dist/utils/metafile-esm.json +1 -1
  38. package/dist/workforce/index.cjs +1 -1
  39. package/dist/workforce/index.d.cts +7 -2
  40. package/dist/workforce/index.d.ts +7 -2
  41. package/dist/workforce/index.js +1 -1
  42. package/dist/workforce/metafile-cjs.json +1 -1
  43. package/dist/workforce/metafile-esm.json +1 -1
  44. package/ownership/ownership-policy.json +2 -2
  45. package/package.json +1 -1
@@ -1,25 +1,25 @@
1
- import{readdirSync as v,readFileSync as K}from"node:fs";import{existsSync as A,statSync as N}from"node:fs";import*as u from"node:fs/promises";import*as a from"node:path";function Yt(t){try{return A(t)&&N(t).isFile()}catch{return!1}}function Ut(t){try{return A(t)&&N(t).isDirectory()}catch{return!1}}function Gt(t,e=""){try{return K(t,"utf-8")}catch{return e}}async function C(t){await u.mkdir(t,{recursive:!0})}async function Z(t,e){let n=a.dirname(t);await C(n);let r=Math.random().toString(36).substring(2,15),o=`${t}.tmp.${process.pid}.${r}`;try{await u.writeFile(o,e),await tt(o,t)}finally{try{await u.unlink(o)}catch{}}}var Q=new Set(["EACCES","EBUSY","EPERM"]),V=[10,20,40,80,160,320,640];async function tt(t,e){for(let n=0;;n+=1)try{await u.rename(t,e);return}catch(r){let o=r.code,i=V[n];if(process.platform!=="win32"||!o||!Q.has(o)||i===void 0)throw r;await new Promise(s=>setTimeout(s,i))}}async function Kt(t,e){let n=a.dirname(t);await C(n),await u.appendFile(t,e+`
2
- `,"utf-8")}async function Zt(t,e){let n=a.dirname(t);await C(n);let r=await u.open(t,"a");try{await r.writeFile(e+`
1
+ import{readdirSync as $,readFileSync as K}from"node:fs";import{existsSync as C,statSync as N}from"node:fs";import*as u from"node:fs/promises";import*as a from"node:path";function Yt(t){try{return C(t)&&N(t).isFile()}catch{return!1}}function Ut(t){try{return C(t)&&N(t).isDirectory()}catch{return!1}}function Gt(t,e=""){try{return K(t,"utf-8")}catch{return e}}async function A(t){await u.mkdir(t,{recursive:!0})}async function Z(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 u.writeFile(o,e),await tt(o,t)}finally{try{await u.unlink(o)}catch{}}}var Q=new Set(["EACCES","EBUSY","EPERM"]),V=[10,20,40,80,160,320,640];async function tt(t,e){for(let n=0;;n+=1)try{await u.rename(t,e);return}catch(r){let o=r.code,i=V[n];if(process.platform!=="win32"||!o||!Q.has(o)||i===void 0)throw r;await new Promise(s=>setTimeout(s,i))}}async function Kt(t,e){let n=a.dirname(t);await A(n),await u.appendFile(t,e+`
2
+ `,"utf-8")}async function Zt(t,e){let n=a.dirname(t);await A(n);let r=await u.open(t,"a");try{await r.writeFile(e+`
3
3
  `,"utf-8"),await r.sync()}finally{await r.close()}}function et(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 O(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 nt(t,e){switch(e){case"utf8-bom":return t.subarray(3).toString("utf8");case"utf16le":return t.subarray(2).toString("utf16le");case"utf16be":return O(t.subarray(2)).toString("utf16le");default:return t.toString("utf8")}}function rt(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]),O(Buffer.from(t,"utf16le"))]);default:return Buffer.from(t,"utf8")}}function ot(t){return t.includes(`\r
4
4
  `)?"CRLF":"LF"}function it(t,e){let n=t.replace(/\r\n/g,`
5
5
  `);return e==="CRLF"?n.replace(/\n/g,`\r
6
6
  `):n}function Qt(t){return t.includes(`\r
7
- `)?/(^|[^\r])\n/.test(t):!1}async function st(t){let e=await u.readFile(t),n=et(e),r=nt(e,n);return{content:r,encoding:n,lineEnding:ot(r),sizeBytes:e.length}}async function Vt(t,e,n){let r=n?.preserveLineEndings?e:it(e,n?.lineEnding??"LF");await Z(t,rt(r,n?.encoding??"utf8"))}async function te(t){let e=new Set,n=a.resolve(t);for(;!e.has(n);){e.add(n);try{let o=v(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 l=a.join(n,i),c=await st(l);if(c.content.length>0)return c.lineEnding}catch{}}}catch{}let r=a.dirname(n);if(r===n)break;n=r}return"LF"}function at(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 l=v(s.dir,{withFileTypes:!0});for(let c of l){let f=a.join(s.dir,c.name);if(c.isFile()){if(r.push(f),r.length>=n)break;continue}c.isDirectory()&&s.depth<e&&!c.name.startsWith(".")&&c.name!=="node_modules"&&o.push({dir:f,depth:s.depth+1})}}catch{}}}return r}function $(t,e){let n=a.relative(t,e);return n===""||!n.startsWith("..")&&!a.isAbsolute(n)}function ee(t,e){try{let n=a.dirname(t),r=a.basename(t,a.extname(t)).toLowerCase(),o=a.basename(t).toLowerCase(),i=[n,a.dirname(n)],s=e!==void 0&&$(e,t)?e:void 0,l=i.flatMap(f=>at(f,2,500)).filter(f=>s===void 0||$(s,f)),c=null;for(let f of l){let x=a.basename(f).toLowerCase(),y=a.basename(f,a.extname(f)).toLowerCase(),g=null;if(x===o?g=0:y===r?g=1:(x.includes(r)||r.includes(y))&&(g=2),g===null)continue;let G=a.relative(n,f).split(a.sep).length,S=g+G*.01;(!c||S<c.score)&&(c={filePath:f,score:S})}return c?.filePath??null}catch{}return null}async function ne(t){try{return await u.readFile(t,"utf-8")}catch(e){if(e.code==="ENOENT")return null;throw e}}function re(t){return A(t)}async function oe(t,e){try{let r=(await u.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 ie(t){try{return(await u.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 se(t){try{await u.unlink(t)}catch(e){if(e.code!=="ENOENT")throw e}}async function ae(t){try{await u.rm(t,{recursive:!0,force:!0})}catch(e){if(e.code!=="ENOENT")throw e}}function ce(t,e){try{return JSON.parse(t)}catch{return e}}function fe(t,e="{}"){try{return JSON.stringify(t)}catch{return e}}function le(t){let e=[];for(let n of t.split(`
8
- `)){let r=n.trim();if(r)try{e.push(JSON.parse(r))}catch{}}return e}function pe(t){let e=ut(t);return{frontmatter:e.frontmatter,content:e.content.trim()}}function me(t,e){let n=Object.fromEntries(Object.entries(t).filter(([r,o])=>o!==void 0));return["---",I(n),"---","",e].join(`
9
- `)}function ge(t){return t.trimStart().startsWith("---")}function ut(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],l=o.index+s.length;return{frontmatter:B(i),content:r.slice(l)}}function B(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=ft(o,r+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){e[i.key]=P(i.value,r+1);continue}let s=ct(n,r+1);e[i.key]=s.value,r=s.nextIndex-1}return e}function ct(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)=>P(i.trimStart().slice(2),e+s+1)),nextIndex:r}:{value:B(n.join(`
10
- `)),nextIndex:r}}function ft(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 P(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 L(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 L(t,e);if(t.includes("[")||t.includes("]")||t.includes("{")||t.includes("}"))throw new Error(`Unsupported YAML scalar at line ${e}.`);return t}function L(t,e){try{return JSON.parse(t)}catch{throw new Error(`Invalid YAML scalar at line ${e}.`)}}function I(t,e=""){return Object.entries(t).map(([n,r])=>lt(n,r,e)).join(`
11
- `)}function lt(t,e,n){return Array.isArray(e)?`${n}${t}: ${JSON.stringify(e)}`:e&&typeof e=="object"?`${n}${t}:
12
- ${I(e,`${n} `)}`:`${n}${t}: ${JSON.stringify(e)}`}import*as d from"path";function dt(t,e){let n=d.resolve(t),r=d.resolve(t,e);return r===n?!0:n===d.parse(n).root?r.startsWith(n):r.startsWith(n+d.sep)}function xe(t,e){if(d.isAbsolute(e))return d.resolve(e);if(!dt(t,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return d.resolve(t,e)}function ye(t,e=process.platform){let n=d.resolve(t);return e==="win32"?n.toLowerCase():n}import{homedir as k,platform as pt,release as mt}from"node:os";import{execSync as gt}from"node:child_process";import{resolve as h}from"node:path";var M=pt(),ht=M==="win32",Te=M==="darwin",Ae=M==="linux",Ce=mt(),ke=k();function Me(){let t=process.env.XENO_AGENT_HOME?.trim();return t?h(t):h(k(),".xeno-agent")}function _e(){let t=process.env.XENO_CONFIG_DIR?.trim();return t?h(t):h(k(),".xeno-code")}function Se(t){return h(t,".xeno-code")}function $e(){return ht?"powershell":process.env.SHELL?.split("/").pop()??"bash"}function ve(t){try{return gt("git rev-parse --is-inside-work-tree",{cwd:t,stdio:"ignore"}),!0}catch{return!1}}function Oe(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 Le(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 Be(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 Pe(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 xt(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 Ie(t,e,n=5e3){let r=xt(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 De(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 yt=(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))(yt||{}),m=1;function je(t){m=t}function We(){return m}function p(){return new Date().toISOString()}function qe(t,e){m<=0&&(e!==void 0?process.stderr.write(`[${p()}] DEBUG: ${t} ${w(e)}
7
+ `)?/(^|[^\r])\n/.test(t):!1}async function st(t){let e=await u.readFile(t),n=et(e),r=nt(e,n);return{content:r,encoding:n,lineEnding:ot(r),sizeBytes:e.length}}async function Vt(t,e,n){let r=n?.preserveLineEndings?e:it(e,n?.lineEnding??"LF");await Z(t,rt(r,n?.encoding??"utf8"))}async function te(t){let e=new Set,n=a.resolve(t);for(;!e.has(n);){e.add(n);try{let o=$(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 f=a.join(n,i),c=await st(f);if(c.content.length>0)return c.lineEnding}catch{}}}catch{}let r=a.dirname(n);if(r===n)break;n=r}return"LF"}function at(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 f=$(s.dir,{withFileTypes:!0});for(let c of f){let l=a.join(s.dir,c.name);if(c.isFile()){if(r.push(l),r.length>=n)break;continue}c.isDirectory()&&s.depth<e&&!c.name.startsWith(".")&&c.name!=="node_modules"&&o.push({dir:l,depth:s.depth+1})}}catch{}}}return r}function v(t,e){let n=a.relative(t,e);return n===""||!n.startsWith("..")&&!a.isAbsolute(n)}function ee(t,e){try{let n=a.dirname(t),r=a.basename(t,a.extname(t)).toLowerCase(),o=a.basename(t).toLowerCase(),i=[n,a.dirname(n)],s=e!==void 0&&v(e,t)?e:void 0,f=i.flatMap(l=>at(l,2,500)).filter(l=>s===void 0||v(s,l)),c=null;for(let l of f){let x=a.basename(l).toLowerCase(),y=a.basename(l,a.extname(l)).toLowerCase(),m=null;if(x===o?m=0:y===r?m=1:(x.includes(r)||r.includes(y))&&(m=2),m===null)continue;let G=a.relative(n,l).split(a.sep).length,S=m+G*.01;(!c||S<c.score)&&(c={filePath:l,score:S})}return c?.filePath??null}catch{}return null}async function ne(t){try{return await u.readFile(t,"utf-8")}catch(e){if(e.code==="ENOENT")return null;throw e}}function re(t){return C(t)}async function oe(t,e){try{let r=(await u.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 ie(t){try{return(await u.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 se(t){try{await u.unlink(t)}catch(e){if(e.code!=="ENOENT")throw e}}async function ae(t){try{await u.rm(t,{recursive:!0,force:!0})}catch(e){if(e.code!=="ENOENT")throw e}}function ce(t,e){try{return JSON.parse(t)}catch{return e}}function le(t,e="{}"){try{return JSON.stringify(t)}catch{return e}}function fe(t){let e=[];for(let n of t.split(`
8
+ `)){let r=n.trim();if(r)try{e.push(JSON.parse(r))}catch{}}return e}function pe(t){let e=ut(t);return{frontmatter:e.frontmatter,content:e.content.trim()}}function ge(t,e){let n=Object.fromEntries(Object.entries(t).filter(([r,o])=>o!==void 0));return["---",I(n),"---","",e].join(`
9
+ `)}function me(t){return t.trimStart().startsWith("---")}function ut(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],f=o.index+s.length;return{frontmatter:B(i),content:r.slice(f)}}function B(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=lt(o,r+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){e[i.key]=P(i.value,r+1);continue}let s=ct(n,r+1);e[i.key]=s.value,r=s.nextIndex-1}return e}function ct(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)=>P(i.trimStart().slice(2),e+s+1)),nextIndex:r}:{value:B(n.join(`
10
+ `)),nextIndex:r}}function lt(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 P(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 L(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 L(t,e);if(t.includes("[")||t.includes("]")||t.includes("{")||t.includes("}"))throw new Error(`Unsupported YAML scalar at line ${e}.`);return t}function L(t,e){try{return JSON.parse(t)}catch{throw new Error(`Invalid YAML scalar at line ${e}.`)}}function I(t,e=""){return Object.entries(t).map(([n,r])=>ft(n,r,e)).join(`
11
+ `)}function ft(t,e,n){return Array.isArray(e)?`${n}${t}: ${JSON.stringify(e)}`:e&&typeof e=="object"?`${n}${t}:
12
+ ${I(e,`${n} `)}`:`${n}${t}: ${JSON.stringify(e)}`}import*as d from"path";function dt(t,e){let n=d.resolve(t),r=d.resolve(t,e);return r===n?!0:n===d.parse(n).root?r.startsWith(n):r.startsWith(n+d.sep)}function xe(t,e){if(d.isAbsolute(e))return d.resolve(e);if(!dt(t,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return d.resolve(t,e)}function ye(t,e=process.platform){let n=d.resolve(t);return e==="win32"?n.toLowerCase():n}import{homedir as k,platform as pt,release as gt}from"node:os";import{execSync as mt}from"node:child_process";import{resolve as h}from"node:path";var M=pt(),ht=M==="win32",Te=M==="darwin",Ce=M==="linux",Ae=gt(),ke=k();function Me(){let t=process.env.XENO_AGENT_HOME?.trim();return t?h(t):h(k(),".xeno-agent")}function _e(){let t=process.env.XENO_CONFIG_DIR?.trim();return t?h(t):h(k(),".xeno-code")}function Se(t){return h(t,".xeno-code")}function ve(){return ht?"powershell":process.env.SHELL?.split("/").pop()??"bash"}function $e(t){try{return mt("git rev-parse --is-inside-work-tree",{cwd:t,stdio:"ignore"}),!0}catch{return!1}}function Oe(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 Le(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 Be(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 Pe(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 xt(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 Ie(t,e,n=5e3){let r=xt(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 De(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 yt=(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))(yt||{}),g=1;function je(t){g=t}function We(){return g}function p(){return new Date().toISOString()}function qe(t,e){g<=0&&(e!==void 0?process.stderr.write(`[${p()}] DEBUG: ${t} ${b(e)}
13
13
  `):process.stderr.write(`[${p()}] DEBUG: ${t}
14
- `))}function Xe(t,e){m<=1&&(e!==void 0?process.stderr.write(`[${p()}] INFO: ${t} ${w(e)}
14
+ `))}function Xe(t,e){g<=1&&(e!==void 0?process.stderr.write(`[${p()}] INFO: ${t} ${b(e)}
15
15
  `):process.stderr.write(`[${p()}] INFO: ${t}
16
- `))}function ze(t,e){m<=2&&(e!==void 0?process.stderr.write(`[${p()}] WARN: ${t} ${w(e)}
16
+ `))}function ze(t,e){g<=2&&(e!==void 0?process.stderr.write(`[${p()}] WARN: ${t} ${b(e)}
17
17
  `):process.stderr.write(`[${p()}] WARN: ${t}
18
- `))}function He(t,e){m<=3&&(e!==void 0?process.stderr.write(`[${p()}] ERROR: ${t} ${w(e)}
18
+ `))}function He(t,e){g<=3&&(e!==void 0?process.stderr.write(`[${p()}] ERROR: ${t} ${b(e)}
19
19
  `):process.stderr.write(`[${p()}] ERROR: ${t}
20
- `))}function w(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 wt=/^[A-Za-z0-9:._*-]{1,64}$/,bt=/^[A-Za-z0-9_-][A-Za-z0-9 _-]{0,30}[A-Za-z0-9_-]$/,Et=/^[0-9][0-9A-Za-z.+-]{0,40}$/;function Ye(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"||!wt.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"||!bt.test(n.name))throw new TypeError("requestContext.client.name must be 2-32 characters of letters, digits, space, _ or -");if(typeof n.version!="string"||!Et.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 Ue(t){return t?{"X-Xeno-Surface":t.surface,...t.client?{"X-Xeno-Client":`${t.client.name}/${t.client.version}`}:{}}:{}}var R=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}},b={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function E(t,e){let n=process.env[t],r=n?Number.parseInt(n,10):Number.NaN;return!Number.isFinite(r)||r<0?e:r}function Rt(t={}){let e=Math.max(0,t.maxRetries??E("XENO_API_MAX_RETRIES",b.maxRetries)),n=Math.max(50,t.baseDelayMs??E("XENO_API_BASE_DELAY_MS",b.baseDelayMs)),r=Math.max(n,t.maxDelayMs??E("XENO_API_MAX_DELAY_MS",b.maxDelayMs)),o=Math.max(0,t.jitterMs??E("XENO_API_RETRY_JITTER_MS",b.jitterMs));return{maxRetries:e,baseDelayMs:n,maxDelayMs:r,jitterMs:o}}function Tt(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 D(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("too many requests")||e.includes("429")}function At(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 F(t){if(t instanceof R)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 D(n)?{statusCode:429}:{}}var _="408|425|429|500|502|503|504";function Ct(t){let e=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${_})\\b`,"i"),n=new RegExp(`\\b(?:${_})\\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*(?:${_})\\b`);return e.test(t)||n.test(t)||r.test(t)}function kt(t){if(t&&typeof t=="object"&&"retryable"in t)return t.retryable===!0;if(t instanceof R){let{statusCode:e}=F(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:Ct(t.message)?!0:D(t.message)||At(t.message.toLowerCase())}return!1}function Mt(t){if(t.onAbort)return t.onAbort();let e=new Error("The operation was aborted");return e.name="AbortError",e}async function Ke(t,e={}){let n=Rt(e),r;for(let o=0;o<=n.maxRetries;o++)try{if(e.signal?.aborted)throw Mt(e);return e.onBeforeAttempt?.(o),await t()}catch(i){if(r=i,!(e.shouldRetry?e.shouldRetry(i,o):kt(i))||o===n.maxRetries)throw i;let l=F(i),c=Tt(o,l,n),f=e.getDelayMs?.(i,o,c),x=typeof f=="number"&&f>=0?f:c;await new Promise(y=>setTimeout(y,x))}throw r}var _t=(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))},St=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:_t,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 Qe(t,e,n=St){return{tokens:Math.max(0,Math.ceil(n.countText(t,e))),source:n.source,adapterId:n.id}}function $t(t){return t?Math.ceil(t.length/4):0}function Ve(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 tn(t,e){return $t(t)<=e}function en(t,e){return Math.max(0,e-t)}var vt={"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 rn(t,e,n){let r=vt[t];return r?e/1e6*r.input+n/1e6*r.output:0}function on(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 Nt}from"node:child_process";function un(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=Nt(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 W(t){return t.replace(/\\/g,"/").toLowerCase()}var Ot=["golden","solution","answer","expected"],Lt=["expected","golden","reference","answer","answers"],Bt=new Set([";","&&","||","|"]);function q(t){return W(t).replace(/^\.\/+/,"").split("/").map(e=>e.trim()).filter(e=>e.length>0)}function Pt(t){return Ot.some(e=>t.includes(e))}function j(t){return Lt.some(e=>t.includes(e))}function X(t){return t.split("::",1)[0]?.split("?",1)[0]?.split("#",1)[0]??t}function T(t){let e=t.trim().replace(/^[({]+/,"").replace(/[),;]+$/,"");return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e}function It(t){return t.match(/"[^"]*"|'[^']*'|&&|\|\||[;|]|[^\s;|&]+/g)?.map(T).filter(e=>e.length>0)??[]}function z(t){let e=q(t),n=X(e.at(-1)??"");return j(n)||e.some(r=>j(r))}function H(t){let e=W(T(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 Dt(t){return/[\\/]/.test(t)||/\.[A-Za-z0-9]{1,8}$/.test(t)}function Ft(t){let e=It(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 l=e[s];if(!l||Bt.has(l))break;l!=="--"&&(l.startsWith("-")||o.push(l))}if(o.length<2)continue;let i=o.at(-1);if(H(i)){for(let s of o.slice(0,-1))if(Dt(s)&&z(s))return{sourcePath:s,destinationPath:i,operation:r}}}return null}function jt(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=T(r[1]??r[2]??r[3]??""),i=T(r[4]??r[5]??r[6]??"");if(!(!o||!i)&&z(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 Y(t){let e=q(t);if(e.includes("solution")||e.includes("xeno-audit")||e.includes(".xeno")&&e.includes("audit"))return!0;let n=X(e.at(-1)??"");return e.includes("tests")&&Pt(n)}function fn(t){return J()?t.filter(e=>!Y(e)):t}function ln(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 dn(t){return t.split(/[\s"'`;|&]+/).map(e=>e.trim()).filter(e=>e.length>0&&/[\\/]/.test(e)).some(e=>Y(e))}function pn(t){if(!J())return null;let e=Ft(t)??jt(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
+ `))}function b(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 bt=/^[A-Za-z0-9:._*-]{1,64}$/,wt=/^[A-Za-z0-9_-][A-Za-z0-9 _-]{0,30}[A-Za-z0-9_-]$/,Et=/^[0-9][0-9A-Za-z.+-]{0,40}$/;function Ye(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"||!bt.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"||!wt.test(n.name))throw new TypeError("requestContext.client.name must be 2-32 characters of letters, digits, space, _ or -");if(typeof n.version!="string"||!Et.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 Ue(t){return t?{"X-Xeno-Surface":t.surface,...t.client?{"X-Xeno-Client":`${t.client.name}/${t.client.version}`}:{}}:{}}var R=class extends Error{statusCode;body;retryAfterMs;requestId;cfRay;constructor(e,n={}){super(e,n.cause!==void 0?{cause:n.cause}:void 0),this.name="ApiTransientError",this.statusCode=n.statusCode,this.retryAfterMs=n.retryAfterMs,this.requestId=n.requestId,this.cfRay=n.cfRay;for(let r of["code","category","retryable","providerCode","remedy"])n[r]!==void 0&&Object.defineProperty(this,r,{value:n[r],enumerable:!0,configurable:!0,writable:!1})}},w={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function E(t,e){let n=process.env[t],r=n?Number.parseInt(n,10):Number.NaN;return!Number.isFinite(r)||r<0?e:r}function Rt(t={}){let e=Math.max(0,t.maxRetries??E("XENO_API_MAX_RETRIES",w.maxRetries)),n=Math.max(50,t.baseDelayMs??E("XENO_API_BASE_DELAY_MS",w.baseDelayMs)),r=Math.max(n,t.maxDelayMs??E("XENO_API_MAX_DELAY_MS",w.maxDelayMs)),o=Math.max(0,t.jitterMs??E("XENO_API_RETRY_JITTER_MS",w.jitterMs));return{maxRetries:e,baseDelayMs:n,maxDelayMs:r,jitterMs:o}}function Tt(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 D(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("too many requests")||e.includes("429")}function Ct(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 F(t){if(t instanceof R)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 D(n)?{statusCode:429}:{}}var _="408|425|429|500|502|503|504";function At(t){let e=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${_})\\b`,"i"),n=new RegExp(`\\b(?:${_})\\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*(?:${_})\\b`);return e.test(t)||n.test(t)||r.test(t)}function kt(t){if(t&&typeof t=="object"&&"retryable"in t)return t.retryable===!0;if(t instanceof R){let{statusCode:e}=F(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:At(t.message)?!0:D(t.message)||Ct(t.message.toLowerCase())}return!1}function Mt(t){if(t.onAbort)return t.onAbort();let e=new Error("The operation was aborted");return e.name="AbortError",e}async function Ke(t,e={}){let n=Rt(e),r;for(let o=0;o<=n.maxRetries;o++)try{if(e.signal?.aborted)throw Mt(e);return e.onBeforeAttempt?.(o),await t()}catch(i){if(r=i,!(e.shouldRetry?e.shouldRetry(i,o):kt(i))||o===n.maxRetries)throw i;let f=F(i),c=Tt(o,f,n),l=e.getDelayMs?.(i,o,c),x=typeof l=="number"&&l>=0?l:c;await new Promise(y=>setTimeout(y,x))}throw r}var _t=(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))},St=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:_t,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 Qe(t,e,n=St){return{tokens:Math.max(0,Math.ceil(n.countText(t,e))),source:n.source,adapterId:n.id}}function vt(t){return t?Math.ceil(t.length/4):0}function Ve(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 tn(t,e){return vt(t)<=e}function en(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 rn(t,e,n){let r=$t[t];return r?e/1e6*r.input+n/1e6*r.output:0}function on(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 Nt}from"node:child_process";function un(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=Nt(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 W(t){return t.replace(/\\/g,"/").toLowerCase()}var Ot=["golden","solution","answer","expected"],Lt=["expected","golden","reference","answer","answers"],Bt=new Set([";","&&","||","|"]);function q(t){return W(t).replace(/^\.\/+/,"").split("/").map(e=>e.trim()).filter(e=>e.length>0)}function Pt(t){return Ot.some(e=>t.includes(e))}function j(t){return Lt.some(e=>t.includes(e))}function X(t){return t.split("::",1)[0]?.split("?",1)[0]?.split("#",1)[0]??t}function T(t){let e=t.trim().replace(/^[({]+/,"").replace(/[),;]+$/,"");return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e}function It(t){return t.match(/"[^"]*"|'[^']*'|&&|\|\||[;|]|[^\s;|&]+/g)?.map(T).filter(e=>e.length>0)??[]}function z(t){let e=q(t),n=X(e.at(-1)??"");return j(n)||e.some(r=>j(r))}function H(t){let e=W(T(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 Dt(t){return/[\\/]/.test(t)||/\.[A-Za-z0-9]{1,8}$/.test(t)}function Ft(t){let e=It(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 f=e[s];if(!f||Bt.has(f))break;f!=="--"&&(f.startsWith("-")||o.push(f))}if(o.length<2)continue;let i=o.at(-1);if(H(i)){for(let s of o.slice(0,-1))if(Dt(s)&&z(s))return{sourcePath:s,destinationPath:i,operation:r}}}return null}function jt(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=T(r[1]??r[2]??r[3]??""),i=T(r[4]??r[5]??r[6]??"");if(!(!o||!i)&&z(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 Y(t){let e=q(t);if(e.includes("solution")||e.includes("xeno-audit")||e.includes(".xeno")&&e.includes("audit"))return!0;let n=X(e.at(-1)??"");return e.includes("tests")&&Pt(n)}function ln(t){return J()?t.filter(e=>!Y(e)):t}function fn(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 dn(t){return t.split(/[\s"'`;|&]+/).map(e=>e.trim()).filter(e=>e.length>0&&/[\\/]/.test(e)).some(e=>Y(e))}function pn(t){if(!J())return null;let e=Ft(t)??jt(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(`
21
21
  `):null}function Wt(t){return/^data:([^;,]+)[;,]/i.exec(t.trim())?.[1]}function qt(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 ${Wt(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(`
22
22
 
23
- `).trim()}function U(t){let e=t.trim();return e.length>0?[{type:"text",text:e}]:[]}function gn(t){return typeof t=="string"?t:qt(t)}function Xt(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
+ `).trim()}function U(t){let e=t.trim();return e.length>0?[{type:"text",text:e}]:[]}function mn(t){return typeof t=="string"?t:qt(t)}function Xt(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(`
24
24
  `)}function hn(t){let e=t.assistant_content&&t.assistant_content.length>0?t.assistant_content:typeof t.content=="string"?U(t.content):t.content,n=t.assistant_only_content??[],r=zt(t),o=[...e,...n,...r?[r]:[]];return o.length>0?o:t.content}function zt(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(`
25
- `)}}function xn(t){return Array.isArray(t)&&t.some(e=>e.type!=="text")}function yn(t){return typeof t=="string"?U(t):t}function wn(t,e){return{type:"tool_result",tool_use_id:t,content:Xt(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 En(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{R as ApiTransientError,ke as HOME_DIR,Ae as IS_LINUX,Te as IS_MAC,ht as IS_WINDOWS,yt as LogLevel,Ce as OS_VERSION,M as PLATFORM,Qe as accountTextTokens,Zt as appendDurableLine,Kt as appendLine,ln as benchmarkLeakError,wn as buildToolResultBlock,Xt as buildToolResultText,rn as calculateCost,dn as commandMentionsBenchmarkLeak,St as conservativeTokenAccountingAdapter,un as copyTextToClipboard,Ie as createSafeRegex,qe as debug,nt as decodeTextBuffer,ae as deleteDir,se as deleteFile,ot as detectLineEnding,te as detectPreferredLineEnding,et as detectTextEncoding,rt as encodeTextBuffer,C as ensureDir,He as error,$t as estimateTokens,_t as estimateTokensForModel,re as existsSync,fn as filterBenchmarkLeakPaths,ee as findSimilarFile,tn as fitsInBudget,on as formatCost,Me as getAgentHome,pn as getBenchmarkReferenceOverwriteHint,Pe as getBoolean,_e as getConfigDir,We as getLogLevel,Be as getNumber,Se as getProjectConfigDir,F as getRetryErrorContext,$e as getShellName,Le as getString,hn as getToolResultTransportContent,Ut as hasDir,En as hasDisallowedAsciiControlCharacter,Yt as hasFile,ge as hasFrontmatter,Qt as hasMixedLineEndings,xn as hasNonTextToolResultContent,Ct as hasTransientStatusMention,Xe as info,Y as isBenchmarkLeakPath,J as isBenchmarkMode,ve as isGitRepo,dt as isPathSafe,kt as isRetryableError,ie as listDirs,oe as listFiles,it as normalizeLineEndings,Ye as normalizeXenoRequestContext,pe as parseDocument,le as parseJsonLines,ye as pathIdentityKey,Gt as readFileSafe,ne as readIfExists,st as readTextFile,en as remainingBudget,tt as renameReplacingWithRetry,ce as safeJsonParse,fe as safeJsonStringify,De as safeRegexTest,xe as safeResolvePath,je as setLogLevel,me as stringifyDocument,yn as toTransportAssistantBlocks,qt as toolAssistantContentToText,gn as toolResultContentToText,Ve as truncateToTokens,xt as validateRegexPattern,Oe as validateRequired,ze as warn,Ke as withRetry,Z as writeAtomic,Vt as writeTextFile,Ue as xenoRequestContextHeaders};
25
+ `)}}function xn(t){return Array.isArray(t)&&t.some(e=>e.type!=="text")}function yn(t){return typeof t=="string"?U(t):t}function bn(t,e){return{type:"tool_result",tool_use_id:t,content:Xt(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 En(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{R as ApiTransientError,ke as HOME_DIR,Ce as IS_LINUX,Te as IS_MAC,ht as IS_WINDOWS,yt as LogLevel,Ae as OS_VERSION,M as PLATFORM,Qe as accountTextTokens,Zt as appendDurableLine,Kt as appendLine,fn as benchmarkLeakError,bn as buildToolResultBlock,Xt as buildToolResultText,rn as calculateCost,dn as commandMentionsBenchmarkLeak,St as conservativeTokenAccountingAdapter,un as copyTextToClipboard,Ie as createSafeRegex,qe as debug,nt as decodeTextBuffer,ae as deleteDir,se as deleteFile,ot as detectLineEnding,te as detectPreferredLineEnding,et as detectTextEncoding,rt as encodeTextBuffer,A as ensureDir,He as error,vt as estimateTokens,_t as estimateTokensForModel,re as existsSync,ln as filterBenchmarkLeakPaths,ee as findSimilarFile,tn as fitsInBudget,on as formatCost,Me as getAgentHome,pn as getBenchmarkReferenceOverwriteHint,Pe as getBoolean,_e as getConfigDir,We as getLogLevel,Be as getNumber,Se as getProjectConfigDir,F as getRetryErrorContext,ve as getShellName,Le as getString,hn as getToolResultTransportContent,Ut as hasDir,En as hasDisallowedAsciiControlCharacter,Yt as hasFile,me as hasFrontmatter,Qt as hasMixedLineEndings,xn as hasNonTextToolResultContent,At as hasTransientStatusMention,Xe as info,Y as isBenchmarkLeakPath,J as isBenchmarkMode,$e as isGitRepo,dt as isPathSafe,kt as isRetryableError,ie as listDirs,oe as listFiles,it as normalizeLineEndings,Ye as normalizeXenoRequestContext,pe as parseDocument,fe as parseJsonLines,ye as pathIdentityKey,Gt as readFileSafe,ne as readIfExists,st as readTextFile,en as remainingBudget,tt as renameReplacingWithRetry,ce as safeJsonParse,le as safeJsonStringify,De as safeRegexTest,xe as safeResolvePath,je as setLogLevel,ge as stringifyDocument,yn as toTransportAssistantBlocks,qt as toolAssistantContentToText,mn as toolResultContentToText,Ve as truncateToTokens,xt as validateRegexPattern,Oe as validateRequired,ze as warn,Ke as withRetry,Z as writeAtomic,Vt as writeTextFile,Ue as xenoRequestContextHeaders};
@@ -1 +1 @@
1
- {"inputs":{"src/utils/fs.ts":{"bytes":13355,"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":1762,"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":2096},"src/utils/fs.ts":{"bytesInOutput":4727},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2639},"src/utils/path-security.ts":{"bytesInOutput":403},"src/utils/platform.ts":{"bytesInOutput":687},"src/utils/validation.ts":{"bytesInOutput":1425},"src/utils/logger.ts":{"bytesInOutput":915},"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":27460}}}
1
+ {"inputs":{"src/utils/fs.ts":{"bytes":13355,"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":1762,"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":13190,"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":2096},"src/utils/fs.ts":{"bytesInOutput":4727},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2639},"src/utils/path-security.ts":{"bytesInOutput":403},"src/utils/platform.ts":{"bytesInOutput":687},"src/utils/validation.ts":{"bytesInOutput":1425},"src/utils/logger.ts":{"bytesInOutput":915},"src/utils/request-context.ts":{"bytesInOutput":1241},"src/utils/retry.ts":{"bytesInOutput":3396},"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":27668}}}
@@ -1 +1 @@
1
- {"inputs":{"src/utils/fs.ts":{"bytes":13355,"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":1762,"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","hasMixedLineEndings","hasNonTextToolResultContent","hasTransientStatusMention","info","isBenchmarkLeakPath","isBenchmarkMode","isGitRepo","isPathSafe","isRetryableError","listDirs","listFiles","normalizeLineEndings","normalizeXenoRequestContext","parseDocument","parseJsonLines","pathIdentityKey","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":4680},"src/utils/index.ts":{"bytesInOutput":0},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2639},"src/utils/path-security.ts":{"bytesInOutput":401},"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":25162}}}
1
+ {"inputs":{"src/utils/fs.ts":{"bytes":13355,"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":1762,"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":13190,"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","hasMixedLineEndings","hasNonTextToolResultContent","hasTransientStatusMention","info","isBenchmarkLeakPath","isBenchmarkMode","isGitRepo","isPathSafe","isRetryableError","listDirs","listFiles","normalizeLineEndings","normalizeXenoRequestContext","parseDocument","parseJsonLines","pathIdentityKey","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":4680},"src/utils/index.ts":{"bytesInOutput":0},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2639},"src/utils/path-security.ts":{"bytesInOutput":401},"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":3393},"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":25370}}}
@@ -1 +1 @@
1
- "use strict";var M=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var G=(e,r)=>{for(var t in r)M(e,t,{get:r[t],enumerable:!0})},Q=(e,r,t,c)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Y(r))!X.call(e,i)&&i!==t&&M(e,i,{get:()=>r[i],enumerable:!(c=F(r,i))||c.enumerable});return e};var ee=e=>Q(M({},"__esModule",{value:!0}),e);var Re={};G(Re,{RUN_LEASE_MAX_SECONDS:()=>$,RUN_LEASE_SKEW_SECONDS:()=>P,RunAuthorityRefusedError:()=>O,RunStepRefused:()=>A,WorkforceAdmissionRefused:()=>w,createWorkforceRunAdmissionClient:()=>ve,createWorkforceRunAuthority:()=>se,verifyWorkforceRunLease:()=>N,workforceDefinitionContentHash:()=>Z});module.exports=ee(Re);var L=require("node:crypto"),te="/api/workforce/run-admissions/authorize-step",ne="/api/oauth2/jwks",$=60,P=5,re="xeno-run-lease+jwt",oe=1e4,V=65536,A=class extends Error{constructor(t){super(`run step refused: ${t}`);this.reason=t;this.name="RunStepRefused",this.details={reason:t}}reason;details};function N(e,r){let t=s=>({valid:!1,reason:s}),c=typeof e=="string"?e.split("."):[];if(c.length!==3)return t("malformed");let i,o;try{i=JSON.parse(Buffer.from(c[0],"base64url").toString("utf8")),o=JSON.parse(Buffer.from(c[1],"base64url").toString("utf8"))}catch{return t("malformed")}if(i.alg!=="ES256"||i.typ!==re)return t("wrong_type");if(!r.publicKey)return t("unknown_key");if(!(0,L.verify)("sha256",Buffer.from(`${c[0]}.${c[1]}`),{key:r.publicKey,dsaEncoding:"ieee-p1363"},Buffer.from(c[2],"base64url")))return t("bad_signature");if(o.iss!=="xeno-platform"||o.aud!=="xeno-run-runtime"||o.sub!==r.admissionId)return t("wrong_subject");if(!Number.isSafeInteger(o.iat)||!Number.isSafeInteger(o.exp)||o.exp<=o.iat||o.exp-o.iat>$)return t("unbounded");if(!Array.isArray(o.caps)||!o.caps.every(s=>typeof s=="string"))return t("malformed");let d;try{d=BigInt(o.seq)}catch{return t("malformed")}if(d<r.minSequence)return t("superseded");if(r.nowWallMs/1e3>=o.exp-P)return t("expired");if(r.receivedAtMono===null)return t("requires_online_reauthorization");let a=(r.nowMono-r.receivedAtMono)/1e3;return a<0?t("requires_online_reauthorization"):a>=o.exp-o.iat-P?t("expired"):{valid:!0,sequence:d,claims:o}}async function ie(e,r){let t=e.headers.get("content-length");if(t!==null&&(!/^\d+$/.test(t)||Number(t)>V))throw new Error("response too large");if(!e.body)return null;let c=e.body.getReader(),i=[],o=0;try{for(;;){let{done:a,value:s}=await c.read();if(r.aborted)throw new Error("response did not complete before the deadline");if(a)break;if(o+=s.byteLength,o>V)throw new Error("response too large");i.push(s)}}finally{try{c.releaseLock()}catch{}}let n=new Uint8Array(o),d=0;for(let a of i)n.set(a,d),d+=a.byteLength;return n.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)):null}function se(e){let r=e.fetchImpl??globalThis.fetch,t=e.clock??{wallMs:()=>Date.now(),monoMs:()=>performance.now()},c=e.admissionId;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c))throw new Error("invalid admission id");let i;try{i=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(i.protocol!=="https:"||i.pathname!=="/"||i.username||i.password||i.search||i.hash)throw new Error("invalid issuer");let o=i.origin,n=new Map,d=new Map,a=null,s=async(f,u,h)=>{let g=`${o}${u}`,v=new AbortController,I=setTimeout(()=>v.abort(),oe);I.unref?.();try{let R=null;if(f==="POST"&&(R=await e.authorizeRequest({method:f,url:g}),!R))throw new A("authority_unavailable");let C=await r(g,{method:f,redirect:"error",signal:v.signal,headers:{accept:"application/json",...h?{"content-type":"application/json"}:{},...R?{authorization:R.authorization,...R.dpop?{dpop:R.dpop}:{}}:{}},...h?{body:JSON.stringify(h)}:{}});return{status:C.status,json:await ie(C,v.signal)}}finally{clearTimeout(I)}},l=async f=>{if(n.has(f))return n.get(f);let{status:u,json:h}=await s("GET",ne);if(u!==200||!h||typeof h!="object"||!Array.isArray(h.keys))return null;for(let g of h.keys)if(!(typeof g.kid!="string"||g.kty!=="EC"||g.crv!=="P-256"))try{n.set(g.kid,(0,L.createPublicKey)({key:{kty:"EC",crv:"P-256",x:g.x,y:g.y},format:"jwk"}))}catch{}return n.get(f)??null},y=()=>e.sequenceStore.read(c)??0n,m=(f,u)=>`${f}:${u??""}`,x=async f=>{let u=JSON.parse(Buffer.from(f.token.split(".")[0],"base64url").toString("utf8")).kid;return N(f.token,{publicKey:await l(u),admissionId:c,receivedAtMono:f.receivedAtMono,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()}).valid},_=async(f,u,h)=>{if(h.throwIfAborted(),a)throw new A(a);let g=d.get(m(f,u));if(g&&await x(g).catch(()=>!1))return;let v;try{v=await s("POST",te,{admissionId:c,operation:f,...u?{capability:u}:{}})}catch(E){throw E instanceof A?E:new A("authority_unavailable")}let I=v.json;if(v.status!==200||I?.success!==!0||typeof I.token!="string"){let E=typeof I?.details?.reason=="string"&&/^[a-z_]{1,64}$/.test(I.details.reason)?I.details.reason:"authority_unavailable";throw E==="admission_revoked"&&(a=E),new A(E)}let R=t.monoMs(),C=(()=>{try{return JSON.parse(Buffer.from(I.token.split(".")[0],"base64url").toString("utf8"))}catch{return null}})();if(typeof C?.kid!="string")throw new A("authority_unavailable");let S=N(I.token,{publicKey:await l(C.kid).catch(()=>null),admissionId:c,receivedAtMono:R,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()});if(!S.valid)throw new A("authority_unavailable");if(f==="privileged_call"&&S.claims.cap!==u)throw new A("authority_unavailable");await e.sequenceStore.write(c,S.sequence),d.set(m(f,u),{token:I.token,sequence:S.sequence,operation:f,capability:u,capabilities:S.claims.caps,iat:S.claims.iat,exp:S.claims.exp,receivedAtMono:R})};return{authorizeDispatch:(f,u)=>_("provider_dispatch",null,u),authorizeToolCall:(f,u)=>{let h=e.capabilityForTool(f.toolName);return h===null||!/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/.test(h)?Promise.reject(new A("capability_not_admitted")):_("privileged_call",h,u)}}}var J=require("node:crypto"),ae="/api/workforce/run-admissions",ce="/api/workforce/run-admissions/revoke",de="/api/workforce/run-admissions/authority",ue="/api/workforce/run-admissions/pin",le="/api/workforce/run-admissions/read",fe="/api/workforce/run-admissions/operations/read",ge="/api/workforce/resources/definition/read",pe=15e3,K=65536,me=256*1024,he=32768,H=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,ye=/^[A-Z][A-Z0-9_]{0,63}$/,b=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,we=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,q=/^[a-z_]{1,64}$/,be=new Set(["bad_input","denied","not_found","needs_approval","conflict","rate_limited","unavailable","timeout","internal"]),w=class extends Error{constructor(t,c,i={}){super(`workforce admission refused: ${t}/${c}`);this.code=t;this.reason=c;this.name="WorkforceAdmissionRefused",this.details={reason:c,...i}}code;reason;details},k=()=>new w("unavailable","authority_unavailable"),p=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),T=e=>Array.isArray(e)&&e.length<=64&&e.every(r=>typeof r=="string"&&we.test(r));function W(e){if(!p(e)||e.schemaVersion!==1||typeof e.admissionId!="string"||!b.test(e.admissionId)||typeof e.operationId!="string"||!b.test(e.operationId))return null;let r=e.agent;if(!p(r)||typeof r.resourceId!="string"||!b.test(r.resourceId)||!Number.isSafeInteger(r.version)||typeof r.contentHash!="string")return null;let t=e.capabilities;if(!p(t)||!T(t.effective)||!T(t.requested))return null;let c=e.payer;if(!p(c)||typeof c.kind!="string")return null;let i=e.budget;return!p(i)||typeof i.ceilingMicro!="string"||!/^[1-9][0-9]{0,17}$/.test(i.ceilingMicro)||!p(e.target)||typeof e.admittedAt!="string"||!Number.isFinite(Date.parse(e.admittedAt))?null:e}var z=/^[0-9a-f]{64}$/;function Ae(e,r,t,c){if(!p(e)||e.schemaVersion!==1)return null;let i=e.agent;if(!p(i)||typeof i.resourceId!="string"||i.resourceId.toLowerCase()!==r||!Number.isSafeInteger(i.version)||i.version<1||typeof i.contentHash!="string"||!z.test(i.contentHash)||!p(e.target)||JSON.stringify(Object.entries(e.target).map(([d,a])=>[d,typeof a=="string"?a.toLowerCase():a]).sort())!==JSON.stringify(Object.entries(t).map(([d,a])=>[d,typeof a=="string"?a.toLowerCase():a]).sort()))return null;let o=e.team;if(c?!p(o)||typeof o.teamId!="string"||o.teamId.toLowerCase()!==c:o!==null)return null;let n=e.terms;return!p(n)||!T(n.definition)||!T(n.target)?null:{schemaVersion:1,agent:{resourceId:r,version:i.version,contentHash:i.contentHash},target:{...t},team:c?{teamId:c}:null,terms:{definition:[...n.definition],target:[...n.target]}}}function B(e,r){return!p(e)||e.schemaVersion!==1||e.admissionId!==r||typeof e.revoked!="boolean"?null:{schemaVersion:1,admissionId:r,revoked:e.revoked,reason:typeof e.reason=="string"&&q.test(e.reason)?e.reason:null,revokedAt:typeof e.revokedAt=="string"?e.revokedAt:null,latestLeaseSequence:typeof e.latestLeaseSequence=="string"?e.latestLeaseSequence:null}}function U(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(U):Object.fromEntries(Object.keys(e).sort().map(r=>[r,U(e[r])]))}function Z(e){return(0,J.createHash)("sha256").update(JSON.stringify(U({schemaVersion:1,content:e.content,provenance:e.provenance,license:e.license}))).digest("hex")}var j=(e,r)=>Object.keys(e).every(t=>r.includes(t)),D=(e,r)=>new Set(e.map(r)).size===e.length;function ke(e){if(!p(e)||!j(e,["instructions","skills","requestedCapabilities","secretReferences"]))return null;let{instructions:r,skills:t,requestedCapabilities:c,secretReferences:i}=e;return typeof r!="string"||r.includes("\0")||new TextEncoder().encode(r).byteLength>he||!Array.isArray(t)||t.length>64||!t.every(o=>p(o)&&j(o,["id","version","hash"])&&typeof o.id=="string"&&H.test(o.id)&&typeof o.version=="string"&&H.test(o.version)&&typeof o.hash=="string"&&z.test(o.hash))||!D(t,o=>o.id)||!Array.isArray(c)||c.length>64||!c.every(o=>typeof o=="string"&&H.test(o))||!D(c,o=>o)||!Array.isArray(i)||i.length>32||!i.every(o=>p(o)&&j(o,["name","ref"])&&typeof o.name=="string"&&ye.test(o.name)&&typeof o.ref=="string"&&b.test(o.ref))||!D(i,o=>o.name)?null:{instructions:r,skills:t.map(({id:o,version:n,hash:d})=>({id:o,version:n,hash:d})),requestedCapabilities:[...c],secretReferences:i.map(({name:o,ref:n})=>({name:o,ref:n}))}}function Ie(e,r){if(!p(e)||e.schemaVersion!==1||!p(e.access)||e.access.allowed!==!0)return null;let t=e.version;if(!p(t)||t.schemaVersion!==1||typeof t.resourceId!="string"||t.resourceId.toLowerCase()!==r.resourceId||t.version!==r.version||t.contentHash!==r.contentHash)return null;let c=ke(t.content);return!c||!p(t.provenance)||!p(t.license)||t.createdByUserId!==null&&(typeof t.createdByUserId!="string"||!b.test(t.createdByUserId))||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||Z({content:t.content,provenance:t.provenance,license:t.license})!==r.contentHash?null:{resourceId:r.resourceId,version:r.version,schemaVersion:1,content:c,contentHash:r.contentHash,provenance:t.provenance,license:t.license,createdByUserId:t.createdByUserId,createdAt:t.createdAt}}async function _e(e,r,t=K){let c=e.headers.get("content-length");if(c!==null&&(!/^\d+$/.test(c)||Number(c)>t))throw new Error("response too large");if(!e.body)return null;let i=e.body.getReader(),o=[],n=0;try{for(;;){let{done:s,value:l}=await i.read();if(r.aborted)throw new Error("response did not complete before the deadline");if(s)break;if(n+=l.byteLength,n>t)throw new Error("response too large");o.push(l)}}finally{try{i.releaseLock()}catch{}}let d=new Uint8Array(n),a=0;for(let s of o)d.set(s,a),a+=s.byteLength;return d.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)):null}function ve(e){let r=e.fetchImpl??globalThis.fetch,t;try{t=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(t.protocol!=="https:"||t.pathname!=="/"||t.username||t.password||t.search||t.hash)throw new Error("invalid issuer");let c=t.origin,i=async(n,d,a,s=K)=>{let l=`${c}${n}`,y=new AbortController,m=()=>y.abort();a?.addEventListener("abort",m,{once:!0});let x=setTimeout(m,pe);x.unref?.();try{a?.throwIfAborted();let _=await e.authorizeRequest({method:"POST",url:l});if(!_)throw k();let f,u;try{f=await r(l,{method:"POST",redirect:"error",signal:y.signal,headers:{accept:"application/json","content-type":"application/json",authorization:_.authorization,..._.dpop?{dpop:_.dpop}:{}},body:JSON.stringify(d)}),u=await _e(f,y.signal,s)}catch(v){throw a?.aborted?v:k()}if(f.status===200&&p(u)&&u.success===!0)return u;let h=p(u)&&typeof u.code=="string"&&be.has(u.code)?u.code:null,g=p(u)&&p(u.details)?u.details:null;throw h&&g&&g.schemaVersion===1&&typeof g.reason=="string"&&q.test(g.reason)?new w(h,g.reason,{...Number.isSafeInteger(g.currentVersion)?{currentVersion:g.currentVersion}:{},...typeof g.availableMicro=="string"&&/^[0-9]{1,20}$/.test(g.availableMicro)?{availableMicro:g.availableMicro}:{},...typeof g.field=="string"&&/^[a-zA-Z.]{1,64}$/.test(g.field)?{field:g.field}:{}}):h?new w(h,h==="denied"&&f.status===403&&p(u)&&typeof u.required_scope=="string"?"insufficient_scope":h):k()}finally{clearTimeout(x),a?.removeEventListener("abort",m)}},o=n=>{if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_admission");return n.toLowerCase()};return{async admit(n,d){if(!b.test(n.operationId))throw new w("bad_input","invalid_operation");if(!T(n.capabilities))throw new w("bad_input","invalid_capabilities");if(n.runtimeCapabilities!==void 0&&!T(n.runtimeCapabilities))throw new w("bad_input","invalid_runtime_capabilities");if(!/^[1-9][0-9]{0,17}$/.test(n.budget?.ceilingMicro??""))throw new w("bad_input","invalid_budget_ceiling");let a={operationId:n.operationId,agent:{resourceId:n.agent.resourceId,version:n.agent.version,contentHash:n.agent.contentHash},target:{...n.target},capabilities:[...n.capabilities],budget:{ceilingMicro:n.budget.ceilingMicro},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{},...n.team?{team:{teamId:n.team.teamId}}:{},...n.conversationId?{conversationId:n.conversationId}:{},...n.root?{root:{bindingId:n.root.bindingId,installationId:n.root.installationId}}:{},...n.runtimeCapabilities?{runtimeCapabilities:[...n.runtimeCapabilities]}:{}},s=await i(ae,a,d),l=W(s.admission);if(!l||l.operationId.toLowerCase()!==n.operationId.toLowerCase())throw k();return{admission:l,replayed:s.replayed===!0}},async revoke(n,d){let a=o(n),s=B(await i(ce,{admissionId:a},d),a);if(!s||!s.revoked)throw k();return s},async pin(n,d){let a=n?.agent?.resourceId;if(typeof a!="string"||!b.test(a))throw new w("bad_input","invalid_agent_resource");let s=n.target,l=p(s)?s.kind==="personal"?[s.ownerUserId]:s.kind==="workspace"?[s.assignmentId]:s.kind==="project"?[s.projectId,s.participationId]:null:null;if(!l||!l.every(f=>typeof f=="string"&&b.test(f)))throw new w("bad_input","invalid_target");let y=s.kind==="personal"?{kind:"personal",ownerUserId:s.ownerUserId}:s.kind==="workspace"?{kind:"workspace",assignmentId:s.assignmentId}:{kind:"project",projectId:s.projectId,participationId:s.participationId},m=n.team?n.team.teamId:null;if(m!==null&&(typeof m!="string"||!b.test(m)))throw new w("bad_input","invalid_team");let x={agent:{resourceId:a},target:y,...m?{team:{teamId:m}}:{},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{}},_=Ae(await i(ue,x,d),a.toLowerCase(),y,m?m.toLowerCase():null);if(!_)throw k();return _},async read(n,d,a){let s=o(n),l=d?.expectedActorAccountId;if(l!==void 0&&(typeof l!="string"||!b.test(l)))throw new w("bad_input","invalid_expected_actor");let y=await i(le,{admissionId:s,...l?{expectedActorAccountId:l}:{}},a),m=W(y.admission);if(!m||m.admissionId.toLowerCase()!==s)throw k();return m},async readOperation(n,d,a){if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_operation");let s=d?.expectedActorAccountId;if(typeof s!="string"||!b.test(s))throw new w("bad_input","invalid_expected_actor");let l=n.toLowerCase(),y=await i(fe,{operationId:l,expectedActorAccountId:s.toLowerCase()},a);if(y.schemaVersion!==1||typeof y.operationId!="string"||y.operationId.toLowerCase()!==l)throw k();if(y.state==="not-observed"&&y.admission===null)return{state:"not-observed",operationId:l,admission:null};if(y.state!=="committed")throw k();let m=W(y.admission);if(!m||m.operationId.toLowerCase()!==l)throw k();return{state:"committed",operationId:l,admission:m}},async readDefinition(n,d){let a=n?.resourceId;if(typeof a!="string"||!b.test(a))throw new w("bad_input","invalid_agent_resource");if(!Number.isSafeInteger(n.version)||n.version<1)throw new w("bad_input","invalid_version");if(typeof n.contentHash!="string"||!z.test(n.contentHash))throw new w("bad_input","invalid_content_hash");let s=n.expectedActorAccountId;if(typeof s!="string"||!b.test(s))throw new w("bad_input","invalid_expected_actor");let l={resourceId:a.toLowerCase(),version:n.version,contentHash:n.contentHash},y=await i(ge,{...l,expectedActorAccountId:s.toLowerCase()},d,me),m=Ie(y,l);if(!m)throw k();return m},async authority(n,d){let a=o(n),s=B(await i(de,{admissionId:a},d),a);if(!s)throw k();return s}}}var O=class extends Error{code="RUN_AUTHORITY_REFUSED";retryable=!1;reason;step;constructor(r,t,c){super(`Run authority refused the ${r==="dispatch"?"provider dispatch":"tool call"}: ${t}`,c),this.name="RunAuthorityRefusedError",this.reason=t,this.step=r}};0&&(module.exports={RUN_LEASE_MAX_SECONDS,RUN_LEASE_SKEW_SECONDS,RunAuthorityRefusedError,RunStepRefused,WorkforceAdmissionRefused,createWorkforceRunAdmissionClient,createWorkforceRunAuthority,verifyWorkforceRunLease,workforceDefinitionContentHash});
1
+ "use strict";var M=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var G=(e,r)=>{for(var t in r)M(e,t,{get:r[t],enumerable:!0})},Q=(e,r,t,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Y(r))!X.call(e,i)&&i!==t&&M(e,i,{get:()=>r[i],enumerable:!(a=F(r,i))||a.enumerable});return e};var ee=e=>Q(M({},"__esModule",{value:!0}),e);var ve={};G(ve,{RUN_LEASE_MAX_SECONDS:()=>$,RUN_LEASE_SKEW_SECONDS:()=>P,RunAuthorityRefusedError:()=>O,RunStepRefused:()=>k,WorkforceAdmissionRefused:()=>w,createWorkforceRunAdmissionClient:()=>Re,createWorkforceRunAuthority:()=>se,verifyWorkforceRunLease:()=>N,workforceDefinitionContentHash:()=>Z});module.exports=ee(ve);var L=require("node:crypto"),te="/api/workforce/run-admissions/authorize-step",ne="/api/oauth2/jwks",$=60,P=5,re="xeno-run-lease+jwt",oe=1e4,V=65536,k=class extends Error{constructor(t){super(`run step refused: ${t}`);this.reason=t;this.name="RunStepRefused",this.details={reason:t}}reason;details};function N(e,r){let t=s=>({valid:!1,reason:s}),a=typeof e=="string"?e.split("."):[];if(a.length!==3)return t("malformed");let i,o;try{i=JSON.parse(Buffer.from(a[0],"base64url").toString("utf8")),o=JSON.parse(Buffer.from(a[1],"base64url").toString("utf8"))}catch{return t("malformed")}if(i.alg!=="ES256"||i.typ!==re)return t("wrong_type");if(!r.publicKey)return t("unknown_key");if(!(0,L.verify)("sha256",Buffer.from(`${a[0]}.${a[1]}`),{key:r.publicKey,dsaEncoding:"ieee-p1363"},Buffer.from(a[2],"base64url")))return t("bad_signature");if(o.iss!=="xeno-platform"||o.aud!=="xeno-run-runtime"||o.sub!==r.admissionId)return t("wrong_subject");if(!Number.isSafeInteger(o.iat)||!Number.isSafeInteger(o.exp)||o.exp<=o.iat||o.exp-o.iat>$)return t("unbounded");if(!Array.isArray(o.caps)||!o.caps.every(s=>typeof s=="string"))return t("malformed");let d;try{d=BigInt(o.seq)}catch{return t("malformed")}if(d<r.minSequence)return t("superseded");if(r.nowWallMs/1e3>=o.exp-P)return t("expired");if(r.receivedAtMono===null)return t("requires_online_reauthorization");let c=(r.nowMono-r.receivedAtMono)/1e3;return c<0?t("requires_online_reauthorization"):c>=o.exp-o.iat-P?t("expired"):{valid:!0,sequence:d,claims:o}}async function ie(e,r){let t=e.headers.get("content-length");if(t!==null&&(!/^\d+$/.test(t)||Number(t)>V))throw new Error("response too large");if(!e.body)return null;let a=e.body.getReader(),i=[],o=0;try{for(;;){let{done:c,value:s}=await a.read();if(r.aborted)throw new Error("response did not complete before the deadline");if(c)break;if(o+=s.byteLength,o>V)throw new Error("response too large");i.push(s)}}finally{try{a.releaseLock()}catch{}}let n=new Uint8Array(o),d=0;for(let c of i)n.set(c,d),d+=c.byteLength;return n.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)):null}function se(e){let r=e.fetchImpl??globalThis.fetch,t=e.clock??{wallMs:()=>Date.now(),monoMs:()=>performance.now()},a=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(a))throw new Error("invalid admission id");let i;try{i=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(i.protocol!=="https:"||i.pathname!=="/"||i.username||i.password||i.search||i.hash)throw new Error("invalid issuer");let o=i.origin,n=new Map,d=new Map,c=null,s=async(l,u,h)=>{let g=`${o}${u}`,R=new AbortController,A=setTimeout(()=>R.abort(),oe);A.unref?.();try{let v=null;if(l==="POST"&&(v=await e.authorizeRequest({method:l,url:g}),!v))throw new k("authority_unavailable");let C=await r(g,{method:l,redirect:"error",signal:R.signal,headers:{accept:"application/json",...h?{"content-type":"application/json"}:{},...v?{authorization:v.authorization,...v.dpop?{dpop:v.dpop}:{}}:{}},...h?{body:JSON.stringify(h)}:{}});return{status:C.status,json:await ie(C,R.signal)}}finally{clearTimeout(A)}},f=async l=>{if(n.has(l))return n.get(l);let{status:u,json:h}=await s("GET",ne);if(u!==200||!h||typeof h!="object"||!Array.isArray(h.keys))return null;for(let g of h.keys)if(!(typeof g.kid!="string"||g.kty!=="EC"||g.crv!=="P-256"))try{n.set(g.kid,(0,L.createPublicKey)({key:{kty:"EC",crv:"P-256",x:g.x,y:g.y},format:"jwk"}))}catch{}return n.get(l)??null},y=()=>e.sequenceStore.read(a)??0n,m=(l,u)=>`${l}:${u??""}`,x=async l=>{let u=JSON.parse(Buffer.from(l.token.split(".")[0],"base64url").toString("utf8")).kid;return N(l.token,{publicKey:await f(u),admissionId:a,receivedAtMono:l.receivedAtMono,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()}).valid},_=async(l,u,h)=>{if(h.throwIfAborted(),c)throw new k(c);let g=d.get(m(l,u));if(l==="privileged_call"&&g&&await x(g).catch(()=>!1))return g.token;let R;try{R=await s("POST",te,{admissionId:a,operation:l,...u?{capability:u}:{}})}catch(T){throw T instanceof k?T:new k("authority_unavailable")}let A=R.json;if(R.status!==200||A?.success!==!0||typeof A.token!="string"){let T=typeof A?.details?.reason=="string"&&/^[a-z_]{1,64}$/.test(A.details.reason)?A.details.reason:"authority_unavailable";throw T==="admission_revoked"&&(c=T),new k(T)}let v=t.monoMs(),C=(()=>{try{return JSON.parse(Buffer.from(A.token.split(".")[0],"base64url").toString("utf8"))}catch{return null}})();if(typeof C?.kid!="string")throw new k("authority_unavailable");let S=N(A.token,{publicKey:await f(C.kid).catch(()=>null),admissionId:a,receivedAtMono:v,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()});if(!S.valid||S.claims.op!==l||A.token.length<16||A.token.length>4096)throw new k("authority_unavailable");if(l==="privileged_call"&&S.claims.cap!==u)throw new k("authority_unavailable");return await e.sequenceStore.write(a,S.sequence),l==="privileged_call"&&d.set(m(l,u),{token:A.token,sequence:S.sequence,operation:l,capability:u,capabilities:S.claims.caps,iat:S.claims.iat,exp:S.claims.exp,receivedAtMono:v}),h.throwIfAborted(),A.token};return{admissionId:a,authorizeDispatch:async(l,u)=>Object.freeze({admissionId:a,lease:await _("provider_dispatch",null,u)}),authorizeToolCall:(l,u)=>{let h=e.capabilityForTool(l.toolName);return h===null||!/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/.test(h)?Promise.reject(new k("capability_not_admitted")):_("privileged_call",h,u).then(()=>{})}}}var J=require("node:crypto"),ae="/api/workforce/run-admissions",ce="/api/workforce/run-admissions/revoke",de="/api/workforce/run-admissions/authority",le="/api/workforce/run-admissions/pin",ue="/api/workforce/run-admissions/read",fe="/api/workforce/run-admissions/operations/read",ge="/api/workforce/resources/definition/read",pe=15e3,K=65536,me=256*1024,he=32768,H=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,ye=/^[A-Z][A-Z0-9_]{0,63}$/,b=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,we=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,q=/^[a-z_]{1,64}$/,be=new Set(["bad_input","denied","not_found","needs_approval","conflict","rate_limited","unavailable","timeout","internal"]),w=class extends Error{constructor(t,a,i={}){super(`workforce admission refused: ${t}/${a}`);this.code=t;this.reason=a;this.name="WorkforceAdmissionRefused",this.details={reason:a,...i}}code;reason;details},I=()=>new w("unavailable","authority_unavailable"),p=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),E=e=>Array.isArray(e)&&e.length<=64&&e.every(r=>typeof r=="string"&&we.test(r));function W(e){if(!p(e)||e.schemaVersion!==1||typeof e.admissionId!="string"||!b.test(e.admissionId)||typeof e.operationId!="string"||!b.test(e.operationId))return null;let r=e.agent;if(!p(r)||typeof r.resourceId!="string"||!b.test(r.resourceId)||!Number.isSafeInteger(r.version)||typeof r.contentHash!="string")return null;let t=e.capabilities;if(!p(t)||!E(t.effective)||!E(t.requested))return null;let a=e.payer;if(!p(a)||typeof a.kind!="string")return null;let i=e.budget;return!p(i)||typeof i.ceilingMicro!="string"||!/^[1-9][0-9]{0,17}$/.test(i.ceilingMicro)||!p(e.target)||typeof e.admittedAt!="string"||!Number.isFinite(Date.parse(e.admittedAt))?null:e}var z=/^[0-9a-f]{64}$/;function Ae(e,r,t,a){if(!p(e)||e.schemaVersion!==1)return null;let i=e.agent;if(!p(i)||typeof i.resourceId!="string"||i.resourceId.toLowerCase()!==r||!Number.isSafeInteger(i.version)||i.version<1||typeof i.contentHash!="string"||!z.test(i.contentHash)||!p(e.target)||JSON.stringify(Object.entries(e.target).map(([d,c])=>[d,typeof c=="string"?c.toLowerCase():c]).sort())!==JSON.stringify(Object.entries(t).map(([d,c])=>[d,typeof c=="string"?c.toLowerCase():c]).sort()))return null;let o=e.team;if(a?!p(o)||typeof o.teamId!="string"||o.teamId.toLowerCase()!==a:o!==null)return null;let n=e.terms;return!p(n)||!E(n.definition)||!E(n.target)?null:{schemaVersion:1,agent:{resourceId:r,version:i.version,contentHash:i.contentHash},target:{...t},team:a?{teamId:a}:null,terms:{definition:[...n.definition],target:[...n.target]}}}function B(e,r){return!p(e)||e.schemaVersion!==1||e.admissionId!==r||typeof e.revoked!="boolean"?null:{schemaVersion:1,admissionId:r,revoked:e.revoked,reason:typeof e.reason=="string"&&q.test(e.reason)?e.reason:null,revokedAt:typeof e.revokedAt=="string"?e.revokedAt:null,latestLeaseSequence:typeof e.latestLeaseSequence=="string"?e.latestLeaseSequence:null}}function U(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(U):Object.fromEntries(Object.keys(e).sort().map(r=>[r,U(e[r])]))}function Z(e){return(0,J.createHash)("sha256").update(JSON.stringify(U({schemaVersion:1,content:e.content,provenance:e.provenance,license:e.license}))).digest("hex")}var j=(e,r)=>Object.keys(e).every(t=>r.includes(t)),D=(e,r)=>new Set(e.map(r)).size===e.length;function ke(e){if(!p(e)||!j(e,["instructions","skills","requestedCapabilities","secretReferences"]))return null;let{instructions:r,skills:t,requestedCapabilities:a,secretReferences:i}=e;return typeof r!="string"||r.includes("\0")||new TextEncoder().encode(r).byteLength>he||!Array.isArray(t)||t.length>64||!t.every(o=>p(o)&&j(o,["id","version","hash"])&&typeof o.id=="string"&&H.test(o.id)&&typeof o.version=="string"&&H.test(o.version)&&typeof o.hash=="string"&&z.test(o.hash))||!D(t,o=>o.id)||!Array.isArray(a)||a.length>64||!a.every(o=>typeof o=="string"&&H.test(o))||!D(a,o=>o)||!Array.isArray(i)||i.length>32||!i.every(o=>p(o)&&j(o,["name","ref"])&&typeof o.name=="string"&&ye.test(o.name)&&typeof o.ref=="string"&&b.test(o.ref))||!D(i,o=>o.name)?null:{instructions:r,skills:t.map(({id:o,version:n,hash:d})=>({id:o,version:n,hash:d})),requestedCapabilities:[...a],secretReferences:i.map(({name:o,ref:n})=>({name:o,ref:n}))}}function Ie(e,r){if(!p(e)||e.schemaVersion!==1||!p(e.access)||e.access.allowed!==!0)return null;let t=e.version;if(!p(t)||t.schemaVersion!==1||typeof t.resourceId!="string"||t.resourceId.toLowerCase()!==r.resourceId||t.version!==r.version||t.contentHash!==r.contentHash)return null;let a=ke(t.content);return!a||!p(t.provenance)||!p(t.license)||t.createdByUserId!==null&&(typeof t.createdByUserId!="string"||!b.test(t.createdByUserId))||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||Z({content:t.content,provenance:t.provenance,license:t.license})!==r.contentHash?null:{resourceId:r.resourceId,version:r.version,schemaVersion:1,content:a,contentHash:r.contentHash,provenance:t.provenance,license:t.license,createdByUserId:t.createdByUserId,createdAt:t.createdAt}}async function _e(e,r,t=K){let a=e.headers.get("content-length");if(a!==null&&(!/^\d+$/.test(a)||Number(a)>t))throw new Error("response too large");if(!e.body)return null;let i=e.body.getReader(),o=[],n=0;try{for(;;){let{done:s,value:f}=await i.read();if(r.aborted)throw new Error("response did not complete before the deadline");if(s)break;if(n+=f.byteLength,n>t)throw new Error("response too large");o.push(f)}}finally{try{i.releaseLock()}catch{}}let d=new Uint8Array(n),c=0;for(let s of o)d.set(s,c),c+=s.byteLength;return d.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)):null}function Re(e){let r=e.fetchImpl??globalThis.fetch,t;try{t=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(t.protocol!=="https:"||t.pathname!=="/"||t.username||t.password||t.search||t.hash)throw new Error("invalid issuer");let a=t.origin,i=async(n,d,c,s=K)=>{let f=`${a}${n}`,y=new AbortController,m=()=>y.abort();c?.addEventListener("abort",m,{once:!0});let x=setTimeout(m,pe);x.unref?.();try{c?.throwIfAborted();let _=await e.authorizeRequest({method:"POST",url:f});if(!_)throw I();let l,u;try{l=await r(f,{method:"POST",redirect:"error",signal:y.signal,headers:{accept:"application/json","content-type":"application/json",authorization:_.authorization,..._.dpop?{dpop:_.dpop}:{}},body:JSON.stringify(d)}),u=await _e(l,y.signal,s)}catch(R){throw c?.aborted?R:I()}if(l.status===200&&p(u)&&u.success===!0)return u;let h=p(u)&&typeof u.code=="string"&&be.has(u.code)?u.code:null,g=p(u)&&p(u.details)?u.details:null;throw h&&g&&g.schemaVersion===1&&typeof g.reason=="string"&&q.test(g.reason)?new w(h,g.reason,{...Number.isSafeInteger(g.currentVersion)?{currentVersion:g.currentVersion}:{},...typeof g.availableMicro=="string"&&/^[0-9]{1,20}$/.test(g.availableMicro)?{availableMicro:g.availableMicro}:{},...typeof g.field=="string"&&/^[a-zA-Z.]{1,64}$/.test(g.field)?{field:g.field}:{}}):h?new w(h,h==="denied"&&l.status===403&&p(u)&&typeof u.required_scope=="string"?"insufficient_scope":h):I()}finally{clearTimeout(x),c?.removeEventListener("abort",m)}},o=n=>{if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_admission");return n.toLowerCase()};return{async admit(n,d){if(!b.test(n.operationId))throw new w("bad_input","invalid_operation");if(!E(n.capabilities))throw new w("bad_input","invalid_capabilities");if(n.runtimeCapabilities!==void 0&&!E(n.runtimeCapabilities))throw new w("bad_input","invalid_runtime_capabilities");if(!/^[1-9][0-9]{0,17}$/.test(n.budget?.ceilingMicro??""))throw new w("bad_input","invalid_budget_ceiling");let c={operationId:n.operationId,agent:{resourceId:n.agent.resourceId,version:n.agent.version,contentHash:n.agent.contentHash},target:{...n.target},capabilities:[...n.capabilities],budget:{ceilingMicro:n.budget.ceilingMicro},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{},...n.team?{team:{teamId:n.team.teamId}}:{},...n.conversationId?{conversationId:n.conversationId}:{},...n.root?{root:{bindingId:n.root.bindingId,installationId:n.root.installationId}}:{},...n.runtimeCapabilities?{runtimeCapabilities:[...n.runtimeCapabilities]}:{}},s=await i(ae,c,d),f=W(s.admission);if(!f||f.operationId.toLowerCase()!==n.operationId.toLowerCase())throw I();return{admission:f,replayed:s.replayed===!0}},async revoke(n,d){let c=o(n),s=B(await i(ce,{admissionId:c},d),c);if(!s||!s.revoked)throw I();return s},async pin(n,d){let c=n?.agent?.resourceId;if(typeof c!="string"||!b.test(c))throw new w("bad_input","invalid_agent_resource");let s=n.target,f=p(s)?s.kind==="personal"?[s.ownerUserId]:s.kind==="workspace"?[s.assignmentId]:s.kind==="project"?[s.projectId,s.participationId]:null:null;if(!f||!f.every(l=>typeof l=="string"&&b.test(l)))throw new w("bad_input","invalid_target");let y=s.kind==="personal"?{kind:"personal",ownerUserId:s.ownerUserId}:s.kind==="workspace"?{kind:"workspace",assignmentId:s.assignmentId}:{kind:"project",projectId:s.projectId,participationId:s.participationId},m=n.team?n.team.teamId:null;if(m!==null&&(typeof m!="string"||!b.test(m)))throw new w("bad_input","invalid_team");let x={agent:{resourceId:c},target:y,...m?{team:{teamId:m}}:{},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{}},_=Ae(await i(le,x,d),c.toLowerCase(),y,m?m.toLowerCase():null);if(!_)throw I();return _},async read(n,d,c){let s=o(n),f=d?.expectedActorAccountId;if(f!==void 0&&(typeof f!="string"||!b.test(f)))throw new w("bad_input","invalid_expected_actor");let y=await i(ue,{admissionId:s,...f?{expectedActorAccountId:f}:{}},c),m=W(y.admission);if(!m||m.admissionId.toLowerCase()!==s)throw I();return m},async readOperation(n,d,c){if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_operation");let s=d?.expectedActorAccountId;if(typeof s!="string"||!b.test(s))throw new w("bad_input","invalid_expected_actor");let f=n.toLowerCase(),y=await i(fe,{operationId:f,expectedActorAccountId:s.toLowerCase()},c);if(y.schemaVersion!==1||typeof y.operationId!="string"||y.operationId.toLowerCase()!==f)throw I();if(y.state==="not-observed"&&y.admission===null)return{state:"not-observed",operationId:f,admission:null};if(y.state!=="committed")throw I();let m=W(y.admission);if(!m||m.operationId.toLowerCase()!==f)throw I();return{state:"committed",operationId:f,admission:m}},async readDefinition(n,d){let c=n?.resourceId;if(typeof c!="string"||!b.test(c))throw new w("bad_input","invalid_agent_resource");if(!Number.isSafeInteger(n.version)||n.version<1)throw new w("bad_input","invalid_version");if(typeof n.contentHash!="string"||!z.test(n.contentHash))throw new w("bad_input","invalid_content_hash");let s=n.expectedActorAccountId;if(typeof s!="string"||!b.test(s))throw new w("bad_input","invalid_expected_actor");let f={resourceId:c.toLowerCase(),version:n.version,contentHash:n.contentHash},y=await i(ge,{...f,expectedActorAccountId:s.toLowerCase()},d,me),m=Ie(y,f);if(!m)throw I();return m},async authority(n,d){let c=o(n),s=B(await i(de,{admissionId:c},d),c);if(!s)throw I();return s}}}var O=class extends Error{code="RUN_AUTHORITY_REFUSED";retryable=!1;reason;step;constructor(r,t,a){super(`Run authority refused the ${r==="dispatch"?"provider dispatch":"tool call"}: ${t}`,a),this.name="RunAuthorityRefusedError",this.reason=t,this.step=r}};0&&(module.exports={RUN_LEASE_MAX_SECONDS,RUN_LEASE_SKEW_SECONDS,RunAuthorityRefusedError,RunStepRefused,WorkforceAdmissionRefused,createWorkforceRunAdmissionClient,createWorkforceRunAuthority,verifyWorkforceRunLease,workforceDefinitionContentHash});
@@ -11,8 +11,13 @@ interface RunAuthorityToolCall {
11
11
  toolName: string;
12
12
  toolCallId: string;
13
13
  }
14
+ interface RunDispatchCredential {
15
+ readonly admissionId: string;
16
+ readonly lease: string;
17
+ }
14
18
  interface RunAuthority {
15
- authorizeDispatch(request: Readonly<RunAuthorityDispatch>, signal: AbortSignal): void | Promise<void>;
19
+ readonly admissionId?: string;
20
+ authorizeDispatch(request: Readonly<RunAuthorityDispatch>, signal: AbortSignal): void | RunDispatchCredential | Promise<void | RunDispatchCredential>;
16
21
  authorizeToolCall(request: Readonly<RunAuthorityToolCall>, signal: AbortSignal): void | Promise<void>;
17
22
  }
18
23
  declare class RunAuthorityRefusedError extends Error {
@@ -262,4 +267,4 @@ declare function workforceDefinitionContentHash(definition: {
262
267
  license: unknown;
263
268
  }): string;
264
269
  declare function createWorkforceRunAdmissionClient(options: WorkforceRunAdmissionClientOptions): WorkforceRunAdmissionClient;
265
- export { RUN_LEASE_MAX_SECONDS, RUN_LEASE_SKEW_SECONDS, type RunAuthority, type RunAuthorityDispatch, RunAuthorityRefusedError, type RunAuthorityToolCall, type RunLeaseSequenceStore, RunStepRefused, type WorkforceAdmission, WorkforceAdmissionRefused, type WorkforceAdmissionRequest, type WorkforceAdmissionTarget, type WorkforceAgentDefinitionContent, type WorkforceAgentDefinitionVersion, type WorkforceRunAdmissionClient, type WorkforceRunAdmissionClientOptions, type WorkforceRunAuthorityOptions, type WorkforceRunAuthorityState, type WorkforceRunnablePin, createWorkforceRunAdmissionClient, createWorkforceRunAuthority, verifyWorkforceRunLease, workforceDefinitionContentHash };
270
+ export { RUN_LEASE_MAX_SECONDS, RUN_LEASE_SKEW_SECONDS, type RunAuthority, type RunAuthorityDispatch, RunAuthorityRefusedError, type RunAuthorityToolCall, type RunDispatchCredential, type RunLeaseSequenceStore, RunStepRefused, type WorkforceAdmission, WorkforceAdmissionRefused, type WorkforceAdmissionRequest, type WorkforceAdmissionTarget, type WorkforceAgentDefinitionContent, type WorkforceAgentDefinitionVersion, type WorkforceRunAdmissionClient, type WorkforceRunAdmissionClientOptions, type WorkforceRunAuthorityOptions, type WorkforceRunAuthorityState, type WorkforceRunnablePin, createWorkforceRunAdmissionClient, createWorkforceRunAuthority, verifyWorkforceRunLease, workforceDefinitionContentHash };
@@ -11,8 +11,13 @@ interface RunAuthorityToolCall {
11
11
  toolName: string;
12
12
  toolCallId: string;
13
13
  }
14
+ interface RunDispatchCredential {
15
+ readonly admissionId: string;
16
+ readonly lease: string;
17
+ }
14
18
  interface RunAuthority {
15
- authorizeDispatch(request: Readonly<RunAuthorityDispatch>, signal: AbortSignal): void | Promise<void>;
19
+ readonly admissionId?: string;
20
+ authorizeDispatch(request: Readonly<RunAuthorityDispatch>, signal: AbortSignal): void | RunDispatchCredential | Promise<void | RunDispatchCredential>;
16
21
  authorizeToolCall(request: Readonly<RunAuthorityToolCall>, signal: AbortSignal): void | Promise<void>;
17
22
  }
18
23
  declare class RunAuthorityRefusedError extends Error {
@@ -262,4 +267,4 @@ declare function workforceDefinitionContentHash(definition: {
262
267
  license: unknown;
263
268
  }): string;
264
269
  declare function createWorkforceRunAdmissionClient(options: WorkforceRunAdmissionClientOptions): WorkforceRunAdmissionClient;
265
- export { RUN_LEASE_MAX_SECONDS, RUN_LEASE_SKEW_SECONDS, type RunAuthority, type RunAuthorityDispatch, RunAuthorityRefusedError, type RunAuthorityToolCall, type RunLeaseSequenceStore, RunStepRefused, type WorkforceAdmission, WorkforceAdmissionRefused, type WorkforceAdmissionRequest, type WorkforceAdmissionTarget, type WorkforceAgentDefinitionContent, type WorkforceAgentDefinitionVersion, type WorkforceRunAdmissionClient, type WorkforceRunAdmissionClientOptions, type WorkforceRunAuthorityOptions, type WorkforceRunAuthorityState, type WorkforceRunnablePin, createWorkforceRunAdmissionClient, createWorkforceRunAuthority, verifyWorkforceRunLease, workforceDefinitionContentHash };
270
+ export { RUN_LEASE_MAX_SECONDS, RUN_LEASE_SKEW_SECONDS, type RunAuthority, type RunAuthorityDispatch, RunAuthorityRefusedError, type RunAuthorityToolCall, type RunDispatchCredential, type RunLeaseSequenceStore, RunStepRefused, type WorkforceAdmission, WorkforceAdmissionRefused, type WorkforceAdmissionRequest, type WorkforceAdmissionTarget, type WorkforceAgentDefinitionContent, type WorkforceAgentDefinitionVersion, type WorkforceRunAdmissionClient, type WorkforceRunAdmissionClientOptions, type WorkforceRunAuthorityOptions, type WorkforceRunAuthorityState, type WorkforceRunnablePin, createWorkforceRunAdmissionClient, createWorkforceRunAuthority, verifyWorkforceRunLease, workforceDefinitionContentHash };
@@ -1 +1 @@
1
- import{createPublicKey as B,verify as J}from"node:crypto";var K="/api/workforce/run-admissions/authorize-step",q="/api/oauth2/jwks",Z=60,j=5,F="xeno-run-lease+jwt",Y=1e4,D=65536,I=class extends Error{constructor(t){super(`run step refused: ${t}`);this.reason=t;this.name="RunStepRefused",this.details={reason:t}}reason;details};function U(e,o){let t=i=>({valid:!1,reason:i}),c=typeof e=="string"?e.split("."):[];if(c.length!==3)return t("malformed");let s,r;try{s=JSON.parse(Buffer.from(c[0],"base64url").toString("utf8")),r=JSON.parse(Buffer.from(c[1],"base64url").toString("utf8"))}catch{return t("malformed")}if(s.alg!=="ES256"||s.typ!==F)return t("wrong_type");if(!o.publicKey)return t("unknown_key");if(!J("sha256",Buffer.from(`${c[0]}.${c[1]}`),{key:o.publicKey,dsaEncoding:"ieee-p1363"},Buffer.from(c[2],"base64url")))return t("bad_signature");if(r.iss!=="xeno-platform"||r.aud!=="xeno-run-runtime"||r.sub!==o.admissionId)return t("wrong_subject");if(!Number.isSafeInteger(r.iat)||!Number.isSafeInteger(r.exp)||r.exp<=r.iat||r.exp-r.iat>Z)return t("unbounded");if(!Array.isArray(r.caps)||!r.caps.every(i=>typeof i=="string"))return t("malformed");let d;try{d=BigInt(r.seq)}catch{return t("malformed")}if(d<o.minSequence)return t("superseded");if(o.nowWallMs/1e3>=r.exp-j)return t("expired");if(o.receivedAtMono===null)return t("requires_online_reauthorization");let a=(o.nowMono-o.receivedAtMono)/1e3;return a<0?t("requires_online_reauthorization"):a>=r.exp-r.iat-j?t("expired"):{valid:!0,sequence:d,claims:r}}async function X(e,o){let t=e.headers.get("content-length");if(t!==null&&(!/^\d+$/.test(t)||Number(t)>D))throw new Error("response too large");if(!e.body)return null;let c=e.body.getReader(),s=[],r=0;try{for(;;){let{done:a,value:i}=await c.read();if(o.aborted)throw new Error("response did not complete before the deadline");if(a)break;if(r+=i.byteLength,r>D)throw new Error("response too large");s.push(i)}}finally{try{c.releaseLock()}catch{}}let n=new Uint8Array(r),d=0;for(let a of s)n.set(a,d),d+=a.byteLength;return n.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)):null}function we(e){let o=e.fetchImpl??globalThis.fetch,t=e.clock??{wallMs:()=>Date.now(),monoMs:()=>performance.now()},c=e.admissionId;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c))throw new Error("invalid admission id");let s;try{s=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(s.protocol!=="https:"||s.pathname!=="/"||s.username||s.password||s.search||s.hash)throw new Error("invalid issuer");let r=s.origin,n=new Map,d=new Map,a=null,i=async(f,u,h)=>{let g=`${r}${u}`,v=new AbortController,k=setTimeout(()=>v.abort(),Y);k.unref?.();try{let R=null;if(f==="POST"&&(R=await e.authorizeRequest({method:f,url:g}),!R))throw new I("authority_unavailable");let C=await o(g,{method:f,redirect:"error",signal:v.signal,headers:{accept:"application/json",...h?{"content-type":"application/json"}:{},...R?{authorization:R.authorization,...R.dpop?{dpop:R.dpop}:{}}:{}},...h?{body:JSON.stringify(h)}:{}});return{status:C.status,json:await X(C,v.signal)}}finally{clearTimeout(k)}},l=async f=>{if(n.has(f))return n.get(f);let{status:u,json:h}=await i("GET",q);if(u!==200||!h||typeof h!="object"||!Array.isArray(h.keys))return null;for(let g of h.keys)if(!(typeof g.kid!="string"||g.kty!=="EC"||g.crv!=="P-256"))try{n.set(g.kid,B({key:{kty:"EC",crv:"P-256",x:g.x,y:g.y},format:"jwk"}))}catch{}return n.get(f)??null},y=()=>e.sequenceStore.read(c)??0n,m=(f,u)=>`${f}:${u??""}`,x=async f=>{let u=JSON.parse(Buffer.from(f.token.split(".")[0],"base64url").toString("utf8")).kid;return U(f.token,{publicKey:await l(u),admissionId:c,receivedAtMono:f.receivedAtMono,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()}).valid},_=async(f,u,h)=>{if(h.throwIfAborted(),a)throw new I(a);let g=d.get(m(f,u));if(g&&await x(g).catch(()=>!1))return;let v;try{v=await i("POST",K,{admissionId:c,operation:f,...u?{capability:u}:{}})}catch(E){throw E instanceof I?E:new I("authority_unavailable")}let k=v.json;if(v.status!==200||k?.success!==!0||typeof k.token!="string"){let E=typeof k?.details?.reason=="string"&&/^[a-z_]{1,64}$/.test(k.details.reason)?k.details.reason:"authority_unavailable";throw E==="admission_revoked"&&(a=E),new I(E)}let R=t.monoMs(),C=(()=>{try{return JSON.parse(Buffer.from(k.token.split(".")[0],"base64url").toString("utf8"))}catch{return null}})();if(typeof C?.kid!="string")throw new I("authority_unavailable");let S=U(k.token,{publicKey:await l(C.kid).catch(()=>null),admissionId:c,receivedAtMono:R,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()});if(!S.valid)throw new I("authority_unavailable");if(f==="privileged_call"&&S.claims.cap!==u)throw new I("authority_unavailable");await e.sequenceStore.write(c,S.sequence),d.set(m(f,u),{token:k.token,sequence:S.sequence,operation:f,capability:u,capabilities:S.claims.caps,iat:S.claims.iat,exp:S.claims.exp,receivedAtMono:R})};return{authorizeDispatch:(f,u)=>_("provider_dispatch",null,u),authorizeToolCall:(f,u)=>{let h=e.capabilityForTool(f.toolName);return h===null||!/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/.test(h)?Promise.reject(new I("capability_not_admitted")):_("privileged_call",h,u)}}}import{createHash as G}from"node:crypto";var Q="/api/workforce/run-admissions",ee="/api/workforce/run-admissions/revoke",te="/api/workforce/run-admissions/authority",ne="/api/workforce/run-admissions/pin",re="/api/workforce/run-admissions/read",oe="/api/workforce/run-admissions/operations/read",ie="/api/workforce/resources/definition/read",se=15e3,V=65536,ae=256*1024,ce=32768,L=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,de=/^[A-Z][A-Z0-9_]{0,63}$/,b=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ue=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,$=/^[a-z_]{1,64}$/,le=new Set(["bad_input","denied","not_found","needs_approval","conflict","rate_limited","unavailable","timeout","internal"]),w=class extends Error{constructor(t,c,s={}){super(`workforce admission refused: ${t}/${c}`);this.code=t;this.reason=c;this.name="WorkforceAdmissionRefused",this.details={reason:c,...s}}code;reason;details},A=()=>new w("unavailable","authority_unavailable"),p=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),T=e=>Array.isArray(e)&&e.length<=64&&e.every(o=>typeof o=="string"&&ue.test(o));function O(e){if(!p(e)||e.schemaVersion!==1||typeof e.admissionId!="string"||!b.test(e.admissionId)||typeof e.operationId!="string"||!b.test(e.operationId))return null;let o=e.agent;if(!p(o)||typeof o.resourceId!="string"||!b.test(o.resourceId)||!Number.isSafeInteger(o.version)||typeof o.contentHash!="string")return null;let t=e.capabilities;if(!p(t)||!T(t.effective)||!T(t.requested))return null;let c=e.payer;if(!p(c)||typeof c.kind!="string")return null;let s=e.budget;return!p(s)||typeof s.ceilingMicro!="string"||!/^[1-9][0-9]{0,17}$/.test(s.ceilingMicro)||!p(e.target)||typeof e.admittedAt!="string"||!Number.isFinite(Date.parse(e.admittedAt))?null:e}var H=/^[0-9a-f]{64}$/;function fe(e,o,t,c){if(!p(e)||e.schemaVersion!==1)return null;let s=e.agent;if(!p(s)||typeof s.resourceId!="string"||s.resourceId.toLowerCase()!==o||!Number.isSafeInteger(s.version)||s.version<1||typeof s.contentHash!="string"||!H.test(s.contentHash)||!p(e.target)||JSON.stringify(Object.entries(e.target).map(([d,a])=>[d,typeof a=="string"?a.toLowerCase():a]).sort())!==JSON.stringify(Object.entries(t).map(([d,a])=>[d,typeof a=="string"?a.toLowerCase():a]).sort()))return null;let r=e.team;if(c?!p(r)||typeof r.teamId!="string"||r.teamId.toLowerCase()!==c:r!==null)return null;let n=e.terms;return!p(n)||!T(n.definition)||!T(n.target)?null:{schemaVersion:1,agent:{resourceId:o,version:s.version,contentHash:s.contentHash},target:{...t},team:c?{teamId:c}:null,terms:{definition:[...n.definition],target:[...n.target]}}}function z(e,o){return!p(e)||e.schemaVersion!==1||e.admissionId!==o||typeof e.revoked!="boolean"?null:{schemaVersion:1,admissionId:o,revoked:e.revoked,reason:typeof e.reason=="string"&&$.test(e.reason)?e.reason:null,revokedAt:typeof e.revokedAt=="string"?e.revokedAt:null,latestLeaseSequence:typeof e.latestLeaseSequence=="string"?e.latestLeaseSequence:null}}function N(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(N):Object.fromEntries(Object.keys(e).sort().map(o=>[o,N(e[o])]))}function ge(e){return G("sha256").update(JSON.stringify(N({schemaVersion:1,content:e.content,provenance:e.provenance,license:e.license}))).digest("hex")}var M=(e,o)=>Object.keys(e).every(t=>o.includes(t)),P=(e,o)=>new Set(e.map(o)).size===e.length;function pe(e){if(!p(e)||!M(e,["instructions","skills","requestedCapabilities","secretReferences"]))return null;let{instructions:o,skills:t,requestedCapabilities:c,secretReferences:s}=e;return typeof o!="string"||o.includes("\0")||new TextEncoder().encode(o).byteLength>ce||!Array.isArray(t)||t.length>64||!t.every(r=>p(r)&&M(r,["id","version","hash"])&&typeof r.id=="string"&&L.test(r.id)&&typeof r.version=="string"&&L.test(r.version)&&typeof r.hash=="string"&&H.test(r.hash))||!P(t,r=>r.id)||!Array.isArray(c)||c.length>64||!c.every(r=>typeof r=="string"&&L.test(r))||!P(c,r=>r)||!Array.isArray(s)||s.length>32||!s.every(r=>p(r)&&M(r,["name","ref"])&&typeof r.name=="string"&&de.test(r.name)&&typeof r.ref=="string"&&b.test(r.ref))||!P(s,r=>r.name)?null:{instructions:o,skills:t.map(({id:r,version:n,hash:d})=>({id:r,version:n,hash:d})),requestedCapabilities:[...c],secretReferences:s.map(({name:r,ref:n})=>({name:r,ref:n}))}}function me(e,o){if(!p(e)||e.schemaVersion!==1||!p(e.access)||e.access.allowed!==!0)return null;let t=e.version;if(!p(t)||t.schemaVersion!==1||typeof t.resourceId!="string"||t.resourceId.toLowerCase()!==o.resourceId||t.version!==o.version||t.contentHash!==o.contentHash)return null;let c=pe(t.content);return!c||!p(t.provenance)||!p(t.license)||t.createdByUserId!==null&&(typeof t.createdByUserId!="string"||!b.test(t.createdByUserId))||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||ge({content:t.content,provenance:t.provenance,license:t.license})!==o.contentHash?null:{resourceId:o.resourceId,version:o.version,schemaVersion:1,content:c,contentHash:o.contentHash,provenance:t.provenance,license:t.license,createdByUserId:t.createdByUserId,createdAt:t.createdAt}}async function he(e,o,t=V){let c=e.headers.get("content-length");if(c!==null&&(!/^\d+$/.test(c)||Number(c)>t))throw new Error("response too large");if(!e.body)return null;let s=e.body.getReader(),r=[],n=0;try{for(;;){let{done:i,value:l}=await s.read();if(o.aborted)throw new Error("response did not complete before the deadline");if(i)break;if(n+=l.byteLength,n>t)throw new Error("response too large");r.push(l)}}finally{try{s.releaseLock()}catch{}}let d=new Uint8Array(n),a=0;for(let i of r)d.set(i,a),a+=i.byteLength;return d.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)):null}function ke(e){let o=e.fetchImpl??globalThis.fetch,t;try{t=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(t.protocol!=="https:"||t.pathname!=="/"||t.username||t.password||t.search||t.hash)throw new Error("invalid issuer");let c=t.origin,s=async(n,d,a,i=V)=>{let l=`${c}${n}`,y=new AbortController,m=()=>y.abort();a?.addEventListener("abort",m,{once:!0});let x=setTimeout(m,se);x.unref?.();try{a?.throwIfAborted();let _=await e.authorizeRequest({method:"POST",url:l});if(!_)throw A();let f,u;try{f=await o(l,{method:"POST",redirect:"error",signal:y.signal,headers:{accept:"application/json","content-type":"application/json",authorization:_.authorization,..._.dpop?{dpop:_.dpop}:{}},body:JSON.stringify(d)}),u=await he(f,y.signal,i)}catch(v){throw a?.aborted?v:A()}if(f.status===200&&p(u)&&u.success===!0)return u;let h=p(u)&&typeof u.code=="string"&&le.has(u.code)?u.code:null,g=p(u)&&p(u.details)?u.details:null;throw h&&g&&g.schemaVersion===1&&typeof g.reason=="string"&&$.test(g.reason)?new w(h,g.reason,{...Number.isSafeInteger(g.currentVersion)?{currentVersion:g.currentVersion}:{},...typeof g.availableMicro=="string"&&/^[0-9]{1,20}$/.test(g.availableMicro)?{availableMicro:g.availableMicro}:{},...typeof g.field=="string"&&/^[a-zA-Z.]{1,64}$/.test(g.field)?{field:g.field}:{}}):h?new w(h,h==="denied"&&f.status===403&&p(u)&&typeof u.required_scope=="string"?"insufficient_scope":h):A()}finally{clearTimeout(x),a?.removeEventListener("abort",m)}},r=n=>{if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_admission");return n.toLowerCase()};return{async admit(n,d){if(!b.test(n.operationId))throw new w("bad_input","invalid_operation");if(!T(n.capabilities))throw new w("bad_input","invalid_capabilities");if(n.runtimeCapabilities!==void 0&&!T(n.runtimeCapabilities))throw new w("bad_input","invalid_runtime_capabilities");if(!/^[1-9][0-9]{0,17}$/.test(n.budget?.ceilingMicro??""))throw new w("bad_input","invalid_budget_ceiling");let a={operationId:n.operationId,agent:{resourceId:n.agent.resourceId,version:n.agent.version,contentHash:n.agent.contentHash},target:{...n.target},capabilities:[...n.capabilities],budget:{ceilingMicro:n.budget.ceilingMicro},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{},...n.team?{team:{teamId:n.team.teamId}}:{},...n.conversationId?{conversationId:n.conversationId}:{},...n.root?{root:{bindingId:n.root.bindingId,installationId:n.root.installationId}}:{},...n.runtimeCapabilities?{runtimeCapabilities:[...n.runtimeCapabilities]}:{}},i=await s(Q,a,d),l=O(i.admission);if(!l||l.operationId.toLowerCase()!==n.operationId.toLowerCase())throw A();return{admission:l,replayed:i.replayed===!0}},async revoke(n,d){let a=r(n),i=z(await s(ee,{admissionId:a},d),a);if(!i||!i.revoked)throw A();return i},async pin(n,d){let a=n?.agent?.resourceId;if(typeof a!="string"||!b.test(a))throw new w("bad_input","invalid_agent_resource");let i=n.target,l=p(i)?i.kind==="personal"?[i.ownerUserId]:i.kind==="workspace"?[i.assignmentId]:i.kind==="project"?[i.projectId,i.participationId]:null:null;if(!l||!l.every(f=>typeof f=="string"&&b.test(f)))throw new w("bad_input","invalid_target");let y=i.kind==="personal"?{kind:"personal",ownerUserId:i.ownerUserId}:i.kind==="workspace"?{kind:"workspace",assignmentId:i.assignmentId}:{kind:"project",projectId:i.projectId,participationId:i.participationId},m=n.team?n.team.teamId:null;if(m!==null&&(typeof m!="string"||!b.test(m)))throw new w("bad_input","invalid_team");let x={agent:{resourceId:a},target:y,...m?{team:{teamId:m}}:{},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{}},_=fe(await s(ne,x,d),a.toLowerCase(),y,m?m.toLowerCase():null);if(!_)throw A();return _},async read(n,d,a){let i=r(n),l=d?.expectedActorAccountId;if(l!==void 0&&(typeof l!="string"||!b.test(l)))throw new w("bad_input","invalid_expected_actor");let y=await s(re,{admissionId:i,...l?{expectedActorAccountId:l}:{}},a),m=O(y.admission);if(!m||m.admissionId.toLowerCase()!==i)throw A();return m},async readOperation(n,d,a){if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_operation");let i=d?.expectedActorAccountId;if(typeof i!="string"||!b.test(i))throw new w("bad_input","invalid_expected_actor");let l=n.toLowerCase(),y=await s(oe,{operationId:l,expectedActorAccountId:i.toLowerCase()},a);if(y.schemaVersion!==1||typeof y.operationId!="string"||y.operationId.toLowerCase()!==l)throw A();if(y.state==="not-observed"&&y.admission===null)return{state:"not-observed",operationId:l,admission:null};if(y.state!=="committed")throw A();let m=O(y.admission);if(!m||m.operationId.toLowerCase()!==l)throw A();return{state:"committed",operationId:l,admission:m}},async readDefinition(n,d){let a=n?.resourceId;if(typeof a!="string"||!b.test(a))throw new w("bad_input","invalid_agent_resource");if(!Number.isSafeInteger(n.version)||n.version<1)throw new w("bad_input","invalid_version");if(typeof n.contentHash!="string"||!H.test(n.contentHash))throw new w("bad_input","invalid_content_hash");let i=n.expectedActorAccountId;if(typeof i!="string"||!b.test(i))throw new w("bad_input","invalid_expected_actor");let l={resourceId:a.toLowerCase(),version:n.version,contentHash:n.contentHash},y=await s(ie,{...l,expectedActorAccountId:i.toLowerCase()},d,ae),m=me(y,l);if(!m)throw A();return m},async authority(n,d){let a=r(n),i=z(await s(te,{admissionId:a},d),a);if(!i)throw A();return i}}}var W=class extends Error{code="RUN_AUTHORITY_REFUSED";retryable=!1;reason;step;constructor(o,t,c){super(`Run authority refused the ${o==="dispatch"?"provider dispatch":"tool call"}: ${t}`,c),this.name="RunAuthorityRefusedError",this.reason=t,this.step=o}};export{Z as RUN_LEASE_MAX_SECONDS,j as RUN_LEASE_SKEW_SECONDS,W as RunAuthorityRefusedError,I as RunStepRefused,w as WorkforceAdmissionRefused,ke as createWorkforceRunAdmissionClient,we as createWorkforceRunAuthority,U as verifyWorkforceRunLease,ge as workforceDefinitionContentHash};
1
+ import{createPublicKey as B,verify as J}from"node:crypto";var K="/api/workforce/run-admissions/authorize-step",q="/api/oauth2/jwks",Z=60,j=5,F="xeno-run-lease+jwt",Y=1e4,D=65536,I=class extends Error{constructor(t){super(`run step refused: ${t}`);this.reason=t;this.name="RunStepRefused",this.details={reason:t}}reason;details};function U(e,o){let t=i=>({valid:!1,reason:i}),c=typeof e=="string"?e.split("."):[];if(c.length!==3)return t("malformed");let s,r;try{s=JSON.parse(Buffer.from(c[0],"base64url").toString("utf8")),r=JSON.parse(Buffer.from(c[1],"base64url").toString("utf8"))}catch{return t("malformed")}if(s.alg!=="ES256"||s.typ!==F)return t("wrong_type");if(!o.publicKey)return t("unknown_key");if(!J("sha256",Buffer.from(`${c[0]}.${c[1]}`),{key:o.publicKey,dsaEncoding:"ieee-p1363"},Buffer.from(c[2],"base64url")))return t("bad_signature");if(r.iss!=="xeno-platform"||r.aud!=="xeno-run-runtime"||r.sub!==o.admissionId)return t("wrong_subject");if(!Number.isSafeInteger(r.iat)||!Number.isSafeInteger(r.exp)||r.exp<=r.iat||r.exp-r.iat>Z)return t("unbounded");if(!Array.isArray(r.caps)||!r.caps.every(i=>typeof i=="string"))return t("malformed");let d;try{d=BigInt(r.seq)}catch{return t("malformed")}if(d<o.minSequence)return t("superseded");if(o.nowWallMs/1e3>=r.exp-j)return t("expired");if(o.receivedAtMono===null)return t("requires_online_reauthorization");let a=(o.nowMono-o.receivedAtMono)/1e3;return a<0?t("requires_online_reauthorization"):a>=r.exp-r.iat-j?t("expired"):{valid:!0,sequence:d,claims:r}}async function X(e,o){let t=e.headers.get("content-length");if(t!==null&&(!/^\d+$/.test(t)||Number(t)>D))throw new Error("response too large");if(!e.body)return null;let c=e.body.getReader(),s=[],r=0;try{for(;;){let{done:a,value:i}=await c.read();if(o.aborted)throw new Error("response did not complete before the deadline");if(a)break;if(r+=i.byteLength,r>D)throw new Error("response too large");s.push(i)}}finally{try{c.releaseLock()}catch{}}let n=new Uint8Array(r),d=0;for(let a of s)n.set(a,d),d+=a.byteLength;return n.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)):null}function we(e){let o=e.fetchImpl??globalThis.fetch,t=e.clock??{wallMs:()=>Date.now(),monoMs:()=>performance.now()},c=e.admissionId;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c))throw new Error("invalid admission id");let s;try{s=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(s.protocol!=="https:"||s.pathname!=="/"||s.username||s.password||s.search||s.hash)throw new Error("invalid issuer");let r=s.origin,n=new Map,d=new Map,a=null,i=async(l,u,h)=>{let g=`${r}${u}`,R=new AbortController,A=setTimeout(()=>R.abort(),Y);A.unref?.();try{let v=null;if(l==="POST"&&(v=await e.authorizeRequest({method:l,url:g}),!v))throw new I("authority_unavailable");let C=await o(g,{method:l,redirect:"error",signal:R.signal,headers:{accept:"application/json",...h?{"content-type":"application/json"}:{},...v?{authorization:v.authorization,...v.dpop?{dpop:v.dpop}:{}}:{}},...h?{body:JSON.stringify(h)}:{}});return{status:C.status,json:await X(C,R.signal)}}finally{clearTimeout(A)}},f=async l=>{if(n.has(l))return n.get(l);let{status:u,json:h}=await i("GET",q);if(u!==200||!h||typeof h!="object"||!Array.isArray(h.keys))return null;for(let g of h.keys)if(!(typeof g.kid!="string"||g.kty!=="EC"||g.crv!=="P-256"))try{n.set(g.kid,B({key:{kty:"EC",crv:"P-256",x:g.x,y:g.y},format:"jwk"}))}catch{}return n.get(l)??null},y=()=>e.sequenceStore.read(c)??0n,m=(l,u)=>`${l}:${u??""}`,x=async l=>{let u=JSON.parse(Buffer.from(l.token.split(".")[0],"base64url").toString("utf8")).kid;return U(l.token,{publicKey:await f(u),admissionId:c,receivedAtMono:l.receivedAtMono,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()}).valid},_=async(l,u,h)=>{if(h.throwIfAborted(),a)throw new I(a);let g=d.get(m(l,u));if(l==="privileged_call"&&g&&await x(g).catch(()=>!1))return g.token;let R;try{R=await i("POST",K,{admissionId:c,operation:l,...u?{capability:u}:{}})}catch(T){throw T instanceof I?T:new I("authority_unavailable")}let A=R.json;if(R.status!==200||A?.success!==!0||typeof A.token!="string"){let T=typeof A?.details?.reason=="string"&&/^[a-z_]{1,64}$/.test(A.details.reason)?A.details.reason:"authority_unavailable";throw T==="admission_revoked"&&(a=T),new I(T)}let v=t.monoMs(),C=(()=>{try{return JSON.parse(Buffer.from(A.token.split(".")[0],"base64url").toString("utf8"))}catch{return null}})();if(typeof C?.kid!="string")throw new I("authority_unavailable");let S=U(A.token,{publicKey:await f(C.kid).catch(()=>null),admissionId:c,receivedAtMono:v,nowMono:t.monoMs(),nowWallMs:t.wallMs(),minSequence:y()});if(!S.valid||S.claims.op!==l||A.token.length<16||A.token.length>4096)throw new I("authority_unavailable");if(l==="privileged_call"&&S.claims.cap!==u)throw new I("authority_unavailable");return await e.sequenceStore.write(c,S.sequence),l==="privileged_call"&&d.set(m(l,u),{token:A.token,sequence:S.sequence,operation:l,capability:u,capabilities:S.claims.caps,iat:S.claims.iat,exp:S.claims.exp,receivedAtMono:v}),h.throwIfAborted(),A.token};return{admissionId:c,authorizeDispatch:async(l,u)=>Object.freeze({admissionId:c,lease:await _("provider_dispatch",null,u)}),authorizeToolCall:(l,u)=>{let h=e.capabilityForTool(l.toolName);return h===null||!/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/.test(h)?Promise.reject(new I("capability_not_admitted")):_("privileged_call",h,u).then(()=>{})}}}import{createHash as G}from"node:crypto";var Q="/api/workforce/run-admissions",ee="/api/workforce/run-admissions/revoke",te="/api/workforce/run-admissions/authority",ne="/api/workforce/run-admissions/pin",re="/api/workforce/run-admissions/read",oe="/api/workforce/run-admissions/operations/read",ie="/api/workforce/resources/definition/read",se=15e3,V=65536,ae=256*1024,ce=32768,L=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,de=/^[A-Z][A-Z0-9_]{0,63}$/,b=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,le=/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/,$=/^[a-z_]{1,64}$/,ue=new Set(["bad_input","denied","not_found","needs_approval","conflict","rate_limited","unavailable","timeout","internal"]),w=class extends Error{constructor(t,c,s={}){super(`workforce admission refused: ${t}/${c}`);this.code=t;this.reason=c;this.name="WorkforceAdmissionRefused",this.details={reason:c,...s}}code;reason;details},k=()=>new w("unavailable","authority_unavailable"),p=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),E=e=>Array.isArray(e)&&e.length<=64&&e.every(o=>typeof o=="string"&&le.test(o));function O(e){if(!p(e)||e.schemaVersion!==1||typeof e.admissionId!="string"||!b.test(e.admissionId)||typeof e.operationId!="string"||!b.test(e.operationId))return null;let o=e.agent;if(!p(o)||typeof o.resourceId!="string"||!b.test(o.resourceId)||!Number.isSafeInteger(o.version)||typeof o.contentHash!="string")return null;let t=e.capabilities;if(!p(t)||!E(t.effective)||!E(t.requested))return null;let c=e.payer;if(!p(c)||typeof c.kind!="string")return null;let s=e.budget;return!p(s)||typeof s.ceilingMicro!="string"||!/^[1-9][0-9]{0,17}$/.test(s.ceilingMicro)||!p(e.target)||typeof e.admittedAt!="string"||!Number.isFinite(Date.parse(e.admittedAt))?null:e}var H=/^[0-9a-f]{64}$/;function fe(e,o,t,c){if(!p(e)||e.schemaVersion!==1)return null;let s=e.agent;if(!p(s)||typeof s.resourceId!="string"||s.resourceId.toLowerCase()!==o||!Number.isSafeInteger(s.version)||s.version<1||typeof s.contentHash!="string"||!H.test(s.contentHash)||!p(e.target)||JSON.stringify(Object.entries(e.target).map(([d,a])=>[d,typeof a=="string"?a.toLowerCase():a]).sort())!==JSON.stringify(Object.entries(t).map(([d,a])=>[d,typeof a=="string"?a.toLowerCase():a]).sort()))return null;let r=e.team;if(c?!p(r)||typeof r.teamId!="string"||r.teamId.toLowerCase()!==c:r!==null)return null;let n=e.terms;return!p(n)||!E(n.definition)||!E(n.target)?null:{schemaVersion:1,agent:{resourceId:o,version:s.version,contentHash:s.contentHash},target:{...t},team:c?{teamId:c}:null,terms:{definition:[...n.definition],target:[...n.target]}}}function z(e,o){return!p(e)||e.schemaVersion!==1||e.admissionId!==o||typeof e.revoked!="boolean"?null:{schemaVersion:1,admissionId:o,revoked:e.revoked,reason:typeof e.reason=="string"&&$.test(e.reason)?e.reason:null,revokedAt:typeof e.revokedAt=="string"?e.revokedAt:null,latestLeaseSequence:typeof e.latestLeaseSequence=="string"?e.latestLeaseSequence:null}}function N(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(N):Object.fromEntries(Object.keys(e).sort().map(o=>[o,N(e[o])]))}function ge(e){return G("sha256").update(JSON.stringify(N({schemaVersion:1,content:e.content,provenance:e.provenance,license:e.license}))).digest("hex")}var M=(e,o)=>Object.keys(e).every(t=>o.includes(t)),P=(e,o)=>new Set(e.map(o)).size===e.length;function pe(e){if(!p(e)||!M(e,["instructions","skills","requestedCapabilities","secretReferences"]))return null;let{instructions:o,skills:t,requestedCapabilities:c,secretReferences:s}=e;return typeof o!="string"||o.includes("\0")||new TextEncoder().encode(o).byteLength>ce||!Array.isArray(t)||t.length>64||!t.every(r=>p(r)&&M(r,["id","version","hash"])&&typeof r.id=="string"&&L.test(r.id)&&typeof r.version=="string"&&L.test(r.version)&&typeof r.hash=="string"&&H.test(r.hash))||!P(t,r=>r.id)||!Array.isArray(c)||c.length>64||!c.every(r=>typeof r=="string"&&L.test(r))||!P(c,r=>r)||!Array.isArray(s)||s.length>32||!s.every(r=>p(r)&&M(r,["name","ref"])&&typeof r.name=="string"&&de.test(r.name)&&typeof r.ref=="string"&&b.test(r.ref))||!P(s,r=>r.name)?null:{instructions:o,skills:t.map(({id:r,version:n,hash:d})=>({id:r,version:n,hash:d})),requestedCapabilities:[...c],secretReferences:s.map(({name:r,ref:n})=>({name:r,ref:n}))}}function me(e,o){if(!p(e)||e.schemaVersion!==1||!p(e.access)||e.access.allowed!==!0)return null;let t=e.version;if(!p(t)||t.schemaVersion!==1||typeof t.resourceId!="string"||t.resourceId.toLowerCase()!==o.resourceId||t.version!==o.version||t.contentHash!==o.contentHash)return null;let c=pe(t.content);return!c||!p(t.provenance)||!p(t.license)||t.createdByUserId!==null&&(typeof t.createdByUserId!="string"||!b.test(t.createdByUserId))||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||ge({content:t.content,provenance:t.provenance,license:t.license})!==o.contentHash?null:{resourceId:o.resourceId,version:o.version,schemaVersion:1,content:c,contentHash:o.contentHash,provenance:t.provenance,license:t.license,createdByUserId:t.createdByUserId,createdAt:t.createdAt}}async function he(e,o,t=V){let c=e.headers.get("content-length");if(c!==null&&(!/^\d+$/.test(c)||Number(c)>t))throw new Error("response too large");if(!e.body)return null;let s=e.body.getReader(),r=[],n=0;try{for(;;){let{done:i,value:f}=await s.read();if(o.aborted)throw new Error("response did not complete before the deadline");if(i)break;if(n+=f.byteLength,n>t)throw new Error("response too large");r.push(f)}}finally{try{s.releaseLock()}catch{}}let d=new Uint8Array(n),a=0;for(let i of r)d.set(i,a),a+=i.byteLength;return d.length?JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)):null}function ke(e){let o=e.fetchImpl??globalThis.fetch,t;try{t=new URL(e.issuer)}catch{throw new Error("invalid issuer")}if(t.protocol!=="https:"||t.pathname!=="/"||t.username||t.password||t.search||t.hash)throw new Error("invalid issuer");let c=t.origin,s=async(n,d,a,i=V)=>{let f=`${c}${n}`,y=new AbortController,m=()=>y.abort();a?.addEventListener("abort",m,{once:!0});let x=setTimeout(m,se);x.unref?.();try{a?.throwIfAborted();let _=await e.authorizeRequest({method:"POST",url:f});if(!_)throw k();let l,u;try{l=await o(f,{method:"POST",redirect:"error",signal:y.signal,headers:{accept:"application/json","content-type":"application/json",authorization:_.authorization,..._.dpop?{dpop:_.dpop}:{}},body:JSON.stringify(d)}),u=await he(l,y.signal,i)}catch(R){throw a?.aborted?R:k()}if(l.status===200&&p(u)&&u.success===!0)return u;let h=p(u)&&typeof u.code=="string"&&ue.has(u.code)?u.code:null,g=p(u)&&p(u.details)?u.details:null;throw h&&g&&g.schemaVersion===1&&typeof g.reason=="string"&&$.test(g.reason)?new w(h,g.reason,{...Number.isSafeInteger(g.currentVersion)?{currentVersion:g.currentVersion}:{},...typeof g.availableMicro=="string"&&/^[0-9]{1,20}$/.test(g.availableMicro)?{availableMicro:g.availableMicro}:{},...typeof g.field=="string"&&/^[a-zA-Z.]{1,64}$/.test(g.field)?{field:g.field}:{}}):h?new w(h,h==="denied"&&l.status===403&&p(u)&&typeof u.required_scope=="string"?"insufficient_scope":h):k()}finally{clearTimeout(x),a?.removeEventListener("abort",m)}},r=n=>{if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_admission");return n.toLowerCase()};return{async admit(n,d){if(!b.test(n.operationId))throw new w("bad_input","invalid_operation");if(!E(n.capabilities))throw new w("bad_input","invalid_capabilities");if(n.runtimeCapabilities!==void 0&&!E(n.runtimeCapabilities))throw new w("bad_input","invalid_runtime_capabilities");if(!/^[1-9][0-9]{0,17}$/.test(n.budget?.ceilingMicro??""))throw new w("bad_input","invalid_budget_ceiling");let a={operationId:n.operationId,agent:{resourceId:n.agent.resourceId,version:n.agent.version,contentHash:n.agent.contentHash},target:{...n.target},capabilities:[...n.capabilities],budget:{ceilingMicro:n.budget.ceilingMicro},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{},...n.team?{team:{teamId:n.team.teamId}}:{},...n.conversationId?{conversationId:n.conversationId}:{},...n.root?{root:{bindingId:n.root.bindingId,installationId:n.root.installationId}}:{},...n.runtimeCapabilities?{runtimeCapabilities:[...n.runtimeCapabilities]}:{}},i=await s(Q,a,d),f=O(i.admission);if(!f||f.operationId.toLowerCase()!==n.operationId.toLowerCase())throw k();return{admission:f,replayed:i.replayed===!0}},async revoke(n,d){let a=r(n),i=z(await s(ee,{admissionId:a},d),a);if(!i||!i.revoked)throw k();return i},async pin(n,d){let a=n?.agent?.resourceId;if(typeof a!="string"||!b.test(a))throw new w("bad_input","invalid_agent_resource");let i=n.target,f=p(i)?i.kind==="personal"?[i.ownerUserId]:i.kind==="workspace"?[i.assignmentId]:i.kind==="project"?[i.projectId,i.participationId]:null:null;if(!f||!f.every(l=>typeof l=="string"&&b.test(l)))throw new w("bad_input","invalid_target");let y=i.kind==="personal"?{kind:"personal",ownerUserId:i.ownerUserId}:i.kind==="workspace"?{kind:"workspace",assignmentId:i.assignmentId}:{kind:"project",projectId:i.projectId,participationId:i.participationId},m=n.team?n.team.teamId:null;if(m!==null&&(typeof m!="string"||!b.test(m)))throw new w("bad_input","invalid_team");let x={agent:{resourceId:a},target:y,...m?{team:{teamId:m}}:{},...n.expectedActorAccountId?{expectedActorAccountId:n.expectedActorAccountId}:{}},_=fe(await s(ne,x,d),a.toLowerCase(),y,m?m.toLowerCase():null);if(!_)throw k();return _},async read(n,d,a){let i=r(n),f=d?.expectedActorAccountId;if(f!==void 0&&(typeof f!="string"||!b.test(f)))throw new w("bad_input","invalid_expected_actor");let y=await s(re,{admissionId:i,...f?{expectedActorAccountId:f}:{}},a),m=O(y.admission);if(!m||m.admissionId.toLowerCase()!==i)throw k();return m},async readOperation(n,d,a){if(typeof n!="string"||!b.test(n))throw new w("bad_input","invalid_operation");let i=d?.expectedActorAccountId;if(typeof i!="string"||!b.test(i))throw new w("bad_input","invalid_expected_actor");let f=n.toLowerCase(),y=await s(oe,{operationId:f,expectedActorAccountId:i.toLowerCase()},a);if(y.schemaVersion!==1||typeof y.operationId!="string"||y.operationId.toLowerCase()!==f)throw k();if(y.state==="not-observed"&&y.admission===null)return{state:"not-observed",operationId:f,admission:null};if(y.state!=="committed")throw k();let m=O(y.admission);if(!m||m.operationId.toLowerCase()!==f)throw k();return{state:"committed",operationId:f,admission:m}},async readDefinition(n,d){let a=n?.resourceId;if(typeof a!="string"||!b.test(a))throw new w("bad_input","invalid_agent_resource");if(!Number.isSafeInteger(n.version)||n.version<1)throw new w("bad_input","invalid_version");if(typeof n.contentHash!="string"||!H.test(n.contentHash))throw new w("bad_input","invalid_content_hash");let i=n.expectedActorAccountId;if(typeof i!="string"||!b.test(i))throw new w("bad_input","invalid_expected_actor");let f={resourceId:a.toLowerCase(),version:n.version,contentHash:n.contentHash},y=await s(ie,{...f,expectedActorAccountId:i.toLowerCase()},d,ae),m=me(y,f);if(!m)throw k();return m},async authority(n,d){let a=r(n),i=z(await s(te,{admissionId:a},d),a);if(!i)throw k();return i}}}var W=class extends Error{code="RUN_AUTHORITY_REFUSED";retryable=!1;reason;step;constructor(o,t,c){super(`Run authority refused the ${o==="dispatch"?"provider dispatch":"tool call"}: ${t}`,c),this.name="RunAuthorityRefusedError",this.reason=t,this.step=o}};export{Z as RUN_LEASE_MAX_SECONDS,j as RUN_LEASE_SKEW_SECONDS,W as RunAuthorityRefusedError,I as RunStepRefused,w as WorkforceAdmissionRefused,ke as createWorkforceRunAdmissionClient,we as createWorkforceRunAuthority,U as verifyWorkforceRunLease,ge as workforceDefinitionContentHash};
@@ -1 +1 @@
1
- {"inputs":{"src/workforce/run-authority-client.ts":{"bytes":15410,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/workforce/run-admission-client.ts":{"bytes":32982,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/core/agent-loop/run-authority.ts":{"bytes":4631,"imports":[],"format":"esm"},"src/workforce/index.ts":{"bytes":745,"imports":[{"path":"src/workforce/run-authority-client.ts","kind":"import-statement","original":"./run-authority-client.js"},{"path":"src/workforce/run-admission-client.ts","kind":"import-statement","original":"./run-admission-client.js"},{"path":"src/core/agent-loop/run-authority.ts","kind":"import-statement","original":"../core/agent-loop/run-authority.js"}],"format":"esm"}},"outputs":{"dist/workforce/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/workforce/index.ts","inputs":{"src/workforce/index.ts":{"bytesInOutput":324},"src/workforce/run-authority-client.ts":{"bytesInOutput":5223},"src/workforce/run-admission-client.ts":{"bytesInOutput":11100},"src/core/agent-loop/run-authority.ts":{"bytesInOutput":257}},"bytes":17581}}}
1
+ {"inputs":{"src/workforce/run-authority-client.ts":{"bytes":15708,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/workforce/run-admission-client.ts":{"bytes":32982,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/core/agent-loop/run-authority.ts":{"bytes":5025,"imports":[],"format":"esm"},"src/workforce/index.ts":{"bytes":768,"imports":[{"path":"src/workforce/run-authority-client.ts","kind":"import-statement","original":"./run-authority-client.js"},{"path":"src/workforce/run-admission-client.ts","kind":"import-statement","original":"./run-admission-client.js"},{"path":"src/core/agent-loop/run-authority.ts","kind":"import-statement","original":"../core/agent-loop/run-authority.js"}],"format":"esm"}},"outputs":{"dist/workforce/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/workforce/index.ts","inputs":{"src/workforce/index.ts":{"bytesInOutput":324},"src/workforce/run-authority-client.ts":{"bytesInOutput":5443},"src/workforce/run-admission-client.ts":{"bytesInOutput":11100},"src/core/agent-loop/run-authority.ts":{"bytesInOutput":257}},"bytes":17801}}}
@@ -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":32982,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/core/agent-loop/run-authority.ts":{"bytes":4631,"imports":[],"format":"esm"},"src/workforce/index.ts":{"bytes":745,"imports":[{"path":"src/workforce/run-authority-client.ts","kind":"import-statement","original":"./run-authority-client.js"},{"path":"src/workforce/run-admission-client.ts","kind":"import-statement","original":"./run-admission-client.js"},{"path":"src/core/agent-loop/run-authority.ts","kind":"import-statement","original":"../core/agent-loop/run-authority.js"}],"format":"esm"}},"outputs":{"dist/workforce/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["RUN_LEASE_MAX_SECONDS","RUN_LEASE_SKEW_SECONDS","RunAuthorityRefusedError","RunStepRefused","WorkforceAdmissionRefused","createWorkforceRunAdmissionClient","createWorkforceRunAuthority","verifyWorkforceRunLease","workforceDefinitionContentHash"],"entryPoint":"src/workforce/index.ts","inputs":{"src/workforce/run-authority-client.ts":{"bytesInOutput":5215},"src/workforce/index.ts":{"bytesInOutput":0},"src/workforce/run-admission-client.ts":{"bytesInOutput":11102},"src/core/agent-loop/run-authority.ts":{"bytesInOutput":257}},"bytes":16859}}}
1
+ {"inputs":{"src/workforce/run-authority-client.ts":{"bytes":15708,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/workforce/run-admission-client.ts":{"bytes":32982,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/core/agent-loop/run-authority.ts":{"bytes":5025,"imports":[],"format":"esm"},"src/workforce/index.ts":{"bytes":768,"imports":[{"path":"src/workforce/run-authority-client.ts","kind":"import-statement","original":"./run-authority-client.js"},{"path":"src/workforce/run-admission-client.ts","kind":"import-statement","original":"./run-admission-client.js"},{"path":"src/core/agent-loop/run-authority.ts","kind":"import-statement","original":"../core/agent-loop/run-authority.js"}],"format":"esm"}},"outputs":{"dist/workforce/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true}],"exports":["RUN_LEASE_MAX_SECONDS","RUN_LEASE_SKEW_SECONDS","RunAuthorityRefusedError","RunStepRefused","WorkforceAdmissionRefused","createWorkforceRunAdmissionClient","createWorkforceRunAuthority","verifyWorkforceRunLease","workforceDefinitionContentHash"],"entryPoint":"src/workforce/index.ts","inputs":{"src/workforce/run-authority-client.ts":{"bytesInOutput":5435},"src/workforce/index.ts":{"bytesInOutput":0},"src/workforce/run-admission-client.ts":{"bytesInOutput":11102},"src/core/agent-loop/run-authority.ts":{"bytesInOutput":257}},"bytes":17079}}}
@@ -22,7 +22,7 @@
22
22
  "sourceRoots": [
23
23
  "src"
24
24
  ],
25
- "reportDirectory": "docs/compliance"
25
+ "reportDirectory": "docs/compliance/memos"
26
26
  },
27
27
  "cli": {
28
28
  "label": "@xenosystem/agent-cli",
@@ -37,7 +37,7 @@
37
37
  "additionalOwnedSourceRoots": [
38
38
  "../xeno-agent-sdk/src"
39
39
  ],
40
- "reportDirectory": "docs/compliance"
40
+ "reportDirectory": "docs/compliance/memos"
41
41
  }
42
42
  },
43
43
  "runtimeComponents": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xenosystem/agent-sdk",
3
- "version": "0.10.34",
3
+ "version": "0.10.36",
4
4
  "description": "XENO Agent SDK built from the same engine as XENO CODE",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",