@xenosystem/agent-sdk 0.10.43 → 0.10.45

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 (43) hide show
  1. package/dist/agents/index.cjs +11 -8
  2. package/dist/agents/index.js +11 -8
  3. package/dist/agents/metafile-cjs.json +1 -1
  4. package/dist/agents/metafile-esm.json +1 -1
  5. package/dist/artifacts/index.cjs +1 -1
  6. package/dist/artifacts/index.js +1 -1
  7. package/dist/automation/index.cjs +1 -1
  8. package/dist/automation/index.d.cts +4 -0
  9. package/dist/automation/index.d.ts +4 -0
  10. package/dist/automation/index.js +1 -1
  11. package/dist/automation/metafile-cjs.json +1 -1
  12. package/dist/automation/metafile-esm.json +1 -1
  13. package/dist/control-plane/index.cjs +1 -1
  14. package/dist/control-plane/index.js +1 -1
  15. package/dist/electron/index.cjs +214 -206
  16. package/dist/electron/index.d.cts +5 -0
  17. package/dist/electron/index.d.ts +5 -0
  18. package/dist/electron/index.js +214 -206
  19. package/dist/electron/metafile-cjs.json +1 -1
  20. package/dist/electron/metafile-esm.json +1 -1
  21. package/dist/governance/index.cjs +1 -1
  22. package/dist/governance/index.js +1 -1
  23. package/dist/governance/metafile-cjs.json +1 -1
  24. package/dist/governance/metafile-esm.json +1 -1
  25. package/dist/index.cjs +386 -373
  26. package/dist/index.d.cts +64 -1
  27. package/dist/index.d.ts +64 -1
  28. package/dist/index.js +387 -374
  29. package/dist/mcp/index.d.cts +4 -0
  30. package/dist/mcp/index.d.ts +4 -0
  31. package/dist/metafile-cjs.json +1 -1
  32. package/dist/metafile-esm.json +1 -1
  33. package/dist/session/index.cjs +1 -1
  34. package/dist/session/index.js +1 -1
  35. package/dist/skills/index.cjs +8 -5
  36. package/dist/skills/index.js +8 -5
  37. package/dist/skills/metafile-cjs.json +1 -1
  38. package/dist/skills/metafile-esm.json +1 -1
  39. package/dist/utils/index.cjs +19 -16
  40. package/dist/utils/index.js +19 -16
  41. package/dist/utils/metafile-cjs.json +1 -1
  42. package/dist/utils/metafile-esm.json +1 -1
  43. package/package.json +1 -1
