@xenosystem/agent-sdk 0.9.9 → 0.9.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/index.cjs +9 -9
- package/dist/agents/index.d.cts +12 -2
- package/dist/agents/index.d.ts +12 -2
- package/dist/agents/index.js +16 -16
- package/dist/agents/metafile-cjs.json +1 -1
- package/dist/agents/metafile-esm.json +1 -1
- package/dist/artifacts/browser.cjs +1 -1
- package/dist/artifacts/browser.d.cts +2 -2
- package/dist/artifacts/browser.d.ts +2 -2
- package/dist/artifacts/browser.js +1 -1
- package/dist/artifacts/{diff-artifact-C2tQZWcs.d.cts → diff-artifact-CmhmeSu5.d.cts} +87 -7
- package/dist/artifacts/{diff-artifact-C2tQZWcs.d.ts → diff-artifact-CmhmeSu5.d.ts} +87 -7
- package/dist/artifacts/index.cjs +8 -8
- package/dist/artifacts/index.d.cts +22 -5
- package/dist/artifacts/index.d.ts +22 -5
- package/dist/artifacts/index.js +8 -8
- package/dist/artifacts/metafile-cjs.json +1 -1
- package/dist/artifacts/metafile-esm.json +1 -1
- package/dist/automation/index.cjs +2 -2
- package/dist/automation/index.d.cts +97 -7
- package/dist/automation/index.d.ts +97 -7
- package/dist/automation/index.js +2 -2
- package/dist/automation/metafile-cjs.json +1 -1
- package/dist/automation/metafile-esm.json +1 -1
- package/dist/control-plane/index.cjs +7 -7
- package/dist/control-plane/index.d.cts +19 -2
- package/dist/control-plane/index.d.ts +19 -2
- package/dist/control-plane/index.js +7 -7
- package/dist/control-plane/metafile-cjs.json +1 -1
- package/dist/control-plane/metafile-esm.json +1 -1
- package/dist/electron/index.cjs +146 -144
- package/dist/electron/index.d.cts +54 -2
- package/dist/electron/index.d.ts +54 -2
- package/dist/electron/index.js +145 -143
- package/dist/electron/metafile-cjs.json +1 -1
- package/dist/electron/metafile-esm.json +1 -1
- package/dist/hooks/index.d.cts +10 -1
- package/dist/hooks/index.d.ts +10 -1
- package/dist/hosted/index.cjs +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/hosted/metafile-cjs.json +1 -1
- package/dist/hosted/metafile-esm.json +1 -1
- package/dist/index.cjs +340 -338
- package/dist/index.d.cts +223 -23
- package/dist/index.d.ts +223 -23
- package/dist/index.js +340 -338
- package/dist/mcp/index.cjs +17 -17
- package/dist/mcp/index.js +17 -17
- package/dist/mcp/metafile-cjs.json +1 -1
- package/dist/mcp/metafile-esm.json +1 -1
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/oracle/index.cjs +1 -1
- package/dist/oracle/index.d.cts +86 -6
- package/dist/oracle/index.d.ts +86 -6
- package/dist/oracle/index.js +1 -1
- package/dist/oracle/metafile-cjs.json +1 -1
- package/dist/oracle/metafile-esm.json +1 -1
- package/dist/providers/index.cjs +10 -10
- package/dist/providers/index.d.cts +1 -0
- package/dist/providers/index.d.ts +1 -0
- package/dist/providers/index.js +10 -10
- package/dist/providers/metafile-cjs.json +1 -1
- package/dist/providers/metafile-esm.json +1 -1
- package/dist/recipes/index.cjs +2 -2
- package/dist/recipes/index.d.cts +10 -1
- package/dist/recipes/index.d.ts +10 -1
- package/dist/recipes/index.js +2 -2
- package/dist/recipes/metafile-cjs.json +1 -1
- package/dist/recipes/metafile-esm.json +1 -1
- package/dist/research/index.cjs +3 -3
- package/dist/research/index.d.cts +86 -6
- package/dist/research/index.d.ts +86 -6
- package/dist/research/index.js +3 -3
- package/dist/research/metafile-cjs.json +1 -1
- package/dist/research/metafile-esm.json +1 -1
- package/dist/session/index.cjs +20 -20
- package/dist/session/index.js +21 -21
- package/dist/session/metafile-cjs.json +1 -1
- package/dist/session/metafile-esm.json +1 -1
- package/dist/utils/index.cjs +20 -20
- package/dist/utils/index.d.cts +3 -1
- package/dist/utils/index.d.ts +3 -1
- package/dist/utils/index.js +17 -17
- package/dist/utils/metafile-cjs.json +1 -1
- package/dist/utils/metafile-esm.json +1 -1
- package/package.json +4 -3
package/dist/utils/index.cjs
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
"use strict";var mt=Object.create;var
|
|
2
|
-
`,"utf-8")}function
|
|
3
|
-
`)?"CRLF":"LF"}function
|
|
1
|
+
"use strict";var mt=Object.create;var E=Object.defineProperty;var ht=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var yt=Object.getPrototypeOf,bt=Object.prototype.hasOwnProperty;var wt=(t,e)=>{for(var n in e)E(t,n,{get:e[n],enumerable:!0})},B=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of xt(e))!bt.call(t,o)&&o!==n&&E(t,o,{get:()=>e[o],enumerable:!(r=ht(e,o))||r.enumerable});return t};var _=(t,e,n)=>(n=t!=null?mt(yt(t)):{},B(e||!t||!t.__esModule?E(n,"default",{value:t,enumerable:!0}):n,t)),Et=t=>B(E({},"__esModule",{value:!0}),t);var Ge={};wt(Ge,{ApiTransientError:()=>w,HOME_DIR:()=>Kt,IS_LINUX:()=>Ut,IS_MAC:()=>Gt,IS_WINDOWS:()=>K,LogLevel:()=>Z,OS_VERSION:()=>Yt,PLATFORM:()=>R,accountTextTokens:()=>be,appendLine:()=>At,benchmarkLeakError:()=>Pe,buildToolResultBlock:()=>Je,buildToolResultText:()=>gt,calculateCost:()=>ke,commandMentionsBenchmarkLeak:()=>Ie,conservativeTokenAccountingAdapter:()=>rt,copyTextToClipboard:()=>Me,createSafeRegex:()=>se,debug:()=>le,decodeTextBuffer:()=>F,deleteDir:()=>Bt,deleteFile:()=>Lt,detectLineEnding:()=>j,detectPreferredLineEnding:()=>Ct,detectTextEncoding:()=>I,encodeTextBuffer:()=>W,ensureDir:()=>S,error:()=>pe,estimateTokens:()=>ot,estimateTokensForModel:()=>nt,existsSync:()=>Nt,filterBenchmarkLeakPaths:()=>Be,findSimilarFile:()=>St,fitsInBudget:()=>Ee,formatCost:()=>Ae,getAgentHome:()=>Qt,getBenchmarkReferenceOverwriteHint:()=>De,getBoolean:()=>ie,getConfigDir:()=>Zt,getLogLevel:()=>ce,getNumber:()=>oe,getProjectConfigDir:()=>Vt,getRetryErrorContext:()=>N,getShellName:()=>te,getString:()=>re,getToolResultTransportContent:()=>je,hasDir:()=>Tt,hasDisallowedAsciiControlCharacter:()=>ze,hasFile:()=>Rt,hasFrontmatter:()=>jt,hasNonTextToolResultContent:()=>He,hasTransientStatusMention:()=>tt,info:()=>fe,isBenchmarkLeakPath:()=>O,isBenchmarkMode:()=>v,isGitRepo:()=>ee,isPathSafe:()=>U,isRetryableError:()=>et,listDirs:()=>Ot,listFiles:()=>vt,normalizeLineEndings:()=>q,parseDocument:()=>Ft,parseJsonLines:()=>Dt,readFileSafe:()=>kt,readIfExists:()=>$t,readTextFile:()=>H,remainingBudget:()=>Re,safeJsonParse:()=>Pt,safeJsonStringify:()=>It,safeRegexTest:()=>ae,safeResolvePath:()=>zt,setLogLevel:()=>ue,stringifyDocument:()=>Wt,toTransportAssistantBlocks:()=>Xe,toolAssistantContentToText:()=>dt,toolResultContentToText:()=>We,truncateToTokens:()=>we,validateRegexPattern:()=>Q,validateRequired:()=>ne,warn:()=>de,withRetry:()=>ye,writeAtomic:()=>P,writeTextFile:()=>Mt});module.exports=Et(Ge);var b=require("node:fs"),h=require("node:fs"),c=_(require("node:fs/promises"),1),a=_(require("node:path"),1);function Rt(t){try{return(0,h.existsSync)(t)&&(0,h.statSync)(t).isFile()}catch{return!1}}function Tt(t){try{return(0,h.existsSync)(t)&&(0,h.statSync)(t).isDirectory()}catch{return!1}}function kt(t,e=""){try{return(0,b.readFileSync)(t,"utf-8")}catch{return e}}async function S(t){await c.mkdir(t,{recursive:!0})}async function P(t,e){let n=a.dirname(t);await S(n);let r=Math.random().toString(36).substring(2,15),o=`${t}.tmp.${process.pid}.${r}`;try{await c.writeFile(o,e),await c.rename(o,t)}finally{try{await c.unlink(o)}catch{}}}async function At(t,e){let n=a.dirname(t);await S(n),await c.appendFile(t,e+`
|
|
2
|
+
`,"utf-8")}function I(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 D(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 F(t,e){switch(e){case"utf8-bom":return t.subarray(3).toString("utf8");case"utf16le":return t.subarray(2).toString("utf16le");case"utf16be":return D(t.subarray(2)).toString("utf16le");default:return t.toString("utf8")}}function W(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]),D(Buffer.from(t,"utf16le"))]);default:return Buffer.from(t,"utf8")}}function j(t){return t.includes(`\r
|
|
3
|
+
`)?"CRLF":"LF"}function q(t,e){let n=t.replace(/\r\n/g,`
|
|
4
4
|
`);return e==="CRLF"?n.replace(/\n/g,`\r
|
|
5
|
-
`):n}async function
|
|
6
|
-
`)){let r=n.trim();if(r)try{e.push(JSON.parse(r))}catch{}}return e}function
|
|
7
|
-
`)}function
|
|
8
|
-
`)),nextIndex:r}}function
|
|
5
|
+
`):n}async function H(t){let e=await c.readFile(t),n=I(e),r=F(e,n);return{content:r,encoding:n,lineEnding:j(r),sizeBytes:e.length}}async function Mt(t,e,n){let r=q(e,n?.lineEnding??"LF");await P(t,W(r,n?.encoding??"utf8"))}async function Ct(t){let e=new Set,n=a.resolve(t);for(;!e.has(n);){e.add(n);try{let o=(0,b.readdirSync)(n,{withFileTypes:!0}).filter(i=>i.isFile()).map(i=>i.name).sort();for(let i of o){if(i.startsWith("."))continue;let s=a.extname(i).toLowerCase();if([".ts",".tsx",".js",".jsx",".json",".md",".txt",".yaml",".yml",".css",".html",".xml",".sh",".ps1"].includes(s))try{let u=a.join(n,i),l=await H(u);if(l.content.length>0)return l.lineEnding}catch{}}}catch{}let r=a.dirname(n);if(r===n)break;n=r}return"LF"}function _t(t,e,n){let r=[],o=[{dir:t,depth:0}],i=new Set;for(;o.length>0&&r.length<n;){let s=o.shift();if(!i.has(s.dir)){i.add(s.dir);try{let u=(0,b.readdirSync)(s.dir,{withFileTypes:!0});for(let l of u){let d=a.join(s.dir,l.name);if(l.isFile()){if(r.push(d),r.length>=n)break;continue}l.isDirectory()&&s.depth<e&&!l.name.startsWith(".")&&l.name!=="node_modules"&&o.push({dir:d,depth:s.depth+1})}}catch{}}}return r}function St(t){try{let e=a.dirname(t),n=a.basename(t,a.extname(t)).toLowerCase(),r=a.basename(t).toLowerCase(),i=[e,a.dirname(e)].flatMap(u=>_t(u,2,500)),s=null;for(let u of i){let l=a.basename(u).toLowerCase(),d=a.basename(u,a.extname(u)).toLowerCase(),m=null;if(l===r?m=0:d===n?m=1:(l.includes(n)||n.includes(d))&&(m=2),m===null)continue;let C=a.relative(e,u).split(a.sep).length,L=m+C*.01;(!s||L<s.score)&&(s={filePath:u,score:L})}return s?.filePath??null}catch{}return null}async function $t(t){try{return await c.readFile(t,"utf-8")}catch(e){if(e.code==="ENOENT")return null;throw e}}function Nt(t){return(0,h.existsSync)(t)}async function vt(t,e){try{let r=(await c.readdir(t,{withFileTypes:!0})).filter(o=>o.isFile()).map(o=>a.join(t,o.name));return e&&(r=r.filter(o=>e.test(a.basename(o)))),r}catch(n){if(n.code==="ENOENT")return[];throw n}}async function Ot(t){try{return(await c.readdir(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>a.join(t,n.name))}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Lt(t){try{await c.unlink(t)}catch(e){if(e.code!=="ENOENT")throw e}}async function Bt(t){try{await c.rm(t,{recursive:!0,force:!0})}catch(e){if(e.code!=="ENOENT")throw e}}function Pt(t,e){try{return JSON.parse(t)}catch{return e}}function It(t,e="{}"){try{return JSON.stringify(t)}catch{return e}}function Dt(t){let e=[];for(let n of t.split(`
|
|
6
|
+
`)){let r=n.trim();if(r)try{e.push(JSON.parse(r))}catch{}}return e}function Ft(t){let e=qt(t);return{frontmatter:e.frontmatter,content:e.content.trim()}}function Wt(t,e){let n=Object.fromEntries(Object.entries(t).filter(([r,o])=>o!==void 0));return["---",G(n),"---","",e].join(`
|
|
7
|
+
`)}function jt(t){return t.trimStart().startsWith("---")}function qt(t){let e=t.replace(/^\uFEFF/,"");if(!e.startsWith("---"))return{frontmatter:{},content:t};let n=e.search(/\r?\n/);if(n<0||e.slice(0,n).trim()!=="---")return{frontmatter:{},content:t};let r=e.slice(n+(e[n]==="\r"?2:1)),o=r.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!o||o.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=r.slice(0,o.index),s=o[0],u=o.index+s.length;return{frontmatter:J(i),content:r.slice(u)}}function J(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=Xt(o,r+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){e[i.key]=z(i.value,r+1);continue}let s=Ht(n,r+1);e[i.key]=s.value,r=s.nextIndex-1}return e}function Ht(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)=>z(i.trimStart().slice(2),e+s+1)),nextIndex:r}:{value:J(n.join(`
|
|
8
|
+
`)),nextIndex:r}}function Xt(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 z(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 X(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 X(t,e);if(t.includes("[")||t.includes("]")||t.includes("{")||t.includes("}"))throw new Error(`Unsupported YAML scalar at line ${e}.`);return t}function X(t,e){try{return JSON.parse(t)}catch{throw new Error(`Invalid YAML scalar at line ${e}.`)}}function G(t,e=""){return Object.entries(t).map(([n,r])=>Jt(n,r,e)).join(`
|
|
9
9
|
`)}function Jt(t,e,n){return Array.isArray(e)?`${n}${t}: ${JSON.stringify(e)}`:e&&typeof e=="object"?`${n}${t}:
|
|
10
|
-
${
|
|
11
|
-
`):process.stderr.write(`[${
|
|
12
|
-
`))}function
|
|
13
|
-
`):process.stderr.write(`[${
|
|
14
|
-
`))}function
|
|
15
|
-
`):process.stderr.write(`[${
|
|
16
|
-
`))}function
|
|
17
|
-
`):process.stderr.write(`[${
|
|
18
|
-
`))}function
|
|
19
|
-
`):null}function
|
|
10
|
+
${G(e,`${n} `)}`:`${n}${t}: ${JSON.stringify(e)}`}var f=_(require("path"),1);function U(t,e){let n=f.resolve(t),r=f.resolve(t,e);return r===n?!0:n===f.parse(n).root?r.startsWith(n):r.startsWith(n+f.sep)}function zt(t,e){if(f.isAbsolute(e))return f.resolve(e);if(!U(t,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return f.resolve(t,e)}var p=require("node:os"),Y=require("node:child_process"),x=require("node:path"),R=(0,p.platform)(),K=R==="win32",Gt=R==="darwin",Ut=R==="linux",Yt=(0,p.release)(),Kt=(0,p.homedir)();function Qt(){let t=process.env.XENO_AGENT_HOME?.trim();return t?(0,x.resolve)(t):(0,x.resolve)((0,p.homedir)(),".xeno-agent")}function Zt(){let t=process.env.XENO_CONFIG_DIR?.trim();return t?(0,x.resolve)(t):(0,x.resolve)((0,p.homedir)(),".xeno-code")}function Vt(t){return(0,x.resolve)(t,".xeno-code")}function te(){return K?"powershell":process.env.SHELL?.split("/").pop()??"bash"}function ee(t){try{return(0,Y.execSync)("git rev-parse --is-inside-work-tree",{cwd:t,stdio:"ignore"}),!0}catch{return!1}}function ne(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 re(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 oe(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 ie(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 Q(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 se(t,e,n=5e3){let r=Q(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 ae(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 Z=(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))(Z||{}),y=1;function ue(t){y=t}function ce(){return y}function g(){return new Date().toISOString()}function le(t,e){y<=0&&(e!==void 0?process.stderr.write(`[${g()}] DEBUG: ${t} ${T(e)}
|
|
11
|
+
`):process.stderr.write(`[${g()}] DEBUG: ${t}
|
|
12
|
+
`))}function fe(t,e){y<=1&&(e!==void 0?process.stderr.write(`[${g()}] INFO: ${t} ${T(e)}
|
|
13
|
+
`):process.stderr.write(`[${g()}] INFO: ${t}
|
|
14
|
+
`))}function de(t,e){y<=2&&(e!==void 0?process.stderr.write(`[${g()}] WARN: ${t} ${T(e)}
|
|
15
|
+
`):process.stderr.write(`[${g()}] WARN: ${t}
|
|
16
|
+
`))}function pe(t,e){y<=3&&(e!==void 0?process.stderr.write(`[${g()}] ERROR: ${t} ${T(e)}
|
|
17
|
+
`):process.stderr.write(`[${g()}] ERROR: ${t}
|
|
18
|
+
`))}function T(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 w=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}},k={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function A(t,e){let n=process.env[t],r=n?Number.parseInt(n,10):Number.NaN;return!Number.isFinite(r)||r<0?e:r}function ge(t={}){let e=Math.max(0,t.maxRetries??A("XENO_API_MAX_RETRIES",k.maxRetries)),n=Math.max(50,t.baseDelayMs??A("XENO_API_BASE_DELAY_MS",k.baseDelayMs)),r=Math.max(n,t.maxDelayMs??A("XENO_API_MAX_DELAY_MS",k.maxDelayMs)),o=Math.max(0,t.jitterMs??A("XENO_API_RETRY_JITTER_MS",k.jitterMs));return{maxRetries:e,baseDelayMs:n,maxDelayMs:r,jitterMs:o}}function me(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 V(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("too many requests")||e.includes("429")}function he(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 N(t){if(t instanceof w)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 V(n)?{statusCode:429}:{}}var $="408|425|429|500|502|503|504";function tt(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 et(t){if(t&&typeof t=="object"&&"retryable"in t)return t.retryable===!0;if(t instanceof w){let{statusCode:e}=N(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:tt(t.message)?!0:V(t.message)||he(t.message.toLowerCase())}return!1}function xe(t){if(t.onAbort)return t.onAbort();let e=new Error("The operation was aborted");return e.name="AbortError",e}async function ye(t,e={}){let n=ge(e),r;for(let o=0;o<=n.maxRetries;o++)try{if(e.signal?.aborted)throw xe(e);return e.onBeforeAttempt?.(o),await t()}catch(i){if(r=i,!(e.shouldRetry?e.shouldRetry(i,o):et(i))||o===n.maxRetries)throw i;let u=N(i),l=me(o,u,n),d=e.getDelayMs?.(i,o,l),m=typeof d=="number"&&d>=0?d:l;await new Promise(C=>setTimeout(C,m))}throw r}var nt=(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))},rt=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:nt,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 be(t,e,n=rt){return{tokens:Math.max(0,Math.ceil(n.countText(t,e))),source:n.source,adapterId:n.id}}function ot(t){return t?Math.ceil(t.length/4):0}function we(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 Ee(t,e){return ot(t)<=e}function Re(t,e){return Math.max(0,e-t)}var Te={"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 ke(t,e,n){let r=Te[t];return r?e/1e6*r.input+n/1e6*r.output:0}function Ae(t){return t<=0?"$0.00":t<.001?"<$0.001":t<.01?`$${t.toFixed(4)}`:t<1?`$${t.toFixed(3)}`:`$${t.toFixed(2)}`}var it=require("node:child_process");function Me(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=(0,it.spawnSync)(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 at(t){return t.replace(/\\/g,"/").toLowerCase()}var Ce=["golden","solution","answer","expected"],_e=["expected","golden","reference","answer","answers"],Se=new Set([";","&&","||","|"]);function ut(t){return at(t).replace(/^\.\/+/,"").split("/").map(e=>e.trim()).filter(e=>e.length>0)}function $e(t){return Ce.some(e=>t.includes(e))}function st(t){return _e.some(e=>t.includes(e))}function ct(t){return t.split("::",1)[0]?.split("?",1)[0]?.split("#",1)[0]??t}function M(t){let e=t.trim().replace(/^[({]+/,"").replace(/[),;]+$/,"");return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e}function Ne(t){return t.match(/"[^"]*"|'[^']*'|&&|\|\||[;|]|[^\s;|&]+/g)?.map(M).filter(e=>e.length>0)??[]}function lt(t){let e=ut(t),n=ct(e.at(-1)??"");return st(n)||e.some(r=>st(r))}function ft(t){let e=at(M(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 ve(t){return/[\\/]/.test(t)||/\.[A-Za-z0-9]{1,8}$/.test(t)}function Oe(t){let e=Ne(t);for(let n=0;n<e.length;n+=1){let r=e[n]?.toLowerCase();if(r!=="cp"&&r!=="mv"&&r!=="rsync"&&r!=="install")continue;let o=[];for(let s=n+1;s<e.length;s+=1){let u=e[s];if(!u||Se.has(u))break;u!=="--"&&(u.startsWith("-")||o.push(u))}if(o.length<2)continue;let i=o.at(-1);if(ft(i)){for(let s of o.slice(0,-1))if(ve(s)&<(s))return{sourcePath:s,destinationPath:i,operation:r}}}return null}function Le(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=M(r[1]??r[2]??r[3]??""),i=M(r[4]??r[5]??r[6]??"");if(!(!o||!i)&<(o)&&ft(i))return{sourcePath:o,destinationPath:i,operation:n.source.startsWith("\\bdd")?"dd":"redirect"}}return null}function v(){return process.env.XENO_BENCHMARK_MODE?.trim().toLowerCase()==="terminal-bench"}function O(t){let e=ut(t);if(e.includes("solution")||e.includes("xeno-audit")||e.includes(".xeno")&&e.includes("audit"))return!0;let n=ct(e.at(-1)??"");return e.includes("tests")&&$e(n)}function Be(t){return v()?t.filter(e=>!O(e)):t}function Pe(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 Ie(t){return t.split(/[\s"'`;|&]+/).map(e=>e.trim()).filter(e=>e.length>0&&/[\\/]/.test(e)).some(e=>O(e))}function De(t){if(!v())return null;let e=Oe(t)??Le(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(`
|
|
19
|
+
`):null}function Fe(t){return/^data:([^;,]+)[;,]/i.exec(t.trim())?.[1]}function dt(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 ${Fe(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(`
|
|
20
20
|
|
|
21
|
-
`).trim()}function
|
|
22
|
-
`)}function
|
|
23
|
-
`)}}function
|
|
21
|
+
`).trim()}function pt(t){let e=t.trim();return e.length>0?[{type:"text",text:e}]:[]}function We(t){return typeof t=="string"?t:dt(t)}function gt(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(`
|
|
22
|
+
`)}function je(t){let e=t.assistant_content&&t.assistant_content.length>0?t.assistant_content:typeof t.content=="string"?pt(t.content):t.content,n=t.assistant_only_content??[],r=qe(t),o=[...e,...n,...r?[r]:[]];return o.length>0?o:t.content}function qe(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(`
|
|
23
|
+
`)}}function He(t){return Array.isArray(t)&&t.some(e=>e.type!=="text")}function Xe(t){return typeof t=="string"?pt(t):t}function Je(t,e){return{type:"tool_result",tool_use_id:t,content:gt(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.retryable!==void 0?{retryable:e.retryable}:{}}}function ze(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}0&&(module.exports={ApiTransientError,HOME_DIR,IS_LINUX,IS_MAC,IS_WINDOWS,LogLevel,OS_VERSION,PLATFORM,accountTextTokens,appendLine,benchmarkLeakError,buildToolResultBlock,buildToolResultText,calculateCost,commandMentionsBenchmarkLeak,conservativeTokenAccountingAdapter,copyTextToClipboard,createSafeRegex,debug,decodeTextBuffer,deleteDir,deleteFile,detectLineEnding,detectPreferredLineEnding,detectTextEncoding,encodeTextBuffer,ensureDir,error,estimateTokens,estimateTokensForModel,existsSync,filterBenchmarkLeakPaths,findSimilarFile,fitsInBudget,formatCost,getAgentHome,getBenchmarkReferenceOverwriteHint,getBoolean,getConfigDir,getLogLevel,getNumber,getProjectConfigDir,getRetryErrorContext,getShellName,getString,getToolResultTransportContent,hasDir,hasDisallowedAsciiControlCharacter,hasFile,hasFrontmatter,hasNonTextToolResultContent,hasTransientStatusMention,info,isBenchmarkLeakPath,isBenchmarkMode,isGitRepo,isPathSafe,isRetryableError,listDirs,listFiles,normalizeLineEndings,parseDocument,parseJsonLines,readFileSafe,readIfExists,readTextFile,remainingBudget,safeJsonParse,safeJsonStringify,safeRegexTest,safeResolvePath,setLogLevel,stringifyDocument,toTransportAssistantBlocks,toolAssistantContentToText,toolResultContentToText,truncateToTokens,validateRegexPattern,validateRequired,warn,withRetry,writeAtomic,writeTextFile});
|
package/dist/utils/index.d.cts
CHANGED
|
@@ -48,6 +48,7 @@ declare const IS_MAC: boolean;
|
|
|
48
48
|
declare const IS_LINUX: boolean;
|
|
49
49
|
declare const OS_VERSION: string;
|
|
50
50
|
declare const HOME_DIR: string;
|
|
51
|
+
declare function getAgentHome(): string;
|
|
51
52
|
declare function getConfigDir(): string;
|
|
52
53
|
declare function getProjectConfigDir(cwd: string): string;
|
|
53
54
|
declare function getShellName(): string;
|
|
@@ -98,6 +99,7 @@ declare class ApiTransientError extends Error {
|
|
|
98
99
|
constructor(message: string, context?: RetryErrorContext);
|
|
99
100
|
}
|
|
100
101
|
declare function getRetryErrorContext(error: unknown): RetryErrorContext;
|
|
102
|
+
declare function hasTransientStatusMention(message: string): boolean;
|
|
101
103
|
declare function isRetryableError(error: unknown): boolean;
|
|
102
104
|
declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
103
105
|
type TokenEstimator = (text: string, model: string) => number;
|
|
@@ -242,4 +244,4 @@ interface XenoAsciiControlCharacterPolicy {
|
|
|
242
244
|
allowLineBreaks?: boolean;
|
|
243
245
|
}
|
|
244
246
|
declare function hasDisallowedAsciiControlCharacter(value: string, policy?: XenoAsciiControlCharacterPolicy): boolean;
|
|
245
|
-
export { ApiTransientError, HOME_DIR, IS_LINUX, IS_MAC, IS_WINDOWS, type LineEnding, LogLevel, OS_VERSION, PLATFORM, type ParsedDocument, type RetryErrorContext, type RetryOptions, type TextEncoding, type TextFileContents, type TokenAccountingAdapter, type TokenAccountingResult, type TokenAccountingSource, type TokenEstimator, type XenoAsciiControlCharacterPolicy, accountTextTokens, 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, getBenchmarkReferenceOverwriteHint, getBoolean, getConfigDir, getLogLevel, getNumber, getProjectConfigDir, getRetryErrorContext, getShellName, getString, getToolResultTransportContent, hasDir, hasDisallowedAsciiControlCharacter, hasFile, hasFrontmatter, hasNonTextToolResultContent, info, isBenchmarkLeakPath, isBenchmarkMode, isGitRepo, isPathSafe, isRetryableError, listDirs, listFiles, normalizeLineEndings, parseDocument, parseJsonLines, readFileSafe, readIfExists, readTextFile, remainingBudget, safeJsonParse, safeJsonStringify, safeRegexTest, safeResolvePath, setLogLevel, stringifyDocument, toTransportAssistantBlocks, toolAssistantContentToText, toolResultContentToText, truncateToTokens, validateRegexPattern, validateRequired, warn, withRetry, writeAtomic, writeTextFile };
|
|
247
|
+
export { ApiTransientError, HOME_DIR, IS_LINUX, IS_MAC, IS_WINDOWS, type LineEnding, LogLevel, OS_VERSION, PLATFORM, type ParsedDocument, type RetryErrorContext, type RetryOptions, type TextEncoding, type TextFileContents, type TokenAccountingAdapter, type TokenAccountingResult, type TokenAccountingSource, type TokenEstimator, type XenoAsciiControlCharacterPolicy, accountTextTokens, appendLine, benchmarkLeakError, buildToolResultBlock, buildToolResultText, calculateCost, commandMentionsBenchmarkLeak, conservativeTokenAccountingAdapter, copyTextToClipboard, createSafeRegex, debug, decodeTextBuffer, deleteDir, deleteFile, detectLineEnding, detectPreferredLineEnding, detectTextEncoding, encodeTextBuffer, ensureDir, error, estimateTokens, estimateTokensForModel, existsSync, filterBenchmarkLeakPaths, findSimilarFile, fitsInBudget, formatCost, getAgentHome, getBenchmarkReferenceOverwriteHint, getBoolean, getConfigDir, getLogLevel, getNumber, getProjectConfigDir, getRetryErrorContext, getShellName, getString, getToolResultTransportContent, hasDir, hasDisallowedAsciiControlCharacter, hasFile, hasFrontmatter, hasNonTextToolResultContent, hasTransientStatusMention, info, isBenchmarkLeakPath, isBenchmarkMode, isGitRepo, isPathSafe, isRetryableError, listDirs, listFiles, normalizeLineEndings, parseDocument, parseJsonLines, readFileSafe, readIfExists, readTextFile, remainingBudget, safeJsonParse, safeJsonStringify, safeRegexTest, safeResolvePath, setLogLevel, stringifyDocument, toTransportAssistantBlocks, toolAssistantContentToText, toolResultContentToText, truncateToTokens, validateRegexPattern, validateRequired, warn, withRetry, writeAtomic, writeTextFile };
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -48,6 +48,7 @@ declare const IS_MAC: boolean;
|
|
|
48
48
|
declare const IS_LINUX: boolean;
|
|
49
49
|
declare const OS_VERSION: string;
|
|
50
50
|
declare const HOME_DIR: string;
|
|
51
|
+
declare function getAgentHome(): string;
|
|
51
52
|
declare function getConfigDir(): string;
|
|
52
53
|
declare function getProjectConfigDir(cwd: string): string;
|
|
53
54
|
declare function getShellName(): string;
|
|
@@ -98,6 +99,7 @@ declare class ApiTransientError extends Error {
|
|
|
98
99
|
constructor(message: string, context?: RetryErrorContext);
|
|
99
100
|
}
|
|
100
101
|
declare function getRetryErrorContext(error: unknown): RetryErrorContext;
|
|
102
|
+
declare function hasTransientStatusMention(message: string): boolean;
|
|
101
103
|
declare function isRetryableError(error: unknown): boolean;
|
|
102
104
|
declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
103
105
|
type TokenEstimator = (text: string, model: string) => number;
|
|
@@ -242,4 +244,4 @@ interface XenoAsciiControlCharacterPolicy {
|
|
|
242
244
|
allowLineBreaks?: boolean;
|
|
243
245
|
}
|
|
244
246
|
declare function hasDisallowedAsciiControlCharacter(value: string, policy?: XenoAsciiControlCharacterPolicy): boolean;
|
|
245
|
-
export { ApiTransientError, HOME_DIR, IS_LINUX, IS_MAC, IS_WINDOWS, type LineEnding, LogLevel, OS_VERSION, PLATFORM, type ParsedDocument, type RetryErrorContext, type RetryOptions, type TextEncoding, type TextFileContents, type TokenAccountingAdapter, type TokenAccountingResult, type TokenAccountingSource, type TokenEstimator, type XenoAsciiControlCharacterPolicy, accountTextTokens, 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, getBenchmarkReferenceOverwriteHint, getBoolean, getConfigDir, getLogLevel, getNumber, getProjectConfigDir, getRetryErrorContext, getShellName, getString, getToolResultTransportContent, hasDir, hasDisallowedAsciiControlCharacter, hasFile, hasFrontmatter, hasNonTextToolResultContent, info, isBenchmarkLeakPath, isBenchmarkMode, isGitRepo, isPathSafe, isRetryableError, listDirs, listFiles, normalizeLineEndings, parseDocument, parseJsonLines, readFileSafe, readIfExists, readTextFile, remainingBudget, safeJsonParse, safeJsonStringify, safeRegexTest, safeResolvePath, setLogLevel, stringifyDocument, toTransportAssistantBlocks, toolAssistantContentToText, toolResultContentToText, truncateToTokens, validateRegexPattern, validateRequired, warn, withRetry, writeAtomic, writeTextFile };
|
|
247
|
+
export { ApiTransientError, HOME_DIR, IS_LINUX, IS_MAC, IS_WINDOWS, type LineEnding, LogLevel, OS_VERSION, PLATFORM, type ParsedDocument, type RetryErrorContext, type RetryOptions, type TextEncoding, type TextFileContents, type TokenAccountingAdapter, type TokenAccountingResult, type TokenAccountingSource, type TokenEstimator, type XenoAsciiControlCharacterPolicy, accountTextTokens, appendLine, benchmarkLeakError, buildToolResultBlock, buildToolResultText, calculateCost, commandMentionsBenchmarkLeak, conservativeTokenAccountingAdapter, copyTextToClipboard, createSafeRegex, debug, decodeTextBuffer, deleteDir, deleteFile, detectLineEnding, detectPreferredLineEnding, detectTextEncoding, encodeTextBuffer, ensureDir, error, estimateTokens, estimateTokensForModel, existsSync, filterBenchmarkLeakPaths, findSimilarFile, fitsInBudget, formatCost, getAgentHome, getBenchmarkReferenceOverwriteHint, getBoolean, getConfigDir, getLogLevel, getNumber, getProjectConfigDir, getRetryErrorContext, getShellName, getString, getToolResultTransportContent, hasDir, hasDisallowedAsciiControlCharacter, hasFile, hasFrontmatter, hasNonTextToolResultContent, hasTransientStatusMention, info, isBenchmarkLeakPath, isBenchmarkMode, isGitRepo, isPathSafe, isRetryableError, listDirs, listFiles, normalizeLineEndings, parseDocument, parseJsonLines, readFileSafe, readIfExists, readTextFile, remainingBudget, safeJsonParse, safeJsonStringify, safeRegexTest, safeResolvePath, setLogLevel, stringifyDocument, toTransportAssistantBlocks, toolAssistantContentToText, toolResultContentToText, truncateToTokens, validateRegexPattern, validateRequired, warn, withRetry, writeAtomic, writeTextFile };
|
package/dist/utils/index.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import{readdirSync as
|
|
2
|
-
`,"utf-8")}function Y(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
|
|
3
|
-
`)?"CRLF":"LF"}function
|
|
1
|
+
import{readdirSync as _,readFileSync as G}from"node:fs";import{existsSync as T,statSync as S}from"node:fs";import*as c from"node:fs/promises";import*as a from"node:path";function Dt(t){try{return T(t)&&S(t).isFile()}catch{return!1}}function Ft(t){try{return T(t)&&S(t).isDirectory()}catch{return!1}}function Wt(t,e=""){try{return G(t,"utf-8")}catch{return e}}async function $(t){await c.mkdir(t,{recursive:!0})}async function U(t,e){let n=a.dirname(t);await $(n);let r=Math.random().toString(36).substring(2,15),o=`${t}.tmp.${process.pid}.${r}`;try{await c.writeFile(o,e),await c.rename(o,t)}finally{try{await c.unlink(o)}catch{}}}async function jt(t,e){let n=a.dirname(t);await $(n),await c.appendFile(t,e+`
|
|
2
|
+
`,"utf-8")}function Y(t){return t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?"utf8-bom":t.length>=2&&t[0]===255&&t[1]===254?"utf16le":t.length>=2&&t[0]===254&&t[1]===255?"utf16be":"utf8"}function N(t){let e=Buffer.from(t);for(let n=0;n+1<e.length;n+=2){let r=e[n];e[n]=e[n+1],e[n+1]=r}return e}function K(t,e){switch(e){case"utf8-bom":return t.subarray(3).toString("utf8");case"utf16le":return t.subarray(2).toString("utf16le");case"utf16be":return N(t.subarray(2)).toString("utf16le");default:return t.toString("utf8")}}function Q(t,e){switch(e){case"utf8-bom":return Buffer.concat([Buffer.from([239,187,191]),Buffer.from(t,"utf8")]);case"utf16le":return Buffer.concat([Buffer.from([255,254]),Buffer.from(t,"utf16le")]);case"utf16be":return Buffer.concat([Buffer.from([254,255]),N(Buffer.from(t,"utf16le"))]);default:return Buffer.from(t,"utf8")}}function Z(t){return t.includes(`\r
|
|
3
|
+
`)?"CRLF":"LF"}function V(t,e){let n=t.replace(/\r\n/g,`
|
|
4
4
|
`);return e==="CRLF"?n.replace(/\n/g,`\r
|
|
5
|
-
`):n}async function
|
|
6
|
-
`)){let r=n.trim();if(r)try{e.push(JSON.parse(r))}catch{}}return e}function
|
|
7
|
-
`)}function
|
|
8
|
-
`)),nextIndex:r}}function
|
|
9
|
-
`)}function
|
|
10
|
-
${
|
|
5
|
+
`):n}async function tt(t){let e=await c.readFile(t),n=Y(e),r=K(e,n);return{content:r,encoding:n,lineEnding:Z(r),sizeBytes:e.length}}async function qt(t,e,n){let r=V(e,n?.lineEnding??"LF");await U(t,Q(r,n?.encoding??"utf8"))}async function Ht(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 u=a.join(n,i),l=await tt(u);if(l.content.length>0)return l.lineEnding}catch{}}}catch{}let r=a.dirname(n);if(r===n)break;n=r}return"LF"}function et(t,e,n){let r=[],o=[{dir:t,depth:0}],i=new Set;for(;o.length>0&&r.length<n;){let s=o.shift();if(!i.has(s.dir)){i.add(s.dir);try{let u=_(s.dir,{withFileTypes:!0});for(let l of u){let d=a.join(s.dir,l.name);if(l.isFile()){if(r.push(d),r.length>=n)break;continue}l.isDirectory()&&s.depth<e&&!l.name.startsWith(".")&&l.name!=="node_modules"&&o.push({dir:d,depth:s.depth+1})}}catch{}}}return r}function Xt(t){try{let e=a.dirname(t),n=a.basename(t,a.extname(t)).toLowerCase(),r=a.basename(t).toLowerCase(),i=[e,a.dirname(e)].flatMap(u=>et(u,2,500)),s=null;for(let u of i){let l=a.basename(u).toLowerCase(),d=a.basename(u,a.extname(u)).toLowerCase(),g=null;if(l===r?g=0:d===n?g=1:(l.includes(n)||n.includes(d))&&(g=2),g===null)continue;let R=a.relative(e,u).split(a.sep).length,C=g+R*.01;(!s||C<s.score)&&(s={filePath:u,score:C})}return s?.filePath??null}catch{}return null}async function Jt(t){try{return await c.readFile(t,"utf-8")}catch(e){if(e.code==="ENOENT")return null;throw e}}function zt(t){return T(t)}async function Gt(t,e){try{let r=(await c.readdir(t,{withFileTypes:!0})).filter(o=>o.isFile()).map(o=>a.join(t,o.name));return e&&(r=r.filter(o=>e.test(a.basename(o)))),r}catch(n){if(n.code==="ENOENT")return[];throw n}}async function Ut(t){try{return(await c.readdir(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>a.join(t,n.name))}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Yt(t){try{await c.unlink(t)}catch(e){if(e.code!=="ENOENT")throw e}}async function Kt(t){try{await c.rm(t,{recursive:!0,force:!0})}catch(e){if(e.code!=="ENOENT")throw e}}function Zt(t,e){try{return JSON.parse(t)}catch{return e}}function Vt(t,e="{}"){try{return JSON.stringify(t)}catch{return e}}function te(t){let e=[];for(let n of t.split(`
|
|
6
|
+
`)){let r=n.trim();if(r)try{e.push(JSON.parse(r))}catch{}}return e}function ne(t){let e=nt(t);return{frontmatter:e.frontmatter,content:e.content.trim()}}function re(t,e){let n=Object.fromEntries(Object.entries(t).filter(([r,o])=>o!==void 0));return["---",B(n),"---","",e].join(`
|
|
7
|
+
`)}function oe(t){return t.trimStart().startsWith("---")}function nt(t){let e=t.replace(/^\uFEFF/,"");if(!e.startsWith("---"))return{frontmatter:{},content:t};let n=e.search(/\r?\n/);if(n<0||e.slice(0,n).trim()!=="---")return{frontmatter:{},content:t};let r=e.slice(n+(e[n]==="\r"?2:1)),o=r.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!o||o.index===void 0)throw new Error("YAML frontmatter is not closed.");let i=r.slice(0,o.index),s=o[0],u=o.index+s.length;return{frontmatter:O(i),content:r.slice(u)}}function O(t){let e={},n=t.split(/\r?\n/);for(let r=0;r<n.length;r+=1){let o=n[r];if(!o.trim()||o.trimStart().startsWith("#"))continue;if(/^\s/.test(o))throw new Error(`Unexpected indentation at line ${r+1}.`);let i=ot(o,r+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){e[i.key]=L(i.value,r+1);continue}let s=rt(n,r+1);e[i.key]=s.value,r=s.nextIndex-1}return e}function rt(t,e){let n=[],r=e;for(;r<t.length;r+=1){let i=t[r];if(!i.trim()){n.push(i);continue}if(!/^\s/.test(i))break;n.push(i.replace(/^ {2}/,""))}let o=n.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return o.length===0?{value:{},nextIndex:r}:o.every(i=>i.trimStart().startsWith("- "))?{value:o.map((i,s)=>L(i.trimStart().slice(2),e+s+1)),nextIndex:r}:{value:O(n.join(`
|
|
8
|
+
`)),nextIndex:r}}function ot(t,e){let n=t.indexOf(":");if(n<=0)throw new Error(`Invalid YAML line ${e}.`);let r=t.slice(0,n).trim(),o=t.slice(n+1).trim();if(!r)throw new Error(`Invalid YAML key at line ${e}.`);return{key:r,value:o}}function L(t,e){if(t==="")return"";if(t==="[]")return[];if(t==="{}")return{};if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(t.startsWith('"'))return v(t,e);if(t.startsWith("'")){if(!t.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${e}.`);return t.slice(1,-1).replace(/''/g,"'")}if(t.startsWith("[")||t.startsWith("{"))return v(t,e);if(t.includes("[")||t.includes("]")||t.includes("{")||t.includes("}"))throw new Error(`Unsupported YAML scalar at line ${e}.`);return t}function v(t,e){try{return JSON.parse(t)}catch{throw new Error(`Invalid YAML scalar at line ${e}.`)}}function B(t,e=""){return Object.entries(t).map(([n,r])=>it(n,r,e)).join(`
|
|
9
|
+
`)}function it(t,e,n){return Array.isArray(e)?`${n}${t}: ${JSON.stringify(e)}`:e&&typeof e=="object"?`${n}${t}:
|
|
10
|
+
${B(e,`${n} `)}`:`${n}${t}: ${JSON.stringify(e)}`}import*as f from"path";function st(t,e){let n=f.resolve(t),r=f.resolve(t,e);return r===n?!0:n===f.parse(n).root?r.startsWith(n):r.startsWith(n+f.sep)}function se(t,e){if(f.isAbsolute(e))return f.resolve(e);if(!st(t,e))throw new Error(`PathSecurity: Path traversal attempt detected: ${e}`);return f.resolve(t,e)}import{homedir as k,platform as at,release as ut}from"node:os";import{execSync as ct}from"node:child_process";import{resolve as h}from"node:path";var A=at(),lt=A==="win32",fe=A==="darwin",de=A==="linux",pe=ut(),ge=k();function me(){let t=process.env.XENO_AGENT_HOME?.trim();return t?h(t):h(k(),".xeno-agent")}function he(){let t=process.env.XENO_CONFIG_DIR?.trim();return t?h(t):h(k(),".xeno-code")}function xe(t){return h(t,".xeno-code")}function ye(){return lt?"powershell":process.env.SHELL?.split("/").pop()??"bash"}function be(t){try{return ct("git rev-parse --is-inside-work-tree",{cwd:t,stdio:"ignore"}),!0}catch{return!1}}function Ee(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 Re(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 Te(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 ke(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 ft(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 Ae(t,e,n=5e3){let r=ft(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 Me(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 dt=(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))(dt||{}),m=1;function _e(t){m=t}function Se(){return m}function p(){return new Date().toISOString()}function $e(t,e){m<=0&&(e!==void 0?process.stderr.write(`[${p()}] DEBUG: ${t} ${x(e)}
|
|
11
11
|
`):process.stderr.write(`[${p()}] DEBUG: ${t}
|
|
12
|
-
`))}function
|
|
12
|
+
`))}function Ne(t,e){m<=1&&(e!==void 0?process.stderr.write(`[${p()}] INFO: ${t} ${x(e)}
|
|
13
13
|
`):process.stderr.write(`[${p()}] INFO: ${t}
|
|
14
|
-
`))}function
|
|
14
|
+
`))}function ve(t,e){m<=2&&(e!==void 0?process.stderr.write(`[${p()}] WARN: ${t} ${x(e)}
|
|
15
15
|
`):process.stderr.write(`[${p()}] WARN: ${t}
|
|
16
|
-
`))}function
|
|
16
|
+
`))}function Oe(t,e){m<=3&&(e!==void 0?process.stderr.write(`[${p()}] ERROR: ${t} ${x(e)}
|
|
17
17
|
`):process.stderr.write(`[${p()}] ERROR: ${t}
|
|
18
|
-
`))}function
|
|
19
|
-
`):null}function
|
|
18
|
+
`))}function x(t){if(t==null)return"";if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}var w=class extends Error{statusCode;body;retryAfterMs;requestId;cfRay;constructor(e,n={}){super(e),this.name="ApiTransientError",this.statusCode=n.statusCode,this.retryAfterMs=n.retryAfterMs,this.requestId=n.requestId,this.cfRay=n.cfRay}},y={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function b(t,e){let n=process.env[t],r=n?Number.parseInt(n,10):Number.NaN;return!Number.isFinite(r)||r<0?e:r}function pt(t={}){let e=Math.max(0,t.maxRetries??b("XENO_API_MAX_RETRIES",y.maxRetries)),n=Math.max(50,t.baseDelayMs??b("XENO_API_BASE_DELAY_MS",y.baseDelayMs)),r=Math.max(n,t.maxDelayMs??b("XENO_API_MAX_DELAY_MS",y.maxDelayMs)),o=Math.max(0,t.jitterMs??b("XENO_API_RETRY_JITTER_MS",y.jitterMs));return{maxRetries:e,baseDelayMs:n,maxDelayMs:r,jitterMs:o}}function gt(t,e,n){if(e.retryAfterMs&&e.retryAfterMs>0)return Math.min(e.retryAfterMs,n.maxDelayMs);let r=Math.min(n.baseDelayMs*Math.pow(2,t),n.maxDelayMs),o=Math.floor(Math.random()*n.jitterMs);return Math.min(r+o,n.maxDelayMs)}function P(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("too many requests")||e.includes("429")}function mt(t){let e=t.toLowerCase();return e.includes("network")||e.includes("timeout")||e.includes("fetch failed")||e.includes("socket hang up")||e.includes("econnreset")||e.includes("eai_again")||e.includes("enotfound")||e.includes("econnrefused")||e.includes("tls")||e.includes("temporarily unavailable")}function I(t){if(t instanceof w)return{statusCode:t.statusCode,retryAfterMs:t.retryAfterMs,requestId:t.requestId,cfRay:t.cfRay};if(!(t instanceof Error))return{};let e=t;if(e.statusCode!==void 0||e.retryAfterMs!==void 0||e.requestId!==void 0||e.cfRay!==void 0)return{statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId,cfRay:e.cfRay};let n=t.message.toLowerCase();return P(n)?{statusCode:429}:{}}var M="408|425|429|500|502|503|504";function ht(t){let e=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${M})\\b`,"i"),n=new RegExp(`\\b(?:${M})\\s+(?:internal|bad\\s+gateway|service\\s+unavailable|gateway\\s+time|request\\s+time|too\\s+early|too\\s+many)`,"i"),r=new RegExp(`^\\s*(?:${M})\\b`);return e.test(t)||n.test(t)||r.test(t)}function xt(t){if(t&&typeof t=="object"&&"retryable"in t)return t.retryable===!0;if(t instanceof w){let{statusCode:e}=I(t);if(e)return e===429||e>=500||e===408||e===409||e===425}if(t instanceof Error){let e=t.name?.toLowerCase()??"";return e==="aborterror"||e==="agentinterruptederror"||t.message.toLowerCase().includes("aborted")||t.message.toLowerCase().includes("interrupted")?!1:ht(t.message)?!0:P(t.message)||mt(t.message.toLowerCase())}return!1}function yt(t){if(t.onAbort)return t.onAbort();let e=new Error("The operation was aborted");return e.name="AbortError",e}async function Be(t,e={}){let n=pt(e),r;for(let o=0;o<=n.maxRetries;o++)try{if(e.signal?.aborted)throw yt(e);return e.onBeforeAttempt?.(o),await t()}catch(i){if(r=i,!(e.shouldRetry?e.shouldRetry(i,o):xt(i))||o===n.maxRetries)throw i;let u=I(i),l=gt(o,u,n),d=e.getDelayMs?.(i,o,l),g=typeof d=="number"&&d>=0?d:l;await new Promise(R=>setTimeout(R,g))}throw r}var bt=(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))},wt=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:bt,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 Ie(t,e,n=wt){return{tokens:Math.max(0,Math.ceil(n.countText(t,e))),source:n.source,adapterId:n.id}}function Et(t){return t?Math.ceil(t.length/4):0}function De(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 Fe(t,e){return Et(t)<=e}function We(t,e){return Math.max(0,e-t)}var Rt={"claude-opus-4-6-thinking":{input:15,output:75},"claude-opus-4-6":{input:15,output:75},"claude-opus-4-5-thinking":{input:15,output:75},"claude-sonnet-4-6":{input:3,output:15},"claude-sonnet-4-5-thinking":{input:3,output:15},"claude-sonnet-4-5":{input:3,output:15},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.5-flash-lite":{input:.075,output:.3},"gemini-3-flash":{input:.15,output:.6},"gemini-3-pro-high":{input:1.25,output:5},"gpt-5":{input:5,output:15},"gpt-5-codex":{input:5,output:15},"gpt-5.1":{input:5,output:15},"gpt-5.1-codex":{input:5,output:15},"gpt-5.2":{input:5,output:15},"gpt-5.2-codex":{input:5,output:15},"kimi-k2":{input:.6,output:2.4},"kimi-k2-thinking":{input:.6,output:2.4},"kimi-k2.5":{input:.6,output:2.4}};function qe(t,e,n){let r=Rt[t];return r?e/1e6*r.input+n/1e6*r.output:0}function He(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 Tt}from"node:child_process";function ze(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=Tt(r.command,r.args,{input:t,encoding:"utf8"});if(o.error){n=o.error.message;continue}if(o.status===0)return;n=o.stderr||o.stdout||`exit ${o.status}`}catch(o){n=o instanceof Error?o.message:String(o)}throw new Error(`Clipboard copy failed${n?`: ${n}`:""}`)}function F(t){return t.replace(/\\/g,"/").toLowerCase()}var kt=["golden","solution","answer","expected"],At=["expected","golden","reference","answer","answers"],Mt=new Set([";","&&","||","|"]);function W(t){return F(t).replace(/^\.\/+/,"").split("/").map(e=>e.trim()).filter(e=>e.length>0)}function Ct(t){return kt.some(e=>t.includes(e))}function D(t){return At.some(e=>t.includes(e))}function j(t){return t.split("::",1)[0]?.split("?",1)[0]?.split("#",1)[0]??t}function E(t){let e=t.trim().replace(/^[({]+/,"").replace(/[),;]+$/,"");return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e}function _t(t){return t.match(/"[^"]*"|'[^']*'|&&|\|\||[;|]|[^\s;|&]+/g)?.map(E).filter(e=>e.length>0)??[]}function q(t){let e=W(t),n=j(e.at(-1)??"");return D(n)||e.some(r=>D(r))}function H(t){let e=F(E(t));return!e||e==="/dev/null"||e.startsWith("/tmp/")||e.startsWith("tmp/")||e.startsWith("/var/tmp/")||e.startsWith("var/tmp/")?!1:e.startsWith("/app/")||e.startsWith("./")?!0:!e.startsWith("/")}function St(t){return/[\\/]/.test(t)||/\.[A-Za-z0-9]{1,8}$/.test(t)}function $t(t){let e=_t(t);for(let n=0;n<e.length;n+=1){let r=e[n]?.toLowerCase();if(r!=="cp"&&r!=="mv"&&r!=="rsync"&&r!=="install")continue;let o=[];for(let s=n+1;s<e.length;s+=1){let u=e[s];if(!u||Mt.has(u))break;u!=="--"&&(u.startsWith("-")||o.push(u))}if(o.length<2)continue;let i=o.at(-1);if(H(i)){for(let s of o.slice(0,-1))if(St(s)&&q(s))return{sourcePath:s,destinationPath:i,operation:r}}}return null}function Nt(t){let e=[/\bcat\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*>\s*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i,/\bdd\b[\s\S]*?\bif=(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))[\s\S]*?\bof=(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i];for(let n of e){let r=t.match(n);if(!r)continue;let o=E(r[1]??r[2]??r[3]??""),i=E(r[4]??r[5]??r[6]??"");if(!(!o||!i)&&q(o)&&H(i))return{sourcePath:o,destinationPath:i,operation:n.source.startsWith("\\bdd")?"dd":"redirect"}}return null}function X(){return process.env.XENO_BENCHMARK_MODE?.trim().toLowerCase()==="terminal-bench"}function J(t){let e=W(t);if(e.includes("solution")||e.includes("xeno-audit")||e.includes(".xeno")&&e.includes("audit"))return!0;let n=j(e.at(-1)??"");return e.includes("tests")&&Ct(n)}function Ue(t){return X()?t.filter(e=>!J(e)):t}function Ye(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 Ke(t){return t.split(/[\s"'`;|&]+/).map(e=>e.trim()).filter(e=>e.length>0&&/[\\/]/.test(e)).some(e=>J(e))}function Qe(t){if(!X())return null;let e=$t(t)??Nt(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(`
|
|
19
|
+
`):null}function vt(t){return/^data:([^;,]+)[;,]/i.exec(t.trim())?.[1]}function Ot(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 ${vt(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(`
|
|
20
20
|
|
|
21
|
-
`).trim()}function
|
|
22
|
-
`)}function
|
|
23
|
-
`)}}function
|
|
21
|
+
`).trim()}function z(t){let e=t.trim();return e.length>0?[{type:"text",text:e}]:[]}function Ve(t){return typeof t=="string"?t:Ot(t)}function Lt(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(`
|
|
22
|
+
`)}function tn(t){let e=t.assistant_content&&t.assistant_content.length>0?t.assistant_content:typeof t.content=="string"?z(t.content):t.content,n=t.assistant_only_content??[],r=Bt(t),o=[...e,...n,...r?[r]:[]];return o.length>0?o:t.content}function Bt(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(`
|
|
23
|
+
`)}}function en(t){return Array.isArray(t)&&t.some(e=>e.type!=="text")}function nn(t){return typeof t=="string"?z(t):t}function rn(t,e){return{type:"tool_result",tool_use_id:t,content:Lt(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.retryable!==void 0?{retryable:e.retryable}:{}}}function sn(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{w as ApiTransientError,ge as HOME_DIR,de as IS_LINUX,fe as IS_MAC,lt as IS_WINDOWS,dt as LogLevel,pe as OS_VERSION,A as PLATFORM,Ie as accountTextTokens,jt as appendLine,Ye as benchmarkLeakError,rn as buildToolResultBlock,Lt as buildToolResultText,qe as calculateCost,Ke as commandMentionsBenchmarkLeak,wt as conservativeTokenAccountingAdapter,ze as copyTextToClipboard,Ae as createSafeRegex,$e as debug,K as decodeTextBuffer,Kt as deleteDir,Yt as deleteFile,Z as detectLineEnding,Ht as detectPreferredLineEnding,Y as detectTextEncoding,Q as encodeTextBuffer,$ as ensureDir,Oe as error,Et as estimateTokens,bt as estimateTokensForModel,zt as existsSync,Ue as filterBenchmarkLeakPaths,Xt as findSimilarFile,Fe as fitsInBudget,He as formatCost,me as getAgentHome,Qe as getBenchmarkReferenceOverwriteHint,ke as getBoolean,he as getConfigDir,Se as getLogLevel,Te as getNumber,xe as getProjectConfigDir,I as getRetryErrorContext,ye as getShellName,Re as getString,tn as getToolResultTransportContent,Ft as hasDir,sn as hasDisallowedAsciiControlCharacter,Dt as hasFile,oe as hasFrontmatter,en as hasNonTextToolResultContent,ht as hasTransientStatusMention,Ne as info,J as isBenchmarkLeakPath,X as isBenchmarkMode,be as isGitRepo,st as isPathSafe,xt as isRetryableError,Ut as listDirs,Gt as listFiles,V as normalizeLineEndings,ne as parseDocument,te as parseJsonLines,Wt as readFileSafe,Jt as readIfExists,tt as readTextFile,We as remainingBudget,Zt as safeJsonParse,Vt as safeJsonStringify,Me as safeRegexTest,se as safeResolvePath,_e as setLogLevel,re as stringifyDocument,nn as toTransportAssistantBlocks,Ot as toolAssistantContentToText,Ve as toolResultContentToText,De as truncateToTokens,ft as validateRegexPattern,Ee as validateRequired,ve as warn,Be as withRetry,U as writeAtomic,qt as writeTextFile};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/utils/fs.ts":{"bytes":10330,"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":842,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":5668,"imports":[],"format":"esm"},"src/utils/path-security.ts":{"bytes":1024,"imports":[{"path":"path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/platform.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/utils/fs.ts":{"bytes":10330,"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":842,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":5668,"imports":[],"format":"esm"},"src/utils/path-security.ts":{"bytes":1024,"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":5519,"imports":[],"format":"esm"},"src/utils/logger.ts":{"bytes":3873,"imports":[],"format":"esm"},"src/utils/retry.ts":{"bytes":12006,"imports":[],"format":"esm"},"src/utils/tokens.ts":{"bytes":3306,"imports":[],"format":"esm"},"src/utils/cost.ts":{"bytes":1876,"imports":[],"format":"esm"},"src/utils/clipboard.ts":{"bytes":1196,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/utils/benchmark-safety.ts":{"bytes":6703,"imports":[],"format":"esm"},"src/utils/tool-result-content.ts":{"bytes":4887,"imports":[],"format":"esm"},"src/utils/text-security.ts":{"bytes":833,"imports":[],"format":"esm"},"src/utils/index.ts":{"bytes":1490,"imports":[{"path":"src/utils/fs.ts","kind":"import-statement","original":"./fs.js"},{"path":"src/utils/json.ts","kind":"import-statement","original":"./json.js"},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"./yaml.js"},{"path":"src/utils/path-security.ts","kind":"import-statement","original":"./path-security.js"},{"path":"src/utils/platform.ts","kind":"import-statement","original":"./platform.js"},{"path":"src/utils/validation.ts","kind":"import-statement","original":"./validation.js"},{"path":"src/utils/logger.ts","kind":"import-statement","original":"./logger.js"},{"path":"src/utils/retry.ts","kind":"import-statement","original":"./retry.js"},{"path":"src/utils/tokens.ts","kind":"import-statement","original":"./tokens.js"},{"path":"src/utils/cost.ts","kind":"import-statement","original":"./cost.js"},{"path":"src/utils/clipboard.ts","kind":"import-statement","original":"./clipboard.js"},{"path":"src/utils/benchmark-safety.ts","kind":"import-statement","original":"./benchmark-safety.js"},{"path":"src/utils/tool-result-content.ts","kind":"import-statement","original":"./tool-result-content.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"./text-security.js"}],"format":"esm"}},"outputs":{"dist/utils/index.cjs":{"imports":[{"path":"node:fs","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"path","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/utils/index.ts","inputs":{"src/utils/index.ts":{"bytesInOutput":1920},"src/utils/fs.ts":{"bytesInOutput":4051},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2639},"src/utils/path-security.ts":{"bytesInOutput":313},"src/utils/platform.ts":{"bytesInOutput":687},"src/utils/validation.ts":{"bytesInOutput":1423},"src/utils/logger.ts":{"bytesInOutput":913},"src/utils/retry.ts":{"bytesInOutput":3185},"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":2072},"src/utils/text-security.ts":{"bytesInOutput":180}},"bytes":25091}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/utils/fs.ts":{"bytes":10330,"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":842,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":5668,"imports":[],"format":"esm"},"src/utils/path-security.ts":{"bytes":1024,"imports":[{"path":"path","kind":"import-statement","external":true}],"format":"esm"},"src/utils/platform.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/utils/fs.ts":{"bytes":10330,"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":842,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":5668,"imports":[],"format":"esm"},"src/utils/path-security.ts":{"bytes":1024,"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":5519,"imports":[],"format":"esm"},"src/utils/logger.ts":{"bytes":3873,"imports":[],"format":"esm"},"src/utils/retry.ts":{"bytes":12006,"imports":[],"format":"esm"},"src/utils/tokens.ts":{"bytes":3306,"imports":[],"format":"esm"},"src/utils/cost.ts":{"bytes":1876,"imports":[],"format":"esm"},"src/utils/clipboard.ts":{"bytes":1196,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/utils/benchmark-safety.ts":{"bytes":6703,"imports":[],"format":"esm"},"src/utils/tool-result-content.ts":{"bytes":4887,"imports":[],"format":"esm"},"src/utils/text-security.ts":{"bytes":833,"imports":[],"format":"esm"},"src/utils/index.ts":{"bytes":1490,"imports":[{"path":"src/utils/fs.ts","kind":"import-statement","original":"./fs.js"},{"path":"src/utils/json.ts","kind":"import-statement","original":"./json.js"},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"./yaml.js"},{"path":"src/utils/path-security.ts","kind":"import-statement","original":"./path-security.js"},{"path":"src/utils/platform.ts","kind":"import-statement","original":"./platform.js"},{"path":"src/utils/validation.ts","kind":"import-statement","original":"./validation.js"},{"path":"src/utils/logger.ts","kind":"import-statement","original":"./logger.js"},{"path":"src/utils/retry.ts","kind":"import-statement","original":"./retry.js"},{"path":"src/utils/tokens.ts","kind":"import-statement","original":"./tokens.js"},{"path":"src/utils/cost.ts","kind":"import-statement","original":"./cost.js"},{"path":"src/utils/clipboard.ts","kind":"import-statement","original":"./clipboard.js"},{"path":"src/utils/benchmark-safety.ts","kind":"import-statement","original":"./benchmark-safety.js"},{"path":"src/utils/tool-result-content.ts","kind":"import-statement","original":"./tool-result-content.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"./text-security.js"}],"format":"esm"}},"outputs":{"dist/utils/index.js":{"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"path","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true}],"exports":["ApiTransientError","HOME_DIR","IS_LINUX","IS_MAC","IS_WINDOWS","LogLevel","OS_VERSION","PLATFORM","accountTextTokens","appendLine","benchmarkLeakError","buildToolResultBlock","buildToolResultText","calculateCost","commandMentionsBenchmarkLeak","conservativeTokenAccountingAdapter","copyTextToClipboard","createSafeRegex","debug","decodeTextBuffer","deleteDir","deleteFile","detectLineEnding","detectPreferredLineEnding","detectTextEncoding","encodeTextBuffer","ensureDir","error","estimateTokens","estimateTokensForModel","existsSync","filterBenchmarkLeakPaths","findSimilarFile","fitsInBudget","formatCost","getAgentHome","getBenchmarkReferenceOverwriteHint","getBoolean","getConfigDir","getLogLevel","getNumber","getProjectConfigDir","getRetryErrorContext","getShellName","getString","getToolResultTransportContent","hasDir","hasDisallowedAsciiControlCharacter","hasFile","hasFrontmatter","hasNonTextToolResultContent","hasTransientStatusMention","info","isBenchmarkLeakPath","isBenchmarkMode","isGitRepo","isPathSafe","isRetryableError","listDirs","listFiles","normalizeLineEndings","parseDocument","parseJsonLines","readFileSafe","readIfExists","readTextFile","remainingBudget","safeJsonParse","safeJsonStringify","safeRegexTest","safeResolvePath","setLogLevel","stringifyDocument","toTransportAssistantBlocks","toolAssistantContentToText","toolResultContentToText","truncateToTokens","validateRegexPattern","validateRequired","warn","withRetry","writeAtomic","writeTextFile"],"entryPoint":"src/utils/index.ts","inputs":{"src/utils/fs.ts":{"bytesInOutput":3998},"src/utils/index.ts":{"bytesInOutput":0},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2639},"src/utils/path-security.ts":{"bytesInOutput":311},"src/utils/platform.ts":{"bytesInOutput":630},"src/utils/validation.ts":{"bytesInOutput":1425},"src/utils/logger.ts":{"bytesInOutput":915},"src/utils/retry.ts":{"bytesInOutput":3185},"src/utils/tokens.ts":{"bytesInOutput":904},"src/utils/cost.ts":{"bytesInOutput":933},"src/utils/clipboard.ts":{"bytesInOutput":601},"src/utils/benchmark-safety.ts":{"bytesInOutput":3090},"src/utils/tool-result-content.ts":{"bytesInOutput":2069},"src/utils/text-security.ts":{"bytesInOutput":180}},"bytes":22929}}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xenosystem/agent-sdk",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.11",
|
|
4
4
|
"description": "XENO Agent SDK built from the same engine as XENO CODE",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -161,7 +161,8 @@
|
|
|
161
161
|
"compliance:release-actions": "node scripts/verify-release-actions.mjs",
|
|
162
162
|
"compliance:observability": "node scripts/write-observability-report.mjs --write",
|
|
163
163
|
"compliance": "npm run compliance:provenance && npm run compliance:licenses && npm run compliance:ownership && npm run compliance:encoding && npm run compliance:release-actions && npm run compliance:observability",
|
|
164
|
-
"test": "npm run build && node --test --test-concurrency=1 \"tests/**/*.test.*\"",
|
|
164
|
+
"test": "npm run build && node --import ./tests/_setup.mjs --test --test-concurrency=1 \"tests/**/*.test.*\"",
|
|
165
|
+
"ci:local": "npm run typecheck && npm run typecheck:tests && npm run lint && npm run test && npm run build",
|
|
165
166
|
"test:media": "npm run build && node --test tests/xeno-deflate.test.mjs tests/xeno-png.test.mjs tests/xeno-jpeg.test.mjs tests/xeno-gif.test.mjs tests/xeno-vp8.test.mjs tests/xeno-webp.test.mjs tests/xeno-svg.test.mjs tests/read-image-preview.test.mjs tests/external-media-coverage-fuzz.test.mjs",
|
|
166
167
|
"test:media:external": "npm run build && node scripts/run-external-media-corpora.mjs",
|
|
167
168
|
"test:media:fuzz": "npm run build && node scripts/fuzz-external-media.mjs --duration-ms 60000",
|
|
@@ -189,7 +190,7 @@
|
|
|
189
190
|
"test:ga:engineering": "npm run typecheck && npm run compliance && npm run test:runtime-coordination && npm run test:tool-schema-conformance && npm run test:tool-failure-guard && npm run test:containment && npm run test:context-compaction && npm run test:provider-conformance && npm run test:app-server-v2 && npm run test:observability && npm run test:package-candidate && npm run test:release-evidence",
|
|
190
191
|
"test:ga": "npm run test:ga:engineering && node scripts/verify-release-version.mjs --manifest package.json --require-unused --require-greater-than-latest && node scripts/verify-sdk-ga-evidence.mjs",
|
|
191
192
|
"bench:coding-tools": "npm run build && node scripts/run-benchmark.mjs",
|
|
192
|
-
"prepublishOnly": "npm run build && npm run typecheck"
|
|
193
|
+
"prepublishOnly": "npm run build && npm run typecheck && node scripts/verify-dist-exports.mjs"
|
|
193
194
|
},
|
|
194
195
|
"devDependencies": {
|
|
195
196
|
"@eslint/js": "^9.39.4",
|