@@ -1,24 +1,27 @@
1
- "use strict";var Ze=Object.create;var $=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var rt=(e,t)=>{for(var r in t)$(e,r,{get:t[r],enumerable:!0})},ee=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qe(t))!tt.call(e,o)&&o!==r&&$(e,o,{get:()=>t[o],enumerable:!(n=Je(t,o))||n.enumerable});return e};var H=(e,t,r)=>(r=e!=null?Ze(et(e)):{},ee(t||!e||!e.__esModule?$(r,"default",{value:e,enumerable:!0}):r,e)),nt=e=>ee($({},"__esModule",{value:!0}),e);var Qr={};rt(Qr,{ApiTransientError:()=>O,HOME_DIR:()=>Yt,IS_LINUX:()=>Kt,IS_MAC:()=>Wt,IS_WINDOWS:()=>C,LogLevel:()=>Ae,OS_VERSION:()=>Gt,PLATFORM:()=>B,accountTextTokens:()=>Cr,appendDurableLine:()=>ht,appendLine:()=>yt,benchmarkLeakError:()=>Br,buildToolResultBlock:()=>Wr,buildToolResultText:()=>Le,calculateCost:()=>Or,clearFileCache:()=>at,commandMentionsBenchmarkLeak:()=>Xr,conservativeTokenAccountingAdapter:()=>Oe,copyTextToClipboard:()=>$r,createSafeRegex:()=>ar,debug:()=>lr,decodeTextBuffer:()=>de,deleteDir:()=>Pt,deleteFile:()=>Ct,detectLineEnding:()=>fe,detectPreferredLineEnding:()=>wt,detectTextEncoding:()=>ce,encodeTextBuffer:()=>le,ensureDir:()=>L,error:()=>mr,estimateTokens:()=>Me,estimateTokensForModel:()=>Ie,existsSync:()=>_t,fetchPinnedEndpoint:()=>Jr,filterBenchmarkLeakPaths:()=>Lr,findSimilarFile:()=>Rt,fitsInBudget:()=>kr,formatCost:()=>Mr,getAgentHome:()=>Zt,getBenchmarkReferenceOverwriteHint:()=>zr,getBoolean:()=>ir,getConfigDir:()=>Jt,getFileCacheStats:()=>st,getLogLevel:()=>dr,getNumber:()=>sr,getProjectConfigDir:()=>Qt,getRetryErrorContext:()=>Y,getShellName:()=>er,getString:()=>or,getToolResultTransportContent:()=>Hr,hasDir:()=>ft,hasDisallowedAsciiControlCharacter:()=>Kr,hasFile:()=>lt,hasFrontmatter:()=>$t,hasMixedLineEndings:()=>Et,hasNonTextToolResultContent:()=>jr,hasTransientStatusMention:()=>ke,info:()=>fr,invalidateFileCache:()=>D,isBenchmarkLeakPath:()=>Dr,isBenchmarkMode:()=>Nr,isGitRepo:()=>tr,isGitRepoAsync:()=>rr,isPathSafe:()=>be,isRetryableError:()=>Se,listDirs:()=>At,listFiles:()=>vt,normalizeLineEndings:()=>pe,normalizeXenoRequestContext:()=>br,parseDocument:()=>Ot,parseJsonLines:()=>It,pathIdentityKey:()=>zt,readDerivedCached:()=>oe,readFileSafe:()=>pt,readIfExists:()=>Tt,readTextCached:()=>dt,readTextFile:()=>me,remainingBudget:()=>Sr,renameReplacingWithRetry:()=>ae,resetFileCacheStats:()=>it,safeJsonParse:()=>kt,safeJsonStringify:()=>St,safeRegexTest:()=>cr,safeResolvePath:()=>Xt,setLogLevel:()=>ur,stringifyDocument:()=>Mt,toTransportAssistantBlocks:()=>Vr,toolAssistantContentToText:()=>Ne,toolResultContentToText:()=>qr,truncateToTokens:()=>Pr,validateRegexPattern:()=>ve,validateRequired:()=>nr,warn:()=>pr,withRetry:()=>Ar,writeAtomic:()=>ie,writeTextFile:()=>bt,xenoRequestContextHeaders:()=>xr});module.exports=nt(Qr);var I=require("node:fs"),_=require("node:fs"),p=H(require("node:fs/promises"),1),d=H(require("node:path"),1);var N=require("node:fs"),ot=8192,re=Symbol.for("@xenosystem/agent-sdk/file-cache"),ne=globalThis,U=ne[re]??{entries:new Map,counters:{reads:0,hits:0}};ne[re]=U;var E=U.entries,A=U.counters;function st(){return{...A}}function it(){A.reads=0,A.hits=0}function D(e){E.delete(e)}function at(){E.clear()}async function ct(e){try{let t=await N.promises.stat(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(t.code==="ENOENT")return null;throw t}}function te(e,t){for(E.delete(e),E.set(e,t);E.size>ot;){let r=E.keys().next().value;if(r===void 0)break;E.delete(r)}}async function ut(e,t,r){let n=await N.promises.open(e,"r");try{let o=Math.min(r,t),s=Buffer.alloc(o);return await n.read(s,0,o,t-o),s.toString("utf-8")}finally{await n.close()}}async function oe(e,t,r,n={}){let o=await ct(e);if(!o)return E.delete(e),null;let s=E.get(e);if(s&&s.mtimeMs===o.mtimeMs&&s.size===o.size&&s.values.has(t))return A.hits+=1,te(e,s),s.values.get(t);let i,a=n.tailBytes;if(a!==void 0&&o.size>a&&(A.reads+=1,i=r(await ut(e,o.size,a),!0)),i===void 0){let f;try{f=await N.promises.readFile(e,"utf-8")}catch(u){if(u.code==="ENOENT")return E.delete(e),null;throw u}A.reads+=1,i=r(f,!1)}let c=E.get(e),l=c&&c.mtimeMs===o.mtimeMs&&c.size===o.size?c:{mtimeMs:o.mtimeMs,size:o.size,values:new Map};return l.values.set(t,i),te(e,l),i}function dt(e){return oe(e,"text",t=>t)}function lt(e){try{return(0,_.existsSync)(e)&&(0,_.statSync)(e).isFile()}catch{return!1}}function ft(e){try{return(0,_.existsSync)(e)&&(0,_.statSync)(e).isDirectory()}catch{return!1}}function pt(e,t=""){try{return(0,I.readFileSync)(e,"utf-8")}catch{return t}}async function L(e){await p.mkdir(e,{recursive:!0})}async function ie(e,t){let r=d.dirname(e);await L(r);let n=Math.random().toString(36).substring(2,15),o=`${e}.tmp.${process.pid}.${n}`;try{await p.writeFile(o,t),await ae(o,e),D(e)}finally{try{await p.unlink(o)}catch{}}}var mt=new Set(["EACCES","EBUSY","EPERM"]),gt=[10,20,40,80,160,320,640];async function ae(e,t){for(let r=0;;r+=1)try{await p.rename(e,t);return}catch(n){let o=n.code,s=gt[r];if(process.platform!=="win32"||!o||!mt.has(o)||s===void 0)throw n;await new Promise(i=>setTimeout(i,s))}}async function yt(e,t){let r=d.dirname(e);await L(r),await p.appendFile(e,t+`
2
- `,"utf-8")}async function ht(e,t){let r=d.dirname(e);await L(r);let n=await p.open(e,"a");try{await n.writeFile(t+`
1
+ "use strict";var Ze=Object.create;var $=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var rt=(e,t)=>{for(var r in t)$(e,r,{get:t[r],enumerable:!0})},ee=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qe(t))!tt.call(e,o)&&o!==r&&$(e,o,{get:()=>t[o],enumerable:!(n=Je(t,o))||n.enumerable});return e};var H=(e,t,r)=>(r=e!=null?Ze(et(e)):{},ee(t||!e||!e.__esModule?$(r,"default",{value:e,enumerable:!0}):r,e)),nt=e=>ee($({},"__esModule",{value:!0}),e);var en={};rt(en,{ApiTransientError:()=>O,HOME_DIR:()=>Zt,IS_LINUX:()=>Gt,IS_MAC:()=>Kt,IS_WINDOWS:()=>k,LogLevel:()=>Ae,OS_VERSION:()=>Yt,PLATFORM:()=>B,accountTextTokens:()=>Cr,appendDurableLine:()=>ht,appendLine:()=>yt,benchmarkLeakError:()=>Xr,buildToolResultBlock:()=>Kr,buildToolResultText:()=>Le,calculateCost:()=>Mr,clearFileCache:()=>at,commandMentionsBenchmarkLeak:()=>zr,conservativeTokenAccountingAdapter:()=>Oe,copyTextToClipboard:()=>Nr,createSafeRegex:()=>cr,debug:()=>fr,decodeTextBuffer:()=>de,deleteDir:()=>Ct,deleteFile:()=>kt,detectLineEnding:()=>fe,detectPreferredLineEnding:()=>wt,detectTextEncoding:()=>ce,encodeTextBuffer:()=>le,ensureDir:()=>L,error:()=>gr,estimateTokens:()=>Me,estimateTokensForModel:()=>Ie,existsSync:()=>_t,fetchPinnedEndpoint:()=>Qr,filterBenchmarkLeakPaths:()=>Br,findSimilarFile:()=>Rt,fitsInBudget:()=>Sr,formatCost:()=>$r,getAgentHome:()=>Jt,getBenchmarkReferenceOverwriteHint:()=>Fr,getBoolean:()=>ar,getConfigDir:()=>Qt,getFileCacheStats:()=>st,getLogLevel:()=>lr,getNumber:()=>ir,getProjectConfigDir:()=>er,getRetryErrorContext:()=>Y,getShellName:()=>tr,getString:()=>sr,getToolResultTransportContent:()=>Ur,hasDir:()=>ft,hasDisallowedAsciiControlCharacter:()=>Gr,hasFile:()=>lt,hasFrontmatter:()=>$t,hasMixedLineEndings:()=>bt,hasNonTextToolResultContent:()=>Vr,hasTransientStatusMention:()=>Pe,info:()=>pr,invalidateFileCache:()=>D,isBenchmarkLeakPath:()=>Lr,isBenchmarkMode:()=>Dr,isGitRepo:()=>rr,isGitRepoAsync:()=>nr,isPathSafe:()=>Ee,isRetryableError:()=>Se,listDirs:()=>At,listFiles:()=>vt,normalizeLineEndings:()=>pe,normalizeXenoRequestContext:()=>wr,parseDocument:()=>Ot,parseJsonLines:()=>It,pathIdentityKey:()=>Ft,readDerivedCached:()=>oe,readFileSafe:()=>pt,readIfExists:()=>Tt,readTextCached:()=>dt,readTextFile:()=>me,remainingBudget:()=>Ir,renameReplacingWithRetry:()=>ae,resetFileCacheStats:()=>it,safeJsonParse:()=>Pt,safeJsonStringify:()=>St,safeRegexTest:()=>ur,safeResolvePath:()=>zt,setLogLevel:()=>dr,stringifyDocument:()=>Mt,toTransportAssistantBlocks:()=>Wr,toolAssistantContentToText:()=>Ne,toolResultContentToText:()=>Hr,truncateToTokens:()=>Pr,validateRegexPattern:()=>ve,validateRequired:()=>or,warn:()=>mr,withRetry:()=>kr,writeAtomic:()=>ie,writeTextFile:()=>Et,xenoRequestContextHeaders:()=>Rr});module.exports=nt(en);var I=require("node:fs"),_=require("node:fs"),p=H(require("node:fs/promises"),1),f=H(require("node:path"),1);var N=require("node:fs"),ot=8192,re=Symbol.for("@xenosystem/agent-sdk/file-cache"),ne=globalThis,U=ne[re]??{entries:new Map,counters:{reads:0,hits:0}};ne[re]=U;var b=U.entries,A=U.counters;function st(){return{...A}}function it(){A.reads=0,A.hits=0}function D(e){b.delete(e)}function at(){b.clear()}async function ct(e){try{let t=await N.promises.stat(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(t.code==="ENOENT")return null;throw t}}function te(e,t){for(b.delete(e),b.set(e,t);b.size>ot;){let r=b.keys().next().value;if(r===void 0)break;b.delete(r)}}async function ut(e,t,r){let n=await N.promises.open(e,"r");try{let o=Math.min(r,t),s=Buffer.alloc(o);return await n.read(s,0,o,t-o),s.toString("utf-8")}finally{await n.close()}}async function oe(e,t,r,n={}){let o=await ct(e);if(!o)return b.delete(e),null;let s=b.get(e);if(s&&s.mtimeMs===o.mtimeMs&&s.size===o.size&&s.values.has(t))return A.hits+=1,te(e,s),s.values.get(t);let i,c=n.tailBytes;if(c!==void 0&&o.size>c&&(A.reads+=1,i=r(await ut(e,o.size,c),!0)),i===void 0){let l;try{l=await N.promises.readFile(e,"utf-8")}catch(u){if(u.code==="ENOENT")return b.delete(e),null;throw u}A.reads+=1,i=r(l,!1)}let a=b.get(e),d=a&&a.mtimeMs===o.mtimeMs&&a.size===o.size?a:{mtimeMs:o.mtimeMs,size:o.size,values:new Map};return d.values.set(t,i),te(e,d),i}function dt(e){return oe(e,"text",t=>t)}function lt(e){try{return(0,_.existsSync)(e)&&(0,_.statSync)(e).isFile()}catch{return!1}}function ft(e){try{return(0,_.existsSync)(e)&&(0,_.statSync)(e).isDirectory()}catch{return!1}}function pt(e,t=""){try{return(0,I.readFileSync)(e,"utf-8")}catch{return t}}async function L(e){await p.mkdir(e,{recursive:!0})}async function ie(e,t){let r=f.dirname(e);await L(r);let n=Math.random().toString(36).substring(2,15),o=`${e}.tmp.${process.pid}.${n}`;try{await p.writeFile(o,t),await ae(o,e),D(e)}finally{try{await p.unlink(o)}catch{}}}var mt=new Set(["EACCES","EBUSY","EPERM"]),gt=[10,20,40,80,160,320,640];async function ae(e,t){for(let r=0;;r+=1)try{await p.rename(e,t);return}catch(n){let o=n.code,s=gt[r];if(process.platform!=="win32"||!o||!mt.has(o)||s===void 0)throw n;await new Promise(i=>setTimeout(i,s))}}async function yt(e,t){let r=f.dirname(e);await L(r),await p.appendFile(e,t+`
2
+ `,"utf-8")}async function ht(e,t){let r=f.dirname(e);await L(r);let n=await p.open(e,"a");try{await n.writeFile(t+`
3
3
  `,"utf-8"),await n.sync()}finally{await n.close()}}function ce(e){return e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?"utf8-bom":e.length>=2&&e[0]===255&&e[1]===254?"utf16le":e.length>=2&&e[0]===254&&e[1]===255?"utf16be":"utf8"}function ue(e){let t=Buffer.from(e);for(let r=0;r+1<t.length;r+=2){let n=t[r];t[r]=t[r+1],t[r+1]=n}return t}function de(e,t){switch(t){case"utf8-bom":return e.subarray(3).toString("utf8");case"utf16le":return e.subarray(2).toString("utf16le");case"utf16be":return ue(e.subarray(2)).toString("utf16le");default:return e.toString("utf8")}}function le(e,t){switch(t){case"utf8-bom":return Buffer.concat([Buffer.from([239,187,191]),Buffer.from(e,"utf8")]);case"utf16le":return Buffer.concat([Buffer.from([255,254]),Buffer.from(e,"utf16le")]);case"utf16be":return Buffer.concat([Buffer.from([254,255]),ue(Buffer.from(e,"utf16le"))]);default:return Buffer.from(e,"utf8")}}function fe(e){return e.includes(`\r
4
4
  `)?"CRLF":"LF"}function pe(e,t){let r=e.replace(/\r\n/g,`
5
5
  `);return t==="CRLF"?r.replace(/\n/g,`\r
6
- `):r}function Et(e){return e.includes(`\r
7
- `)?/(^|[^\r])\n/.test(e):!1}async function me(e){let t=await p.readFile(e),r=ce(t),n=de(t,r);return{content:n,encoding:r,lineEnding:fe(n),sizeBytes:t.length}}async function bt(e,t,r){let n=r?.preserveLineEndings?t:pe(t,r?.lineEnding??"LF");await ie(e,le(n,r?.encoding??"utf8"))}async function wt(e,t){let r=new Set,n=d.resolve(e),o=t===void 0?void 0:d.resolve(t);if(o!==void 0){let s=d.relative(o,n);if(d.isAbsolute(s)||s===".."||s.startsWith(`..${d.sep}`))return"LF"}for(;!r.has(n);){r.add(n);try{let i=(0,I.readdirSync)(n,{withFileTypes:!0}).filter(a=>a.isFile()).map(a=>a.name).sort();for(let a of i){if(a.startsWith("."))continue;let c=d.extname(a).toLowerCase();if([".ts",".tsx",".js",".jsx",".json",".md",".txt",".yaml",".yml",".css",".html",".xml",".sh",".ps1"].includes(c))try{let l=d.join(n,a),f=await me(l);if(f.content.length>0)return f.lineEnding}catch{}}}catch{}if(o!==void 0&&d.relative(o,n)==="")break;let s=d.dirname(n);if(s===n)break;n=s}return"LF"}function xt(e,t,r){let n=[],o=[{dir:e,depth:0}],s=new Set;for(;o.length>0&&n.length<r;){let i=o.shift();if(!s.has(i.dir)){s.add(i.dir);try{let a=(0,I.readdirSync)(i.dir,{withFileTypes:!0});for(let c of a){let l=d.join(i.dir,c.name);if(c.isFile()){if(n.push(l),n.length>=r)break;continue}c.isDirectory()&&i.depth<t&&!c.name.startsWith(".")&&c.name!=="node_modules"&&o.push({dir:l,depth:i.depth+1})}}catch{}}}return n}function se(e,t){let r=d.relative(e,t);return r===""||!r.startsWith("..")&&!d.isAbsolute(r)}function Rt(e,t){try{let r=d.dirname(e),n=d.basename(e,d.extname(e)).toLowerCase(),o=d.basename(e).toLowerCase(),s=[r,d.dirname(r)],i=t!==void 0&&se(t,e)?t:void 0,a=s.flatMap(l=>xt(l,2,500)).filter(l=>i===void 0||se(i,l)),c=null;for(let l of a){let f=d.basename(l).toLowerCase(),u=d.basename(l,d.extname(l)).toLowerCase(),g=null;if(f===o?g=0:u===n?g=1:(f.includes(n)||n.includes(u))&&(g=2),g===null)continue;let v=d.relative(r,l).split(d.sep).length,h=g+v*.01;(!c||h<c.score)&&(c={filePath:l,score:h})}return c?.filePath??null}catch{}return null}async function Tt(e){try{return await p.readFile(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function _t(e){return(0,_.existsSync)(e)}async function vt(e,t){try{let n=(await p.readdir(e,{withFileTypes:!0})).filter(o=>o.isFile()).map(o=>d.join(e,o.name));return t&&(n=n.filter(o=>t.test(d.basename(o)))),n}catch(r){if(r.code==="ENOENT")return[];throw r}}async function At(e){try{return(await p.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>d.join(e,r.name))}catch(t){if(t.code==="ENOENT")return[];throw t}}async function Ct(e){try{await p.unlink(e)}catch(t){if(t.code!=="ENOENT")throw t}finally{D(e)}}async function Pt(e){try{await p.rm(e,{recursive:!0,force:!0})}catch(t){if(t.code!=="ENOENT")throw t}}function kt(e,t){try{return JSON.parse(e)}catch{return t}}function St(e,t="{}"){try{return JSON.stringify(e)}catch{return t}}function It(e){let t=[];for(let r of e.split(`
8
- `)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}function Ot(e){let t=Nt(e);return{frontmatter:t.frontmatter,content:t.content.trim()}}function Mt(e,t){let r=Object.fromEntries(Object.entries(e).filter(([n,o])=>o!==void 0));return["---",Ee(r),"---","",t].join(`
9
- `)}function $t(e){return e.trimStart().startsWith("---")}function Nt(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return{frontmatter:{},content:e};let r=t.search(/\r?\n/);if(r<0||t.slice(0,r).trim()!=="---")return{frontmatter:{},content:e};let n=t.slice(r+(t[r]==="\r"?2:1)),o=n.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!o||o.index===void 0)throw new Error("YAML frontmatter is not closed.");let s=n.slice(0,o.index),i=o[0],a=o.index+i.length;return{frontmatter:ye(s),content:n.slice(a)}}function ye(e){let t={},r=e.split(/\r?\n/);for(let n=0;n<r.length;n+=1){let o=r[n];if(!o.trim()||o.trimStart().startsWith("#"))continue;if(/^\s/.test(o))throw new Error(`Unexpected indentation at line ${n+1}.`);let s=Lt(o,n+1);if(s.key==="<<")throw new Error("YAML merge keys are not supported.");if(s.value!==""){t[s.key]=he(s.value,n+1);continue}let i=Dt(r,n+1);t[s.key]=i.value,n=i.nextIndex-1}return t}function Dt(e,t){let r=[],n=t;for(;n<e.length;n+=1){let s=e[n];if(!s.trim()){r.push(s);continue}if(!/^\s/.test(s))break;r.push(s.replace(/^ {2}/,""))}let o=r.filter(s=>s.trim()&&!s.trimStart().startsWith("#"));return o.length===0?{value:{},nextIndex:n}:o.every(s=>s.trimStart().startsWith("- "))?{value:o.map((s,i)=>he(s.trimStart().slice(2),t+i+1)),nextIndex:n}:{value:ye(r.join(`
10
- `)),nextIndex:n}}function Lt(e,t){let r=e.indexOf(":");if(r<=0)throw new Error(`Invalid YAML line ${t}.`);let n=e.slice(0,r).trim(),o=e.slice(r+1).trim();if(!n)throw new Error(`Invalid YAML key at line ${t}.`);return{key:n,value:o}}function he(e,t){if(e==="")return"";if(e==="[]")return[];if(e==="{}")return{};if(e==="true")return!0;if(e==="false")return!1;if(e==="null"||e==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(e))return Number(e);if(e.startsWith('"'))return ge(e,t);if(e.startsWith("'")){if(!e.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${t}.`);return e.slice(1,-1).replace(/''/g,"'")}if(e.startsWith("[")||e.startsWith("{"))return ge(e,t);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${t}.`);return e}function ge(e,t){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${t}.`)}}function Ee(e,t=""){return Object.entries(e).map(([r,n])=>Bt(r,n,t)).join(`
11
- `)}function Bt(e,t,r){return Array.isArray(t)?`${r}${e}: ${JSON.stringify(t)}`:t&&typeof t=="object"?`${r}${e}:
12
- ${Ee(t,`${r} `)}`:`${r}${e}: ${JSON.stringify(t)}`}var y=H(require("path"),1);function be(e,t){let r=y.resolve(e),n=y.resolve(e,t);return n===r?!0:r===y.parse(r).root?n.startsWith(r):n.startsWith(r+y.sep)}function Xt(e,t){if(y.isAbsolute(t))return y.resolve(t);if(!be(e,t))throw new Error(`PathSecurity: Path traversal attempt detected: ${t}`);return y.resolve(e,t)}function zt(e,t=process.platform){let r=y.resolve(e);return t==="win32"?r.toLowerCase():r}var x=require("node:os"),P=require("node:child_process"),Te=require("node:fs"),b=require("node:path");var j=require("node:child_process"),Ft=5e3,we=128;function qt(e,t,r){let n={tool:e,timeoutMs:r};return t.timedOut?{...n,terminated:!1,reason:"timeout",exitCode:null,detail:`${e} did not finish within ${r}ms`}:t.error!==void 0?{...n,terminated:!1,reason:"spawn-error",exitCode:null,detail:t.error}:t.status===0?{...n,terminated:!0,reason:"terminated",exitCode:0}:e==="taskkill"&&t.status===we?{...n,terminated:!0,reason:"not-running",exitCode:we}:{...n,terminated:!1,reason:"failed",exitCode:t.status,detail:`${e} exited with code ${t.status??"unknown"}`}}var Ht=(e,t,r)=>new Promise(n=>{let o=!1,s={},i=c=>{o||(o=!0,s.timer&&clearTimeout(s.timer),n(c))},a;try{a=(0,j.spawn)(e,[...t],{stdio:"ignore",windowsHide:!0})}catch(c){i({status:null,timedOut:!1,error:c instanceof Error?c.message:String(c)});return}s.timer=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}i({status:null,timedOut:!0})},r),s.timer.unref?.(),a.once("error",c=>{i({status:null,timedOut:!1,error:c.code??c.message})}),a.once("close",c=>{i(c===null?{status:null,timedOut:!1,error:"no exit status"}:{status:c,timedOut:!1})})});function xe(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):Ft}function Ut(e,t){return{terminated:!1,reason:"failed",tool:e,exitCode:null,timeoutMs:t,detail:"pid is not a positive integer"}}function jt(e){return["/PID",String(e),"/T","/F"]}async function Re(e,t={}){let r=xe(t.timeoutMs);return!Number.isSafeInteger(e)||e<=0?Ut("taskkill",r):Vt("taskkill","taskkill.exe",jt(e),{timeoutMs:r,run:t.run})}async function Vt(e,t,r,n={}){let o=xe(n.timeoutMs),s;try{s=await(n.run??Ht)(t,r,o)}catch(i){s={status:null,timedOut:!1,error:i instanceof Error?i.message:String(i)}}return qt(e,s,o)}var B=(0,x.platform)(),C=B==="win32",Wt=B==="darwin",Kt=B==="linux",Gt=(0,x.release)(),Yt=(0,x.homedir)();function Zt(){let e=process.env.XENO_AGENT_HOME?.trim();return e?(0,b.resolve)(e):(0,b.resolve)((0,x.homedir)(),".xeno-agent")}function Jt(){let e=process.env.XENO_CONFIG_DIR?.trim();return e?(0,b.resolve)(e):(0,b.resolve)((0,x.homedir)(),".xeno-code")}function Qt(e){return(0,b.resolve)(e,".xeno-code")}function er(){return C?"powershell":process.env.SHELL?.split("/").pop()??"bash"}var W=5e3,K=4096,V=["rev-parse","--is-inside-work-tree"];function _e(){if(!C)return{file:"git",args:V};let e=(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(t=>t.toLowerCase()).filter(t=>[".exe",".com",".cmd",".bat"].includes(t));for(let t of(process.env.PATH??"").split(b.delimiter).filter(Boolean)){let r=t.replace(/^"(.*)"$/,"$1");for(let n of e){let o=(0,b.resolve)(r,`git${n}`);try{if(!(0,Te.statSync)(o).isFile())continue}catch{continue}if(n!==".cmd"&&n!==".bat")return{file:o,args:V};if(/["%!\r\n\0]/.test(o))throw new Error("Git wrapper path cannot be represented safely");let s=process.env.SystemRoot??process.env.WINDIR;if(!s)throw new Error("Windows command interpreter is unavailable");return{file:(0,b.join)(s,"System32","cmd.exe"),args:["/d","/s","/c",`""${o}" rev-parse --is-inside-work-tree"`],windowsVerbatimArguments:!0}}}return{file:"git",args:V}}function tr(e){try{let t=_e();if(t.windowsVerbatimArguments){let r=(0,P.spawnSync)(t.file,t.args,{cwd:e,encoding:"utf8",windowsHide:!0,windowsVerbatimArguments:!0,timeout:W,maxBuffer:K,stdio:["ignore","pipe","ignore"]});return!r.error&&r.status===0&&r.stdout.trim()==="true"}return(0,P.execFileSync)(t.file,t.args,{cwd:e,encoding:"utf8",windowsHide:!0,timeout:W,maxBuffer:K,stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}function rr(e){return new Promise(t=>{let r,n=!1,o={},s=0,i=[],a=l=>{n||(n=!0,o.timer&&clearTimeout(o.timer),r?.stdout?.destroy(),r?.unref(),t(l))},c=()=>{if(r.exitCode===null&&r.signalCode===null)if(C&&r.pid)Re(r.pid);else if(!C&&r.pid)try{process.kill(-r.pid,"SIGKILL")}catch{try{r.kill("SIGKILL")}catch{}}else try{r.kill("SIGKILL")}catch{}a(!1)};try{let l=_e();r=(0,P.spawn)(l.file,l.args,{cwd:e,windowsHide:!0,detached:!C,windowsVerbatimArguments:l.windowsVerbatimArguments,stdio:["ignore","pipe","ignore"]})}catch{a(!1);return}o.timer=setTimeout(c,W),r.stdout?.on("data",l=>{if(!n){if(s+=l.byteLength,s>K){c();return}i.push(Buffer.from(l))}}),r.once("error",()=>a(!1)),r.once("close",l=>a(l===0&&Buffer.concat(i).toString("utf8").trim()==="true"))})}function nr(e,t){for(let r of t)if(e[r]===void 0||e[r]===null||e[r]==="")return`Missing required parameter: ${r}`;return null}function or(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="string")throw new Error(`Parameter ${t} must be a string, got ${typeof n}`);return n}function sr(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="number")throw new Error(`Parameter ${t} must be a number, got ${typeof n}`);if(isNaN(n))throw new Error(`Parameter ${t} is NaN`);return n}function ir(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="boolean")throw new Error(`Parameter ${t} must be a boolean, got ${typeof n}`);return n}function ve(e){if(e.length>5e3)return"Pattern too long (max 5000 characters)";let r=[/(\.\*){3,}/,/(\+\+|\*\*)/,/(.*\+.*\+.*\+)/];for(let n of r)if(n.test(e))return"Pattern contains potentially unsafe constructs that could cause excessive backtracking";return null}function ar(e,t,r=5e3){let n=ve(e);if(n)throw new Error(n);try{return new RegExp(e,t)}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Invalid regex pattern: ${s}`)}}function cr(e,t,r=1e3){if(t.length>1e5)throw new Error(`Input too large for safe regex test (${t.length} chars, max 100000)`);return e.test(t)}var Ae=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(Ae||{}),k=1;function ur(e){k=e}function dr(){return k}function R(){return new Date().toISOString()}function lr(e,t){k<=0&&(t!==void 0?process.stderr.write(`[${R()}] DEBUG: ${e} ${X(t)}
6
+ `):r}function bt(e){return e.includes(`\r
7
+ `)?/(^|[^\r])\n/.test(e):!1}async function me(e){let t=await p.readFile(e),r=ce(t),n=de(t,r);return{content:n,encoding:r,lineEnding:fe(n),sizeBytes:t.length}}async function Et(e,t,r){let n=r?.preserveLineEndings?t:pe(t,r?.lineEnding??"LF");await ie(e,le(n,r?.encoding??"utf8"))}async function wt(e,t){let r=new Set,n=f.resolve(e),o=t===void 0?void 0:f.resolve(t);if(o!==void 0){let s=f.relative(o,n);if(f.isAbsolute(s)||s===".."||s.startsWith(`..${f.sep}`))return"LF"}for(;!r.has(n);){r.add(n);try{let i=(0,I.readdirSync)(n,{withFileTypes:!0}).filter(c=>c.isFile()).map(c=>c.name).sort();for(let c of i){if(c.startsWith("."))continue;let a=f.extname(c).toLowerCase();if([".ts",".tsx",".js",".jsx",".json",".md",".txt",".yaml",".yml",".css",".html",".xml",".sh",".ps1"].includes(a))try{let d=f.join(n,c),l=await me(d);if(l.content.length>0)return l.lineEnding}catch{}}}catch{}if(o!==void 0&&f.relative(o,n)==="")break;let s=f.dirname(n);if(s===n)break;n=s}return"LF"}function xt(e,t,r){let n=[],o=[{dir:e,depth:0}],s=new Set;for(;o.length>0&&n.length<r;){let i=o.shift();if(!s.has(i.dir)){s.add(i.dir);try{let c=(0,I.readdirSync)(i.dir,{withFileTypes:!0});for(let a of c){let d=f.join(i.dir,a.name);if(a.isFile()){if(n.push(d),n.length>=r)break;continue}a.isDirectory()&&i.depth<t&&!a.name.startsWith(".")&&a.name!=="node_modules"&&o.push({dir:d,depth:i.depth+1})}}catch{}}}return n}function se(e,t){let r=f.relative(e,t);return r===""||!r.startsWith("..")&&!f.isAbsolute(r)}function Rt(e,t){try{let r=f.dirname(e),n=f.basename(e,f.extname(e)).toLowerCase(),o=f.basename(e).toLowerCase(),s=[r,f.dirname(r)],i=t!==void 0&&se(t,e)?t:void 0,c=s.flatMap(d=>xt(d,2,500)).filter(d=>i===void 0||se(i,d)),a=null;for(let d of c){let l=f.basename(d).toLowerCase(),u=f.basename(d,f.extname(d)).toLowerCase(),g=null;if(l===o?g=0:u===n?g=1:(l.includes(n)||n.includes(u))&&(g=2),g===null)continue;let v=f.relative(r,d).split(f.sep).length,h=g+v*.01;(!a||h<a.score)&&(a={filePath:d,score:h})}return a?.filePath??null}catch{}return null}async function Tt(e){try{return await p.readFile(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function _t(e){return(0,_.existsSync)(e)}async function vt(e,t){try{let n=(await p.readdir(e,{withFileTypes:!0})).filter(o=>o.isFile()).map(o=>f.join(e,o.name));return t&&(n=n.filter(o=>t.test(f.basename(o)))),n}catch(r){if(r.code==="ENOENT")return[];throw r}}async function At(e){try{return(await p.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>f.join(e,r.name))}catch(t){if(t.code==="ENOENT")return[];throw t}}async function kt(e){try{await p.unlink(e)}catch(t){if(t.code!=="ENOENT")throw t}finally{D(e)}}async function Ct(e){try{await p.rm(e,{recursive:!0,force:!0})}catch(t){if(t.code!=="ENOENT")throw t}}function Pt(e,t){try{return JSON.parse(e)}catch{return t}}function St(e,t="{}"){try{return JSON.stringify(e)}catch{return t}}function It(e){let t=[];for(let r of e.split(`
8
+ `)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}function Ot(e){let t=Nt(e);return{frontmatter:t.frontmatter,content:t.content.trim()}}function Mt(e,t){let r=Object.fromEntries(Object.entries(e).filter(([n,o])=>o!==void 0));return["---",be(r),"---","",t].join(`
9
+ `)}function $t(e){return e.trimStart().startsWith("---")}function Nt(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return{frontmatter:{},content:e};let r=t.search(/\r?\n/);if(r<0||t.slice(0,r).trim()!=="---")return{frontmatter:{},content:e};let n=t.slice(r+(t[r]==="\r"?2:1)),o=n.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!o||o.index===void 0)throw new Error("YAML frontmatter is not closed.");let s=n.slice(0,o.index),i=o[0],c=o.index+i.length;return{frontmatter:ye(s),content:n.slice(c)}}function ye(e){let t={},r=e.split(/\r?\n/);for(let n=0;n<r.length;n+=1){let o=r[n];if(!o.trim()||o.trimStart().startsWith("#"))continue;if(/^\s/.test(o))throw new Error(`Unexpected indentation at line ${n+1}.`);let s=Bt(o,n+1);if(s.key==="<<")throw new Error("YAML merge keys are not supported.");let i=s.value.match(/^([|>])([+-]?)$/);if(i){let a=Dt(r,n+1,i[1],i[2]??"");t[s.key]=a.value,n=a.nextIndex-1;continue}if(s.value!==""){t[s.key]=he(s.value,n+1);continue}let c=Lt(r,n+1);t[s.key]=c.value,n=c.nextIndex-1}return t}function Dt(e,t,r,n){let o=[],s=t;for(;s<e.length;s+=1){let l=e[s];if(l.trim()===""){o.push("");continue}if(!/^\s/.test(l))break;o.push(l)}let i=o.filter(l=>l.trim()!=="").map(l=>l.match(/^ */)[0].length),c=i.length>0?Math.min(...i):0,a=o.map(l=>l.trim()===""?"":l.slice(c));for(;a.length>0&&a[a.length-1]==="";)a.pop();let d;return r==="|"?d=a.join(`
10
+ `):(d="",a.forEach((l,u)=>{if(u===0){d=l;return}let g=a[u-1];l===""?d+=`
11
+ `:g===""?d+=l:d+=" "+l})),{value:n==="-"?d:d+`
12
+ `,nextIndex:s}}function Lt(e,t){let r=[],n=t;for(;n<e.length;n+=1){let s=e[n];if(!s.trim()){r.push(s);continue}if(!/^\s/.test(s))break;r.push(s.replace(/^ {2}/,""))}let o=r.filter(s=>s.trim()&&!s.trimStart().startsWith("#"));return o.length===0?{value:{},nextIndex:n}:o.every(s=>s.trimStart().startsWith("- "))?{value:o.map((s,i)=>he(s.trimStart().slice(2),t+i+1)),nextIndex:n}:{value:ye(r.join(`
13
+ `)),nextIndex:n}}function Bt(e,t){let r=e.indexOf(":");if(r<=0)throw new Error(`Invalid YAML line ${t}.`);let n=e.slice(0,r).trim(),o=e.slice(r+1).trim();if(!n)throw new Error(`Invalid YAML key at line ${t}.`);return{key:n,value:o}}function he(e,t){if(e==="")return"";if(e==="[]")return[];if(e==="{}")return{};if(e==="true")return!0;if(e==="false")return!1;if(e==="null"||e==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(e))return Number(e);if(e.startsWith('"'))return ge(e,t);if(e.startsWith("'")){if(!e.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${t}.`);return e.slice(1,-1).replace(/''/g,"'")}if(e.startsWith("[")||e.startsWith("{"))return ge(e,t);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${t}.`);return e}function ge(e,t){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${t}.`)}}function be(e,t=""){return Object.entries(e).map(([r,n])=>Xt(r,n,t)).join(`
14
+ `)}function Xt(e,t,r){return Array.isArray(t)?`${r}${e}: ${JSON.stringify(t)}`:t&&typeof t=="object"?`${r}${e}:
15
+ ${be(t,`${r} `)}`:`${r}${e}: ${JSON.stringify(t)}`}var y=H(require("path"),1);function Ee(e,t){let r=y.resolve(e),n=y.resolve(e,t);return n===r?!0:r===y.parse(r).root?n.startsWith(r):n.startsWith(r+y.sep)}function zt(e,t){if(y.isAbsolute(t))return y.resolve(t);if(!Ee(e,t))throw new Error(`PathSecurity: Path traversal attempt detected: ${t}`);return y.resolve(e,t)}function Ft(e,t=process.platform){let r=y.resolve(e);return t==="win32"?r.toLowerCase():r}var x=require("node:os"),C=require("node:child_process"),Te=require("node:fs"),E=require("node:path");var j=require("node:child_process"),qt=5e3,we=128;function Ht(e,t,r){let n={tool:e,timeoutMs:r};return t.timedOut?{...n,terminated:!1,reason:"timeout",exitCode:null,detail:`${e} did not finish within ${r}ms`}:t.error!==void 0?{...n,terminated:!1,reason:"spawn-error",exitCode:null,detail:t.error}:t.status===0?{...n,terminated:!0,reason:"terminated",exitCode:0}:e==="taskkill"&&t.status===we?{...n,terminated:!0,reason:"not-running",exitCode:we}:{...n,terminated:!1,reason:"failed",exitCode:t.status,detail:`${e} exited with code ${t.status??"unknown"}`}}var Ut=(e,t,r)=>new Promise(n=>{let o=!1,s={},i=a=>{o||(o=!0,s.timer&&clearTimeout(s.timer),n(a))},c;try{c=(0,j.spawn)(e,[...t],{stdio:"ignore",windowsHide:!0})}catch(a){i({status:null,timedOut:!1,error:a instanceof Error?a.message:String(a)});return}s.timer=setTimeout(()=>{try{c.kill("SIGKILL")}catch{}i({status:null,timedOut:!0})},r),s.timer.unref?.(),c.once("error",a=>{i({status:null,timedOut:!1,error:a.code??a.message})}),c.once("close",a=>{i(a===null?{status:null,timedOut:!1,error:"no exit status"}:{status:a,timedOut:!1})})});function xe(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):qt}function jt(e,t){return{terminated:!1,reason:"failed",tool:e,exitCode:null,timeoutMs:t,detail:"pid is not a positive integer"}}function Vt(e){return["/PID",String(e),"/T","/F"]}async function Re(e,t={}){let r=xe(t.timeoutMs);return!Number.isSafeInteger(e)||e<=0?jt("taskkill",r):Wt("taskkill","taskkill.exe",Vt(e),{timeoutMs:r,run:t.run})}async function Wt(e,t,r,n={}){let o=xe(n.timeoutMs),s;try{s=await(n.run??Ut)(t,r,o)}catch(i){s={status:null,timedOut:!1,error:i instanceof Error?i.message:String(i)}}return Ht(e,s,o)}var B=(0,x.platform)(),k=B==="win32",Kt=B==="darwin",Gt=B==="linux",Yt=(0,x.release)(),Zt=(0,x.homedir)();function Jt(){let e=process.env.XENO_AGENT_HOME?.trim();return e?(0,E.resolve)(e):(0,E.resolve)((0,x.homedir)(),".xeno-agent")}function Qt(){let e=process.env.XENO_CONFIG_DIR?.trim();return e?(0,E.resolve)(e):(0,E.resolve)((0,x.homedir)(),".xeno-code")}function er(e){return(0,E.resolve)(e,".xeno-code")}function tr(){return k?"powershell":process.env.SHELL?.split("/").pop()??"bash"}var W=5e3,K=4096,V=["rev-parse","--is-inside-work-tree"];function _e(){if(!k)return{file:"git",args:V};let e=(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(t=>t.toLowerCase()).filter(t=>[".exe",".com",".cmd",".bat"].includes(t));for(let t of(process.env.PATH??"").split(E.delimiter).filter(Boolean)){let r=t.replace(/^"(.*)"$/,"$1");for(let n of e){let o=(0,E.resolve)(r,`git${n}`);try{if(!(0,Te.statSync)(o).isFile())continue}catch{continue}if(n!==".cmd"&&n!==".bat")return{file:o,args:V};if(/["%!\r\n\0]/.test(o))throw new Error("Git wrapper path cannot be represented safely");let s=process.env.SystemRoot??process.env.WINDIR;if(!s)throw new Error("Windows command interpreter is unavailable");return{file:(0,E.join)(s,"System32","cmd.exe"),args:["/d","/s","/c",`""${o}" rev-parse --is-inside-work-tree"`],windowsVerbatimArguments:!0}}}return{file:"git",args:V}}function rr(e){try{let t=_e();if(t.windowsVerbatimArguments){let r=(0,C.spawnSync)(t.file,t.args,{cwd:e,encoding:"utf8",windowsHide:!0,windowsVerbatimArguments:!0,timeout:W,maxBuffer:K,stdio:["ignore","pipe","ignore"]});return!r.error&&r.status===0&&r.stdout.trim()==="true"}return(0,C.execFileSync)(t.file,t.args,{cwd:e,encoding:"utf8",windowsHide:!0,timeout:W,maxBuffer:K,stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}function nr(e){return new Promise(t=>{let r,n=!1,o={},s=0,i=[],c=d=>{n||(n=!0,o.timer&&clearTimeout(o.timer),r?.stdout?.destroy(),r?.unref(),t(d))},a=()=>{if(r.exitCode===null&&r.signalCode===null)if(k&&r.pid)Re(r.pid);else if(!k&&r.pid)try{process.kill(-r.pid,"SIGKILL")}catch{try{r.kill("SIGKILL")}catch{}}else try{r.kill("SIGKILL")}catch{}c(!1)};try{let d=_e();r=(0,C.spawn)(d.file,d.args,{cwd:e,windowsHide:!0,detached:!k,windowsVerbatimArguments:d.windowsVerbatimArguments,stdio:["ignore","pipe","ignore"]})}catch{c(!1);return}o.timer=setTimeout(a,W),r.stdout?.on("data",d=>{if(!n){if(s+=d.byteLength,s>K){a();return}i.push(Buffer.from(d))}}),r.once("error",()=>c(!1)),r.once("close",d=>c(d===0&&Buffer.concat(i).toString("utf8").trim()==="true"))})}function or(e,t){for(let r of t)if(e[r]===void 0||e[r]===null||e[r]==="")return`Missing required parameter: ${r}`;return null}function sr(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="string")throw new Error(`Parameter ${t} must be a string, got ${typeof n}`);return n}function ir(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="number")throw new Error(`Parameter ${t} must be a number, got ${typeof n}`);if(isNaN(n))throw new Error(`Parameter ${t} is NaN`);return n}function ar(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="boolean")throw new Error(`Parameter ${t} must be a boolean, got ${typeof n}`);return n}function ve(e){if(e.length>5e3)return"Pattern too long (max 5000 characters)";let r=[/(\.\*){3,}/,/(\+\+|\*\*)/,/(.*\+.*\+.*\+)/];for(let n of r)if(n.test(e))return"Pattern contains potentially unsafe constructs that could cause excessive backtracking";return null}function cr(e,t,r=5e3){let n=ve(e);if(n)throw new Error(n);try{return new RegExp(e,t)}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Invalid regex pattern: ${s}`)}}function ur(e,t,r=1e3){if(t.length>1e5)throw new Error(`Input too large for safe regex test (${t.length} chars, max 100000)`);return e.test(t)}var Ae=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(Ae||{}),P=1;function dr(e){P=e}function lr(){return P}function R(){return new Date().toISOString()}function fr(e,t){P<=0&&(t!==void 0?process.stderr.write(`[${R()}] DEBUG: ${e} ${X(t)}
13
16
  `):process.stderr.write(`[${R()}] DEBUG: ${e}
14
- `))}function fr(e,t){k<=1&&(t!==void 0?process.stderr.write(`[${R()}] INFO: ${e} ${X(t)}
17
+ `))}function pr(e,t){P<=1&&(t!==void 0?process.stderr.write(`[${R()}] INFO: ${e} ${X(t)}
15
18
  `):process.stderr.write(`[${R()}] INFO: ${e}
16
- `))}function pr(e,t){k<=2&&(t!==void 0?process.stderr.write(`[${R()}] WARN: ${e} ${X(t)}
19
+ `))}function mr(e,t){P<=2&&(t!==void 0?process.stderr.write(`[${R()}] WARN: ${e} ${X(t)}
17
20
  `):process.stderr.write(`[${R()}] WARN: ${e}
18
- `))}function mr(e,t){k<=3&&(t!==void 0?process.stderr.write(`[${R()}] ERROR: ${e} ${X(t)}
21
+ `))}function gr(e,t){P<=3&&(t!==void 0?process.stderr.write(`[${R()}] ERROR: ${e} ${X(t)}
19
22
  `):process.stderr.write(`[${R()}] ERROR: ${e}
20
- `))}function X(e){if(e==null)return"";if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}var gr=/^[A-Za-z0-9:._*-]{1,64}$/,yr=/^[A-Za-z0-9_-][A-Za-z0-9 _-]{0,30}[A-Za-z0-9_-]$/,hr=/^[0-9][0-9A-Za-z.+-]{0,40}$/,Ce=Object.freeze({"x-xeno-source":Object.freeze(["auto","quota","credits","byok"]),"x-xeno-byok-mode":Object.freeze(["local","cloud"])}),Er=/^[\x21-\x7E]{1,64}$/;function br(e){if(!e||typeof e!="object")throw new TypeError("requestContext must be an object");let t=Object.keys(e).filter(s=>s!=="surface"&&s!=="client"&&s!=="headers");if(t.length>0)throw new TypeError(`requestContext does not accept: ${t.join(", ")}`);if(typeof e.surface!="string"||!gr.test(e.surface))throw new TypeError("requestContext.surface must match /^[A-Za-z0-9:._*-]{1,64}$/");let r=wr(e.headers),n=r?{surface:e.surface,headers:r}:{surface:e.surface};if(e.client===void 0)return Object.freeze(n);let o=e.client;if(!o||typeof o!="object"||Object.keys(o).some(s=>s!=="name"&&s!=="version"))throw new TypeError("requestContext.client must be { name, version }");if(typeof o.name!="string"||!yr.test(o.name))throw new TypeError("requestContext.client.name must be 2-32 characters of letters, digits, space, _ or -");if(typeof o.version!="string"||!hr.test(o.version))throw new TypeError("requestContext.client.version must start with a digit, e.g. 1.2.3");return Object.freeze({...n,client:Object.freeze({name:o.name,version:o.version})})}function wr(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("requestContext.headers must be an object");let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase(),s=Object.prototype.hasOwnProperty.call(Ce,o)?Ce[o]:void 0;if(!s)throw new TypeError(`requestContext.headers does not accept: ${r}`);if(typeof n!="string"||!Er.test(n))throw new TypeError(`requestContext.headers.${o} must be 1-64 printable ASCII characters`);if(!s.includes(n))throw new TypeError(`requestContext.headers.${o} must be one of: ${s.join(", ")}`);if(Object.prototype.hasOwnProperty.call(t,o))throw new TypeError(`requestContext.headers.${o} is given twice`);t[o]=n}return Object.freeze(t)}function xr(e){return e?{...e.headers??{},"X-Xeno-Surface":e.surface,...e.client?{"X-Xeno-Client":`${e.client.name}/${e.client.version}`}:{}}:{}}var O=class extends Error{statusCode;body;retryAfterMs;requestId;cfRay;constructor(t,r={}){super(t,r.cause!==void 0?{cause:r.cause}:void 0),this.name="ApiTransientError",this.statusCode=r.statusCode,this.retryAfterMs=r.retryAfterMs,this.requestId=r.requestId,this.cfRay=r.cfRay;for(let n of["code","category","retryable","providerCode","remedy"])r[n]!==void 0&&Object.defineProperty(this,n,{value:r[n],enumerable:!0,configurable:!0,writable:!1})}},z={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function F(e,t){let r=process.env[e],n=r?Number.parseInt(r,10):Number.NaN;return!Number.isFinite(n)||n<0?t:n}function Rr(e={}){let t=Math.max(0,e.maxRetries??F("XENO_API_MAX_RETRIES",z.maxRetries)),r=Math.max(50,e.baseDelayMs??F("XENO_API_BASE_DELAY_MS",z.baseDelayMs)),n=Math.max(r,e.maxDelayMs??F("XENO_API_MAX_DELAY_MS",z.maxDelayMs)),o=Math.max(0,e.jitterMs??F("XENO_API_RETRY_JITTER_MS",z.jitterMs));return{maxRetries:t,baseDelayMs:r,maxDelayMs:n,jitterMs:o}}function Tr(e,t,r){if(t.retryAfterMs&&t.retryAfterMs>0)return Math.min(t.retryAfterMs,r.maxDelayMs);let n=Math.min(r.baseDelayMs*Math.pow(2,e),r.maxDelayMs),o=Math.floor(Math.random()*r.jitterMs);return Math.min(n+o,r.maxDelayMs)}function Pe(e){let t=e.toLowerCase();return t.includes("rate limit")||t.includes("too many requests")||t.includes("429")}function _r(e){let t=e.toLowerCase();return t.includes("network")||t.includes("timeout")||t.includes("fetch failed")||t.includes("socket hang up")||t.includes("econnreset")||t.includes("eai_again")||t.includes("enotfound")||t.includes("econnrefused")||t.includes("tls")||t.includes("temporarily unavailable")}function Y(e){if(e instanceof O)return{statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId,cfRay:e.cfRay};if(!(e instanceof Error))return{};let t=e;if(t.statusCode!==void 0||t.retryAfterMs!==void 0||t.requestId!==void 0||t.cfRay!==void 0)return{statusCode:t.statusCode,retryAfterMs:t.retryAfterMs,requestId:t.requestId,cfRay:t.cfRay};let r=e.message.toLowerCase();return Pe(r)?{statusCode:429}:{}}var G="408|425|429|500|502|503|504";function ke(e){let t=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${G})\\b`,"i"),r=new RegExp(`\\b(?:${G})\\s+(?:internal|bad\\s+gateway|service\\s+unavailable|gateway\\s+time|request\\s+time|too\\s+early|too\\s+many)`,"i"),n=new RegExp(`^\\s*(?:${G})\\b`);return t.test(e)||r.test(e)||n.test(e)}function Se(e){if(e&&typeof e=="object"&&"retryable"in e)return e.retryable===!0;if(e instanceof O){let{statusCode:t}=Y(e);if(t)return t===429||t>=500||t===408||t===409||t===425}if(e instanceof Error){let t=e.name?.toLowerCase()??"";return t==="aborterror"||t==="agentinterruptederror"||e.message.toLowerCase().includes("aborted")||e.message.toLowerCase().includes("interrupted")?!1:ke(e.message)?!0:Pe(e.message)||_r(e.message.toLowerCase())}return!1}function vr(e){if(e.onAbort)return e.onAbort();let t=new Error("The operation was aborted");return t.name="AbortError",t}async function Ar(e,t={}){let r=Rr(t),n;for(let o=0;o<=r.maxRetries;o++)try{if(t.signal?.aborted)throw vr(t);return t.onBeforeAttempt?.(o),await e()}catch(s){if(n=s,!(t.shouldRetry?t.shouldRetry(s,o):Se(s))||o===r.maxRetries)throw s;let a=Y(s),c=Tr(o,a,r),l=t.getDelayMs?.(s,o,c),f=typeof l=="number"&&l>=0?l:c;await new Promise(u=>setTimeout(u,f))}throw n}var Ie=(e,t)=>{if(!e)return 0;let r=t.toLowerCase(),n=r.includes("claude")?3.5:r.includes("gemini")?3.8:(/(^|[/_-])(gpt|o\d)/.test(r),4),o=[...e].filter(i=>i.codePointAt(0)>127).length,s=Math.ceil(e.length/n);return Math.max(1,s+Math.ceil(o*.35))},Oe=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:Ie,countImage:({detail:e})=>e==="high"?2e3:e==="low"?512:1200,safetyMarginRatio:e=>{let t=e.toLowerCase();return t.includes("claude")?.12:t.includes("gemini")?.14:/(^|[/_-])(gpt|o\d)/.test(t)?.1:.18}});function Cr(e,t,r=Oe){return{tokens:Math.max(0,Math.ceil(r.countText(e,t))),source:r.source,adapterId:r.id}}function Me(e){return e?Math.ceil(e.length/4):0}function Pr(e,t){if(!e||t<=0)return"";let r=t*4;if(e.length<=r)return e;let n=e.slice(0,r),o=n.lastIndexOf(" ");return o>r*.8&&(n=n.slice(0,o)),n+"..."}function kr(e,t){return Me(e)<=t}function Sr(e,t){return Math.max(0,t-e)}var Ir={"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 Or(e,t,r){let n=Ir[e];return n?t/1e6*n.input+r/1e6*n.output:0}function Mr(e){return e<=0?"$0.00":e<.001?"<$0.001":e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}var $e=require("node:child_process");function $r(e){let t=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"]}],r=null;for(let n of t)try{let o=(0,$e.spawnSync)(n.command,n.args,{input:e,encoding:"utf8"});if(o.error){r=o.error.message;continue}if(o.status===0)return;r=o.stderr||o.stdout||`exit ${o.status}`}catch(o){r=o instanceof Error?o.message:String(o)}throw new Error(`Clipboard copy failed${r?`: ${r}`:""}`)}function Nr(){return!1}function Dr(e){return!1}function Lr(e){return e}function Br(e){return`Access to ${e} is not restricted.`}function Xr(e){return!1}function zr(e){return null}function Fr(e){return/^data:([^;,]+)[;,]/i.exec(e.trim())?.[1]}function Ne(e){let t=[];for(let r of e){if(r.type==="text"){t.push(r.text);continue}if(r.type==="image_url"){t.push(`[image ${Fr(r.image_url.url)??"unknown"}]`);continue}let n=r.text??r.data;if(n&&n.trim().length>0){t.push(n);continue}let o=r.uri??r.mimeType??"resource";t.push(`[resource ${o}]`)}return t.join(`
23
+ `))}function X(e){if(e==null)return"";if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}var yr=/^[A-Za-z0-9:._*-]{1,64}$/,hr=/^[A-Za-z0-9_-][A-Za-z0-9 _-]{0,30}[A-Za-z0-9_-]$/,br=/^[0-9][0-9A-Za-z.+-]{0,40}$/,ke=Object.freeze({"x-xeno-source":Object.freeze(["auto","quota","credits","byok"]),"x-xeno-byok-mode":Object.freeze(["local","cloud"])}),Er=/^[\x21-\x7E]{1,64}$/;function wr(e){if(!e||typeof e!="object")throw new TypeError("requestContext must be an object");let t=Object.keys(e).filter(s=>s!=="surface"&&s!=="client"&&s!=="headers");if(t.length>0)throw new TypeError(`requestContext does not accept: ${t.join(", ")}`);if(typeof e.surface!="string"||!yr.test(e.surface))throw new TypeError("requestContext.surface must match /^[A-Za-z0-9:._*-]{1,64}$/");let r=xr(e.headers),n=r?{surface:e.surface,headers:r}:{surface:e.surface};if(e.client===void 0)return Object.freeze(n);let o=e.client;if(!o||typeof o!="object"||Object.keys(o).some(s=>s!=="name"&&s!=="version"))throw new TypeError("requestContext.client must be { name, version }");if(typeof o.name!="string"||!hr.test(o.name))throw new TypeError("requestContext.client.name must be 2-32 characters of letters, digits, space, _ or -");if(typeof o.version!="string"||!br.test(o.version))throw new TypeError("requestContext.client.version must start with a digit, e.g. 1.2.3");return Object.freeze({...n,client:Object.freeze({name:o.name,version:o.version})})}function xr(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("requestContext.headers must be an object");let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase(),s=Object.prototype.hasOwnProperty.call(ke,o)?ke[o]:void 0;if(!s)throw new TypeError(`requestContext.headers does not accept: ${r}`);if(typeof n!="string"||!Er.test(n))throw new TypeError(`requestContext.headers.${o} must be 1-64 printable ASCII characters`);if(!s.includes(n))throw new TypeError(`requestContext.headers.${o} must be one of: ${s.join(", ")}`);if(Object.prototype.hasOwnProperty.call(t,o))throw new TypeError(`requestContext.headers.${o} is given twice`);t[o]=n}return Object.freeze(t)}function Rr(e){return e?{...e.headers??{},"X-Xeno-Surface":e.surface,...e.client?{"X-Xeno-Client":`${e.client.name}/${e.client.version}`}:{}}:{}}var O=class extends Error{statusCode;body;retryAfterMs;requestId;cfRay;constructor(t,r={}){super(t,r.cause!==void 0?{cause:r.cause}:void 0),this.name="ApiTransientError",this.statusCode=r.statusCode,this.retryAfterMs=r.retryAfterMs,this.requestId=r.requestId,this.cfRay=r.cfRay;for(let n of["code","category","retryable","providerCode","remedy"])r[n]!==void 0&&Object.defineProperty(this,n,{value:r[n],enumerable:!0,configurable:!0,writable:!1})}},z={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function F(e,t){let r=process.env[e],n=r?Number.parseInt(r,10):Number.NaN;return!Number.isFinite(n)||n<0?t:n}function Tr(e={}){let t=Math.max(0,e.maxRetries??F("XENO_API_MAX_RETRIES",z.maxRetries)),r=Math.max(50,e.baseDelayMs??F("XENO_API_BASE_DELAY_MS",z.baseDelayMs)),n=Math.max(r,e.maxDelayMs??F("XENO_API_MAX_DELAY_MS",z.maxDelayMs)),o=Math.max(0,e.jitterMs??F("XENO_API_RETRY_JITTER_MS",z.jitterMs));return{maxRetries:t,baseDelayMs:r,maxDelayMs:n,jitterMs:o}}function _r(e,t,r){if(t.retryAfterMs&&t.retryAfterMs>0)return Math.min(t.retryAfterMs,r.maxDelayMs);let n=Math.min(r.baseDelayMs*Math.pow(2,e),r.maxDelayMs),o=Math.floor(Math.random()*r.jitterMs);return Math.min(n+o,r.maxDelayMs)}function Ce(e){let t=e.toLowerCase();return t.includes("rate limit")||t.includes("too many requests")||t.includes("429")}function vr(e){let t=e.toLowerCase();return t.includes("network")||t.includes("timeout")||t.includes("fetch failed")||t.includes("socket hang up")||t.includes("econnreset")||t.includes("eai_again")||t.includes("enotfound")||t.includes("econnrefused")||t.includes("tls")||t.includes("temporarily unavailable")}function Y(e){if(e instanceof O)return{statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId,cfRay:e.cfRay};if(!(e instanceof Error))return{};let t=e;if(t.statusCode!==void 0||t.retryAfterMs!==void 0||t.requestId!==void 0||t.cfRay!==void 0)return{statusCode:t.statusCode,retryAfterMs:t.retryAfterMs,requestId:t.requestId,cfRay:t.cfRay};let r=e.message.toLowerCase();return Ce(r)?{statusCode:429}:{}}var G="408|425|429|500|502|503|504";function Pe(e){let t=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${G})\\b`,"i"),r=new RegExp(`\\b(?:${G})\\s+(?:internal|bad\\s+gateway|service\\s+unavailable|gateway\\s+time|request\\s+time|too\\s+early|too\\s+many)`,"i"),n=new RegExp(`^\\s*(?:${G})\\b`);return t.test(e)||r.test(e)||n.test(e)}function Se(e){if(e&&typeof e=="object"&&"retryable"in e)return e.retryable===!0;if(e instanceof O){let{statusCode:t}=Y(e);if(t)return t===429||t>=500||t===408||t===409||t===425}if(e instanceof Error){let t=e.name?.toLowerCase()??"";return t==="aborterror"||t==="agentinterruptederror"||e.message.toLowerCase().includes("aborted")||e.message.toLowerCase().includes("interrupted")?!1:Pe(e.message)?!0:Ce(e.message)||vr(e.message.toLowerCase())}return!1}function Ar(e){if(e.onAbort)return e.onAbort();let t=new Error("The operation was aborted");return t.name="AbortError",t}async function kr(e,t={}){let r=Tr(t),n;for(let o=0;o<=r.maxRetries;o++)try{if(t.signal?.aborted)throw Ar(t);return t.onBeforeAttempt?.(o),await e()}catch(s){if(n=s,!(t.shouldRetry?t.shouldRetry(s,o):Se(s))||o===r.maxRetries)throw s;let c=Y(s),a=_r(o,c,r),d=t.getDelayMs?.(s,o,a),l=typeof d=="number"&&d>=0?d:a;await new Promise(u=>setTimeout(u,l))}throw n}var Ie=(e,t)=>{if(!e)return 0;let r=t.toLowerCase(),n=r.includes("claude")?3.5:r.includes("gemini")?3.8:(/(^|[/_-])(gpt|o\d)/.test(r),4),o=[...e].filter(i=>i.codePointAt(0)>127).length,s=Math.ceil(e.length/n);return Math.max(1,s+Math.ceil(o*.35))},Oe=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:Ie,countImage:({detail:e})=>e==="high"?2e3:e==="low"?512:1200,safetyMarginRatio:e=>{let t=e.toLowerCase();return t.includes("claude")?.12:t.includes("gemini")?.14:/(^|[/_-])(gpt|o\d)/.test(t)?.1:.18}});function Cr(e,t,r=Oe){return{tokens:Math.max(0,Math.ceil(r.countText(e,t))),source:r.source,adapterId:r.id}}function Me(e){return e?Math.ceil(e.length/4):0}function Pr(e,t){if(!e||t<=0)return"";let r=t*4;if(e.length<=r)return e;let n=e.slice(0,r),o=n.lastIndexOf(" ");return o>r*.8&&(n=n.slice(0,o)),n+"..."}function Sr(e,t){return Me(e)<=t}function Ir(e,t){return Math.max(0,t-e)}var Or={"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 Mr(e,t,r){let n=Or[e];return n?t/1e6*n.input+r/1e6*n.output:0}function $r(e){return e<=0?"$0.00":e<.001?"<$0.001":e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}var $e=require("node:child_process");function Nr(e){let t=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"]}],r=null;for(let n of t)try{let o=(0,$e.spawnSync)(n.command,n.args,{input:e,encoding:"utf8"});if(o.error){r=o.error.message;continue}if(o.status===0)return;r=o.stderr||o.stdout||`exit ${o.status}`}catch(o){r=o instanceof Error?o.message:String(o)}throw new Error(`Clipboard copy failed${r?`: ${r}`:""}`)}function Dr(){return!1}function Lr(e){return!1}function Br(e){return e}function Xr(e){return`Access to ${e} is not restricted.`}function zr(e){return!1}function Fr(e){return null}function qr(e){return/^data:([^;,]+)[;,]/i.exec(e.trim())?.[1]}function Ne(e){let t=[];for(let r of e){if(r.type==="text"){t.push(r.text);continue}if(r.type==="image_url"){t.push(`[image ${qr(r.image_url.url)??"unknown"}]`);continue}let n=r.text??r.data;if(n&&n.trim().length>0){t.push(n);continue}let o=r.uri??r.mimeType??"resource";t.push(`[resource ${o}]`)}return t.join(`
21
24
 
22
- `).trim()}function De(e){let t=e.trim();return t.length>0?[{type:"text",text:t}]:[]}function qr(e){return typeof e=="string"?e:Ne(e)}function Le(e){if(e.success)return e.output;let t=[`Error: ${e.error??"Tool execution failed"}`];return e.output.trim().length>0&&t.push(e.output),t.join(`
23
- `)}function Hr(e){let t=e.assistant_content&&e.assistant_content.length>0?e.assistant_content:typeof e.content=="string"?De(e.content):e.content,r=e.assistant_only_content??[],n=Ur(e),o=[...t,...r,...n?[n]:[]];return o.length>0?o:e.content}function Ur(e){let t=e.operation;if(!t)return null;let r=e.evidence??t.evidence??[],n=r.filter(s=>s.status==="verified").length,o=r.filter(s=>s.status==="failed").length;return{type:"text",text:["[xeno_operation]",`operation_id: ${t.operationId}`,`state: ${t.state}`,`terminal: ${t.terminal?"yes":"no"}`,`completion_policy: ${t.completionPolicy}`,t.taskId?`task_id: ${t.taskId}`:null,t.completionReason?`completion_reason: ${t.completionReason}`:null,`evidence: ${n} verified, ${o} failed`,e.retryable===void 0?null:`retryable: ${e.retryable?"yes":"no"}`,"[/xeno_operation]"].filter(s=>!!s).join(`
24
- `)}}function jr(e){return Array.isArray(e)&&e.some(t=>t.type!=="text")}function Vr(e){return typeof e=="string"?De(e):e}function Wr(e,t){return{type:"tool_result",tool_use_id:e,content:Le(t),...t.assistantContent&&t.assistantContent.length>0?{assistant_content:t.assistantContent}:{},...t.assistantOnlyContent&&t.assistantOnlyContent.length>0?{assistant_only_content:t.assistantOnlyContent}:{},is_error:!t.success,...t.operation?{operation:t.operation}:{},...t.evidence&&t.evidence.length>0?{evidence:t.evidence}:{},...t.webContext?{web_context:t.webContext}:{},...t.retryable!==void 0?{retryable:t.retryable}:{}}}function Kr(e,t={}){for(let r of e){let n=r.codePointAt(0);if(n===127)return!0;if(!(n>31)&&!(n===9&&t.allowTab===!0)&&!((n===10||n===13)&&t.allowLineBreaks===!0))return!0}return!1}var Fe=require("node:dns/promises"),M=require("node:net");var w="[redacted]";var Gr=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[redacted:private-key]"],[/((?:^|[\s{,;"'(\[])["']?(?:cookie|set-cookie)["']?\s*[:=]\s*["']?)(?!\[redacted)[^\s"',;]+(?:;\s*[^\s"',;=]+=[^\s"',;]*)*/gi,`$1${w}`],[/((?:^|[\s{,;"'(\[])["']?(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-xeno-api-key|api[-_]?key|apikey|dpop)["']?\s*[:=]\s*["']?)(?:(?:Bearer|Basic|Token|DPoP)\s+)?(?!\[redacted)[^\s"',;]+/gi,`$1${w}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${w}`],[/\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|xeno-[A-Za-z0-9]{24,}|xrun_[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{30,}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9]{30,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g,w],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,w],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${w}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${w}@`]];function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function S(e,t=[]){if(!e)return e;let r=e,n=[...new Set([...t].filter(o=>typeof o=="string"&&o.length>=12))].sort((o,s)=>s.length-o.length);for(let o of n){r=r.replace(new RegExp(`(?<![A-Za-z0-9_-])${Be(o)}(?![A-Za-z0-9_-])`,"g"),w);let s=encodeURIComponent(o);s!==o&&(r=r.replace(new RegExp(`(?<![A-Za-z0-9_-])${Be(s)}(?![A-Za-z0-9_-])`,"g"),w))}for(let[o,s]of Gr)o.lastIndex=0,r=r.replace(o,s);return r}function Z(e,t,r){try{Object.defineProperty(e,t,{value:r,writable:!0,configurable:!0,enumerable:!1})}catch{}}function J(e,t=[],r=0){if(!(e instanceof Error)||r>6)return e;let n=[...t],o=S(e.message,n);if(o!==e.message&&Z(e,"message",o),typeof e.stack=="string"){let i=S(e.stack,n);i!==e.stack&&Z(e,"stack",i)}let s=e.cause;if(s instanceof Error)J(s,n,r+1);else if(s!=null){let i;try{i=typeof s=="string"?s:JSON.stringify(s)??String(s)}catch{i=String(s)}let a=S(i,n);a!==i&&Z(e,"cause",a)}for(let i of Object.keys(e)){let a=e[i];if(typeof a=="string"){let c=S(a,n);if(c!==a)try{e[i]=c}catch{}}}return e}var q=class extends Error{category;code;retryable;providerId;statusCode;retryAfterMs;requestId;providerCode;remedy;constructor(t,r){super(S(t),r.cause!==void 0?{cause:r.cause}:void 0),this.name="ProviderError",this.category=r.category,this.code=r.code,this.retryable=r.retryable??!1,this.providerId=r.providerId,this.statusCode=r.statusCode,this.retryAfterMs=r.retryAfterMs,this.requestId=r.requestId,r.providerCode!==void 0&&(this.providerCode=r.providerCode),r.remedy!==void 0&&(this.remedy=r.remedy),J(this)}};var qe=new Set(["metadata.google.internal","metadata.azure.internal","instance-data.ec2.internal"]);function m(e){return new q(`Provider endpoint rejected: ${e}`,{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"})}function Yr(e){let t=e.split(".");if(t.length!==4)return null;let r=t.map(n=>Number(n));return r.every(n=>Number.isInteger(n)&&n>=0&&n<=255)?r:null}function Xe(e){let t=Yr(e);if(!t)return"public";let[r,n]=t;return r===0?"unspecified":r===127?"loopback":r===169&&n===254?"link-local":r===10||r===172&&n>=16&&n<=31||r===192&&n===168?"private":"public"}function T(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"").split("%")[0];(0,M.isIP)(t)===6&&(t=new URL(`http://[${t}]`).hostname.slice(1,-1));let r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(r){let n=Number.parseInt(r[1],16),o=Number.parseInt(r[2],16);return`${n>>8}.${n&255}.${o>>8}.${o&255}`}return t}function He(e){let t=T(e);return(0,M.isIP)(t)===4?Xe(t):t==="::"||t==="::0"?"unspecified":t==="::1"?"loopback":t.startsWith("::ffff:")?Xe(t.slice(7)):/^f[cd]/.test(t)?"private":/^fe[89ab]/.test(t)?"link-local":"public"}function ze(e){return e==="example"||e.endsWith(".example")||e==="test"||e.endsWith(".test")||e==="invalid"||e.endsWith(".invalid")}function Zr(e){return e==="localhost"||e.endsWith(".localhost")}function Ue(e,t={}){let r;try{r=new URL(e)}catch{throw m("the URL is invalid")}if(r.username||r.password)throw m("embedded credentials are forbidden");if(r.hash||r.search)throw m("base URLs cannot contain a query or fragment");if(!r.hostname||r.hostname.includes("%"))throw m("the hostname is empty or ambiguous");if(qe.has(r.hostname.toLowerCase()))throw m("cloud metadata destinations are forbidden");if(r.protocol!=="https:"&&r.protocol!=="http:")throw m(`scheme ${r.protocol} is unsupported`);let n=t.profile??"public-https";if(r.protocol==="http:"&&n!=="local-network")throw m("plain HTTP requires the explicit local-network profile");let o=r.hostname.replace(/^\[|\]$/g,""),s=(0,M.isIP)(o)?He(o):null;if(s==="link-local"||s==="unspecified")throw m(`${s} destinations are forbidden`);if(n==="public-https"&&(s==="private"||s==="loopback"||Zr(r.hostname)))throw m("private and loopback destinations require the local-network profile");if(n==="local-network"&&r.protocol==="http:"&&s==="public"&&!t.allowedHosts?.includes(r.hostname))throw m("local-network HTTP must resolve to loopback or a private address");return r}async function je(e,t={}){let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(qe.has(r))throw m("cloud metadata destinations are forbidden");let n=new Set((t.allowedHosts??[]).map(i=>i.toLowerCase())),o=(0,M.isIP)(r)?[r]:ze(r)?[]:t.resolveHostname?await t.resolveHostname(r):(await(0,Fe.lookup)(r,{all:!0,verbatim:!0})).map(i=>i.address);if(!o.length&&!ze(r))throw m("DNS resolution returned no addresses");let s=t.profile??"public-https";for(let i of o){let a=He(i);if(a==="link-local"||a==="unspecified")throw m(`DNS resolved to a forbidden ${a} address`);if(s==="public-https"&&a!=="public"&&!n.has(r))throw m(`DNS resolved public endpoint to ${a} address ${i}`);if(s==="local-network"&&e.protocol==="http:"&&a==="public"&&!n.has(r))throw m(`local-network HTTP resolved to public address ${i}`)}return o}var Ve=require("node:http"),We=require("node:https"),Q=require("node:net"),Ke=require("node:events");function Ge(e,t,r){return{dispatch(n,o){let s,i=!1,a=u=>{i||(i=!0,s?.destroy(),o.onError(u))},c=t[0];if(!c||!(0,Q.isIP)(c)||new URL(n.origin).origin!==e.origin)return queueMicrotask(()=>a(new Error("Provider connection has no authorized pinned address"))),!0;let l=n.headers??{},f=(e.protocol==="https:"?We.request:Ve.request)(new URL(n.path,e.origin),{method:n.method,headers:l,agent:!1,rejectUnauthorized:!0,lookup:(u,g,v)=>{let h={address:c,family:(0,Q.isIP)(c)};typeof g=="object"&&g.all?v(null,[h]):v(null,c,h.family)}},u=>{s=u;let g=u.rawHeaders.map(h=>Buffer.from(h)),v=()=>u.resume();o.onHeaders(u.statusCode??500,g,v,u.statusMessage??"")===!1&&u.pause(),u.on("data",h=>{o.onData(h)||u.pause()}),u.on("end",()=>{i||(i=!0,o.onComplete(u.rawTrailers.map(h=>Buffer.from(h))))}),u.on("error",a),u.on("aborted",()=>a(new Error("Provider response was interrupted")))});return f.on("socket",u=>{u.once("connect",()=>{if(!u.remoteAddress||T(u.remoteAddress)!==T(c)){f.destroy(new Error("Provider socket did not connect to its authorized address"));return}e.protocol==="http:"&&r?.()}),e.protocol==="https:"&&u.once("secureConnect",()=>{u.authorized&&u.remoteAddress&&T(u.remoteAddress)===T(c)&&r?.()})}),f.on("error",a),o.onConnect(u=>f.destroy(u??new Error("Provider request aborted"))),(async()=>{try{let u=n.body;if(typeof u=="string"||u instanceof Uint8Array)f.end(u);else{if(u)for await(let g of u){if(f.destroyed)return;f.write(g)||await(0,Ke.once)(f,"drain")}f.end()}}catch(u){f.destroy(u instanceof Error?u:new Error("Provider request body failed"))}})(),!0}}}async function Jr(e,t,r={}){let n=new URL(e.toString()),o=new URL(n);o.search="",o.hash="",Ue(o.toString(),r.policy),t.signal?.throwIfAborted();let s=await Ye(je(o,r.policy),t.signal);if(!s.length)throw new Error("Pinned endpoint resolution returned no addresses.");if(r.authorizeAddress&&s.some(c=>r.authorizeAddress(T(c),new URL(n))!==!0))throw new Error("Pinned endpoint resolved outside the authorized address scope.");t.signal?.throwIfAborted();let i=fetch(n,{...t,redirect:"manual",credentials:"omit",dispatcher:Ge(n,s)});i.then(c=>{t.signal?.aborted&&c.body?.cancel().catch(()=>{})},()=>{});let a=await Ye(i,t.signal);if(a.redirected)throw await a.body?.cancel(),new Error("Pinned endpoint transport followed a redirect without authorization.");return a}async function Ye(e,t){if(!t)return e;let r,n=new Promise((o,s)=>{r=()=>s(t.reason??new Error("Pinned endpoint read cancelled.")),t.addEventListener("abort",r,{once:!0}),t.aborted&&r()});try{return await Promise.race([e,n])}finally{t.removeEventListener("abort",r)}}0&&(module.exports={ApiTransientError,HOME_DIR,IS_LINUX,IS_MAC,IS_WINDOWS,LogLevel,OS_VERSION,PLATFORM,accountTextTokens,appendDurableLine,appendLine,benchmarkLeakError,buildToolResultBlock,buildToolResultText,calculateCost,clearFileCache,commandMentionsBenchmarkLeak,conservativeTokenAccountingAdapter,copyTextToClipboard,createSafeRegex,debug,decodeTextBuffer,deleteDir,deleteFile,detectLineEnding,detectPreferredLineEnding,detectTextEncoding,encodeTextBuffer,ensureDir,error,estimateTokens,estimateTokensForModel,existsSync,fetchPinnedEndpoint,filterBenchmarkLeakPaths,findSimilarFile,fitsInBudget,formatCost,getAgentHome,getBenchmarkReferenceOverwriteHint,getBoolean,getConfigDir,getFileCacheStats,getLogLevel,getNumber,getProjectConfigDir,getRetryErrorContext,getShellName,getString,getToolResultTransportContent,hasDir,hasDisallowedAsciiControlCharacter,hasFile,hasFrontmatter,hasMixedLineEndings,hasNonTextToolResultContent,hasTransientStatusMention,info,invalidateFileCache,isBenchmarkLeakPath,isBenchmarkMode,isGitRepo,isGitRepoAsync,isPathSafe,isRetryableError,listDirs,listFiles,normalizeLineEndings,normalizeXenoRequestContext,parseDocument,parseJsonLines,pathIdentityKey,readDerivedCached,readFileSafe,readIfExists,readTextCached,readTextFile,remainingBudget,renameReplacingWithRetry,resetFileCacheStats,safeJsonParse,safeJsonStringify,safeRegexTest,safeResolvePath,setLogLevel,stringifyDocument,toTransportAssistantBlocks,toolAssistantContentToText,toolResultContentToText,truncateToTokens,validateRegexPattern,validateRequired,warn,withRetry,writeAtomic,writeTextFile,xenoRequestContextHeaders});
25
+ `).trim()}function De(e){let t=e.trim();return t.length>0?[{type:"text",text:t}]:[]}function Hr(e){return typeof e=="string"?e:Ne(e)}function Le(e){if(e.success)return e.output;let t=[`Error: ${e.error??"Tool execution failed"}`];return e.output.trim().length>0&&t.push(e.output),t.join(`
26
+ `)}function Ur(e){let t=e.assistant_content&&e.assistant_content.length>0?e.assistant_content:typeof e.content=="string"?De(e.content):e.content,r=e.assistant_only_content??[],n=jr(e),o=[...t,...r,...n?[n]:[]];return o.length>0?o:e.content}function jr(e){let t=e.operation;if(!t)return null;let r=e.evidence??t.evidence??[],n=r.filter(s=>s.status==="verified").length,o=r.filter(s=>s.status==="failed").length;return{type:"text",text:["[xeno_operation]",`operation_id: ${t.operationId}`,`state: ${t.state}`,`terminal: ${t.terminal?"yes":"no"}`,`completion_policy: ${t.completionPolicy}`,t.taskId?`task_id: ${t.taskId}`:null,t.completionReason?`completion_reason: ${t.completionReason}`:null,`evidence: ${n} verified, ${o} failed`,e.retryable===void 0?null:`retryable: ${e.retryable?"yes":"no"}`,"[/xeno_operation]"].filter(s=>!!s).join(`
27
+ `)}}function Vr(e){return Array.isArray(e)&&e.some(t=>t.type!=="text")}function Wr(e){return typeof e=="string"?De(e):e}function Kr(e,t){return{type:"tool_result",tool_use_id:e,content:Le(t),...t.assistantContent&&t.assistantContent.length>0?{assistant_content:t.assistantContent}:{},...t.assistantOnlyContent&&t.assistantOnlyContent.length>0?{assistant_only_content:t.assistantOnlyContent}:{},is_error:!t.success,...t.operation?{operation:t.operation}:{},...t.evidence&&t.evidence.length>0?{evidence:t.evidence}:{},...t.webContext?{web_context:t.webContext}:{},...t.retryable!==void 0?{retryable:t.retryable}:{}}}function Gr(e,t={}){for(let r of e){let n=r.codePointAt(0);if(n===127)return!0;if(!(n>31)&&!(n===9&&t.allowTab===!0)&&!((n===10||n===13)&&t.allowLineBreaks===!0))return!0}return!1}var Fe=require("node:dns/promises"),M=require("node:net");var w="[redacted]";var Yr=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[redacted:private-key]"],[/((?:^|[\s{,;"'(\[])["']?(?:cookie|set-cookie)["']?\s*[:=]\s*["']?)(?!\[redacted)[^\s"',;]+(?:;\s*[^\s"',;=]+=[^\s"',;]*)*/gi,`$1${w}`],[/((?:^|[\s{,;"'(\[])["']?(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-xeno-api-key|api[-_]?key|apikey|dpop)["']?\s*[:=]\s*["']?)(?:(?:Bearer|Basic|Token|DPoP)\s+)?(?!\[redacted)[^\s"',;]+/gi,`$1${w}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${w}`],[/\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|xeno-[A-Za-z0-9]{24,}|xrun_[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{30,}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9]{30,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g,w],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,w],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${w}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${w}@`]];function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function S(e,t=[]){if(!e)return e;let r=e,n=[...new Set([...t].filter(o=>typeof o=="string"&&o.length>=12))].sort((o,s)=>s.length-o.length);for(let o of n){r=r.replace(new RegExp(`(?<![A-Za-z0-9_-])${Be(o)}(?![A-Za-z0-9_-])`,"g"),w);let s=encodeURIComponent(o);s!==o&&(r=r.replace(new RegExp(`(?<![A-Za-z0-9_-])${Be(s)}(?![A-Za-z0-9_-])`,"g"),w))}for(let[o,s]of Yr)o.lastIndex=0,r=r.replace(o,s);return r}function Z(e,t,r){try{Object.defineProperty(e,t,{value:r,writable:!0,configurable:!0,enumerable:!1})}catch{}}function J(e,t=[],r=0){if(!(e instanceof Error)||r>6)return e;let n=[...t],o=S(e.message,n);if(o!==e.message&&Z(e,"message",o),typeof e.stack=="string"){let i=S(e.stack,n);i!==e.stack&&Z(e,"stack",i)}let s=e.cause;if(s instanceof Error)J(s,n,r+1);else if(s!=null){let i;try{i=typeof s=="string"?s:JSON.stringify(s)??String(s)}catch{i=String(s)}let c=S(i,n);c!==i&&Z(e,"cause",c)}for(let i of Object.keys(e)){let c=e[i];if(typeof c=="string"){let a=S(c,n);if(a!==c)try{e[i]=a}catch{}}}return e}var q=class extends Error{category;code;retryable;providerId;statusCode;retryAfterMs;requestId;providerCode;remedy;constructor(t,r){super(S(t),r.cause!==void 0?{cause:r.cause}:void 0),this.name="ProviderError",this.category=r.category,this.code=r.code,this.retryable=r.retryable??!1,this.providerId=r.providerId,this.statusCode=r.statusCode,this.retryAfterMs=r.retryAfterMs,this.requestId=r.requestId,r.providerCode!==void 0&&(this.providerCode=r.providerCode),r.remedy!==void 0&&(this.remedy=r.remedy),J(this)}};var qe=new Set(["metadata.google.internal","metadata.azure.internal","instance-data.ec2.internal"]);function m(e){return new q(`Provider endpoint rejected: ${e}`,{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"})}function Zr(e){let t=e.split(".");if(t.length!==4)return null;let r=t.map(n=>Number(n));return r.every(n=>Number.isInteger(n)&&n>=0&&n<=255)?r:null}function Xe(e){let t=Zr(e);if(!t)return"public";let[r,n]=t;return r===0?"unspecified":r===127?"loopback":r===169&&n===254?"link-local":r===10||r===172&&n>=16&&n<=31||r===192&&n===168?"private":"public"}function T(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"").split("%")[0];(0,M.isIP)(t)===6&&(t=new URL(`http://[${t}]`).hostname.slice(1,-1));let r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(r){let n=Number.parseInt(r[1],16),o=Number.parseInt(r[2],16);return`${n>>8}.${n&255}.${o>>8}.${o&255}`}return t}function He(e){let t=T(e);return(0,M.isIP)(t)===4?Xe(t):t==="::"||t==="::0"?"unspecified":t==="::1"?"loopback":t.startsWith("::ffff:")?Xe(t.slice(7)):/^f[cd]/.test(t)?"private":/^fe[89ab]/.test(t)?"link-local":"public"}function ze(e){return e==="example"||e.endsWith(".example")||e==="test"||e.endsWith(".test")||e==="invalid"||e.endsWith(".invalid")}function Jr(e){return e==="localhost"||e.endsWith(".localhost")}function Ue(e,t={}){let r;try{r=new URL(e)}catch{throw m("the URL is invalid")}if(r.username||r.password)throw m("embedded credentials are forbidden");if(r.hash||r.search)throw m("base URLs cannot contain a query or fragment");if(!r.hostname||r.hostname.includes("%"))throw m("the hostname is empty or ambiguous");if(qe.has(r.hostname.toLowerCase()))throw m("cloud metadata destinations are forbidden");if(r.protocol!=="https:"&&r.protocol!=="http:")throw m(`scheme ${r.protocol} is unsupported`);let n=t.profile??"public-https";if(r.protocol==="http:"&&n!=="local-network")throw m("plain HTTP requires the explicit local-network profile");let o=r.hostname.replace(/^\[|\]$/g,""),s=(0,M.isIP)(o)?He(o):null;if(s==="link-local"||s==="unspecified")throw m(`${s} destinations are forbidden`);if(n==="public-https"&&(s==="private"||s==="loopback"||Jr(r.hostname)))throw m("private and loopback destinations require the local-network profile");if(n==="local-network"&&r.protocol==="http:"&&s==="public"&&!t.allowedHosts?.includes(r.hostname))throw m("local-network HTTP must resolve to loopback or a private address");return r}async function je(e,t={}){let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(qe.has(r))throw m("cloud metadata destinations are forbidden");let n=new Set((t.allowedHosts??[]).map(i=>i.toLowerCase())),o=(0,M.isIP)(r)?[r]:ze(r)?[]:t.resolveHostname?await t.resolveHostname(r):(await(0,Fe.lookup)(r,{all:!0,verbatim:!0})).map(i=>i.address);if(!o.length&&!ze(r))throw m("DNS resolution returned no addresses");let s=t.profile??"public-https";for(let i of o){let c=He(i);if(c==="link-local"||c==="unspecified")throw m(`DNS resolved to a forbidden ${c} address`);if(s==="public-https"&&c!=="public"&&!n.has(r))throw m(`DNS resolved public endpoint to ${c} address ${i}`);if(s==="local-network"&&e.protocol==="http:"&&c==="public"&&!n.has(r))throw m(`local-network HTTP resolved to public address ${i}`)}return o}var Ve=require("node:http"),We=require("node:https"),Q=require("node:net"),Ke=require("node:events");function Ge(e,t,r){return{dispatch(n,o){let s,i=!1,c=u=>{i||(i=!0,s?.destroy(),o.onError(u))},a=t[0];if(!a||!(0,Q.isIP)(a)||new URL(n.origin).origin!==e.origin)return queueMicrotask(()=>c(new Error("Provider connection has no authorized pinned address"))),!0;let d=n.headers??{},l=(e.protocol==="https:"?We.request:Ve.request)(new URL(n.path,e.origin),{method:n.method,headers:d,agent:!1,rejectUnauthorized:!0,lookup:(u,g,v)=>{let h={address:a,family:(0,Q.isIP)(a)};typeof g=="object"&&g.all?v(null,[h]):v(null,a,h.family)}},u=>{s=u;let g=u.rawHeaders.map(h=>Buffer.from(h)),v=()=>u.resume();o.onHeaders(u.statusCode??500,g,v,u.statusMessage??"")===!1&&u.pause(),u.on("data",h=>{o.onData(h)||u.pause()}),u.on("end",()=>{i||(i=!0,o.onComplete(u.rawTrailers.map(h=>Buffer.from(h))))}),u.on("error",c),u.on("aborted",()=>c(new Error("Provider response was interrupted")))});return l.on("socket",u=>{u.once("connect",()=>{if(!u.remoteAddress||T(u.remoteAddress)!==T(a)){l.destroy(new Error("Provider socket did not connect to its authorized address"));return}e.protocol==="http:"&&r?.()}),e.protocol==="https:"&&u.once("secureConnect",()=>{u.authorized&&u.remoteAddress&&T(u.remoteAddress)===T(a)&&r?.()})}),l.on("error",c),o.onConnect(u=>l.destroy(u??new Error("Provider request aborted"))),(async()=>{try{let u=n.body;if(typeof u=="string"||u instanceof Uint8Array)l.end(u);else{if(u)for await(let g of u){if(l.destroyed)return;l.write(g)||await(0,Ke.once)(l,"drain")}l.end()}}catch(u){l.destroy(u instanceof Error?u:new Error("Provider request body failed"))}})(),!0}}}async function Qr(e,t,r={}){let n=new URL(e.toString()),o=new URL(n);o.search="",o.hash="",Ue(o.toString(),r.policy),t.signal?.throwIfAborted();let s=await Ye(je(o,r.policy),t.signal);if(!s.length)throw new Error("Pinned endpoint resolution returned no addresses.");if(r.authorizeAddress&&s.some(a=>r.authorizeAddress(T(a),new URL(n))!==!0))throw new Error("Pinned endpoint resolved outside the authorized address scope.");t.signal?.throwIfAborted();let i=fetch(n,{...t,redirect:"manual",credentials:"omit",dispatcher:Ge(n,s)});i.then(a=>{t.signal?.aborted&&a.body?.cancel().catch(()=>{})},()=>{});let c=await Ye(i,t.signal);if(c.redirected)throw await c.body?.cancel(),new Error("Pinned endpoint transport followed a redirect without authorization.");return c}async function Ye(e,t){if(!t)return e;let r,n=new Promise((o,s)=>{r=()=>s(t.reason??new Error("Pinned endpoint read cancelled.")),t.addEventListener("abort",r,{once:!0}),t.aborted&&r()});try{return await Promise.race([e,n])}finally{t.removeEventListener("abort",r)}}0&&(module.exports={ApiTransientError,HOME_DIR,IS_LINUX,IS_MAC,IS_WINDOWS,LogLevel,OS_VERSION,PLATFORM,accountTextTokens,appendDurableLine,appendLine,benchmarkLeakError,buildToolResultBlock,buildToolResultText,calculateCost,clearFileCache,commandMentionsBenchmarkLeak,conservativeTokenAccountingAdapter,copyTextToClipboard,createSafeRegex,debug,decodeTextBuffer,deleteDir,deleteFile,detectLineEnding,detectPreferredLineEnding,detectTextEncoding,encodeTextBuffer,ensureDir,error,estimateTokens,estimateTokensForModel,existsSync,fetchPinnedEndpoint,filterBenchmarkLeakPaths,findSimilarFile,fitsInBudget,formatCost,getAgentHome,getBenchmarkReferenceOverwriteHint,getBoolean,getConfigDir,getFileCacheStats,getLogLevel,getNumber,getProjectConfigDir,getRetryErrorContext,getShellName,getString,getToolResultTransportContent,hasDir,hasDisallowedAsciiControlCharacter,hasFile,hasFrontmatter,hasMixedLineEndings,hasNonTextToolResultContent,hasTransientStatusMention,info,invalidateFileCache,isBenchmarkLeakPath,isBenchmarkMode,isGitRepo,isGitRepoAsync,isPathSafe,isRetryableError,listDirs,listFiles,normalizeLineEndings,normalizeXenoRequestContext,parseDocument,parseJsonLines,pathIdentityKey,readDerivedCached,readFileSafe,readIfExists,readTextCached,readTextFile,remainingBudget,renameReplacingWithRetry,resetFileCacheStats,safeJsonParse,safeJsonStringify,safeRegexTest,safeResolvePath,setLogLevel,stringifyDocument,toTransportAssistantBlocks,toolAssistantContentToText,toolResultContentToText,truncateToTokens,validateRegexPattern,validateRequired,warn,withRetry,writeAtomic,writeTextFile,xenoRequestContextHeaders});
@@ -1,24 +1,27 @@
1
- import{readdirSync as Z,readFileSync as Ae}from"node:fs";import{existsSync as L,statSync as J}from"node:fs";import*as p from"node:fs/promises";import*as d from"node:path";import{promises as $}from"node:fs";var Re=8192,K=Symbol.for("@xenosystem/agent-sdk/file-cache"),G=globalThis,N=G[K]??{entries:new Map,counters:{reads:0,hits:0}};G[K]=N;var E=N.entries,T=N.counters;function $t(){return{...T}}function Nt(){T.reads=0,T.hits=0}function D(e){E.delete(e)}function Dt(){E.clear()}async function Te(e){try{let t=await $.stat(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(t.code==="ENOENT")return null;throw t}}function W(e,t){for(E.delete(e),E.set(e,t);E.size>Re;){let r=E.keys().next().value;if(r===void 0)break;E.delete(r)}}async function _e(e,t,r){let n=await $.open(e,"r");try{let o=Math.min(r,t),s=Buffer.alloc(o);return await n.read(s,0,o,t-o),s.toString("utf-8")}finally{await n.close()}}async function ve(e,t,r,n={}){let o=await Te(e);if(!o)return E.delete(e),null;let s=E.get(e);if(s&&s.mtimeMs===o.mtimeMs&&s.size===o.size&&s.values.has(t))return T.hits+=1,W(e,s),s.values.get(t);let i,a=n.tailBytes;if(a!==void 0&&o.size>a&&(T.reads+=1,i=r(await _e(e,o.size,a),!0)),i===void 0){let f;try{f=await $.readFile(e,"utf-8")}catch(u){if(u.code==="ENOENT")return E.delete(e),null;throw u}T.reads+=1,i=r(f,!1)}let c=E.get(e),l=c&&c.mtimeMs===o.mtimeMs&&c.size===o.size?c:{mtimeMs:o.mtimeMs,size:o.size,values:new Map};return l.values.set(t,i),W(e,l),i}function Lt(e){return ve(e,"text",t=>t)}function qt(e){try{return L(e)&&J(e).isFile()}catch{return!1}}function Ht(e){try{return L(e)&&J(e).isDirectory()}catch{return!1}}function Ut(e,t=""){try{return Ae(e,"utf-8")}catch{return t}}async function B(e){await p.mkdir(e,{recursive:!0})}async function Ce(e,t){let r=d.dirname(e);await B(r);let n=Math.random().toString(36).substring(2,15),o=`${e}.tmp.${process.pid}.${n}`;try{await p.writeFile(o,t),await Se(o,e),D(e)}finally{try{await p.unlink(o)}catch{}}}var Pe=new Set(["EACCES","EBUSY","EPERM"]),ke=[10,20,40,80,160,320,640];async function Se(e,t){for(let r=0;;r+=1)try{await p.rename(e,t);return}catch(n){let o=n.code,s=ke[r];if(process.platform!=="win32"||!o||!Pe.has(o)||s===void 0)throw n;await new Promise(i=>setTimeout(i,s))}}async function jt(e,t){let r=d.dirname(e);await B(r),await p.appendFile(e,t+`
2
- `,"utf-8")}async function Vt(e,t){let r=d.dirname(e);await B(r);let n=await p.open(e,"a");try{await n.writeFile(t+`
1
+ import{readdirSync as Z,readFileSync as Ae}from"node:fs";import{existsSync as L,statSync as J}from"node:fs";import*as p from"node:fs/promises";import*as f from"node:path";import{promises as $}from"node:fs";var Re=8192,K=Symbol.for("@xenosystem/agent-sdk/file-cache"),G=globalThis,N=G[K]??{entries:new Map,counters:{reads:0,hits:0}};G[K]=N;var b=N.entries,T=N.counters;function Nt(){return{...T}}function Dt(){T.reads=0,T.hits=0}function D(e){b.delete(e)}function Lt(){b.clear()}async function Te(e){try{let t=await $.stat(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(t.code==="ENOENT")return null;throw t}}function W(e,t){for(b.delete(e),b.set(e,t);b.size>Re;){let r=b.keys().next().value;if(r===void 0)break;b.delete(r)}}async function _e(e,t,r){let n=await $.open(e,"r");try{let o=Math.min(r,t),s=Buffer.alloc(o);return await n.read(s,0,o,t-o),s.toString("utf-8")}finally{await n.close()}}async function ve(e,t,r,n={}){let o=await Te(e);if(!o)return b.delete(e),null;let s=b.get(e);if(s&&s.mtimeMs===o.mtimeMs&&s.size===o.size&&s.values.has(t))return T.hits+=1,W(e,s),s.values.get(t);let i,c=n.tailBytes;if(c!==void 0&&o.size>c&&(T.reads+=1,i=r(await _e(e,o.size,c),!0)),i===void 0){let l;try{l=await $.readFile(e,"utf-8")}catch(u){if(u.code==="ENOENT")return b.delete(e),null;throw u}T.reads+=1,i=r(l,!1)}let a=b.get(e),d=a&&a.mtimeMs===o.mtimeMs&&a.size===o.size?a:{mtimeMs:o.mtimeMs,size:o.size,values:new Map};return d.values.set(t,i),W(e,d),i}function Bt(e){return ve(e,"text",t=>t)}function Ht(e){try{return L(e)&&J(e).isFile()}catch{return!1}}function Ut(e){try{return L(e)&&J(e).isDirectory()}catch{return!1}}function jt(e,t=""){try{return Ae(e,"utf-8")}catch{return t}}async function B(e){await p.mkdir(e,{recursive:!0})}async function ke(e,t){let r=f.dirname(e);await B(r);let n=Math.random().toString(36).substring(2,15),o=`${e}.tmp.${process.pid}.${n}`;try{await p.writeFile(o,t),await Se(o,e),D(e)}finally{try{await p.unlink(o)}catch{}}}var Ce=new Set(["EACCES","EBUSY","EPERM"]),Pe=[10,20,40,80,160,320,640];async function Se(e,t){for(let r=0;;r+=1)try{await p.rename(e,t);return}catch(n){let o=n.code,s=Pe[r];if(process.platform!=="win32"||!o||!Ce.has(o)||s===void 0)throw n;await new Promise(i=>setTimeout(i,s))}}async function Vt(e,t){let r=f.dirname(e);await B(r),await p.appendFile(e,t+`
2
+ `,"utf-8")}async function Wt(e,t){let r=f.dirname(e);await B(r);let n=await p.open(e,"a");try{await n.writeFile(t+`
3
3
  `,"utf-8"),await n.sync()}finally{await n.close()}}function Ie(e){return e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?"utf8-bom":e.length>=2&&e[0]===255&&e[1]===254?"utf16le":e.length>=2&&e[0]===254&&e[1]===255?"utf16be":"utf8"}function Q(e){let t=Buffer.from(e);for(let r=0;r+1<t.length;r+=2){let n=t[r];t[r]=t[r+1],t[r+1]=n}return t}function Oe(e,t){switch(t){case"utf8-bom":return e.subarray(3).toString("utf8");case"utf16le":return e.subarray(2).toString("utf16le");case"utf16be":return Q(e.subarray(2)).toString("utf16le");default:return e.toString("utf8")}}function Me(e,t){switch(t){case"utf8-bom":return Buffer.concat([Buffer.from([239,187,191]),Buffer.from(e,"utf8")]);case"utf16le":return Buffer.concat([Buffer.from([255,254]),Buffer.from(e,"utf16le")]);case"utf16be":return Buffer.concat([Buffer.from([254,255]),Q(Buffer.from(e,"utf16le"))]);default:return Buffer.from(e,"utf8")}}function $e(e){return e.includes(`\r
4
4
  `)?"CRLF":"LF"}function Ne(e,t){let r=e.replace(/\r\n/g,`
5
5
  `);return t==="CRLF"?r.replace(/\n/g,`\r
6
- `):r}function Wt(e){return e.includes(`\r
7
- `)?/(^|[^\r])\n/.test(e):!1}async function De(e){let t=await p.readFile(e),r=Ie(t),n=Oe(t,r);return{content:n,encoding:r,lineEnding:$e(n),sizeBytes:t.length}}async function Kt(e,t,r){let n=r?.preserveLineEndings?t:Ne(t,r?.lineEnding??"LF");await Ce(e,Me(n,r?.encoding??"utf8"))}async function Gt(e,t){let r=new Set,n=d.resolve(e),o=t===void 0?void 0:d.resolve(t);if(o!==void 0){let s=d.relative(o,n);if(d.isAbsolute(s)||s===".."||s.startsWith(`..${d.sep}`))return"LF"}for(;!r.has(n);){r.add(n);try{let i=Z(n,{withFileTypes:!0}).filter(a=>a.isFile()).map(a=>a.name).sort();for(let a of i){if(a.startsWith("."))continue;let c=d.extname(a).toLowerCase();if([".ts",".tsx",".js",".jsx",".json",".md",".txt",".yaml",".yml",".css",".html",".xml",".sh",".ps1"].includes(c))try{let l=d.join(n,a),f=await De(l);if(f.content.length>0)return f.lineEnding}catch{}}}catch{}if(o!==void 0&&d.relative(o,n)==="")break;let s=d.dirname(n);if(s===n)break;n=s}return"LF"}function Le(e,t,r){let n=[],o=[{dir:e,depth:0}],s=new Set;for(;o.length>0&&n.length<r;){let i=o.shift();if(!s.has(i.dir)){s.add(i.dir);try{let a=Z(i.dir,{withFileTypes:!0});for(let c of a){let l=d.join(i.dir,c.name);if(c.isFile()){if(n.push(l),n.length>=r)break;continue}c.isDirectory()&&i.depth<t&&!c.name.startsWith(".")&&c.name!=="node_modules"&&o.push({dir:l,depth:i.depth+1})}}catch{}}}return n}function Y(e,t){let r=d.relative(e,t);return r===""||!r.startsWith("..")&&!d.isAbsolute(r)}function Yt(e,t){try{let r=d.dirname(e),n=d.basename(e,d.extname(e)).toLowerCase(),o=d.basename(e).toLowerCase(),s=[r,d.dirname(r)],i=t!==void 0&&Y(t,e)?t:void 0,a=s.flatMap(l=>Le(l,2,500)).filter(l=>i===void 0||Y(i,l)),c=null;for(let l of a){let f=d.basename(l).toLowerCase(),u=d.basename(l,d.extname(l)).toLowerCase(),g=null;if(f===o?g=0:u===n?g=1:(f.includes(n)||n.includes(u))&&(g=2),g===null)continue;let R=d.relative(r,l).split(d.sep).length,h=g+R*.01;(!c||h<c.score)&&(c={filePath:l,score:h})}return c?.filePath??null}catch{}return null}async function Zt(e){try{return await p.readFile(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function Jt(e){return L(e)}async function Qt(e,t){try{let n=(await p.readdir(e,{withFileTypes:!0})).filter(o=>o.isFile()).map(o=>d.join(e,o.name));return t&&(n=n.filter(o=>t.test(d.basename(o)))),n}catch(r){if(r.code==="ENOENT")return[];throw r}}async function er(e){try{return(await p.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>d.join(e,r.name))}catch(t){if(t.code==="ENOENT")return[];throw t}}async function tr(e){try{await p.unlink(e)}catch(t){if(t.code!=="ENOENT")throw t}finally{D(e)}}async function rr(e){try{await p.rm(e,{recursive:!0,force:!0})}catch(t){if(t.code!=="ENOENT")throw t}}function or(e,t){try{return JSON.parse(e)}catch{return t}}function sr(e,t="{}"){try{return JSON.stringify(e)}catch{return t}}function ir(e){let t=[];for(let r of e.split(`
8
- `)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}function cr(e){let t=Be(e);return{frontmatter:t.frontmatter,content:t.content.trim()}}function ur(e,t){let r=Object.fromEntries(Object.entries(e).filter(([n,o])=>o!==void 0));return["---",ne(r),"---","",t].join(`
9
- `)}function dr(e){return e.trimStart().startsWith("---")}function Be(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return{frontmatter:{},content:e};let r=t.search(/\r?\n/);if(r<0||t.slice(0,r).trim()!=="---")return{frontmatter:{},content:e};let n=t.slice(r+(t[r]==="\r"?2:1)),o=n.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!o||o.index===void 0)throw new Error("YAML frontmatter is not closed.");let s=n.slice(0,o.index),i=o[0],a=o.index+i.length;return{frontmatter:te(s),content:n.slice(a)}}function te(e){let t={},r=e.split(/\r?\n/);for(let n=0;n<r.length;n+=1){let o=r[n];if(!o.trim()||o.trimStart().startsWith("#"))continue;if(/^\s/.test(o))throw new Error(`Unexpected indentation at line ${n+1}.`);let s=ze(o,n+1);if(s.key==="<<")throw new Error("YAML merge keys are not supported.");if(s.value!==""){t[s.key]=re(s.value,n+1);continue}let i=Xe(r,n+1);t[s.key]=i.value,n=i.nextIndex-1}return t}function Xe(e,t){let r=[],n=t;for(;n<e.length;n+=1){let s=e[n];if(!s.trim()){r.push(s);continue}if(!/^\s/.test(s))break;r.push(s.replace(/^ {2}/,""))}let o=r.filter(s=>s.trim()&&!s.trimStart().startsWith("#"));return o.length===0?{value:{},nextIndex:n}:o.every(s=>s.trimStart().startsWith("- "))?{value:o.map((s,i)=>re(s.trimStart().slice(2),t+i+1)),nextIndex:n}:{value:te(r.join(`
10
- `)),nextIndex:n}}function ze(e,t){let r=e.indexOf(":");if(r<=0)throw new Error(`Invalid YAML line ${t}.`);let n=e.slice(0,r).trim(),o=e.slice(r+1).trim();if(!n)throw new Error(`Invalid YAML key at line ${t}.`);return{key:n,value:o}}function re(e,t){if(e==="")return"";if(e==="[]")return[];if(e==="{}")return{};if(e==="true")return!0;if(e==="false")return!1;if(e==="null"||e==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(e))return Number(e);if(e.startsWith('"'))return ee(e,t);if(e.startsWith("'")){if(!e.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${t}.`);return e.slice(1,-1).replace(/''/g,"'")}if(e.startsWith("[")||e.startsWith("{"))return ee(e,t);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${t}.`);return e}function ee(e,t){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${t}.`)}}function ne(e,t=""){return Object.entries(e).map(([r,n])=>Fe(r,n,t)).join(`
11
- `)}function Fe(e,t,r){return Array.isArray(t)?`${r}${e}: ${JSON.stringify(t)}`:t&&typeof t=="object"?`${r}${e}:
12
- ${ne(t,`${r} `)}`:`${r}${e}: ${JSON.stringify(t)}`}import*as y from"path";function qe(e,t){let r=y.resolve(e),n=y.resolve(e,t);return n===r?!0:r===y.parse(r).root?n.startsWith(r):n.startsWith(r+y.sep)}function fr(e,t){if(y.isAbsolute(t))return y.resolve(t);if(!qe(e,t))throw new Error(`PathSecurity: Path traversal attempt detected: ${t}`);return y.resolve(e,t)}function pr(e,t=process.platform){let r=y.resolve(e);return t==="win32"?r.toLowerCase():r}import{homedir as q,platform as Ye,release as Ze}from"node:os";import{execFileSync as Je,spawn as Qe,spawnSync as et}from"node:child_process";import{statSync as tt}from"node:fs";import{delimiter as rt,join as nt,resolve as _}from"node:path";import{spawn as He,spawnSync as yr}from"node:child_process";var Ue=5e3,oe=128;function je(e,t,r){let n={tool:e,timeoutMs:r};return t.timedOut?{...n,terminated:!1,reason:"timeout",exitCode:null,detail:`${e} did not finish within ${r}ms`}:t.error!==void 0?{...n,terminated:!1,reason:"spawn-error",exitCode:null,detail:t.error}:t.status===0?{...n,terminated:!0,reason:"terminated",exitCode:0}:e==="taskkill"&&t.status===oe?{...n,terminated:!0,reason:"not-running",exitCode:oe}:{...n,terminated:!1,reason:"failed",exitCode:t.status,detail:`${e} exited with code ${t.status??"unknown"}`}}var Ve=(e,t,r)=>new Promise(n=>{let o=!1,s={},i=c=>{o||(o=!0,s.timer&&clearTimeout(s.timer),n(c))},a;try{a=He(e,[...t],{stdio:"ignore",windowsHide:!0})}catch(c){i({status:null,timedOut:!1,error:c instanceof Error?c.message:String(c)});return}s.timer=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}i({status:null,timedOut:!0})},r),s.timer.unref?.(),a.once("error",c=>{i({status:null,timedOut:!1,error:c.code??c.message})}),a.once("close",c=>{i(c===null?{status:null,timedOut:!1,error:"no exit status"}:{status:c,timedOut:!1})})});function se(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):Ue}function We(e,t){return{terminated:!1,reason:"failed",tool:e,exitCode:null,timeoutMs:t,detail:"pid is not a positive integer"}}function Ke(e){return["/PID",String(e),"/T","/F"]}async function ie(e,t={}){let r=se(t.timeoutMs);return!Number.isSafeInteger(e)||e<=0?We("taskkill",r):Ge("taskkill","taskkill.exe",Ke(e),{timeoutMs:r,run:t.run})}async function Ge(e,t,r,n={}){let o=se(n.timeoutMs),s;try{s=await(n.run??Ve)(t,r,o)}catch(i){s={status:null,timedOut:!1,error:i instanceof Error?i.message:String(i)}}return je(e,s,o)}var H=Ye(),C=H==="win32",Tr=H==="darwin",_r=H==="linux",vr=Ze(),Ar=q();function Cr(){let e=process.env.XENO_AGENT_HOME?.trim();return e?_(e):_(q(),".xeno-agent")}function Pr(){let e=process.env.XENO_CONFIG_DIR?.trim();return e?_(e):_(q(),".xeno-code")}function kr(e){return _(e,".xeno-code")}function Sr(){return C?"powershell":process.env.SHELL?.split("/").pop()??"bash"}var z=5e3,F=4096,X=["rev-parse","--is-inside-work-tree"];function ae(){if(!C)return{file:"git",args:X};let e=(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(t=>t.toLowerCase()).filter(t=>[".exe",".com",".cmd",".bat"].includes(t));for(let t of(process.env.PATH??"").split(rt).filter(Boolean)){let r=t.replace(/^"(.*)"$/,"$1");for(let n of e){let o=_(r,`git${n}`);try{if(!tt(o).isFile())continue}catch{continue}if(n!==".cmd"&&n!==".bat")return{file:o,args:X};if(/["%!\r\n\0]/.test(o))throw new Error("Git wrapper path cannot be represented safely");let s=process.env.SystemRoot??process.env.WINDIR;if(!s)throw new Error("Windows command interpreter is unavailable");return{file:nt(s,"System32","cmd.exe"),args:["/d","/s","/c",`""${o}" rev-parse --is-inside-work-tree"`],windowsVerbatimArguments:!0}}}return{file:"git",args:X}}function Ir(e){try{let t=ae();if(t.windowsVerbatimArguments){let r=et(t.file,t.args,{cwd:e,encoding:"utf8",windowsHide:!0,windowsVerbatimArguments:!0,timeout:z,maxBuffer:F,stdio:["ignore","pipe","ignore"]});return!r.error&&r.status===0&&r.stdout.trim()==="true"}return Je(t.file,t.args,{cwd:e,encoding:"utf8",windowsHide:!0,timeout:z,maxBuffer:F,stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}function Or(e){return new Promise(t=>{let r,n=!1,o={},s=0,i=[],a=l=>{n||(n=!0,o.timer&&clearTimeout(o.timer),r?.stdout?.destroy(),r?.unref(),t(l))},c=()=>{if(r.exitCode===null&&r.signalCode===null)if(C&&r.pid)ie(r.pid);else if(!C&&r.pid)try{process.kill(-r.pid,"SIGKILL")}catch{try{r.kill("SIGKILL")}catch{}}else try{r.kill("SIGKILL")}catch{}a(!1)};try{let l=ae();r=Qe(l.file,l.args,{cwd:e,windowsHide:!0,detached:!C,windowsVerbatimArguments:l.windowsVerbatimArguments,stdio:["ignore","pipe","ignore"]})}catch{a(!1);return}o.timer=setTimeout(c,z),r.stdout?.on("data",l=>{if(!n){if(s+=l.byteLength,s>F){c();return}i.push(Buffer.from(l))}}),r.once("error",()=>a(!1)),r.once("close",l=>a(l===0&&Buffer.concat(i).toString("utf8").trim()==="true"))})}function $r(e,t){for(let r of t)if(e[r]===void 0||e[r]===null||e[r]==="")return`Missing required parameter: ${r}`;return null}function Nr(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="string")throw new Error(`Parameter ${t} must be a string, got ${typeof n}`);return n}function Dr(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="number")throw new Error(`Parameter ${t} must be a number, got ${typeof n}`);if(isNaN(n))throw new Error(`Parameter ${t} is NaN`);return n}function Lr(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="boolean")throw new Error(`Parameter ${t} must be a boolean, got ${typeof n}`);return n}function ot(e){if(e.length>5e3)return"Pattern too long (max 5000 characters)";let r=[/(\.\*){3,}/,/(\+\+|\*\*)/,/(.*\+.*\+.*\+)/];for(let n of r)if(n.test(e))return"Pattern contains potentially unsafe constructs that could cause excessive backtracking";return null}function Br(e,t,r=5e3){let n=ot(e);if(n)throw new Error(n);try{return new RegExp(e,t)}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Invalid regex pattern: ${s}`)}}function Xr(e,t,r=1e3){if(t.length>1e5)throw new Error(`Input too large for safe regex test (${t.length} chars, max 100000)`);return e.test(t)}var st=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(st||{}),v=1;function Fr(e){v=e}function qr(){return v}function w(){return new Date().toISOString()}function Hr(e,t){v<=0&&(t!==void 0?process.stderr.write(`[${w()}] DEBUG: ${e} ${P(t)}
6
+ `):r}function Kt(e){return e.includes(`\r
7
+ `)?/(^|[^\r])\n/.test(e):!1}async function De(e){let t=await p.readFile(e),r=Ie(t),n=Oe(t,r);return{content:n,encoding:r,lineEnding:$e(n),sizeBytes:t.length}}async function Gt(e,t,r){let n=r?.preserveLineEndings?t:Ne(t,r?.lineEnding??"LF");await ke(e,Me(n,r?.encoding??"utf8"))}async function Yt(e,t){let r=new Set,n=f.resolve(e),o=t===void 0?void 0:f.resolve(t);if(o!==void 0){let s=f.relative(o,n);if(f.isAbsolute(s)||s===".."||s.startsWith(`..${f.sep}`))return"LF"}for(;!r.has(n);){r.add(n);try{let i=Z(n,{withFileTypes:!0}).filter(c=>c.isFile()).map(c=>c.name).sort();for(let c of i){if(c.startsWith("."))continue;let a=f.extname(c).toLowerCase();if([".ts",".tsx",".js",".jsx",".json",".md",".txt",".yaml",".yml",".css",".html",".xml",".sh",".ps1"].includes(a))try{let d=f.join(n,c),l=await De(d);if(l.content.length>0)return l.lineEnding}catch{}}}catch{}if(o!==void 0&&f.relative(o,n)==="")break;let s=f.dirname(n);if(s===n)break;n=s}return"LF"}function Le(e,t,r){let n=[],o=[{dir:e,depth:0}],s=new Set;for(;o.length>0&&n.length<r;){let i=o.shift();if(!s.has(i.dir)){s.add(i.dir);try{let c=Z(i.dir,{withFileTypes:!0});for(let a of c){let d=f.join(i.dir,a.name);if(a.isFile()){if(n.push(d),n.length>=r)break;continue}a.isDirectory()&&i.depth<t&&!a.name.startsWith(".")&&a.name!=="node_modules"&&o.push({dir:d,depth:i.depth+1})}}catch{}}}return n}function Y(e,t){let r=f.relative(e,t);return r===""||!r.startsWith("..")&&!f.isAbsolute(r)}function Zt(e,t){try{let r=f.dirname(e),n=f.basename(e,f.extname(e)).toLowerCase(),o=f.basename(e).toLowerCase(),s=[r,f.dirname(r)],i=t!==void 0&&Y(t,e)?t:void 0,c=s.flatMap(d=>Le(d,2,500)).filter(d=>i===void 0||Y(i,d)),a=null;for(let d of c){let l=f.basename(d).toLowerCase(),u=f.basename(d,f.extname(d)).toLowerCase(),g=null;if(l===o?g=0:u===n?g=1:(l.includes(n)||n.includes(u))&&(g=2),g===null)continue;let R=f.relative(r,d).split(f.sep).length,h=g+R*.01;(!a||h<a.score)&&(a={filePath:d,score:h})}return a?.filePath??null}catch{}return null}async function Jt(e){try{return await p.readFile(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function Qt(e){return L(e)}async function er(e,t){try{let n=(await p.readdir(e,{withFileTypes:!0})).filter(o=>o.isFile()).map(o=>f.join(e,o.name));return t&&(n=n.filter(o=>t.test(f.basename(o)))),n}catch(r){if(r.code==="ENOENT")return[];throw r}}async function tr(e){try{return(await p.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>f.join(e,r.name))}catch(t){if(t.code==="ENOENT")return[];throw t}}async function rr(e){try{await p.unlink(e)}catch(t){if(t.code!=="ENOENT")throw t}finally{D(e)}}async function nr(e){try{await p.rm(e,{recursive:!0,force:!0})}catch(t){if(t.code!=="ENOENT")throw t}}function sr(e,t){try{return JSON.parse(e)}catch{return t}}function ir(e,t="{}"){try{return JSON.stringify(e)}catch{return t}}function ar(e){let t=[];for(let r of e.split(`
8
+ `)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}function ur(e){let t=Be(e);return{frontmatter:t.frontmatter,content:t.content.trim()}}function dr(e,t){let r=Object.fromEntries(Object.entries(e).filter(([n,o])=>o!==void 0));return["---",ne(r),"---","",t].join(`
9
+ `)}function lr(e){return e.trimStart().startsWith("---")}function Be(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return{frontmatter:{},content:e};let r=t.search(/\r?\n/);if(r<0||t.slice(0,r).trim()!=="---")return{frontmatter:{},content:e};let n=t.slice(r+(t[r]==="\r"?2:1)),o=n.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!o||o.index===void 0)throw new Error("YAML frontmatter is not closed.");let s=n.slice(0,o.index),i=o[0],c=o.index+i.length;return{frontmatter:te(s),content:n.slice(c)}}function te(e){let t={},r=e.split(/\r?\n/);for(let n=0;n<r.length;n+=1){let o=r[n];if(!o.trim()||o.trimStart().startsWith("#"))continue;if(/^\s/.test(o))throw new Error(`Unexpected indentation at line ${n+1}.`);let s=Fe(o,n+1);if(s.key==="<<")throw new Error("YAML merge keys are not supported.");let i=s.value.match(/^([|>])([+-]?)$/);if(i){let a=Xe(r,n+1,i[1],i[2]??"");t[s.key]=a.value,n=a.nextIndex-1;continue}if(s.value!==""){t[s.key]=re(s.value,n+1);continue}let c=ze(r,n+1);t[s.key]=c.value,n=c.nextIndex-1}return t}function Xe(e,t,r,n){let o=[],s=t;for(;s<e.length;s+=1){let l=e[s];if(l.trim()===""){o.push("");continue}if(!/^\s/.test(l))break;o.push(l)}let i=o.filter(l=>l.trim()!=="").map(l=>l.match(/^ */)[0].length),c=i.length>0?Math.min(...i):0,a=o.map(l=>l.trim()===""?"":l.slice(c));for(;a.length>0&&a[a.length-1]==="";)a.pop();let d;return r==="|"?d=a.join(`
10
+ `):(d="",a.forEach((l,u)=>{if(u===0){d=l;return}let g=a[u-1];l===""?d+=`
11
+ `:g===""?d+=l:d+=" "+l})),{value:n==="-"?d:d+`
12
+ `,nextIndex:s}}function ze(e,t){let r=[],n=t;for(;n<e.length;n+=1){let s=e[n];if(!s.trim()){r.push(s);continue}if(!/^\s/.test(s))break;r.push(s.replace(/^ {2}/,""))}let o=r.filter(s=>s.trim()&&!s.trimStart().startsWith("#"));return o.length===0?{value:{},nextIndex:n}:o.every(s=>s.trimStart().startsWith("- "))?{value:o.map((s,i)=>re(s.trimStart().slice(2),t+i+1)),nextIndex:n}:{value:te(r.join(`
13
+ `)),nextIndex:n}}function Fe(e,t){let r=e.indexOf(":");if(r<=0)throw new Error(`Invalid YAML line ${t}.`);let n=e.slice(0,r).trim(),o=e.slice(r+1).trim();if(!n)throw new Error(`Invalid YAML key at line ${t}.`);return{key:n,value:o}}function re(e,t){if(e==="")return"";if(e==="[]")return[];if(e==="{}")return{};if(e==="true")return!0;if(e==="false")return!1;if(e==="null"||e==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(e))return Number(e);if(e.startsWith('"'))return ee(e,t);if(e.startsWith("'")){if(!e.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${t}.`);return e.slice(1,-1).replace(/''/g,"'")}if(e.startsWith("[")||e.startsWith("{"))return ee(e,t);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${t}.`);return e}function ee(e,t){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${t}.`)}}function ne(e,t=""){return Object.entries(e).map(([r,n])=>qe(r,n,t)).join(`
14
+ `)}function qe(e,t,r){return Array.isArray(t)?`${r}${e}: ${JSON.stringify(t)}`:t&&typeof t=="object"?`${r}${e}:
15
+ ${ne(t,`${r} `)}`:`${r}${e}: ${JSON.stringify(t)}`}import*as y from"path";function He(e,t){let r=y.resolve(e),n=y.resolve(e,t);return n===r?!0:r===y.parse(r).root?n.startsWith(r):n.startsWith(r+y.sep)}function pr(e,t){if(y.isAbsolute(t))return y.resolve(t);if(!He(e,t))throw new Error(`PathSecurity: Path traversal attempt detected: ${t}`);return y.resolve(e,t)}function mr(e,t=process.platform){let r=y.resolve(e);return t==="win32"?r.toLowerCase():r}import{homedir as q,platform as Ze,release as Je}from"node:os";import{execFileSync as Qe,spawn as et,spawnSync as tt}from"node:child_process";import{statSync as rt}from"node:fs";import{delimiter as nt,join as ot,resolve as _}from"node:path";import{spawn as Ue,spawnSync as hr}from"node:child_process";var je=5e3,oe=128;function Ve(e,t,r){let n={tool:e,timeoutMs:r};return t.timedOut?{...n,terminated:!1,reason:"timeout",exitCode:null,detail:`${e} did not finish within ${r}ms`}:t.error!==void 0?{...n,terminated:!1,reason:"spawn-error",exitCode:null,detail:t.error}:t.status===0?{...n,terminated:!0,reason:"terminated",exitCode:0}:e==="taskkill"&&t.status===oe?{...n,terminated:!0,reason:"not-running",exitCode:oe}:{...n,terminated:!1,reason:"failed",exitCode:t.status,detail:`${e} exited with code ${t.status??"unknown"}`}}var We=(e,t,r)=>new Promise(n=>{let o=!1,s={},i=a=>{o||(o=!0,s.timer&&clearTimeout(s.timer),n(a))},c;try{c=Ue(e,[...t],{stdio:"ignore",windowsHide:!0})}catch(a){i({status:null,timedOut:!1,error:a instanceof Error?a.message:String(a)});return}s.timer=setTimeout(()=>{try{c.kill("SIGKILL")}catch{}i({status:null,timedOut:!0})},r),s.timer.unref?.(),c.once("error",a=>{i({status:null,timedOut:!1,error:a.code??a.message})}),c.once("close",a=>{i(a===null?{status:null,timedOut:!1,error:"no exit status"}:{status:a,timedOut:!1})})});function se(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):je}function Ke(e,t){return{terminated:!1,reason:"failed",tool:e,exitCode:null,timeoutMs:t,detail:"pid is not a positive integer"}}function Ge(e){return["/PID",String(e),"/T","/F"]}async function ie(e,t={}){let r=se(t.timeoutMs);return!Number.isSafeInteger(e)||e<=0?Ke("taskkill",r):Ye("taskkill","taskkill.exe",Ge(e),{timeoutMs:r,run:t.run})}async function Ye(e,t,r,n={}){let o=se(n.timeoutMs),s;try{s=await(n.run??We)(t,r,o)}catch(i){s={status:null,timedOut:!1,error:i instanceof Error?i.message:String(i)}}return Ve(e,s,o)}var H=Ze(),k=H==="win32",_r=H==="darwin",vr=H==="linux",Ar=Je(),kr=q();function Cr(){let e=process.env.XENO_AGENT_HOME?.trim();return e?_(e):_(q(),".xeno-agent")}function Pr(){let e=process.env.XENO_CONFIG_DIR?.trim();return e?_(e):_(q(),".xeno-code")}function Sr(e){return _(e,".xeno-code")}function Ir(){return k?"powershell":process.env.SHELL?.split("/").pop()??"bash"}var z=5e3,F=4096,X=["rev-parse","--is-inside-work-tree"];function ae(){if(!k)return{file:"git",args:X};let e=(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(t=>t.toLowerCase()).filter(t=>[".exe",".com",".cmd",".bat"].includes(t));for(let t of(process.env.PATH??"").split(nt).filter(Boolean)){let r=t.replace(/^"(.*)"$/,"$1");for(let n of e){let o=_(r,`git${n}`);try{if(!rt(o).isFile())continue}catch{continue}if(n!==".cmd"&&n!==".bat")return{file:o,args:X};if(/["%!\r\n\0]/.test(o))throw new Error("Git wrapper path cannot be represented safely");let s=process.env.SystemRoot??process.env.WINDIR;if(!s)throw new Error("Windows command interpreter is unavailable");return{file:ot(s,"System32","cmd.exe"),args:["/d","/s","/c",`""${o}" rev-parse --is-inside-work-tree"`],windowsVerbatimArguments:!0}}}return{file:"git",args:X}}function Or(e){try{let t=ae();if(t.windowsVerbatimArguments){let r=tt(t.file,t.args,{cwd:e,encoding:"utf8",windowsHide:!0,windowsVerbatimArguments:!0,timeout:z,maxBuffer:F,stdio:["ignore","pipe","ignore"]});return!r.error&&r.status===0&&r.stdout.trim()==="true"}return Qe(t.file,t.args,{cwd:e,encoding:"utf8",windowsHide:!0,timeout:z,maxBuffer:F,stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}function Mr(e){return new Promise(t=>{let r,n=!1,o={},s=0,i=[],c=d=>{n||(n=!0,o.timer&&clearTimeout(o.timer),r?.stdout?.destroy(),r?.unref(),t(d))},a=()=>{if(r.exitCode===null&&r.signalCode===null)if(k&&r.pid)ie(r.pid);else if(!k&&r.pid)try{process.kill(-r.pid,"SIGKILL")}catch{try{r.kill("SIGKILL")}catch{}}else try{r.kill("SIGKILL")}catch{}c(!1)};try{let d=ae();r=et(d.file,d.args,{cwd:e,windowsHide:!0,detached:!k,windowsVerbatimArguments:d.windowsVerbatimArguments,stdio:["ignore","pipe","ignore"]})}catch{c(!1);return}o.timer=setTimeout(a,z),r.stdout?.on("data",d=>{if(!n){if(s+=d.byteLength,s>F){a();return}i.push(Buffer.from(d))}}),r.once("error",()=>c(!1)),r.once("close",d=>c(d===0&&Buffer.concat(i).toString("utf8").trim()==="true"))})}function Nr(e,t){for(let r of t)if(e[r]===void 0||e[r]===null||e[r]==="")return`Missing required parameter: ${r}`;return null}function Dr(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="string")throw new Error(`Parameter ${t} must be a string, got ${typeof n}`);return n}function Lr(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="number")throw new Error(`Parameter ${t} must be a number, got ${typeof n}`);if(isNaN(n))throw new Error(`Parameter ${t} is NaN`);return n}function Br(e,t,r){let n=e[t];if(n==null){if(r!==void 0)return r;throw new Error(`Missing required parameter: ${t}`)}if(typeof n!="boolean")throw new Error(`Parameter ${t} must be a boolean, got ${typeof n}`);return n}function st(e){if(e.length>5e3)return"Pattern too long (max 5000 characters)";let r=[/(\.\*){3,}/,/(\+\+|\*\*)/,/(.*\+.*\+.*\+)/];for(let n of r)if(n.test(e))return"Pattern contains potentially unsafe constructs that could cause excessive backtracking";return null}function Xr(e,t,r=5e3){let n=st(e);if(n)throw new Error(n);try{return new RegExp(e,t)}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Invalid regex pattern: ${s}`)}}function zr(e,t,r=1e3){if(t.length>1e5)throw new Error(`Input too large for safe regex test (${t.length} chars, max 100000)`);return e.test(t)}var it=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(it||{}),v=1;function qr(e){v=e}function Hr(){return v}function w(){return new Date().toISOString()}function Ur(e,t){v<=0&&(t!==void 0?process.stderr.write(`[${w()}] DEBUG: ${e} ${C(t)}
13
16
  `):process.stderr.write(`[${w()}] DEBUG: ${e}
14
- `))}function Ur(e,t){v<=1&&(t!==void 0?process.stderr.write(`[${w()}] INFO: ${e} ${P(t)}
17
+ `))}function jr(e,t){v<=1&&(t!==void 0?process.stderr.write(`[${w()}] INFO: ${e} ${C(t)}
15
18
  `):process.stderr.write(`[${w()}] INFO: ${e}
16
- `))}function jr(e,t){v<=2&&(t!==void 0?process.stderr.write(`[${w()}] WARN: ${e} ${P(t)}
19
+ `))}function Vr(e,t){v<=2&&(t!==void 0?process.stderr.write(`[${w()}] WARN: ${e} ${C(t)}
17
20
  `):process.stderr.write(`[${w()}] WARN: ${e}
18
- `))}function Vr(e,t){v<=3&&(t!==void 0?process.stderr.write(`[${w()}] ERROR: ${e} ${P(t)}
21
+ `))}function Wr(e,t){v<=3&&(t!==void 0?process.stderr.write(`[${w()}] ERROR: ${e} ${C(t)}
19
22
  `):process.stderr.write(`[${w()}] ERROR: ${e}
20
- `))}function P(e){if(e==null)return"";if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}var it=/^[A-Za-z0-9:._*-]{1,64}$/,at=/^[A-Za-z0-9_-][A-Za-z0-9 _-]{0,30}[A-Za-z0-9_-]$/,ct=/^[0-9][0-9A-Za-z.+-]{0,40}$/,ce=Object.freeze({"x-xeno-source":Object.freeze(["auto","quota","credits","byok"]),"x-xeno-byok-mode":Object.freeze(["local","cloud"])}),ut=/^[\x21-\x7E]{1,64}$/;function Kr(e){if(!e||typeof e!="object")throw new TypeError("requestContext must be an object");let t=Object.keys(e).filter(s=>s!=="surface"&&s!=="client"&&s!=="headers");if(t.length>0)throw new TypeError(`requestContext does not accept: ${t.join(", ")}`);if(typeof e.surface!="string"||!it.test(e.surface))throw new TypeError("requestContext.surface must match /^[A-Za-z0-9:._*-]{1,64}$/");let r=dt(e.headers),n=r?{surface:e.surface,headers:r}:{surface:e.surface};if(e.client===void 0)return Object.freeze(n);let o=e.client;if(!o||typeof o!="object"||Object.keys(o).some(s=>s!=="name"&&s!=="version"))throw new TypeError("requestContext.client must be { name, version }");if(typeof o.name!="string"||!at.test(o.name))throw new TypeError("requestContext.client.name must be 2-32 characters of letters, digits, space, _ or -");if(typeof o.version!="string"||!ct.test(o.version))throw new TypeError("requestContext.client.version must start with a digit, e.g. 1.2.3");return Object.freeze({...n,client:Object.freeze({name:o.name,version:o.version})})}function dt(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("requestContext.headers must be an object");let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase(),s=Object.prototype.hasOwnProperty.call(ce,o)?ce[o]:void 0;if(!s)throw new TypeError(`requestContext.headers does not accept: ${r}`);if(typeof n!="string"||!ut.test(n))throw new TypeError(`requestContext.headers.${o} must be 1-64 printable ASCII characters`);if(!s.includes(n))throw new TypeError(`requestContext.headers.${o} must be one of: ${s.join(", ")}`);if(Object.prototype.hasOwnProperty.call(t,o))throw new TypeError(`requestContext.headers.${o} is given twice`);t[o]=n}return Object.freeze(t)}function Gr(e){return e?{...e.headers??{},"X-Xeno-Surface":e.surface,...e.client?{"X-Xeno-Client":`${e.client.name}/${e.client.version}`}:{}}:{}}var I=class extends Error{statusCode;body;retryAfterMs;requestId;cfRay;constructor(t,r={}){super(t,r.cause!==void 0?{cause:r.cause}:void 0),this.name="ApiTransientError",this.statusCode=r.statusCode,this.retryAfterMs=r.retryAfterMs,this.requestId=r.requestId,this.cfRay=r.cfRay;for(let n of["code","category","retryable","providerCode","remedy"])r[n]!==void 0&&Object.defineProperty(this,n,{value:r[n],enumerable:!0,configurable:!0,writable:!1})}},k={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function S(e,t){let r=process.env[e],n=r?Number.parseInt(r,10):Number.NaN;return!Number.isFinite(n)||n<0?t:n}function lt(e={}){let t=Math.max(0,e.maxRetries??S("XENO_API_MAX_RETRIES",k.maxRetries)),r=Math.max(50,e.baseDelayMs??S("XENO_API_BASE_DELAY_MS",k.baseDelayMs)),n=Math.max(r,e.maxDelayMs??S("XENO_API_MAX_DELAY_MS",k.maxDelayMs)),o=Math.max(0,e.jitterMs??S("XENO_API_RETRY_JITTER_MS",k.jitterMs));return{maxRetries:t,baseDelayMs:r,maxDelayMs:n,jitterMs:o}}function ft(e,t,r){if(t.retryAfterMs&&t.retryAfterMs>0)return Math.min(t.retryAfterMs,r.maxDelayMs);let n=Math.min(r.baseDelayMs*Math.pow(2,e),r.maxDelayMs),o=Math.floor(Math.random()*r.jitterMs);return Math.min(n+o,r.maxDelayMs)}function ue(e){let t=e.toLowerCase();return t.includes("rate limit")||t.includes("too many requests")||t.includes("429")}function pt(e){let t=e.toLowerCase();return t.includes("network")||t.includes("timeout")||t.includes("fetch failed")||t.includes("socket hang up")||t.includes("econnreset")||t.includes("eai_again")||t.includes("enotfound")||t.includes("econnrefused")||t.includes("tls")||t.includes("temporarily unavailable")}function de(e){if(e instanceof I)return{statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId,cfRay:e.cfRay};if(!(e instanceof Error))return{};let t=e;if(t.statusCode!==void 0||t.retryAfterMs!==void 0||t.requestId!==void 0||t.cfRay!==void 0)return{statusCode:t.statusCode,retryAfterMs:t.retryAfterMs,requestId:t.requestId,cfRay:t.cfRay};let r=e.message.toLowerCase();return ue(r)?{statusCode:429}:{}}var U="408|425|429|500|502|503|504";function mt(e){let t=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${U})\\b`,"i"),r=new RegExp(`\\b(?:${U})\\s+(?:internal|bad\\s+gateway|service\\s+unavailable|gateway\\s+time|request\\s+time|too\\s+early|too\\s+many)`,"i"),n=new RegExp(`^\\s*(?:${U})\\b`);return t.test(e)||r.test(e)||n.test(e)}function gt(e){if(e&&typeof e=="object"&&"retryable"in e)return e.retryable===!0;if(e instanceof I){let{statusCode:t}=de(e);if(t)return t===429||t>=500||t===408||t===409||t===425}if(e instanceof Error){let t=e.name?.toLowerCase()??"";return t==="aborterror"||t==="agentinterruptederror"||e.message.toLowerCase().includes("aborted")||e.message.toLowerCase().includes("interrupted")?!1:mt(e.message)?!0:ue(e.message)||pt(e.message.toLowerCase())}return!1}function yt(e){if(e.onAbort)return e.onAbort();let t=new Error("The operation was aborted");return t.name="AbortError",t}async function Zr(e,t={}){let r=lt(t),n;for(let o=0;o<=r.maxRetries;o++)try{if(t.signal?.aborted)throw yt(t);return t.onBeforeAttempt?.(o),await e()}catch(s){if(n=s,!(t.shouldRetry?t.shouldRetry(s,o):gt(s))||o===r.maxRetries)throw s;let a=de(s),c=ft(o,a,r),l=t.getDelayMs?.(s,o,c),f=typeof l=="number"&&l>=0?l:c;await new Promise(u=>setTimeout(u,f))}throw n}var ht=(e,t)=>{if(!e)return 0;let r=t.toLowerCase(),n=r.includes("claude")?3.5:r.includes("gemini")?3.8:(/(^|[/_-])(gpt|o\d)/.test(r),4),o=[...e].filter(i=>i.codePointAt(0)>127).length,s=Math.ceil(e.length/n);return Math.max(1,s+Math.ceil(o*.35))},Et=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:ht,countImage:({detail:e})=>e==="high"?2e3:e==="low"?512:1200,safetyMarginRatio:e=>{let t=e.toLowerCase();return t.includes("claude")?.12:t.includes("gemini")?.14:/(^|[/_-])(gpt|o\d)/.test(t)?.1:.18}});function Qr(e,t,r=Et){return{tokens:Math.max(0,Math.ceil(r.countText(e,t))),source:r.source,adapterId:r.id}}function bt(e){return e?Math.ceil(e.length/4):0}function en(e,t){if(!e||t<=0)return"";let r=t*4;if(e.length<=r)return e;let n=e.slice(0,r),o=n.lastIndexOf(" ");return o>r*.8&&(n=n.slice(0,o)),n+"..."}function tn(e,t){return bt(e)<=t}function rn(e,t){return Math.max(0,t-e)}var wt={"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 on(e,t,r){let n=wt[e];return n?t/1e6*n.input+r/1e6*n.output:0}function sn(e){return e<=0?"$0.00":e<.001?"<$0.001":e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}import{spawnSync as xt}from"node:child_process";function un(e){let t=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"]}],r=null;for(let n of t)try{let o=xt(n.command,n.args,{input:e,encoding:"utf8"});if(o.error){r=o.error.message;continue}if(o.status===0)return;r=o.stderr||o.stdout||`exit ${o.status}`}catch(o){r=o instanceof Error?o.message:String(o)}throw new Error(`Clipboard copy failed${r?`: ${r}`:""}`)}function ln(){return!1}function fn(e){return!1}function pn(e){return e}function mn(e){return`Access to ${e} is not restricted.`}function gn(e){return!1}function yn(e){return null}function Rt(e){return/^data:([^;,]+)[;,]/i.exec(e.trim())?.[1]}function Tt(e){let t=[];for(let r of e){if(r.type==="text"){t.push(r.text);continue}if(r.type==="image_url"){t.push(`[image ${Rt(r.image_url.url)??"unknown"}]`);continue}let n=r.text??r.data;if(n&&n.trim().length>0){t.push(n);continue}let o=r.uri??r.mimeType??"resource";t.push(`[resource ${o}]`)}return t.join(`
23
+ `))}function C(e){if(e==null)return"";if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}var at=/^[A-Za-z0-9:._*-]{1,64}$/,ct=/^[A-Za-z0-9_-][A-Za-z0-9 _-]{0,30}[A-Za-z0-9_-]$/,ut=/^[0-9][0-9A-Za-z.+-]{0,40}$/,ce=Object.freeze({"x-xeno-source":Object.freeze(["auto","quota","credits","byok"]),"x-xeno-byok-mode":Object.freeze(["local","cloud"])}),dt=/^[\x21-\x7E]{1,64}$/;function Gr(e){if(!e||typeof e!="object")throw new TypeError("requestContext must be an object");let t=Object.keys(e).filter(s=>s!=="surface"&&s!=="client"&&s!=="headers");if(t.length>0)throw new TypeError(`requestContext does not accept: ${t.join(", ")}`);if(typeof e.surface!="string"||!at.test(e.surface))throw new TypeError("requestContext.surface must match /^[A-Za-z0-9:._*-]{1,64}$/");let r=lt(e.headers),n=r?{surface:e.surface,headers:r}:{surface:e.surface};if(e.client===void 0)return Object.freeze(n);let o=e.client;if(!o||typeof o!="object"||Object.keys(o).some(s=>s!=="name"&&s!=="version"))throw new TypeError("requestContext.client must be { name, version }");if(typeof o.name!="string"||!ct.test(o.name))throw new TypeError("requestContext.client.name must be 2-32 characters of letters, digits, space, _ or -");if(typeof o.version!="string"||!ut.test(o.version))throw new TypeError("requestContext.client.version must start with a digit, e.g. 1.2.3");return Object.freeze({...n,client:Object.freeze({name:o.name,version:o.version})})}function lt(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("requestContext.headers must be an object");let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase(),s=Object.prototype.hasOwnProperty.call(ce,o)?ce[o]:void 0;if(!s)throw new TypeError(`requestContext.headers does not accept: ${r}`);if(typeof n!="string"||!dt.test(n))throw new TypeError(`requestContext.headers.${o} must be 1-64 printable ASCII characters`);if(!s.includes(n))throw new TypeError(`requestContext.headers.${o} must be one of: ${s.join(", ")}`);if(Object.prototype.hasOwnProperty.call(t,o))throw new TypeError(`requestContext.headers.${o} is given twice`);t[o]=n}return Object.freeze(t)}function Yr(e){return e?{...e.headers??{},"X-Xeno-Surface":e.surface,...e.client?{"X-Xeno-Client":`${e.client.name}/${e.client.version}`}:{}}:{}}var I=class extends Error{statusCode;body;retryAfterMs;requestId;cfRay;constructor(t,r={}){super(t,r.cause!==void 0?{cause:r.cause}:void 0),this.name="ApiTransientError",this.statusCode=r.statusCode,this.retryAfterMs=r.retryAfterMs,this.requestId=r.requestId,this.cfRay=r.cfRay;for(let n of["code","category","retryable","providerCode","remedy"])r[n]!==void 0&&Object.defineProperty(this,n,{value:r[n],enumerable:!0,configurable:!0,writable:!1})}},P={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function S(e,t){let r=process.env[e],n=r?Number.parseInt(r,10):Number.NaN;return!Number.isFinite(n)||n<0?t:n}function ft(e={}){let t=Math.max(0,e.maxRetries??S("XENO_API_MAX_RETRIES",P.maxRetries)),r=Math.max(50,e.baseDelayMs??S("XENO_API_BASE_DELAY_MS",P.baseDelayMs)),n=Math.max(r,e.maxDelayMs??S("XENO_API_MAX_DELAY_MS",P.maxDelayMs)),o=Math.max(0,e.jitterMs??S("XENO_API_RETRY_JITTER_MS",P.jitterMs));return{maxRetries:t,baseDelayMs:r,maxDelayMs:n,jitterMs:o}}function pt(e,t,r){if(t.retryAfterMs&&t.retryAfterMs>0)return Math.min(t.retryAfterMs,r.maxDelayMs);let n=Math.min(r.baseDelayMs*Math.pow(2,e),r.maxDelayMs),o=Math.floor(Math.random()*r.jitterMs);return Math.min(n+o,r.maxDelayMs)}function ue(e){let t=e.toLowerCase();return t.includes("rate limit")||t.includes("too many requests")||t.includes("429")}function mt(e){let t=e.toLowerCase();return t.includes("network")||t.includes("timeout")||t.includes("fetch failed")||t.includes("socket hang up")||t.includes("econnreset")||t.includes("eai_again")||t.includes("enotfound")||t.includes("econnrefused")||t.includes("tls")||t.includes("temporarily unavailable")}function de(e){if(e instanceof I)return{statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId,cfRay:e.cfRay};if(!(e instanceof Error))return{};let t=e;if(t.statusCode!==void 0||t.retryAfterMs!==void 0||t.requestId!==void 0||t.cfRay!==void 0)return{statusCode:t.statusCode,retryAfterMs:t.retryAfterMs,requestId:t.requestId,cfRay:t.cfRay};let r=e.message.toLowerCase();return ue(r)?{statusCode:429}:{}}var U="408|425|429|500|502|503|504";function gt(e){let t=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${U})\\b`,"i"),r=new RegExp(`\\b(?:${U})\\s+(?:internal|bad\\s+gateway|service\\s+unavailable|gateway\\s+time|request\\s+time|too\\s+early|too\\s+many)`,"i"),n=new RegExp(`^\\s*(?:${U})\\b`);return t.test(e)||r.test(e)||n.test(e)}function yt(e){if(e&&typeof e=="object"&&"retryable"in e)return e.retryable===!0;if(e instanceof I){let{statusCode:t}=de(e);if(t)return t===429||t>=500||t===408||t===409||t===425}if(e instanceof Error){let t=e.name?.toLowerCase()??"";return t==="aborterror"||t==="agentinterruptederror"||e.message.toLowerCase().includes("aborted")||e.message.toLowerCase().includes("interrupted")?!1:gt(e.message)?!0:ue(e.message)||mt(e.message.toLowerCase())}return!1}function ht(e){if(e.onAbort)return e.onAbort();let t=new Error("The operation was aborted");return t.name="AbortError",t}async function Jr(e,t={}){let r=ft(t),n;for(let o=0;o<=r.maxRetries;o++)try{if(t.signal?.aborted)throw ht(t);return t.onBeforeAttempt?.(o),await e()}catch(s){if(n=s,!(t.shouldRetry?t.shouldRetry(s,o):yt(s))||o===r.maxRetries)throw s;let c=de(s),a=pt(o,c,r),d=t.getDelayMs?.(s,o,a),l=typeof d=="number"&&d>=0?d:a;await new Promise(u=>setTimeout(u,l))}throw n}var bt=(e,t)=>{if(!e)return 0;let r=t.toLowerCase(),n=r.includes("claude")?3.5:r.includes("gemini")?3.8:(/(^|[/_-])(gpt|o\d)/.test(r),4),o=[...e].filter(i=>i.codePointAt(0)>127).length,s=Math.ceil(e.length/n);return Math.max(1,s+Math.ceil(o*.35))},Et=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:bt,countImage:({detail:e})=>e==="high"?2e3:e==="low"?512:1200,safetyMarginRatio:e=>{let t=e.toLowerCase();return t.includes("claude")?.12:t.includes("gemini")?.14:/(^|[/_-])(gpt|o\d)/.test(t)?.1:.18}});function en(e,t,r=Et){return{tokens:Math.max(0,Math.ceil(r.countText(e,t))),source:r.source,adapterId:r.id}}function wt(e){return e?Math.ceil(e.length/4):0}function tn(e,t){if(!e||t<=0)return"";let r=t*4;if(e.length<=r)return e;let n=e.slice(0,r),o=n.lastIndexOf(" ");return o>r*.8&&(n=n.slice(0,o)),n+"..."}function rn(e,t){return wt(e)<=t}function nn(e,t){return Math.max(0,t-e)}var xt={"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 sn(e,t,r){let n=xt[e];return n?t/1e6*n.input+r/1e6*n.output:0}function an(e){return e<=0?"$0.00":e<.001?"<$0.001":e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}import{spawnSync as Rt}from"node:child_process";function dn(e){let t=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"]}],r=null;for(let n of t)try{let o=Rt(n.command,n.args,{input:e,encoding:"utf8"});if(o.error){r=o.error.message;continue}if(o.status===0)return;r=o.stderr||o.stdout||`exit ${o.status}`}catch(o){r=o instanceof Error?o.message:String(o)}throw new Error(`Clipboard copy failed${r?`: ${r}`:""}`)}function fn(){return!1}function pn(e){return!1}function mn(e){return e}function gn(e){return`Access to ${e} is not restricted.`}function yn(e){return!1}function hn(e){return null}function Tt(e){return/^data:([^;,]+)[;,]/i.exec(e.trim())?.[1]}function _t(e){let t=[];for(let r of e){if(r.type==="text"){t.push(r.text);continue}if(r.type==="image_url"){t.push(`[image ${Tt(r.image_url.url)??"unknown"}]`);continue}let n=r.text??r.data;if(n&&n.trim().length>0){t.push(n);continue}let o=r.uri??r.mimeType??"resource";t.push(`[resource ${o}]`)}return t.join(`
21
24
 
22
- `).trim()}function le(e){let t=e.trim();return t.length>0?[{type:"text",text:t}]:[]}function En(e){return typeof e=="string"?e:Tt(e)}function _t(e){if(e.success)return e.output;let t=[`Error: ${e.error??"Tool execution failed"}`];return e.output.trim().length>0&&t.push(e.output),t.join(`
23
- `)}function bn(e){let t=e.assistant_content&&e.assistant_content.length>0?e.assistant_content:typeof e.content=="string"?le(e.content):e.content,r=e.assistant_only_content??[],n=vt(e),o=[...t,...r,...n?[n]:[]];return o.length>0?o:e.content}function vt(e){let t=e.operation;if(!t)return null;let r=e.evidence??t.evidence??[],n=r.filter(s=>s.status==="verified").length,o=r.filter(s=>s.status==="failed").length;return{type:"text",text:["[xeno_operation]",`operation_id: ${t.operationId}`,`state: ${t.state}`,`terminal: ${t.terminal?"yes":"no"}`,`completion_policy: ${t.completionPolicy}`,t.taskId?`task_id: ${t.taskId}`:null,t.completionReason?`completion_reason: ${t.completionReason}`:null,`evidence: ${n} verified, ${o} failed`,e.retryable===void 0?null:`retryable: ${e.retryable?"yes":"no"}`,"[/xeno_operation]"].filter(s=>!!s).join(`
24
- `)}}function wn(e){return Array.isArray(e)&&e.some(t=>t.type!=="text")}function xn(e){return typeof e=="string"?le(e):e}function Rn(e,t){return{type:"tool_result",tool_use_id:e,content:_t(t),...t.assistantContent&&t.assistantContent.length>0?{assistant_content:t.assistantContent}:{},...t.assistantOnlyContent&&t.assistantOnlyContent.length>0?{assistant_only_content:t.assistantOnlyContent}:{},is_error:!t.success,...t.operation?{operation:t.operation}:{},...t.evidence&&t.evidence.length>0?{evidence:t.evidence}:{},...t.webContext?{web_context:t.webContext}:{},...t.retryable!==void 0?{retryable:t.retryable}:{}}}function _n(e,t={}){for(let r of e){let n=r.codePointAt(0);if(n===127)return!0;if(!(n>31)&&!(n===9&&t.allowTab===!0)&&!((n===10||n===13)&&t.allowLineBreaks===!0))return!0}return!1}import{lookup as Ct}from"node:dns/promises";import{isIP as M}from"node:net";var b="[redacted]";var At=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[redacted:private-key]"],[/((?:^|[\s{,;"'(\[])["']?(?:cookie|set-cookie)["']?\s*[:=]\s*["']?)(?!\[redacted)[^\s"',;]+(?:;\s*[^\s"',;=]+=[^\s"',;]*)*/gi,`$1${b}`],[/((?:^|[\s{,;"'(\[])["']?(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-xeno-api-key|api[-_]?key|apikey|dpop)["']?\s*[:=]\s*["']?)(?:(?:Bearer|Basic|Token|DPoP)\s+)?(?!\[redacted)[^\s"',;]+/gi,`$1${b}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${b}`],[/\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|xeno-[A-Za-z0-9]{24,}|xrun_[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{30,}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9]{30,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g,b],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,b],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${b}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${b}@`]];function fe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A(e,t=[]){if(!e)return e;let r=e,n=[...new Set([...t].filter(o=>typeof o=="string"&&o.length>=12))].sort((o,s)=>s.length-o.length);for(let o of n){r=r.replace(new RegExp(`(?<![A-Za-z0-9_-])${fe(o)}(?![A-Za-z0-9_-])`,"g"),b);let s=encodeURIComponent(o);s!==o&&(r=r.replace(new RegExp(`(?<![A-Za-z0-9_-])${fe(s)}(?![A-Za-z0-9_-])`,"g"),b))}for(let[o,s]of At)o.lastIndex=0,r=r.replace(o,s);return r}function j(e,t,r){try{Object.defineProperty(e,t,{value:r,writable:!0,configurable:!0,enumerable:!1})}catch{}}function V(e,t=[],r=0){if(!(e instanceof Error)||r>6)return e;let n=[...t],o=A(e.message,n);if(o!==e.message&&j(e,"message",o),typeof e.stack=="string"){let i=A(e.stack,n);i!==e.stack&&j(e,"stack",i)}let s=e.cause;if(s instanceof Error)V(s,n,r+1);else if(s!=null){let i;try{i=typeof s=="string"?s:JSON.stringify(s)??String(s)}catch{i=String(s)}let a=A(i,n);a!==i&&j(e,"cause",a)}for(let i of Object.keys(e)){let a=e[i];if(typeof a=="string"){let c=A(a,n);if(c!==a)try{e[i]=c}catch{}}}return e}var O=class extends Error{category;code;retryable;providerId;statusCode;retryAfterMs;requestId;providerCode;remedy;constructor(t,r){super(A(t),r.cause!==void 0?{cause:r.cause}:void 0),this.name="ProviderError",this.category=r.category,this.code=r.code,this.retryable=r.retryable??!1,this.providerId=r.providerId,this.statusCode=r.statusCode,this.retryAfterMs=r.retryAfterMs,this.requestId=r.requestId,r.providerCode!==void 0&&(this.providerCode=r.providerCode),r.remedy!==void 0&&(this.remedy=r.remedy),V(this)}};var ge=new Set(["metadata.google.internal","metadata.azure.internal","instance-data.ec2.internal"]);function m(e){return new O(`Provider endpoint rejected: ${e}`,{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"})}function Pt(e){let t=e.split(".");if(t.length!==4)return null;let r=t.map(n=>Number(n));return r.every(n=>Number.isInteger(n)&&n>=0&&n<=255)?r:null}function pe(e){let t=Pt(e);if(!t)return"public";let[r,n]=t;return r===0?"unspecified":r===127?"loopback":r===169&&n===254?"link-local":r===10||r===172&&n>=16&&n<=31||r===192&&n===168?"private":"public"}function x(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"").split("%")[0];M(t)===6&&(t=new URL(`http://[${t}]`).hostname.slice(1,-1));let r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(r){let n=Number.parseInt(r[1],16),o=Number.parseInt(r[2],16);return`${n>>8}.${n&255}.${o>>8}.${o&255}`}return t}function ye(e){let t=x(e);return M(t)===4?pe(t):t==="::"||t==="::0"?"unspecified":t==="::1"?"loopback":t.startsWith("::ffff:")?pe(t.slice(7)):/^f[cd]/.test(t)?"private":/^fe[89ab]/.test(t)?"link-local":"public"}function me(e){return e==="example"||e.endsWith(".example")||e==="test"||e.endsWith(".test")||e==="invalid"||e.endsWith(".invalid")}function kt(e){return e==="localhost"||e.endsWith(".localhost")}function he(e,t={}){let r;try{r=new URL(e)}catch{throw m("the URL is invalid")}if(r.username||r.password)throw m("embedded credentials are forbidden");if(r.hash||r.search)throw m("base URLs cannot contain a query or fragment");if(!r.hostname||r.hostname.includes("%"))throw m("the hostname is empty or ambiguous");if(ge.has(r.hostname.toLowerCase()))throw m("cloud metadata destinations are forbidden");if(r.protocol!=="https:"&&r.protocol!=="http:")throw m(`scheme ${r.protocol} is unsupported`);let n=t.profile??"public-https";if(r.protocol==="http:"&&n!=="local-network")throw m("plain HTTP requires the explicit local-network profile");let o=r.hostname.replace(/^\[|\]$/g,""),s=M(o)?ye(o):null;if(s==="link-local"||s==="unspecified")throw m(`${s} destinations are forbidden`);if(n==="public-https"&&(s==="private"||s==="loopback"||kt(r.hostname)))throw m("private and loopback destinations require the local-network profile");if(n==="local-network"&&r.protocol==="http:"&&s==="public"&&!t.allowedHosts?.includes(r.hostname))throw m("local-network HTTP must resolve to loopback or a private address");return r}async function Ee(e,t={}){let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(ge.has(r))throw m("cloud metadata destinations are forbidden");let n=new Set((t.allowedHosts??[]).map(i=>i.toLowerCase())),o=M(r)?[r]:me(r)?[]:t.resolveHostname?await t.resolveHostname(r):(await Ct(r,{all:!0,verbatim:!0})).map(i=>i.address);if(!o.length&&!me(r))throw m("DNS resolution returned no addresses");let s=t.profile??"public-https";for(let i of o){let a=ye(i);if(a==="link-local"||a==="unspecified")throw m(`DNS resolved to a forbidden ${a} address`);if(s==="public-https"&&a!=="public"&&!n.has(r))throw m(`DNS resolved public endpoint to ${a} address ${i}`);if(s==="local-network"&&e.protocol==="http:"&&a==="public"&&!n.has(r))throw m(`local-network HTTP resolved to public address ${i}`)}return o}import{request as St}from"node:http";import{request as It}from"node:https";import{isIP as be}from"node:net";import{once as Ot}from"node:events";function we(e,t,r){return{dispatch(n,o){let s,i=!1,a=u=>{i||(i=!0,s?.destroy(),o.onError(u))},c=t[0];if(!c||!be(c)||new URL(n.origin).origin!==e.origin)return queueMicrotask(()=>a(new Error("Provider connection has no authorized pinned address"))),!0;let l=n.headers??{},f=(e.protocol==="https:"?It:St)(new URL(n.path,e.origin),{method:n.method,headers:l,agent:!1,rejectUnauthorized:!0,lookup:(u,g,R)=>{let h={address:c,family:be(c)};typeof g=="object"&&g.all?R(null,[h]):R(null,c,h.family)}},u=>{s=u;let g=u.rawHeaders.map(h=>Buffer.from(h)),R=()=>u.resume();o.onHeaders(u.statusCode??500,g,R,u.statusMessage??"")===!1&&u.pause(),u.on("data",h=>{o.onData(h)||u.pause()}),u.on("end",()=>{i||(i=!0,o.onComplete(u.rawTrailers.map(h=>Buffer.from(h))))}),u.on("error",a),u.on("aborted",()=>a(new Error("Provider response was interrupted")))});return f.on("socket",u=>{u.once("connect",()=>{if(!u.remoteAddress||x(u.remoteAddress)!==x(c)){f.destroy(new Error("Provider socket did not connect to its authorized address"));return}e.protocol==="http:"&&r?.()}),e.protocol==="https:"&&u.once("secureConnect",()=>{u.authorized&&u.remoteAddress&&x(u.remoteAddress)===x(c)&&r?.()})}),f.on("error",a),o.onConnect(u=>f.destroy(u??new Error("Provider request aborted"))),(async()=>{try{let u=n.body;if(typeof u=="string"||u instanceof Uint8Array)f.end(u);else{if(u)for await(let g of u){if(f.destroyed)return;f.write(g)||await Ot(f,"drain")}f.end()}}catch(u){f.destroy(u instanceof Error?u:new Error("Provider request body failed"))}})(),!0}}}async function Gn(e,t,r={}){let n=new URL(e.toString()),o=new URL(n);o.search="",o.hash="",he(o.toString(),r.policy),t.signal?.throwIfAborted();let s=await xe(Ee(o,r.policy),t.signal);if(!s.length)throw new Error("Pinned endpoint resolution returned no addresses.");if(r.authorizeAddress&&s.some(c=>r.authorizeAddress(x(c),new URL(n))!==!0))throw new Error("Pinned endpoint resolved outside the authorized address scope.");t.signal?.throwIfAborted();let i=fetch(n,{...t,redirect:"manual",credentials:"omit",dispatcher:we(n,s)});i.then(c=>{t.signal?.aborted&&c.body?.cancel().catch(()=>{})},()=>{});let a=await xe(i,t.signal);if(a.redirected)throw await a.body?.cancel(),new Error("Pinned endpoint transport followed a redirect without authorization.");return a}async function xe(e,t){if(!t)return e;let r,n=new Promise((o,s)=>{r=()=>s(t.reason??new Error("Pinned endpoint read cancelled.")),t.addEventListener("abort",r,{once:!0}),t.aborted&&r()});try{return await Promise.race([e,n])}finally{t.removeEventListener("abort",r)}}export{I as ApiTransientError,Ar as HOME_DIR,_r as IS_LINUX,Tr as IS_MAC,C as IS_WINDOWS,st as LogLevel,vr as OS_VERSION,H as PLATFORM,Qr as accountTextTokens,Vt as appendDurableLine,jt as appendLine,mn as benchmarkLeakError,Rn as buildToolResultBlock,_t as buildToolResultText,on as calculateCost,Dt as clearFileCache,gn as commandMentionsBenchmarkLeak,Et as conservativeTokenAccountingAdapter,un as copyTextToClipboard,Br as createSafeRegex,Hr as debug,Oe as decodeTextBuffer,rr as deleteDir,tr as deleteFile,$e as detectLineEnding,Gt as detectPreferredLineEnding,Ie as detectTextEncoding,Me as encodeTextBuffer,B as ensureDir,Vr as error,bt as estimateTokens,ht as estimateTokensForModel,Jt as existsSync,Gn as fetchPinnedEndpoint,pn as filterBenchmarkLeakPaths,Yt as findSimilarFile,tn as fitsInBudget,sn as formatCost,Cr as getAgentHome,yn as getBenchmarkReferenceOverwriteHint,Lr as getBoolean,Pr as getConfigDir,$t as getFileCacheStats,qr as getLogLevel,Dr as getNumber,kr as getProjectConfigDir,de as getRetryErrorContext,Sr as getShellName,Nr as getString,bn as getToolResultTransportContent,Ht as hasDir,_n as hasDisallowedAsciiControlCharacter,qt as hasFile,dr as hasFrontmatter,Wt as hasMixedLineEndings,wn as hasNonTextToolResultContent,mt as hasTransientStatusMention,Ur as info,D as invalidateFileCache,fn as isBenchmarkLeakPath,ln as isBenchmarkMode,Ir as isGitRepo,Or as isGitRepoAsync,qe as isPathSafe,gt as isRetryableError,er as listDirs,Qt as listFiles,Ne as normalizeLineEndings,Kr as normalizeXenoRequestContext,cr as parseDocument,ir as parseJsonLines,pr as pathIdentityKey,ve as readDerivedCached,Ut as readFileSafe,Zt as readIfExists,Lt as readTextCached,De as readTextFile,rn as remainingBudget,Se as renameReplacingWithRetry,Nt as resetFileCacheStats,or as safeJsonParse,sr as safeJsonStringify,Xr as safeRegexTest,fr as safeResolvePath,Fr as setLogLevel,ur as stringifyDocument,xn as toTransportAssistantBlocks,Tt as toolAssistantContentToText,En as toolResultContentToText,en as truncateToTokens,ot as validateRegexPattern,$r as validateRequired,jr as warn,Zr as withRetry,Ce as writeAtomic,Kt as writeTextFile,Gr as xenoRequestContextHeaders};
25
+ `).trim()}function le(e){let t=e.trim();return t.length>0?[{type:"text",text:t}]:[]}function En(e){return typeof e=="string"?e:_t(e)}function vt(e){if(e.success)return e.output;let t=[`Error: ${e.error??"Tool execution failed"}`];return e.output.trim().length>0&&t.push(e.output),t.join(`
26
+ `)}function wn(e){let t=e.assistant_content&&e.assistant_content.length>0?e.assistant_content:typeof e.content=="string"?le(e.content):e.content,r=e.assistant_only_content??[],n=At(e),o=[...t,...r,...n?[n]:[]];return o.length>0?o:e.content}function At(e){let t=e.operation;if(!t)return null;let r=e.evidence??t.evidence??[],n=r.filter(s=>s.status==="verified").length,o=r.filter(s=>s.status==="failed").length;return{type:"text",text:["[xeno_operation]",`operation_id: ${t.operationId}`,`state: ${t.state}`,`terminal: ${t.terminal?"yes":"no"}`,`completion_policy: ${t.completionPolicy}`,t.taskId?`task_id: ${t.taskId}`:null,t.completionReason?`completion_reason: ${t.completionReason}`:null,`evidence: ${n} verified, ${o} failed`,e.retryable===void 0?null:`retryable: ${e.retryable?"yes":"no"}`,"[/xeno_operation]"].filter(s=>!!s).join(`
27
+ `)}}function xn(e){return Array.isArray(e)&&e.some(t=>t.type!=="text")}function Rn(e){return typeof e=="string"?le(e):e}function Tn(e,t){return{type:"tool_result",tool_use_id:e,content:vt(t),...t.assistantContent&&t.assistantContent.length>0?{assistant_content:t.assistantContent}:{},...t.assistantOnlyContent&&t.assistantOnlyContent.length>0?{assistant_only_content:t.assistantOnlyContent}:{},is_error:!t.success,...t.operation?{operation:t.operation}:{},...t.evidence&&t.evidence.length>0?{evidence:t.evidence}:{},...t.webContext?{web_context:t.webContext}:{},...t.retryable!==void 0?{retryable:t.retryable}:{}}}function vn(e,t={}){for(let r of e){let n=r.codePointAt(0);if(n===127)return!0;if(!(n>31)&&!(n===9&&t.allowTab===!0)&&!((n===10||n===13)&&t.allowLineBreaks===!0))return!0}return!1}import{lookup as Ct}from"node:dns/promises";import{isIP as M}from"node:net";var E="[redacted]";var kt=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[redacted:private-key]"],[/((?:^|[\s{,;"'(\[])["']?(?:cookie|set-cookie)["']?\s*[:=]\s*["']?)(?!\[redacted)[^\s"',;]+(?:;\s*[^\s"',;=]+=[^\s"',;]*)*/gi,`$1${E}`],[/((?:^|[\s{,;"'(\[])["']?(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-xeno-api-key|api[-_]?key|apikey|dpop)["']?\s*[:=]\s*["']?)(?:(?:Bearer|Basic|Token|DPoP)\s+)?(?!\[redacted)[^\s"',;]+/gi,`$1${E}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${E}`],[/\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|xeno-[A-Za-z0-9]{24,}|xrun_[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{30,}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9]{30,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g,E],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,E],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${E}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${E}@`]];function fe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A(e,t=[]){if(!e)return e;let r=e,n=[...new Set([...t].filter(o=>typeof o=="string"&&o.length>=12))].sort((o,s)=>s.length-o.length);for(let o of n){r=r.replace(new RegExp(`(?<![A-Za-z0-9_-])${fe(o)}(?![A-Za-z0-9_-])`,"g"),E);let s=encodeURIComponent(o);s!==o&&(r=r.replace(new RegExp(`(?<![A-Za-z0-9_-])${fe(s)}(?![A-Za-z0-9_-])`,"g"),E))}for(let[o,s]of kt)o.lastIndex=0,r=r.replace(o,s);return r}function j(e,t,r){try{Object.defineProperty(e,t,{value:r,writable:!0,configurable:!0,enumerable:!1})}catch{}}function V(e,t=[],r=0){if(!(e instanceof Error)||r>6)return e;let n=[...t],o=A(e.message,n);if(o!==e.message&&j(e,"message",o),typeof e.stack=="string"){let i=A(e.stack,n);i!==e.stack&&j(e,"stack",i)}let s=e.cause;if(s instanceof Error)V(s,n,r+1);else if(s!=null){let i;try{i=typeof s=="string"?s:JSON.stringify(s)??String(s)}catch{i=String(s)}let c=A(i,n);c!==i&&j(e,"cause",c)}for(let i of Object.keys(e)){let c=e[i];if(typeof c=="string"){let a=A(c,n);if(a!==c)try{e[i]=a}catch{}}}return e}var O=class extends Error{category;code;retryable;providerId;statusCode;retryAfterMs;requestId;providerCode;remedy;constructor(t,r){super(A(t),r.cause!==void 0?{cause:r.cause}:void 0),this.name="ProviderError",this.category=r.category,this.code=r.code,this.retryable=r.retryable??!1,this.providerId=r.providerId,this.statusCode=r.statusCode,this.retryAfterMs=r.retryAfterMs,this.requestId=r.requestId,r.providerCode!==void 0&&(this.providerCode=r.providerCode),r.remedy!==void 0&&(this.remedy=r.remedy),V(this)}};var ge=new Set(["metadata.google.internal","metadata.azure.internal","instance-data.ec2.internal"]);function m(e){return new O(`Provider endpoint rejected: ${e}`,{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"})}function Pt(e){let t=e.split(".");if(t.length!==4)return null;let r=t.map(n=>Number(n));return r.every(n=>Number.isInteger(n)&&n>=0&&n<=255)?r:null}function pe(e){let t=Pt(e);if(!t)return"public";let[r,n]=t;return r===0?"unspecified":r===127?"loopback":r===169&&n===254?"link-local":r===10||r===172&&n>=16&&n<=31||r===192&&n===168?"private":"public"}function x(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"").split("%")[0];M(t)===6&&(t=new URL(`http://[${t}]`).hostname.slice(1,-1));let r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(r){let n=Number.parseInt(r[1],16),o=Number.parseInt(r[2],16);return`${n>>8}.${n&255}.${o>>8}.${o&255}`}return t}function ye(e){let t=x(e);return M(t)===4?pe(t):t==="::"||t==="::0"?"unspecified":t==="::1"?"loopback":t.startsWith("::ffff:")?pe(t.slice(7)):/^f[cd]/.test(t)?"private":/^fe[89ab]/.test(t)?"link-local":"public"}function me(e){return e==="example"||e.endsWith(".example")||e==="test"||e.endsWith(".test")||e==="invalid"||e.endsWith(".invalid")}function St(e){return e==="localhost"||e.endsWith(".localhost")}function he(e,t={}){let r;try{r=new URL(e)}catch{throw m("the URL is invalid")}if(r.username||r.password)throw m("embedded credentials are forbidden");if(r.hash||r.search)throw m("base URLs cannot contain a query or fragment");if(!r.hostname||r.hostname.includes("%"))throw m("the hostname is empty or ambiguous");if(ge.has(r.hostname.toLowerCase()))throw m("cloud metadata destinations are forbidden");if(r.protocol!=="https:"&&r.protocol!=="http:")throw m(`scheme ${r.protocol} is unsupported`);let n=t.profile??"public-https";if(r.protocol==="http:"&&n!=="local-network")throw m("plain HTTP requires the explicit local-network profile");let o=r.hostname.replace(/^\[|\]$/g,""),s=M(o)?ye(o):null;if(s==="link-local"||s==="unspecified")throw m(`${s} destinations are forbidden`);if(n==="public-https"&&(s==="private"||s==="loopback"||St(r.hostname)))throw m("private and loopback destinations require the local-network profile");if(n==="local-network"&&r.protocol==="http:"&&s==="public"&&!t.allowedHosts?.includes(r.hostname))throw m("local-network HTTP must resolve to loopback or a private address");return r}async function be(e,t={}){let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(ge.has(r))throw m("cloud metadata destinations are forbidden");let n=new Set((t.allowedHosts??[]).map(i=>i.toLowerCase())),o=M(r)?[r]:me(r)?[]:t.resolveHostname?await t.resolveHostname(r):(await Ct(r,{all:!0,verbatim:!0})).map(i=>i.address);if(!o.length&&!me(r))throw m("DNS resolution returned no addresses");let s=t.profile??"public-https";for(let i of o){let c=ye(i);if(c==="link-local"||c==="unspecified")throw m(`DNS resolved to a forbidden ${c} address`);if(s==="public-https"&&c!=="public"&&!n.has(r))throw m(`DNS resolved public endpoint to ${c} address ${i}`);if(s==="local-network"&&e.protocol==="http:"&&c==="public"&&!n.has(r))throw m(`local-network HTTP resolved to public address ${i}`)}return o}import{request as It}from"node:http";import{request as Ot}from"node:https";import{isIP as Ee}from"node:net";import{once as Mt}from"node:events";function we(e,t,r){return{dispatch(n,o){let s,i=!1,c=u=>{i||(i=!0,s?.destroy(),o.onError(u))},a=t[0];if(!a||!Ee(a)||new URL(n.origin).origin!==e.origin)return queueMicrotask(()=>c(new Error("Provider connection has no authorized pinned address"))),!0;let d=n.headers??{},l=(e.protocol==="https:"?Ot:It)(new URL(n.path,e.origin),{method:n.method,headers:d,agent:!1,rejectUnauthorized:!0,lookup:(u,g,R)=>{let h={address:a,family:Ee(a)};typeof g=="object"&&g.all?R(null,[h]):R(null,a,h.family)}},u=>{s=u;let g=u.rawHeaders.map(h=>Buffer.from(h)),R=()=>u.resume();o.onHeaders(u.statusCode??500,g,R,u.statusMessage??"")===!1&&u.pause(),u.on("data",h=>{o.onData(h)||u.pause()}),u.on("end",()=>{i||(i=!0,o.onComplete(u.rawTrailers.map(h=>Buffer.from(h))))}),u.on("error",c),u.on("aborted",()=>c(new Error("Provider response was interrupted")))});return l.on("socket",u=>{u.once("connect",()=>{if(!u.remoteAddress||x(u.remoteAddress)!==x(a)){l.destroy(new Error("Provider socket did not connect to its authorized address"));return}e.protocol==="http:"&&r?.()}),e.protocol==="https:"&&u.once("secureConnect",()=>{u.authorized&&u.remoteAddress&&x(u.remoteAddress)===x(a)&&r?.()})}),l.on("error",c),o.onConnect(u=>l.destroy(u??new Error("Provider request aborted"))),(async()=>{try{let u=n.body;if(typeof u=="string"||u instanceof Uint8Array)l.end(u);else{if(u)for await(let g of u){if(l.destroyed)return;l.write(g)||await Mt(l,"drain")}l.end()}}catch(u){l.destroy(u instanceof Error?u:new Error("Provider request body failed"))}})(),!0}}}async function Yn(e,t,r={}){let n=new URL(e.toString()),o=new URL(n);o.search="",o.hash="",he(o.toString(),r.policy),t.signal?.throwIfAborted();let s=await xe(be(o,r.policy),t.signal);if(!s.length)throw new Error("Pinned endpoint resolution returned no addresses.");if(r.authorizeAddress&&s.some(a=>r.authorizeAddress(x(a),new URL(n))!==!0))throw new Error("Pinned endpoint resolved outside the authorized address scope.");t.signal?.throwIfAborted();let i=fetch(n,{...t,redirect:"manual",credentials:"omit",dispatcher:we(n,s)});i.then(a=>{t.signal?.aborted&&a.body?.cancel().catch(()=>{})},()=>{});let c=await xe(i,t.signal);if(c.redirected)throw await c.body?.cancel(),new Error("Pinned endpoint transport followed a redirect without authorization.");return c}async function xe(e,t){if(!t)return e;let r,n=new Promise((o,s)=>{r=()=>s(t.reason??new Error("Pinned endpoint read cancelled.")),t.addEventListener("abort",r,{once:!0}),t.aborted&&r()});try{return await Promise.race([e,n])}finally{t.removeEventListener("abort",r)}}export{I as ApiTransientError,kr as HOME_DIR,vr as IS_LINUX,_r as IS_MAC,k as IS_WINDOWS,it as LogLevel,Ar as OS_VERSION,H as PLATFORM,en as accountTextTokens,Wt as appendDurableLine,Vt as appendLine,gn as benchmarkLeakError,Tn as buildToolResultBlock,vt as buildToolResultText,sn as calculateCost,Lt as clearFileCache,yn as commandMentionsBenchmarkLeak,Et as conservativeTokenAccountingAdapter,dn as copyTextToClipboard,Xr as createSafeRegex,Ur as debug,Oe as decodeTextBuffer,nr as deleteDir,rr as deleteFile,$e as detectLineEnding,Yt as detectPreferredLineEnding,Ie as detectTextEncoding,Me as encodeTextBuffer,B as ensureDir,Wr as error,wt as estimateTokens,bt as estimateTokensForModel,Qt as existsSync,Yn as fetchPinnedEndpoint,mn as filterBenchmarkLeakPaths,Zt as findSimilarFile,rn as fitsInBudget,an as formatCost,Cr as getAgentHome,hn as getBenchmarkReferenceOverwriteHint,Br as getBoolean,Pr as getConfigDir,Nt as getFileCacheStats,Hr as getLogLevel,Lr as getNumber,Sr as getProjectConfigDir,de as getRetryErrorContext,Ir as getShellName,Dr as getString,wn as getToolResultTransportContent,Ut as hasDir,vn as hasDisallowedAsciiControlCharacter,Ht as hasFile,lr as hasFrontmatter,Kt as hasMixedLineEndings,xn as hasNonTextToolResultContent,gt as hasTransientStatusMention,jr as info,D as invalidateFileCache,pn as isBenchmarkLeakPath,fn as isBenchmarkMode,Or as isGitRepo,Mr as isGitRepoAsync,He as isPathSafe,yt as isRetryableError,tr as listDirs,er as listFiles,Ne as normalizeLineEndings,Gr as normalizeXenoRequestContext,ur as parseDocument,ar as parseJsonLines,mr as pathIdentityKey,ve as readDerivedCached,jt as readFileSafe,Jt as readIfExists,Bt as readTextCached,De as readTextFile,nn as remainingBudget,Se as renameReplacingWithRetry,Dt as resetFileCacheStats,sr as safeJsonParse,ir as safeJsonStringify,zr as safeRegexTest,pr as safeResolvePath,qr as setLogLevel,dr as stringifyDocument,Rn as toTransportAssistantBlocks,_t as toolAssistantContentToText,En as toolResultContentToText,tn as truncateToTokens,st as validateRegexPattern,Nr as validateRequired,Vr as warn,Jr as withRetry,ke as writeAtomic,Gt as writeTextFile,Yr as xenoRequestContextHeaders};
@@ -1 +1 @@
1
- {"inputs":{"src/utils/file-cache.ts":{"bytes":6195,"imports":[{"path":"node:fs","kind":"import-statement","external":true}],"format":"esm"},"src/utils/fs.ts":{"bytes":13885,"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":"src/utils/file-cache.ts","kind":"import-statement","original":"./file-cache.js"}],"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/runtime/process-tree-kill.ts":{"bytes":9124,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/utils/platform.ts":{"bytes":9633,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/runtime/process-tree-kill.ts","kind":"import-statement","original":"../runtime/process-tree-kill.js"}],"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":6154,"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/deprecated-benchmark.ts":{"bytes":1119,"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/observability/telemetry.ts":{"bytes":7271,"imports":[{"path":"node:perf_hooks","kind":"import-statement","external":true}],"format":"esm"},"src/observability/index.ts":{"bytes":32,"imports":[{"path":"src/observability/telemetry.ts","kind":"import-statement","original":"./telemetry.js"}],"format":"esm"},"src/utils/context-overflow-phrases.ts":{"bytes":2266,"imports":[],"format":"esm"},"src/providers/provider-error-redaction.ts":{"bytes":9369,"imports":[],"format":"esm"},"src/providers/provider-errors.ts":{"bytes":19820,"imports":[{"path":"src/observability/index.ts","kind":"import-statement","original":"../observability/index.js"},{"path":"src/utils/context-overflow-phrases.ts","kind":"import-statement","original":"../utils/context-overflow-phrases.js"},{"path":"src/providers/provider-error-redaction.ts","kind":"import-statement","original":"./provider-error-redaction.js"}],"format":"esm"},"src/providers/endpoint-policy.ts":{"bytes":6439,"imports":[{"path":"node:dns/promises","kind":"import-statement","external":true},{"path":"node:net","kind":"import-statement","external":true},{"path":"src/providers/provider-errors.ts","kind":"import-statement","original":"./provider-errors.js"}],"format":"esm"},"src/providers/pinned-provider-dispatcher.ts":{"bytes":4419,"imports":[{"path":"node:http","kind":"import-statement","external":true},{"path":"node:https","kind":"import-statement","external":true},{"path":"node:net","kind":"import-statement","external":true},{"path":"node:events","kind":"import-statement","external":true},{"path":"src/providers/endpoint-policy.ts","kind":"import-statement","original":"./endpoint-policy.js"}],"format":"esm"},"src/utils/pinned-fetch.ts":{"bytes":2516,"imports":[{"path":"src/providers/endpoint-policy.ts","kind":"import-statement","original":"../providers/endpoint-policy.js"},{"path":"src/providers/pinned-provider-dispatcher.ts","kind":"import-statement","original":"../providers/pinned-provider-dispatcher.js"}],"format":"esm"},"src/utils/index.ts":{"bytes":1563,"imports":[{"path":"src/utils/fs.ts","kind":"import-statement","original":"./fs.js"},{"path":"src/utils/file-cache.ts","kind":"import-statement","original":"./file-cache.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/deprecated-benchmark.ts","kind":"import-statement","original":"./deprecated-benchmark.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"},{"path":"src/utils/pinned-fetch.ts","kind":"import-statement","original":"./pinned-fetch.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":"node:fs","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:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:dns/promises","kind":"require-call","external":true},{"path":"node:net","kind":"require-call","external":true},{"path":"node:http","kind":"require-call","external":true},{"path":"node:https","kind":"require-call","external":true},{"path":"node:net","kind":"require-call","external":true},{"path":"node:events","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/utils/index.ts","inputs":{"src/utils/index.ts":{"bytesInOutput":2303},"src/utils/fs.ts":{"bytesInOutput":4947},"src/utils/file-cache.ts":{"bytesInOutput":1349},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":2651},"src/utils/path-security.ts":{"bytesInOutput":405},"src/utils/platform.ts":{"bytesInOutput":2666},"src/runtime/process-tree-kill.ts":{"bytesInOutput":1696},"src/utils/validation.ts":{"bytesInOutput":1425},"src/utils/logger.ts":{"bytesInOutput":915},"src/utils/request-context.ts":{"bytesInOutput":2188},"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/deprecated-benchmark.ts":{"bytesInOutput":179},"src/utils/tool-result-content.ts":{"bytesInOutput":2118},"src/utils/text-security.ts":{"bytesInOutput":180},"src/providers/endpoint-policy.ts":{"bytesInOutput":3297},"src/observability/index.ts":{"bytesInOutput":0},"src/providers/provider-error-redaction.ts":{"bytesInOutput":2155},"src/providers/provider-errors.ts":{"bytesInOutput":513},"src/providers/pinned-provider-dispatcher.ts":{"bytesInOutput":1669},"src/utils/pinned-fetch.ts":{"bytesInOutput":1027}},"bytes":39956}}}
1
+ {"inputs":{"src/utils/file-cache.ts":{"bytes":6195,"imports":[{"path":"node:fs","kind":"import-statement","external":true}],"format":"esm"},"src/utils/fs.ts":{"bytes":13885,"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":"src/utils/file-cache.ts","kind":"import-statement","original":"./file-cache.js"}],"format":"esm"},"src/utils/json.ts":{"bytes":804,"imports":[],"format":"esm"},"src/utils/yaml.ts":{"bytes":7264,"imports":[],"format":"esm"},"src/utils/path-security.ts":{"bytes":1762,"imports":[{"path":"path","kind":"import-statement","external":true}],"format":"esm"},"src/runtime/process-tree-kill.ts":{"bytes":9124,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/utils/platform.ts":{"bytes":9633,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/runtime/process-tree-kill.ts","kind":"import-statement","original":"../runtime/process-tree-kill.js"}],"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":6154,"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/deprecated-benchmark.ts":{"bytes":1119,"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/observability/telemetry.ts":{"bytes":7271,"imports":[{"path":"node:perf_hooks","kind":"import-statement","external":true}],"format":"esm"},"src/observability/index.ts":{"bytes":32,"imports":[{"path":"src/observability/telemetry.ts","kind":"import-statement","original":"./telemetry.js"}],"format":"esm"},"src/utils/context-overflow-phrases.ts":{"bytes":2266,"imports":[],"format":"esm"},"src/providers/provider-error-redaction.ts":{"bytes":9369,"imports":[],"format":"esm"},"src/providers/provider-errors.ts":{"bytes":19820,"imports":[{"path":"src/observability/index.ts","kind":"import-statement","original":"../observability/index.js"},{"path":"src/utils/context-overflow-phrases.ts","kind":"import-statement","original":"../utils/context-overflow-phrases.js"},{"path":"src/providers/provider-error-redaction.ts","kind":"import-statement","original":"./provider-error-redaction.js"}],"format":"esm"},"src/providers/endpoint-policy.ts":{"bytes":6439,"imports":[{"path":"node:dns/promises","kind":"import-statement","external":true},{"path":"node:net","kind":"import-statement","external":true},{"path":"src/providers/provider-errors.ts","kind":"import-statement","original":"./provider-errors.js"}],"format":"esm"},"src/providers/pinned-provider-dispatcher.ts":{"bytes":4419,"imports":[{"path":"node:http","kind":"import-statement","external":true},{"path":"node:https","kind":"import-statement","external":true},{"path":"node:net","kind":"import-statement","external":true},{"path":"node:events","kind":"import-statement","external":true},{"path":"src/providers/endpoint-policy.ts","kind":"import-statement","original":"./endpoint-policy.js"}],"format":"esm"},"src/utils/pinned-fetch.ts":{"bytes":2516,"imports":[{"path":"src/providers/endpoint-policy.ts","kind":"import-statement","original":"../providers/endpoint-policy.js"},{"path":"src/providers/pinned-provider-dispatcher.ts","kind":"import-statement","original":"../providers/pinned-provider-dispatcher.js"}],"format":"esm"},"src/utils/index.ts":{"bytes":1563,"imports":[{"path":"src/utils/fs.ts","kind":"import-statement","original":"./fs.js"},{"path":"src/utils/file-cache.ts","kind":"import-statement","original":"./file-cache.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/deprecated-benchmark.ts","kind":"import-statement","original":"./deprecated-benchmark.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"},{"path":"src/utils/pinned-fetch.ts","kind":"import-statement","original":"./pinned-fetch.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":"node:fs","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:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:dns/promises","kind":"require-call","external":true},{"path":"node:net","kind":"require-call","external":true},{"path":"node:http","kind":"require-call","external":true},{"path":"node:https","kind":"require-call","external":true},{"path":"node:net","kind":"require-call","external":true},{"path":"node:events","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/utils/index.ts","inputs":{"src/utils/index.ts":{"bytesInOutput":2303},"src/utils/fs.ts":{"bytesInOutput":4947},"src/utils/file-cache.ts":{"bytesInOutput":1349},"src/utils/json.ts":{"bytesInOutput":239},"src/utils/yaml.ts":{"bytesInOutput":3255},"src/utils/path-security.ts":{"bytesInOutput":405},"src/utils/platform.ts":{"bytesInOutput":2666},"src/runtime/process-tree-kill.ts":{"bytesInOutput":1696},"src/utils/validation.ts":{"bytesInOutput":1425},"src/utils/logger.ts":{"bytesInOutput":915},"src/utils/request-context.ts":{"bytesInOutput":2188},"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/deprecated-benchmark.ts":{"bytesInOutput":179},"src/utils/tool-result-content.ts":{"bytesInOutput":2118},"src/utils/text-security.ts":{"bytesInOutput":180},"src/providers/endpoint-policy.ts":{"bytesInOutput":3297},"src/observability/index.ts":{"bytesInOutput":0},"src/providers/provider-error-redaction.ts":{"bytesInOutput":2155},"src/providers/provider-errors.ts":{"bytesInOutput":513},"src/providers/pinned-provider-dispatcher.ts":{"bytesInOutput":1669},"src/utils/pinned-fetch.ts":{"bytesInOutput":1027}},"bytes":40560}}}