@xenosystem/agent-sdk 0.10.35 → 0.10.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/agents/index.cjs +9 -9
- package/dist/agents/index.d.cts +4 -1
- package/dist/agents/index.d.ts +4 -1
- package/dist/agents/index.js +16 -16
- package/dist/agents/metafile-cjs.json +1 -1
- package/dist/agents/metafile-esm.json +1 -1
- package/dist/artifacts/index.cjs +1 -1
- package/dist/artifacts/index.js +1 -1
- package/dist/artifacts/metafile-cjs.json +1 -1
- package/dist/artifacts/metafile-esm.json +1 -1
- package/dist/automation/index.cjs +35 -24
- package/dist/automation/index.d.cts +194 -12
- package/dist/automation/index.d.ts +194 -12
- package/dist/automation/index.js +35 -24
- package/dist/automation/metafile-cjs.json +1 -1
- package/dist/automation/metafile-esm.json +1 -1
- package/dist/control-plane/index.cjs +8 -8
- package/dist/control-plane/index.js +8 -8
- package/dist/control-plane/metafile-cjs.json +1 -1
- package/dist/control-plane/metafile-esm.json +1 -1
- package/dist/coordination/index.cjs +2 -2
- package/dist/coordination/index.js +2 -2
- package/dist/coordination/metafile-cjs.json +1 -1
- package/dist/coordination/metafile-esm.json +1 -1
- package/dist/electron/index.cjs +243 -223
- package/dist/electron/index.d.cts +198 -1
- package/dist/electron/index.d.ts +198 -1
- package/dist/electron/index.js +243 -223
- package/dist/electron/metafile-cjs.json +1 -1
- package/dist/electron/metafile-esm.json +1 -1
- package/dist/hosted/metafile-cjs.json +1 -1
- package/dist/hosted/metafile-esm.json +1 -1
- package/dist/index.cjs +406 -395
- package/dist/index.d.cts +325 -172
- package/dist/index.d.ts +325 -172
- package/dist/index.js +406 -395
- package/dist/intelligence/index.cjs +4 -4
- package/dist/intelligence/index.js +4 -4
- package/dist/intelligence/metafile-cjs.json +1 -1
- package/dist/intelligence/metafile-esm.json +1 -1
- package/dist/mcp/index.cjs +20 -20
- package/dist/mcp/index.d.cts +146 -0
- package/dist/mcp/index.d.ts +146 -0
- package/dist/mcp/index.js +17 -17
- package/dist/mcp/metafile-cjs.json +1 -1
- package/dist/mcp/metafile-esm.json +1 -1
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/providers/index.cjs +10 -10
- package/dist/providers/index.d.cts +49 -5
- package/dist/providers/index.d.ts +49 -5
- package/dist/providers/index.js +10 -10
- package/dist/providers/metafile-cjs.json +1 -1
- package/dist/providers/metafile-esm.json +1 -1
- package/dist/recipes/metafile-cjs.json +1 -1
- package/dist/recipes/metafile-esm.json +1 -1
- package/dist/research/metafile-cjs.json +1 -1
- package/dist/research/metafile-esm.json +1 -1
- package/dist/session/index.cjs +24 -24
- package/dist/session/index.js +16 -16
- package/dist/session/metafile-cjs.json +1 -1
- package/dist/session/metafile-esm.json +1 -1
- package/dist/sharing/index.cjs +1 -1
- package/dist/sharing/index.js +3 -3
- package/dist/sharing/metafile-cjs.json +1 -1
- package/dist/sharing/metafile-esm.json +1 -1
- package/dist/skills/index.d.cts +6 -0
- package/dist/skills/index.d.ts +6 -0
- package/dist/utils/index.cjs +24 -24
- package/dist/utils/index.d.cts +14 -2
- package/dist/utils/index.d.ts +14 -2
- package/dist/utils/index.js +24 -24
- package/dist/utils/metafile-cjs.json +1 -1
- package/dist/utils/metafile-esm.json +1 -1
- package/ownership/evidence/PROPRIETARY-PTY-1/implementation-record.md +1 -1
- package/ownership/ownership-policy.json +14 -3
- package/package.json +1 -1
package/dist/sharing/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
"use strict";var oe=Object.create;var I=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var ce=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var ue=(e,t)=>{for(var r in t)I(e,r,{get:t[r],enumerable:!0})},$=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ae(t))!de.call(e,i)&&i!==r&&I(e,i,{get:()=>t[i],enumerable:!(n=se(t,i))||n.enumerable});return e};var le=(e,t,r)=>(r=e!=null?oe(ce(e)):{},$(t||!e||!e.__esModule?I(r,"default",{value:e,enumerable:!0}):r,e)),fe=e=>$(I({},"__esModule",{value:!0}),e);var Ue={};ue(Ue,{FileXenoShareRegistry:()=>V,XENO_HANDOFF_SCHEMA_VERSION:()=>v,XENO_SHARE_REGISTRY_SCHEMA_VERSION:()=>x,XENO_SHARE_SCHEMA_VERSION:()=>A,createXenoSecureShare:()=>ke,createXenoSessionHandoff:()=>ve,createXenoShareSigningIdentity:()=>Re,publicKeyFingerprint:()=>_,redactXenoShareValue:()=>T,signSharePayload:()=>J,verifyXenoSecureShare:()=>Ae,verifyXenoSessionHandoff:()=>Pe});module.exports=fe(Ue);var A=2,v=1,x=1;var ge=/(?:^|[_-])(api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token|auth(?:orization)?|bearer|secret|password|passwd|credential|cookie|private[_-]?key|client[_-]?secret)(?:$|[_-])/i,pe=/\b([A-Z][A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CLIENT_SECRET)[A-Z0-9_]*)\s*=\s*([^\s"']+)/g,he=/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,me=/\b(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g,ye=/-----BEGIN (?:RSA |EC |OPENSSH |)PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH |)PRIVATE KEY-----/g,Se=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,we=/([?&#](?:access_token|refresh_token|token|key|secret|password|api[_-]?key|signature)=)[^&#\s]+/gi;function T(e,t={}){let r={options:{...t,redactEmails:t.redactEmails??!0,maxDepth:t.maxDepth??48,maxStringLength:t.maxStringLength??2e5,maxEvents:t.maxEvents??256},seen:new Set,events:[],byCategory:{},total:0};return{value:P(e,"$","",0,r),report:{schemaVersion:1,total:r.total,byCategory:r.byCategory,events:r.events,eventsTruncated:r.total>r.events.length}}}function h(e,t,r){e.total+=1,e.byCategory[r]=(e.byCategory[r]??0)+1,e.events.length<e.options.maxEvents&&e.events.push({path:t,category:r})}function P(e,t,r,n,i){if(ge.test(r))return e!=null&&e!==""&&h(i,t,"secret-field"),e==null||e===""?null:"[redacted]";if(n>i.options.maxDepth)return h(i,t,"truncated"),"[redacted:depth-limit]";if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:String(e);if(typeof e=="bigint")return e.toString();if(typeof e=="string")return Ie(e,t,i);if(e instanceof Date)return e.toISOString();if(e instanceof Uint8Array)return h(i,t,"binary"),`[redacted:binary:${e.byteLength}-bytes]`;if(Array.isArray(e)){if(i.seen.has(e))return h(i,t,"cycle"),"[redacted:cycle]";i.seen.add(e);let o=e.map((s,a)=>P(s,`${t}[${a}]`,"",n+1,i));return i.seen.delete(e),o}if(e&&typeof e=="object"){if(i.seen.has(e))return h(i,t,"cycle"),"[redacted:cycle]";i.seen.add(e);let o={};for(let[s,a]of Object.entries(e))o[s]=P(a,`${t}.${Ee(s)}`,s,n+1,i);return i.seen.delete(e),o}return null}function Ie(e,t,r){let n=e;return n=p(n,ye,"[redacted:private-key]",t,"private-key",r),n=p(n,he,"$1[redacted]",t,"authorization",r),n=p(n,me,"[redacted:credential]",t,"credential-pattern",r),n=p(n,pe,"$1=[redacted]",t,"environment-secret",r),n=p(n,we,"$1[redacted]",t,"url-secret",r),r.options.redactEmails&&(n=p(n,Se,"[redacted:email]",t,"email",r)),n=F(n,r.options.workspaceRoot,"<workspace>",t,"workspace-path",r),n=F(n,r.options.homeDirectory,"<home>",t,"home-path",r),n.length>r.options.maxStringLength&&(h(r,t,"truncated"),n=`${n.slice(0,r.options.maxStringLength)}
|
|
2
|
-
[truncated]`),n}function p(e,t,r,n,i,o){t.lastIndex=0;let s=0,a=e.replace(t,(...d)=>(s+=1,r.includes("$1")?r.replace("$1",String(d[1]??"")):r));for(let d=0;d<s;d+=1)h(o,n,i);return t.lastIndex=0,a}function F(e,t,r,n,i,o){let s=t?.trim().replace(/[\\/]+$/,"");if(!s)return e;let a=new RegExp(xe(s).replace(/[\\/]+/g,"[\\\\/]"),process.platform==="win32"?"gi":"g");return p(e,a,r,n,i,o)}function xe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ee(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}var c=require("node:crypto");function S(e){return JSON.stringify(C(e,new Set))}function C(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let n=e.map(i=>C(i,t));return t.delete(e),n}let r={};for(let n of Object.keys(e).sort((i,o)=>i.localeCompare(o))){let i=e[n];if(i===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);r[n]=C(i,t)}return t.delete(e),r}function w(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 Xe=10080*60*1e3,be=365*24*60*60*1e3;function Re(){let{publicKey:e,privateKey:t}=(0,c.generateKeyPairSync)("ed25519"),r=e.export({type:"spki",format:"pem"}).toString(),n=t.export({type:"pkcs8",format:"pem"}).toString();return{keyId:_(r),publicKeyPem:r,privateKeyPem:n}}function _(e){let t=(0,c.createPublicKey)(e).export({type:"spki",format:"der"});return`ed25519:${(0,c.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}function ke(e){let t=e.now??new Date,r=t.toISOString(),n=M(t,e.expiresAt,e.ttlMs),i=(0,c.randomBytes)(32).toString("base64url"),o=T(e.content,e.redaction),s=e.visibility??"private";Le(s,e.workspaceId,e.teamId,e.allowedPrincipalIds);let a={schemaVersion:2,kind:"xeno-secure-share",shareId:u(e.shareId??`share_${(0,c.randomUUID)()}`,"shareId"),createdAt:r,expiresAt:n,issuer:j(e.issuer),session:q({...e.session,name:e.session.name??e.name}),access:{mode:"read-only",visibility:s,...e.workspaceId?{workspaceId:u(e.workspaceId,"workspaceId")}:{},...e.teamId?{teamId:u(e.teamId,"teamId")}:{},...e.allowedPrincipalIds?.length?{allowedPrincipalIds:X(e.allowedPrincipalIds,"allowedPrincipalIds")}:{},capabilityToken:{algorithm:"sha256",hash:Z(i)}},content:o.value,references:z(e.references??[]),redaction:o.report};return{envelope:J(a,e.signingIdentity),capabilityToken:i,url:Oe(e.baseUrl,a.shareId,i)}}function J(e,t){if(t.keyId!==_(t.publicKeyPem))throw new Error("Signing identity keyId does not match public key");let r=B(e,t);return{payload:e,signature:r}}function Ae(e,t={}){let r=[],n=!1,i=!1;if(e?.payload?.kind!=="xeno-secure-share"||e.payload.schemaVersion!==2)r.push("Unsupported secure-share envelope");else{let H=U(t.trustedPublicKeys,e.signature.keyId),D=H??(t.allowEmbeddedPublicKey===!1?void 0:e.signature.publicKeySpki);if(i=!!H,!D)r.push("No trusted or embedded issuer public key is available");else try{n=K(e.payload,e.signature,D),n||r.push("Share signature is invalid")}catch(k){r.push(k instanceof Error?k.message:String(k))}}let o=(t.now??new Date).getTime(),s=Date.parse(e?.payload?.expiresAt??""),d=t.revokedShareIds?.has(e?.payload?.shareId??"")??!1?"revoked":Number.isFinite(s)&&s<=o?"expired":"active";d==="revoked"&&r.push("Share has been revoked"),d==="expired"&&r.push("Share has expired");let y=Te(e?.payload,t.capabilityToken);y||r.push("Capability token is missing or invalid");let R=Ce(e?.payload,t.principal);return R||r.push("Principal is outside the share audience"),{valid:n&&y&&R&&d==="active",integrityValid:n,issuerTrusted:i,capabilityValid:y,audienceAllowed:R,status:d,errors:r}}function ve(e){let t=e.now??new Date,r={schemaVersion:1,kind:"xeno-session-handoff",handoffId:u(e.handoffId??`handoff_${(0,c.randomUUID)()}`,"handoffId"),createdAt:t.toISOString(),expiresAt:M(t,e.expiresAt,e.ttlMs??1440*60*1e3),issuer:j(e.issuer),source:q(e.source),target:_e(e.target),resume:Ne(e.resume),authority:Ve(e.authority),references:z(e.references??[]),...e.shareId?{shareId:u(e.shareId,"shareId")}:{}};return{payload:r,signature:B(r,e.signingIdentity)}}function Pe(e,t={}){let r=[];if(e?.payload?.kind!=="xeno-session-handoff"||e.payload.schemaVersion!==1)return{valid:!1,integrityValid:!1,issuerTrusted:!1,expired:!1,errors:["Unsupported handoff envelope"]};let n=U(t.trustedPublicKeys,e.signature.keyId),i=n??(t.allowEmbeddedPublicKey===!1?void 0:e.signature.publicKeySpki),o=!!n,s=!1;if(!i)r.push("No trusted or embedded issuer public key is available");else try{s=K(e.payload,e.signature,i),s||r.push("Handoff signature is invalid")}catch(d){r.push(d instanceof Error?d.message:String(d))}let a=Date.parse(e.payload.expiresAt)<=(t.now??new Date).getTime();return a&&r.push("Handoff has expired"),{valid:s&&!a,integrityValid:s,issuerTrusted:o,expired:a,errors:r}}function B(e,t){let r=S(e),n=(0,c.sign)(null,Buffer.from(r),(0,c.createPrivateKey)(t.privateKeyPem)).toString("base64");return{algorithm:"ed25519",keyId:t.keyId,value:n,publicKeySpki:t.publicKeyPem}}function K(e,t,r){if(t.algorithm!=="ed25519")return!1;let n=Buffer.from(t.value,"base64");if(n.toString("base64")!==t.value)throw new Error("Signature is not canonical base64");return(0,c.verify)(null,Buffer.from(S(e)),(0,c.createPublicKey)(r),n)}function Te(e,t){if(!e||!t)return!1;let r=Buffer.from(e.access.capabilityToken.hash,"hex"),n=Buffer.from(Z(t),"hex");return r.length===n.length&&(0,c.timingSafeEqual)(r,n)}function Ce(e,t){if(!e)return!1;let r=e.access;return r.allowedPrincipalIds?.length&&(!t?.id||!r.allowedPrincipalIds.includes(t.id))?!1:r.visibility==="workspace"?!!(t?.workspaceId&&t.workspaceId===r.workspaceId):r.visibility==="team"?!!(r.teamId&&t?.teamIds?.includes(r.teamId)):r.visibility==="private"?!!(t?.id&&t.id===e.issuer.id):r.visibility==="link"}function Oe(e,t,r){let n=new URL(e??"xeno://share/");if(n.username||n.password)throw new Error("Share base URL cannot contain credentials");if(n.protocol!=="https:"&&n.protocol!=="xeno:")throw new Error("Share base URL must use https: or xeno:");return n.pathname=`${n.pathname.replace(/\/$/,"")}/${encodeURIComponent(t)}`,n.search="",n.hash=new URLSearchParams({access_token:r}).toString(),n.toString()}function M(e,t,r=Xe){let n=t?new Date(t):new Date(e.getTime()+r);if(!Number.isFinite(n.getTime()))throw new Error("expiresAt must be a valid timestamp");let i=n.getTime()-e.getTime();if(i<=0)throw new Error("expiresAt must be in the future");if(i>be)throw new Error("Share and handoff expiry cannot exceed 365 days");return n.toISOString()}function j(e){return{id:u(e.id,"issuer.id"),...e.displayName?.trim()?{displayName:e.displayName.trim().slice(0,160)}:{},...e.workspaceId?{workspaceId:u(e.workspaceId,"issuer.workspaceId")}:{},...e.teamId?{teamId:u(e.teamId,"issuer.teamId")}:{}}}function q(e){let t={name:E(e.name,"session.name",200),surface:e.surface};for(let r of["sessionId","runId","hostedRunId","conversationId","parentSessionId","forkedFromSessionId","forkedAtEventId"])e[r]&&(t[r]=u(e[r],`session.${r}`));if(!t.sessionId&&!t.runId&&!t.hostedRunId&&!t.conversationId)throw new Error("Session identity requires sessionId, runId, hostedRunId, or conversationId");return e.git&&(t.git={...e.git.repositoryId?{repositoryId:u(e.git.repositoryId,"git.repositoryId")}:{},...e.git.remoteUrl?{remoteUrl:O(e.git.remoteUrl,"git.remoteUrl")}:{},...e.git.branch?{branch:E(e.git.branch,"git.branch",300)}:{},...e.git.commit?{commit:W(e.git.commit,"git.commit")}:{},...e.git.pullRequest?{pullRequest:{provider:e.git.pullRequest.provider,repository:E(e.git.pullRequest.repository,"git.pullRequest.repository",300),number:He(e.git.pullRequest.number,"git.pullRequest.number"),...e.git.pullRequest.url?{url:O(e.git.pullRequest.url,"git.pullRequest.url")}:{}}}:{}}),t}function z(e){let t=new Set;return e.map(r=>{let n=`${r.kind}:${r.id}`;if(t.has(n))throw new Error(`Duplicate share reference: ${n}`);return t.add(n),{kind:r.kind,id:u(r.id,"reference.id"),...r.title?.trim()?{title:r.title.trim().slice(0,300)}:{},...r.uri?{uri:O(r.uri,"reference.uri")}:{},...r.hash?{hash:W(r.hash,"reference.hash")}:{}}})}function _e(e){return{surface:e.surface,...e.workspaceId?{workspaceId:u(e.workspaceId,"target.workspaceId")}:{},...e.teamId?{teamId:u(e.teamId,"target.teamId")}:{},...e.environmentId?{environmentId:u(e.environmentId,"target.environmentId")}:{},...e.repositoryId?{repositoryId:u(e.repositoryId,"target.repositoryId")}:{}}}function Ne(e){let t={};for(let r of["sessionId","runId","hostedRunId","checkpointId","transcriptEventId"])e[r]&&(t[r]=u(e[r],`resume.${r}`));if(e.artifactIds?.length&&(t.artifactIds=X(e.artifactIds,"resume.artifactIds")),e.taskIds?.length&&(t.taskIds=X(e.taskIds,"resume.taskIds")),!Object.keys(t).length)throw new Error("Handoff resume point cannot be empty");return t}function Ve(e){return{filesystem:e.filesystem,network:e.network,externalActions:e.externalActions,secretRefs:X(e.secretRefs,"authority.secretRefs")}}function Le(e,t,r,n){if(e==="workspace"&&!t)throw new Error("workspace visibility requires workspaceId");if(e==="team"&&!r)throw new Error("team visibility requires teamId");if(e==="private"&&n?.length)throw new Error("private shares cannot add allowed principals; use link/workspace/team visibility")}function U(e,t){if(!e)return;let r=e;return typeof r.get=="function"?r.get(t):e[t]}function Z(e){return(0,c.createHash)("sha256").update(e).digest("hex")}function X(e,t){return[...new Set(e.map(r=>u(r,t)))].sort()}function u(e,t){let r=e.trim();if(!r||r.length>500||w(r))throw new Error(`${t} is invalid`);return r}function W(e,t){let r=e.trim();if(!/^[A-Za-z0-9:+._-]{7,256}$/.test(r))throw new Error(`${t} is invalid`);return r}function E(e,t,r){let n=e.trim();if(!n||n.length>r||w(n,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return n}function He(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function O(e,t){let r=E(e,t,2e3),n=new URL(r);if(n.username||n.password)throw new Error(`${t} cannot contain credentials`);if(!["https:","xeno:","artifact:","urn:"].includes(n.protocol))throw new Error(`${t} uses an unsupported scheme`);return n.toString()}var L=require("node:crypto"),l=require("node:fs/promises"),m=require("node:path");var f=le(require("node:fs/promises"),1);var De=new Set(["EACCES","EBUSY","EPERM"]),$e=[10,20,40,80,160,320,640];async function Y(e,t){for(let r=0;;r+=1)try{await f.rename(e,t);return}catch(n){let i=n.code,o=$e[r];if(process.platform!=="win32"||!i||!De.has(i)||o===void 0)throw n;await new Promise(s=>setTimeout(s,o))}}var g=require("node:fs"),N=require("node:os"),Q=require("node:path");function Fe(){return new Date().toISOString()}function Je(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function ee(e){try{return JSON.parse((0,g.readFileSync)(e,"utf8"))}catch{return null}}function Be(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Ke(e){return e.hostname!==(0,N.hostname)()?!0:Be(e.pid)}function G(e,t){(0,g.mkdirSync)((0,Q.dirname)(e),{recursive:!0}),(0,g.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
2
|
+
[truncated]`),n}function p(e,t,r,n,i,o){t.lastIndex=0;let s=0,a=e.replace(t,(...d)=>(s+=1,r.includes("$1")?r.replace("$1",String(d[1]??"")):r));for(let d=0;d<s;d+=1)h(o,n,i);return t.lastIndex=0,a}function F(e,t,r,n,i,o){let s=t?.trim().replace(/[\\/]+$/,"");if(!s)return e;let a=new RegExp(xe(s).replace(/[\\/]+/g,"[\\\\/]"),process.platform==="win32"?"gi":"g");return p(e,a,r,n,i,o)}function xe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ee(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}var c=require("node:crypto");function S(e){return JSON.stringify(C(e,new Set))}function C(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let n=e.map(i=>C(i,t));return t.delete(e),n}let r={};for(let n of Object.keys(e).sort((i,o)=>i.localeCompare(o))){let i=e[n];if(i===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);r[n]=C(i,t)}return t.delete(e),r}function w(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 Xe=10080*60*1e3,be=365*24*60*60*1e3;function Re(){let{publicKey:e,privateKey:t}=(0,c.generateKeyPairSync)("ed25519"),r=e.export({type:"spki",format:"pem"}).toString(),n=t.export({type:"pkcs8",format:"pem"}).toString();return{keyId:_(r),publicKeyPem:r,privateKeyPem:n}}function _(e){let t=(0,c.createPublicKey)(e).export({type:"spki",format:"der"});return`ed25519:${(0,c.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}function ke(e){let t=e.now??new Date,r=t.toISOString(),n=M(t,e.expiresAt,e.ttlMs),i=(0,c.randomBytes)(32).toString("base64url"),o=T(e.content,e.redaction),s=e.visibility??"private";Le(s,e.workspaceId,e.teamId,e.allowedPrincipalIds);let a={schemaVersion:2,kind:"xeno-secure-share",shareId:u(e.shareId??`share_${(0,c.randomUUID)()}`,"shareId"),createdAt:r,expiresAt:n,issuer:j(e.issuer),session:q({...e.session,name:e.session.name??e.name}),access:{mode:"read-only",visibility:s,...e.workspaceId?{workspaceId:u(e.workspaceId,"workspaceId")}:{},...e.teamId?{teamId:u(e.teamId,"teamId")}:{},...e.allowedPrincipalIds?.length?{allowedPrincipalIds:X(e.allowedPrincipalIds,"allowedPrincipalIds")}:{},capabilityToken:{algorithm:"sha256",hash:W(i)}},content:o.value,references:z(e.references??[]),redaction:o.report};return{envelope:J(a,e.signingIdentity),capabilityToken:i,url:Oe(e.baseUrl,a.shareId,i)}}function J(e,t){if(t.keyId!==_(t.publicKeyPem))throw new Error("Signing identity keyId does not match public key");let r=B(e,t);return{payload:e,signature:r}}function Ae(e,t={}){let r=[],n=!1,i=!1;if(e?.payload?.kind!=="xeno-secure-share"||e.payload.schemaVersion!==2)r.push("Unsupported secure-share envelope");else{let H=U(t.trustedPublicKeys,e.signature.keyId),D=H??(t.allowEmbeddedPublicKey===!1?void 0:e.signature.publicKeySpki);if(i=!!H,!D)r.push("No trusted or embedded issuer public key is available");else try{n=K(e.payload,e.signature,D),n||r.push("Share signature is invalid")}catch(k){r.push(k instanceof Error?k.message:String(k))}}let o=(t.now??new Date).getTime(),s=Date.parse(e?.payload?.expiresAt??""),d=t.revokedShareIds?.has(e?.payload?.shareId??"")??!1?"revoked":Number.isFinite(s)&&s<=o?"expired":"active";d==="revoked"&&r.push("Share has been revoked"),d==="expired"&&r.push("Share has expired");let y=Te(e?.payload,t.capabilityToken);y||r.push("Capability token is missing or invalid");let R=Ce(e?.payload,t.principal);return R||r.push("Principal is outside the share audience"),{valid:n&&y&&R&&d==="active",integrityValid:n,issuerTrusted:i,capabilityValid:y,audienceAllowed:R,status:d,errors:r}}function ve(e){let t=e.now??new Date,r={schemaVersion:1,kind:"xeno-session-handoff",handoffId:u(e.handoffId??`handoff_${(0,c.randomUUID)()}`,"handoffId"),createdAt:t.toISOString(),expiresAt:M(t,e.expiresAt,e.ttlMs??1440*60*1e3),issuer:j(e.issuer),source:q(e.source),target:_e(e.target),resume:Ne(e.resume),authority:Ve(e.authority),references:z(e.references??[]),...e.shareId?{shareId:u(e.shareId,"shareId")}:{}};return{payload:r,signature:B(r,e.signingIdentity)}}function Pe(e,t={}){let r=[];if(e?.payload?.kind!=="xeno-session-handoff"||e.payload.schemaVersion!==1)return{valid:!1,integrityValid:!1,issuerTrusted:!1,expired:!1,errors:["Unsupported handoff envelope"]};let n=U(t.trustedPublicKeys,e.signature.keyId),i=n??(t.allowEmbeddedPublicKey===!1?void 0:e.signature.publicKeySpki),o=!!n,s=!1;if(!i)r.push("No trusted or embedded issuer public key is available");else try{s=K(e.payload,e.signature,i),s||r.push("Handoff signature is invalid")}catch(d){r.push(d instanceof Error?d.message:String(d))}let a=Date.parse(e.payload.expiresAt)<=(t.now??new Date).getTime();return a&&r.push("Handoff has expired"),{valid:s&&!a,integrityValid:s,issuerTrusted:o,expired:a,errors:r}}function B(e,t){let r=S(e),n=(0,c.sign)(null,Buffer.from(r),(0,c.createPrivateKey)(t.privateKeyPem)).toString("base64");return{algorithm:"ed25519",keyId:t.keyId,value:n,publicKeySpki:t.publicKeyPem}}function K(e,t,r){if(t.algorithm!=="ed25519")return!1;let n=Buffer.from(t.value,"base64");if(n.toString("base64")!==t.value)throw new Error("Signature is not canonical base64");return(0,c.verify)(null,Buffer.from(S(e)),(0,c.createPublicKey)(r),n)}function Te(e,t){if(!e||!t)return!1;let r=Buffer.from(e.access.capabilityToken.hash,"hex"),n=Buffer.from(W(t),"hex");return r.length===n.length&&(0,c.timingSafeEqual)(r,n)}function Ce(e,t){if(!e)return!1;let r=e.access;return r.allowedPrincipalIds?.length&&(!t?.id||!r.allowedPrincipalIds.includes(t.id))?!1:r.visibility==="workspace"?!!(t?.workspaceId&&t.workspaceId===r.workspaceId):r.visibility==="team"?!!(r.teamId&&t?.teamIds?.includes(r.teamId)):r.visibility==="private"?!!(t?.id&&t.id===e.issuer.id):r.visibility==="link"}function Oe(e,t,r){let n=new URL(e??"xeno://share/");if(n.username||n.password)throw new Error("Share base URL cannot contain credentials");if(n.protocol!=="https:"&&n.protocol!=="xeno:")throw new Error("Share base URL must use https: or xeno:");return n.pathname=`${n.pathname.replace(/\/$/,"")}/${encodeURIComponent(t)}`,n.search="",n.hash=new URLSearchParams({access_token:r}).toString(),n.toString()}function M(e,t,r=Xe){let n=t?new Date(t):new Date(e.getTime()+r);if(!Number.isFinite(n.getTime()))throw new Error("expiresAt must be a valid timestamp");let i=n.getTime()-e.getTime();if(i<=0)throw new Error("expiresAt must be in the future");if(i>be)throw new Error("Share and handoff expiry cannot exceed 365 days");return n.toISOString()}function j(e){return{id:u(e.id,"issuer.id"),...e.displayName?.trim()?{displayName:e.displayName.trim().slice(0,160)}:{},...e.workspaceId?{workspaceId:u(e.workspaceId,"issuer.workspaceId")}:{},...e.teamId?{teamId:u(e.teamId,"issuer.teamId")}:{}}}function q(e){let t={name:E(e.name,"session.name",200),surface:e.surface};for(let r of["sessionId","runId","hostedRunId","conversationId","parentSessionId","forkedFromSessionId","forkedAtEventId"])e[r]&&(t[r]=u(e[r],`session.${r}`));if(!t.sessionId&&!t.runId&&!t.hostedRunId&&!t.conversationId)throw new Error("Session identity requires sessionId, runId, hostedRunId, or conversationId");return e.git&&(t.git={...e.git.repositoryId?{repositoryId:u(e.git.repositoryId,"git.repositoryId")}:{},...e.git.remoteUrl?{remoteUrl:O(e.git.remoteUrl,"git.remoteUrl")}:{},...e.git.branch?{branch:E(e.git.branch,"git.branch",300)}:{},...e.git.commit?{commit:Z(e.git.commit,"git.commit")}:{},...e.git.pullRequest?{pullRequest:{provider:e.git.pullRequest.provider,repository:E(e.git.pullRequest.repository,"git.pullRequest.repository",300),number:He(e.git.pullRequest.number,"git.pullRequest.number"),...e.git.pullRequest.url?{url:O(e.git.pullRequest.url,"git.pullRequest.url")}:{}}}:{}}),t}function z(e){let t=new Set;return e.map(r=>{let n=`${r.kind}:${r.id}`;if(t.has(n))throw new Error(`Duplicate share reference: ${n}`);return t.add(n),{kind:r.kind,id:u(r.id,"reference.id"),...r.title?.trim()?{title:r.title.trim().slice(0,300)}:{},...r.uri?{uri:O(r.uri,"reference.uri")}:{},...r.hash?{hash:Z(r.hash,"reference.hash")}:{}}})}function _e(e){return{surface:e.surface,...e.workspaceId?{workspaceId:u(e.workspaceId,"target.workspaceId")}:{},...e.teamId?{teamId:u(e.teamId,"target.teamId")}:{},...e.environmentId?{environmentId:u(e.environmentId,"target.environmentId")}:{},...e.repositoryId?{repositoryId:u(e.repositoryId,"target.repositoryId")}:{}}}function Ne(e){let t={};for(let r of["sessionId","runId","hostedRunId","checkpointId","transcriptEventId"])e[r]&&(t[r]=u(e[r],`resume.${r}`));if(e.artifactIds?.length&&(t.artifactIds=X(e.artifactIds,"resume.artifactIds")),e.taskIds?.length&&(t.taskIds=X(e.taskIds,"resume.taskIds")),!Object.keys(t).length)throw new Error("Handoff resume point cannot be empty");return t}function Ve(e){return{filesystem:e.filesystem,network:e.network,externalActions:e.externalActions,secretRefs:X(e.secretRefs,"authority.secretRefs")}}function Le(e,t,r,n){if(e==="workspace"&&!t)throw new Error("workspace visibility requires workspaceId");if(e==="team"&&!r)throw new Error("team visibility requires teamId");if(e==="private"&&n?.length)throw new Error("private shares cannot add allowed principals; use link/workspace/team visibility")}function U(e,t){if(!e)return;let r=e;return typeof r.get=="function"?r.get(t):e[t]}function W(e){return(0,c.createHash)("sha256").update(e).digest("hex")}function X(e,t){return[...new Set(e.map(r=>u(r,t)))].sort()}function u(e,t){let r=e.trim();if(!r||r.length>500||w(r))throw new Error(`${t} is invalid`);return r}function Z(e,t){let r=e.trim();if(!/^[A-Za-z0-9:+._-]{7,256}$/.test(r))throw new Error(`${t} is invalid`);return r}function E(e,t,r){let n=e.trim();if(!n||n.length>r||w(n,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return n}function He(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function O(e,t){let r=E(e,t,2e3),n=new URL(r);if(n.username||n.password)throw new Error(`${t} cannot contain credentials`);if(!["https:","xeno:","artifact:","urn:"].includes(n.protocol))throw new Error(`${t} uses an unsupported scheme`);return n.toString()}var L=require("node:crypto"),l=require("node:fs/promises"),m=require("node:path");var f=le(require("node:fs/promises"),1);var De=new Set(["EACCES","EBUSY","EPERM"]),$e=[10,20,40,80,160,320,640];async function Y(e,t){for(let r=0;;r+=1)try{await f.rename(e,t);return}catch(n){let i=n.code,o=$e[r];if(process.platform!=="win32"||!i||!De.has(i)||o===void 0)throw n;await new Promise(s=>setTimeout(s,o))}}var g=require("node:fs"),N=require("node:os"),Q=require("node:path");function Fe(){return new Date().toISOString()}function Je(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function ee(e){try{return JSON.parse((0,g.readFileSync)(e,"utf8"))}catch{return null}}function Be(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Ke(e){return e.hostname!==(0,N.hostname)()?!0:Be(e.pid)}function G(e,t){(0,g.mkdirSync)((0,Q.dirname)(e),{recursive:!0}),(0,g.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
3
3
|
`,{encoding:"utf8",flag:"wx"})}function Me(e,t){let r=ee(e);r?.pid!==t.pid||r.hostname!==t.hostname||(0,g.rmSync)(e,{force:!0})}function te(e,t,r){let n=Fe(),i={schemaVersion:1,name:t,pid:process.pid,hostname:(0,N.hostname)(),processStartedAt:Je(),version:r,acquiredAt:n,updatedAt:n};try{G(e,i)}catch(o){if(o.code!=="EEXIST")throw o;let a=ee(e);if(a&&Ke(a))throw new Error(`${t} is already locked by PID ${a.pid} on ${a.hostname}.`);(0,g.rmSync)(e,{force:!0}),G(e,i)}return{record:i,release:()=>{Me(e,i)}}}var V=class{directory;snapshotPath;lockPath;now;constructor(t){this.directory=(0,m.resolve)(t.directory),this.snapshotPath=(0,m.join)(this.directory,"registry.json"),this.lockPath=(0,m.join)(this.directory,"registry.lock"),this.now=t.now??(()=>new Date)}async register(t,r="created"){return this.mutate(n=>{let i=n.records.find(s=>s.shareId===t.payload.shareId);if(i){if(b(i.envelope)!==b(t))throw new Error(`Share ${t.payload.shareId} already exists with different content`);return{snapshot:n,result:i}}let o={shareId:t.payload.shareId,envelope:t,status:Date.parse(t.payload.expiresAt)<=this.now().getTime()?"expired":"active",registeredAt:this.now().toISOString(),origin:r};return{snapshot:re(n,[...n.records,o],this.now()),result:o}})}async revoke(t,r,n){return this.mutate(i=>{let o=i.records.findIndex(y=>y.shareId===t);if(o<0)throw new Error(`Share not found: ${t}`);let s=i.records[o];if(s.status==="revoked")return{snapshot:i,result:s};let a={...s,status:"revoked",revokedAt:this.now().toISOString(),revokedBy:ne(r,"actor"),revocationReason:ne(n,"reason")},d=[...i.records];return d[o]=a,{snapshot:re(i,d,this.now()),result:a}})}async get(t){return(await this.load()).records.find(r=>r.shareId===t)??null}async list(){let t=this.now().getTime();return(await this.load()).records.map(r=>r.status==="active"&&Date.parse(r.envelope.payload.expiresAt)<=t?{...r,status:"expired"}:r).sort((r,n)=>n.registeredAt.localeCompare(r.registeredAt))}async revokedIds(){return new Set((await this.list()).filter(t=>t.status==="revoked").map(t=>t.shareId))}async load(){try{let t=await(0,l.readFile)(this.snapshotPath,"utf8"),r=JSON.parse(t);return qe(r),r}catch(t){if(t.code==="ENOENT")return je(this.now());throw t}}async mutate(t){await(0,l.mkdir)(this.directory,{recursive:!0,mode:448});let r=te(this.lockPath,"xeno secure-share registry","1");try{let n=await this.load(),{snapshot:i,result:o}=t(n);return i!==n&&await ze(this.snapshotPath,`${JSON.stringify(i,null,2)}
|
|
4
4
|
`),o}finally{r.release()}}};function je(e){return ie({schemaVersion:1,generation:0,updatedAt:e.toISOString(),records:[]})}function re(e,t,r){return ie({schemaVersion:1,generation:e.generation+1,updatedAt:r.toISOString(),records:[...t].sort((n,i)=>n.shareId.localeCompare(i.shareId))})}function ie(e){return{...e,checksum:{algorithm:"sha256",value:(0,L.createHash)("sha256").update(b(e)).digest("hex")}}}function qe(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new Error("Invalid secure-share registry snapshot");let{checksum:t,...r}=e,n=(0,L.createHash)("sha256").update(b(r)).digest("hex");if(t?.algorithm!=="sha256"||t.value!==n)throw new Error("Secure-share registry checksum mismatch");let i=new Set;for(let o of e.records){if(o.shareId!==o.envelope?.payload?.shareId)throw new Error("Secure-share registry identity mismatch");if(i.has(o.shareId))throw new Error(`Duplicate secure-share registry record: ${o.shareId}`);i.add(o.shareId)}}async function ze(e,t){await(0,l.mkdir)((0,m.dirname)(e),{recursive:!0,mode:448});let r=`${e}.${process.pid}.${Date.now()}.tmp`,n;try{n=await(0,l.open)(r,"wx",384),await n.writeFile(t,"utf8"),await n.sync(),await n.close(),n=void 0,await Y(r,e),await(0,l.chmod)(e,384).catch(()=>{})}finally{n&&await n.close().catch(()=>{}),await(0,l.unlink)(r).catch(()=>{})}}function b(e){return S(e)}function ne(e,t){let r=e.trim();if(!r||r.length>500||w(r))throw new Error(`${t} is invalid`);return r}0&&(module.exports={FileXenoShareRegistry,XENO_HANDOFF_SCHEMA_VERSION,XENO_SHARE_REGISTRY_SCHEMA_VERSION,XENO_SHARE_SCHEMA_VERSION,createXenoSecureShare,createXenoSessionHandoff,createXenoShareSigningIdentity,publicKeyFingerprint,redactXenoShareValue,signSharePayload,verifyXenoSecureShare,verifyXenoSessionHandoff});
|
package/dist/sharing/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
var E=2,X=1,m=1;var ne=/(?:^|[_-])(api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token|auth(?:orization)?|bearer|secret|password|passwd|credential|cookie|private[_-]?key|client[_-]?secret)(?:$|[_-])/i,ie=/\b([A-Z][A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CLIENT_SECRET)[A-Z0-9_]*)\s*=\s*([^\s"']+)/g,oe=/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,se=/\b(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g,ae=/-----BEGIN (?:RSA |EC |OPENSSH |)PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH |)PRIVATE KEY-----/g,ce=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,de=/([?&#](?:access_token|refresh_token|token|key|secret|password|api[_-]?key|signature)=)[^&#\s]+/gi;function T(e,t={}){let r={options:{...t,redactEmails:t.redactEmails??!0,maxDepth:t.maxDepth??48,maxStringLength:t.maxStringLength??2e5,maxEvents:t.maxEvents??256},seen:new Set,events:[],byCategory:{},total:0};return{value:b(e,"$","",0,r),report:{schemaVersion:1,total:r.total,byCategory:r.byCategory,events:r.events,eventsTruncated:r.total>r.events.length}}}function f(e,t,r){e.total+=1,e.byCategory[r]=(e.byCategory[r]??0)+1,e.events.length<e.options.maxEvents&&e.events.push({path:t,category:r})}function b(e,t,r,n,i){if(ne.test(r))return e!=null&&e!==""&&f(i,t,"secret-field"),e==null||e===""?null:"[redacted]";if(n>i.options.maxDepth)return f(i,t,"truncated"),"[redacted:depth-limit]";if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:String(e);if(typeof e=="bigint")return e.toString();if(typeof e=="string")return ue(e,t,i);if(e instanceof Date)return e.toISOString();if(e instanceof Uint8Array)return f(i,t,"binary"),`[redacted:binary:${e.byteLength}-bytes]`;if(Array.isArray(e)){if(i.seen.has(e))return f(i,t,"cycle"),"[redacted:cycle]";i.seen.add(e);let o=e.map((s,a)=>b(s,`${t}[${a}]`,"",n+1,i));return i.seen.delete(e),o}if(e&&typeof e=="object"){if(i.seen.has(e))return f(i,t,"cycle"),"[redacted:cycle]";i.seen.add(e);let o={};for(let[s,a]of Object.entries(e))o[s]=b(a,`${t}.${fe(s)}`,s,n+1,i);return i.seen.delete(e),o}return null}function ue(e,t,r){let n=e;return n=l(n,ae,"[redacted:private-key]",t,"private-key",r),n=l(n,oe,"$1[redacted]",t,"authorization",r),n=l(n,se,"[redacted:credential]",t,"credential-pattern",r),n=l(n,ie,"$1=[redacted]",t,"environment-secret",r),n=l(n,de,"$1[redacted]",t,"url-secret",r),r.options.redactEmails&&(n=l(n,ce,"[redacted:email]",t,"email",r)),n=P(n,r.options.workspaceRoot,"<workspace>",t,"workspace-path",r),n=P(n,r.options.homeDirectory,"<home>",t,"home-path",r),n.length>r.options.maxStringLength&&(f(r,t,"truncated"),n=`${n.slice(0,r.options.maxStringLength)}
|
|
2
|
-
[truncated]`),n}function l(e,t,r,n,i,o){t.lastIndex=0;let s=0,a=e.replace(t,(...c)=>(s+=1,r.includes("$1")?r.replace("$1",String(c[1]??"")):r));for(let c=0;c<s;c+=1)f(o,n,i);return t.lastIndex=0,a}function P(e,t,r,n,i,o){let s=t?.trim().replace(/[\\/]+$/,"");if(!s)return e;let a=new RegExp(le(s).replace(/[\\/]+/g,"[\\\\/]"),process.platform==="win32"?"gi":"g");return l(e,a,r,n,i,o)}function le(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fe(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}import{createHash as C,createPrivateKey as ge,createPublicKey as O,generateKeyPairSync as pe,randomBytes as he,randomUUID as _,sign as me,timingSafeEqual as ye,verify as Se}from"node:crypto";function p(e){return JSON.stringify(R(e,new Set))}function R(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let n=e.map(i=>R(i,t));return t.delete(e),n}let r={};for(let n of Object.keys(e).sort((i,o)=>i.localeCompare(o))){let i=e[n];if(i===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);r[n]=R(i,t)}return t.delete(e),r}function h(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 we=10080*60*1e3,Ie=365*24*60*60*1e3;function ot(){let{publicKey:e,privateKey:t}=pe("ed25519"),r=e.export({type:"spki",format:"pem"}).toString(),n=t.export({type:"pkcs8",format:"pem"}).toString();return{keyId:N(r),publicKeyPem:r,privateKeyPem:n}}function N(e){let t=O(e).export({type:"spki",format:"der"});return`ed25519:${C("sha256").update(t).digest("hex").slice(0,32)}`}function st(e){let t=e.now??new Date,r=t.toISOString(),n=H(t,e.expiresAt,e.ttlMs),i=he(32).toString("base64url"),o=T(e.content,e.redaction),s=e.visibility??"private";ve(s,e.workspaceId,e.teamId,e.allowedPrincipalIds);let a={schemaVersion:2,kind:"xeno-secure-share",shareId:d(e.shareId??`share_${_()}`,"shareId"),createdAt:r,expiresAt:n,issuer:D(e.issuer),session:$({...e.session,name:e.session.name??e.name}),access:{mode:"read-only",visibility:s,...e.workspaceId?{workspaceId:d(e.workspaceId,"workspaceId")}:{},...e.teamId?{teamId:d(e.teamId,"teamId")}:{},...e.allowedPrincipalIds?.length?{allowedPrincipalIds:S(e.allowedPrincipalIds,"allowedPrincipalIds")}:{},capabilityToken:{algorithm:"sha256",hash:B(i)}},content:o.value,references:F(e.references??[]),redaction:o.report};return{envelope:xe(a,e.signingIdentity),capabilityToken:i,url:be(e.baseUrl,a.shareId,i)}}function xe(e,t){if(t.keyId!==N(t.publicKeyPem))throw new Error("Signing identity keyId does not match public key");let r=V(e,t);return{payload:e,signature:r}}function at(e,t={}){let r=[],n=!1,i=!1;if(e?.payload?.kind!=="xeno-secure-share"||e.payload.schemaVersion!==2)r.push("Unsupported secure-share envelope");else{let A=J(t.trustedPublicKeys,e.signature.keyId),v=A??(t.allowEmbeddedPublicKey===!1?void 0:e.signature.publicKeySpki);if(i=!!A,!v)r.push("No trusted or embedded issuer public key is available");else try{n=L(e.payload,e.signature,v),n||r.push("Share signature is invalid")}catch(x){r.push(x instanceof Error?x.message:String(x))}}let o=(t.now??new Date).getTime(),s=Date.parse(e?.payload?.expiresAt??""),c=t.revokedShareIds?.has(e?.payload?.shareId??"")??!1?"revoked":Number.isFinite(s)&&s<=o?"expired":"active";c==="revoked"&&r.push("Share has been revoked"),c==="expired"&&r.push("Share has expired");let g=Ee(e?.payload,t.capabilityToken);g||r.push("Capability token is missing or invalid");let I=Xe(e?.payload,t.principal);return I||r.push("Principal is outside the share audience"),{valid:n&&g&&I&&c==="active",integrityValid:n,issuerTrusted:i,capabilityValid:g,audienceAllowed:I,status:c,errors:r}}function ct(e){let t=e.now??new Date,r={schemaVersion:1,kind:"xeno-session-handoff",handoffId:d(e.handoffId??`handoff_${_()}`,"handoffId"),createdAt:t.toISOString(),expiresAt:H(t,e.expiresAt,e.ttlMs??1440*60*1e3),issuer:D(e.issuer),source:$(e.source),target:Re(e.target),resume:ke(e.resume),authority:Ae(e.authority),references:F(e.references??[]),...e.shareId?{shareId:d(e.shareId,"shareId")}:{}};return{payload:r,signature:V(r,e.signingIdentity)}}function dt(e,t={}){let r=[];if(e?.payload?.kind!=="xeno-session-handoff"||e.payload.schemaVersion!==1)return{valid:!1,integrityValid:!1,issuerTrusted:!1,expired:!1,errors:["Unsupported handoff envelope"]};let n=J(t.trustedPublicKeys,e.signature.keyId),i=n??(t.allowEmbeddedPublicKey===!1?void 0:e.signature.publicKeySpki),o=!!n,s=!1;if(!i)r.push("No trusted or embedded issuer public key is available");else try{s=L(e.payload,e.signature,i),s||r.push("Handoff signature is invalid")}catch(c){r.push(c instanceof Error?c.message:String(c))}let a=Date.parse(e.payload.expiresAt)<=(t.now??new Date).getTime();return a&&r.push("Handoff has expired"),{valid:s&&!a,integrityValid:s,issuerTrusted:o,expired:a,errors:r}}function V(e,t){let r=p(e),n=me(null,Buffer.from(r),ge(t.privateKeyPem)).toString("base64");return{algorithm:"ed25519",keyId:t.keyId,value:n,publicKeySpki:t.publicKeyPem}}function L(e,t,r){if(t.algorithm!=="ed25519")return!1;let n=Buffer.from(t.value,"base64");if(n.toString("base64")!==t.value)throw new Error("Signature is not canonical base64");return Se(null,Buffer.from(p(e)),O(r),n)}function Ee(e,t){if(!e||!t)return!1;let r=Buffer.from(e.access.capabilityToken.hash,"hex"),n=Buffer.from(B(t),"hex");return r.length===n.length&&ye(r,n)}function Xe(e,t){if(!e)return!1;let r=e.access;return r.allowedPrincipalIds?.length&&(!t?.id||!r.allowedPrincipalIds.includes(t.id))?!1:r.visibility==="workspace"?!!(t?.workspaceId&&t.workspaceId===r.workspaceId):r.visibility==="team"?!!(r.teamId&&t?.teamIds?.includes(r.teamId)):r.visibility==="private"?!!(t?.id&&t.id===e.issuer.id):r.visibility==="link"}function be(e,t,r){let n=new URL(e??"xeno://share/");if(n.username||n.password)throw new Error("Share base URL cannot contain credentials");if(n.protocol!=="https:"&&n.protocol!=="xeno:")throw new Error("Share base URL must use https: or xeno:");return n.pathname=`${n.pathname.replace(/\/$/,"")}/${encodeURIComponent(t)}`,n.search="",n.hash=new URLSearchParams({access_token:r}).toString(),n.toString()}function H(e,t,r=we){let n=t?new Date(t):new Date(e.getTime()+r);if(!Number.isFinite(n.getTime()))throw new Error("expiresAt must be a valid timestamp");let i=n.getTime()-e.getTime();if(i<=0)throw new Error("expiresAt must be in the future");if(i>Ie)throw new Error("Share and handoff expiry cannot exceed 365 days");return n.toISOString()}function D(e){return{id:d(e.id,"issuer.id"),...e.displayName?.trim()?{displayName:e.displayName.trim().slice(0,160)}:{},...e.workspaceId?{workspaceId:d(e.workspaceId,"issuer.workspaceId")}:{},...e.teamId?{teamId:d(e.teamId,"issuer.teamId")}:{}}}function $(e){let t={name:y(e.name,"session.name",200),surface:e.surface};for(let r of["sessionId","runId","hostedRunId","conversationId","parentSessionId","forkedFromSessionId","forkedAtEventId"])e[r]&&(t[r]=d(e[r],`session.${r}`));if(!t.sessionId&&!t.runId&&!t.hostedRunId&&!t.conversationId)throw new Error("Session identity requires sessionId, runId, hostedRunId, or conversationId");return e.git&&(t.git={...e.git.repositoryId?{repositoryId:d(e.git.repositoryId,"git.repositoryId")}:{},...e.git.remoteUrl?{remoteUrl:k(e.git.remoteUrl,"git.remoteUrl")}:{},...e.git.branch?{branch:y(e.git.branch,"git.branch",300)}:{},...e.git.commit?{commit:K(e.git.commit,"git.commit")}:{},...e.git.pullRequest?{pullRequest:{provider:e.git.pullRequest.provider,repository:y(e.git.pullRequest.repository,"git.pullRequest.repository",300),number:Pe(e.git.pullRequest.number,"git.pullRequest.number"),...e.git.pullRequest.url?{url:k(e.git.pullRequest.url,"git.pullRequest.url")}:{}}}:{}}),t}function F(e){let t=new Set;return e.map(r=>{let n=`${r.kind}:${r.id}`;if(t.has(n))throw new Error(`Duplicate share reference: ${n}`);return t.add(n),{kind:r.kind,id:d(r.id,"reference.id"),...r.title?.trim()?{title:r.title.trim().slice(0,300)}:{},...r.uri?{uri:k(r.uri,"reference.uri")}:{},...r.hash?{hash:K(r.hash,"reference.hash")}:{}}})}function Re(e){return{surface:e.surface,...e.workspaceId?{workspaceId:d(e.workspaceId,"target.workspaceId")}:{},...e.teamId?{teamId:d(e.teamId,"target.teamId")}:{},...e.environmentId?{environmentId:d(e.environmentId,"target.environmentId")}:{},...e.repositoryId?{repositoryId:d(e.repositoryId,"target.repositoryId")}:{}}}function ke(e){let t={};for(let r of["sessionId","runId","hostedRunId","checkpointId","transcriptEventId"])e[r]&&(t[r]=d(e[r],`resume.${r}`));if(e.artifactIds?.length&&(t.artifactIds=S(e.artifactIds,"resume.artifactIds")),e.taskIds?.length&&(t.taskIds=S(e.taskIds,"resume.taskIds")),!Object.keys(t).length)throw new Error("Handoff resume point cannot be empty");return t}function Ae(e){return{filesystem:e.filesystem,network:e.network,externalActions:e.externalActions,secretRefs:S(e.secretRefs,"authority.secretRefs")}}function ve(e,t,r,n){if(e==="workspace"&&!t)throw new Error("workspace visibility requires workspaceId");if(e==="team"&&!r)throw new Error("team visibility requires teamId");if(e==="private"&&n?.length)throw new Error("private shares cannot add allowed principals; use link/workspace/team visibility")}function J(e,t){if(!e)return;let r=e;return typeof r.get=="function"?r.get(t):e[t]}function B(e){return C("sha256").update(e).digest("hex")}function S(e,t){return[...new Set(e.map(r=>d(r,t)))].sort()}function d(e,t){let r=e.trim();if(!r||r.length>500||h(r))throw new Error(`${t} is invalid`);return r}function K(e,t){let r=e.trim();if(!/^[A-Za-z0-9:+._-]{7,256}$/.test(r))throw new Error(`${t} is invalid`);return r}function y(e,t,r){let n=e.trim();if(!n||n.length>r||h(n,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return n}function Pe(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function k(e,t){let r=y(e,t,2e3),n=new URL(r);if(n.username||n.password)throw new Error(`${t} cannot contain credentials`);if(!["https:","xeno:","artifact:","urn:"].includes(n.protocol))throw new Error(`${t} uses an unsupported scheme`);return n.toString()}import{createHash as ee}from"node:crypto";import{chmod as Je,mkdir as te,open as Be,readFile as Ke,unlink as Me}from"node:fs/promises";import{dirname as je,join as W,resolve as qe}from"node:path";import*as u from"node:fs/promises";var Te=new Set(["EACCES","EBUSY","EPERM"]),Ce=[10,20,40,80,160,320,640];async function M(e,t){for(let r=0;;r+=1)try{await u.rename(e,t);return}catch(n){let i=n.code,o=Ce[r];if(process.platform!=="win32"||!i||!Te.has(i)||o===void 0)throw n;await new Promise(s=>setTimeout(s,o))}}import{mkdirSync as Oe,readFileSync as _e,rmSync as q,writeFileSync as Ne}from"node:fs";import{hostname as z}from"node:os";import{dirname as Ve}from"node:path";function Le(){return new Date().toISOString()}function He(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function U(e){try{return JSON.parse(_e(e,"utf8"))}catch{return null}}function De(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function $e(e){return e.hostname!==z()?!0:De(e.pid)}function j(e,t){Oe(Ve(e),{recursive:!0}),Ne(e,JSON.stringify(t,null,2)+`
|
|
3
|
-
`,{encoding:"utf8",flag:"wx"})}function Fe(e,t){let r=U(e);r?.pid!==t.pid||r.hostname!==t.hostname||q(e,{force:!0})}function
|
|
4
|
-
`),o}finally{r.release()}}};function ze(e){return re({schemaVersion:1,generation:0,updatedAt:e.toISOString(),records:[]})}function G(e,t,r){return re({schemaVersion:1,generation:e.generation+1,updatedAt:r.toISOString(),records:[...t].sort((n,i)=>n.shareId.localeCompare(i.shareId))})}function re(e){return{...e,checksum:{algorithm:"sha256",value:ee("sha256").update(w(e)).digest("hex")}}}function Ue(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new Error("Invalid secure-share registry snapshot");let{checksum:t,...r}=e,n=ee("sha256").update(w(r)).digest("hex");if(t?.algorithm!=="sha256"||t.value!==n)throw new Error("Secure-share registry checksum mismatch");let i=new Set;for(let o of e.records){if(o.shareId!==o.envelope?.payload?.shareId)throw new Error("Secure-share registry identity mismatch");if(i.has(o.shareId))throw new Error(`Duplicate secure-share registry record: ${o.shareId}`);i.add(o.shareId)}}async function
|
|
2
|
+
[truncated]`),n}function l(e,t,r,n,i,o){t.lastIndex=0;let s=0,a=e.replace(t,(...c)=>(s+=1,r.includes("$1")?r.replace("$1",String(c[1]??"")):r));for(let c=0;c<s;c+=1)f(o,n,i);return t.lastIndex=0,a}function P(e,t,r,n,i,o){let s=t?.trim().replace(/[\\/]+$/,"");if(!s)return e;let a=new RegExp(le(s).replace(/[\\/]+/g,"[\\\\/]"),process.platform==="win32"?"gi":"g");return l(e,a,r,n,i,o)}function le(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fe(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}import{createHash as C,createPrivateKey as ge,createPublicKey as O,generateKeyPairSync as pe,randomBytes as he,randomUUID as _,sign as me,timingSafeEqual as ye,verify as Se}from"node:crypto";function p(e){return JSON.stringify(R(e,new Set))}function R(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let n=e.map(i=>R(i,t));return t.delete(e),n}let r={};for(let n of Object.keys(e).sort((i,o)=>i.localeCompare(o))){let i=e[n];if(i===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);r[n]=R(i,t)}return t.delete(e),r}function h(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 we=10080*60*1e3,Ie=365*24*60*60*1e3;function ot(){let{publicKey:e,privateKey:t}=pe("ed25519"),r=e.export({type:"spki",format:"pem"}).toString(),n=t.export({type:"pkcs8",format:"pem"}).toString();return{keyId:N(r),publicKeyPem:r,privateKeyPem:n}}function N(e){let t=O(e).export({type:"spki",format:"der"});return`ed25519:${C("sha256").update(t).digest("hex").slice(0,32)}`}function st(e){let t=e.now??new Date,r=t.toISOString(),n=H(t,e.expiresAt,e.ttlMs),i=he(32).toString("base64url"),o=T(e.content,e.redaction),s=e.visibility??"private";ve(s,e.workspaceId,e.teamId,e.allowedPrincipalIds);let a={schemaVersion:2,kind:"xeno-secure-share",shareId:d(e.shareId??`share_${_()}`,"shareId"),createdAt:r,expiresAt:n,issuer:D(e.issuer),session:$({...e.session,name:e.session.name??e.name}),access:{mode:"read-only",visibility:s,...e.workspaceId?{workspaceId:d(e.workspaceId,"workspaceId")}:{},...e.teamId?{teamId:d(e.teamId,"teamId")}:{},...e.allowedPrincipalIds?.length?{allowedPrincipalIds:S(e.allowedPrincipalIds,"allowedPrincipalIds")}:{},capabilityToken:{algorithm:"sha256",hash:B(i)}},content:o.value,references:F(e.references??[]),redaction:o.report};return{envelope:xe(a,e.signingIdentity),capabilityToken:i,url:be(e.baseUrl,a.shareId,i)}}function xe(e,t){if(t.keyId!==N(t.publicKeyPem))throw new Error("Signing identity keyId does not match public key");let r=V(e,t);return{payload:e,signature:r}}function at(e,t={}){let r=[],n=!1,i=!1;if(e?.payload?.kind!=="xeno-secure-share"||e.payload.schemaVersion!==2)r.push("Unsupported secure-share envelope");else{let A=J(t.trustedPublicKeys,e.signature.keyId),v=A??(t.allowEmbeddedPublicKey===!1?void 0:e.signature.publicKeySpki);if(i=!!A,!v)r.push("No trusted or embedded issuer public key is available");else try{n=L(e.payload,e.signature,v),n||r.push("Share signature is invalid")}catch(x){r.push(x instanceof Error?x.message:String(x))}}let o=(t.now??new Date).getTime(),s=Date.parse(e?.payload?.expiresAt??""),c=t.revokedShareIds?.has(e?.payload?.shareId??"")??!1?"revoked":Number.isFinite(s)&&s<=o?"expired":"active";c==="revoked"&&r.push("Share has been revoked"),c==="expired"&&r.push("Share has expired");let g=Ee(e?.payload,t.capabilityToken);g||r.push("Capability token is missing or invalid");let I=Xe(e?.payload,t.principal);return I||r.push("Principal is outside the share audience"),{valid:n&&g&&I&&c==="active",integrityValid:n,issuerTrusted:i,capabilityValid:g,audienceAllowed:I,status:c,errors:r}}function ct(e){let t=e.now??new Date,r={schemaVersion:1,kind:"xeno-session-handoff",handoffId:d(e.handoffId??`handoff_${_()}`,"handoffId"),createdAt:t.toISOString(),expiresAt:H(t,e.expiresAt,e.ttlMs??1440*60*1e3),issuer:D(e.issuer),source:$(e.source),target:Re(e.target),resume:ke(e.resume),authority:Ae(e.authority),references:F(e.references??[]),...e.shareId?{shareId:d(e.shareId,"shareId")}:{}};return{payload:r,signature:V(r,e.signingIdentity)}}function dt(e,t={}){let r=[];if(e?.payload?.kind!=="xeno-session-handoff"||e.payload.schemaVersion!==1)return{valid:!1,integrityValid:!1,issuerTrusted:!1,expired:!1,errors:["Unsupported handoff envelope"]};let n=J(t.trustedPublicKeys,e.signature.keyId),i=n??(t.allowEmbeddedPublicKey===!1?void 0:e.signature.publicKeySpki),o=!!n,s=!1;if(!i)r.push("No trusted or embedded issuer public key is available");else try{s=L(e.payload,e.signature,i),s||r.push("Handoff signature is invalid")}catch(c){r.push(c instanceof Error?c.message:String(c))}let a=Date.parse(e.payload.expiresAt)<=(t.now??new Date).getTime();return a&&r.push("Handoff has expired"),{valid:s&&!a,integrityValid:s,issuerTrusted:o,expired:a,errors:r}}function V(e,t){let r=p(e),n=me(null,Buffer.from(r),ge(t.privateKeyPem)).toString("base64");return{algorithm:"ed25519",keyId:t.keyId,value:n,publicKeySpki:t.publicKeyPem}}function L(e,t,r){if(t.algorithm!=="ed25519")return!1;let n=Buffer.from(t.value,"base64");if(n.toString("base64")!==t.value)throw new Error("Signature is not canonical base64");return Se(null,Buffer.from(p(e)),O(r),n)}function Ee(e,t){if(!e||!t)return!1;let r=Buffer.from(e.access.capabilityToken.hash,"hex"),n=Buffer.from(B(t),"hex");return r.length===n.length&&ye(r,n)}function Xe(e,t){if(!e)return!1;let r=e.access;return r.allowedPrincipalIds?.length&&(!t?.id||!r.allowedPrincipalIds.includes(t.id))?!1:r.visibility==="workspace"?!!(t?.workspaceId&&t.workspaceId===r.workspaceId):r.visibility==="team"?!!(r.teamId&&t?.teamIds?.includes(r.teamId)):r.visibility==="private"?!!(t?.id&&t.id===e.issuer.id):r.visibility==="link"}function be(e,t,r){let n=new URL(e??"xeno://share/");if(n.username||n.password)throw new Error("Share base URL cannot contain credentials");if(n.protocol!=="https:"&&n.protocol!=="xeno:")throw new Error("Share base URL must use https: or xeno:");return n.pathname=`${n.pathname.replace(/\/$/,"")}/${encodeURIComponent(t)}`,n.search="",n.hash=new URLSearchParams({access_token:r}).toString(),n.toString()}function H(e,t,r=we){let n=t?new Date(t):new Date(e.getTime()+r);if(!Number.isFinite(n.getTime()))throw new Error("expiresAt must be a valid timestamp");let i=n.getTime()-e.getTime();if(i<=0)throw new Error("expiresAt must be in the future");if(i>Ie)throw new Error("Share and handoff expiry cannot exceed 365 days");return n.toISOString()}function D(e){return{id:d(e.id,"issuer.id"),...e.displayName?.trim()?{displayName:e.displayName.trim().slice(0,160)}:{},...e.workspaceId?{workspaceId:d(e.workspaceId,"issuer.workspaceId")}:{},...e.teamId?{teamId:d(e.teamId,"issuer.teamId")}:{}}}function $(e){let t={name:y(e.name,"session.name",200),surface:e.surface};for(let r of["sessionId","runId","hostedRunId","conversationId","parentSessionId","forkedFromSessionId","forkedAtEventId"])e[r]&&(t[r]=d(e[r],`session.${r}`));if(!t.sessionId&&!t.runId&&!t.hostedRunId&&!t.conversationId)throw new Error("Session identity requires sessionId, runId, hostedRunId, or conversationId");return e.git&&(t.git={...e.git.repositoryId?{repositoryId:d(e.git.repositoryId,"git.repositoryId")}:{},...e.git.remoteUrl?{remoteUrl:k(e.git.remoteUrl,"git.remoteUrl")}:{},...e.git.branch?{branch:y(e.git.branch,"git.branch",300)}:{},...e.git.commit?{commit:K(e.git.commit,"git.commit")}:{},...e.git.pullRequest?{pullRequest:{provider:e.git.pullRequest.provider,repository:y(e.git.pullRequest.repository,"git.pullRequest.repository",300),number:Pe(e.git.pullRequest.number,"git.pullRequest.number"),...e.git.pullRequest.url?{url:k(e.git.pullRequest.url,"git.pullRequest.url")}:{}}}:{}}),t}function F(e){let t=new Set;return e.map(r=>{let n=`${r.kind}:${r.id}`;if(t.has(n))throw new Error(`Duplicate share reference: ${n}`);return t.add(n),{kind:r.kind,id:d(r.id,"reference.id"),...r.title?.trim()?{title:r.title.trim().slice(0,300)}:{},...r.uri?{uri:k(r.uri,"reference.uri")}:{},...r.hash?{hash:K(r.hash,"reference.hash")}:{}}})}function Re(e){return{surface:e.surface,...e.workspaceId?{workspaceId:d(e.workspaceId,"target.workspaceId")}:{},...e.teamId?{teamId:d(e.teamId,"target.teamId")}:{},...e.environmentId?{environmentId:d(e.environmentId,"target.environmentId")}:{},...e.repositoryId?{repositoryId:d(e.repositoryId,"target.repositoryId")}:{}}}function ke(e){let t={};for(let r of["sessionId","runId","hostedRunId","checkpointId","transcriptEventId"])e[r]&&(t[r]=d(e[r],`resume.${r}`));if(e.artifactIds?.length&&(t.artifactIds=S(e.artifactIds,"resume.artifactIds")),e.taskIds?.length&&(t.taskIds=S(e.taskIds,"resume.taskIds")),!Object.keys(t).length)throw new Error("Handoff resume point cannot be empty");return t}function Ae(e){return{filesystem:e.filesystem,network:e.network,externalActions:e.externalActions,secretRefs:S(e.secretRefs,"authority.secretRefs")}}function ve(e,t,r,n){if(e==="workspace"&&!t)throw new Error("workspace visibility requires workspaceId");if(e==="team"&&!r)throw new Error("team visibility requires teamId");if(e==="private"&&n?.length)throw new Error("private shares cannot add allowed principals; use link/workspace/team visibility")}function J(e,t){if(!e)return;let r=e;return typeof r.get=="function"?r.get(t):e[t]}function B(e){return C("sha256").update(e).digest("hex")}function S(e,t){return[...new Set(e.map(r=>d(r,t)))].sort()}function d(e,t){let r=e.trim();if(!r||r.length>500||h(r))throw new Error(`${t} is invalid`);return r}function K(e,t){let r=e.trim();if(!/^[A-Za-z0-9:+._-]{7,256}$/.test(r))throw new Error(`${t} is invalid`);return r}function y(e,t,r){let n=e.trim();if(!n||n.length>r||h(n,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return n}function Pe(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function k(e,t){let r=y(e,t,2e3),n=new URL(r);if(n.username||n.password)throw new Error(`${t} cannot contain credentials`);if(!["https:","xeno:","artifact:","urn:"].includes(n.protocol))throw new Error(`${t} uses an unsupported scheme`);return n.toString()}import{createHash as ee}from"node:crypto";import{chmod as Je,mkdir as te,open as Be,readFile as Ke,unlink as Me}from"node:fs/promises";import{dirname as je,join as Z,resolve as qe}from"node:path";import*as u from"node:fs/promises";var Te=new Set(["EACCES","EBUSY","EPERM"]),Ce=[10,20,40,80,160,320,640];async function M(e,t){for(let r=0;;r+=1)try{await u.rename(e,t);return}catch(n){let i=n.code,o=Ce[r];if(process.platform!=="win32"||!i||!Te.has(i)||o===void 0)throw n;await new Promise(s=>setTimeout(s,o))}}import{mkdirSync as Oe,readFileSync as _e,rmSync as q,writeFileSync as Ne}from"node:fs";import{hostname as z}from"node:os";import{dirname as Ve}from"node:path";function Le(){return new Date().toISOString()}function He(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function U(e){try{return JSON.parse(_e(e,"utf8"))}catch{return null}}function De(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function $e(e){return e.hostname!==z()?!0:De(e.pid)}function j(e,t){Oe(Ve(e),{recursive:!0}),Ne(e,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,{encoding:"utf8",flag:"wx"})}function Fe(e,t){let r=U(e);r?.pid!==t.pid||r.hostname!==t.hostname||q(e,{force:!0})}function W(e,t,r){let n=Le(),i={schemaVersion:1,name:t,pid:process.pid,hostname:z(),processStartedAt:He(),version:r,acquiredAt:n,updatedAt:n};try{j(e,i)}catch(o){if(o.code!=="EEXIST")throw o;let a=U(e);if(a&&$e(a))throw new Error(`${t} is already locked by PID ${a.pid} on ${a.hostname}.`);q(e,{force:!0}),j(e,i)}return{record:i,release:()=>{Fe(e,i)}}}var Y=class{directory;snapshotPath;lockPath;now;constructor(t){this.directory=qe(t.directory),this.snapshotPath=Z(this.directory,"registry.json"),this.lockPath=Z(this.directory,"registry.lock"),this.now=t.now??(()=>new Date)}async register(t,r="created"){return this.mutate(n=>{let i=n.records.find(s=>s.shareId===t.payload.shareId);if(i){if(w(i.envelope)!==w(t))throw new Error(`Share ${t.payload.shareId} already exists with different content`);return{snapshot:n,result:i}}let o={shareId:t.payload.shareId,envelope:t,status:Date.parse(t.payload.expiresAt)<=this.now().getTime()?"expired":"active",registeredAt:this.now().toISOString(),origin:r};return{snapshot:G(n,[...n.records,o],this.now()),result:o}})}async revoke(t,r,n){return this.mutate(i=>{let o=i.records.findIndex(g=>g.shareId===t);if(o<0)throw new Error(`Share not found: ${t}`);let s=i.records[o];if(s.status==="revoked")return{snapshot:i,result:s};let a={...s,status:"revoked",revokedAt:this.now().toISOString(),revokedBy:Q(r,"actor"),revocationReason:Q(n,"reason")},c=[...i.records];return c[o]=a,{snapshot:G(i,c,this.now()),result:a}})}async get(t){return(await this.load()).records.find(r=>r.shareId===t)??null}async list(){let t=this.now().getTime();return(await this.load()).records.map(r=>r.status==="active"&&Date.parse(r.envelope.payload.expiresAt)<=t?{...r,status:"expired"}:r).sort((r,n)=>n.registeredAt.localeCompare(r.registeredAt))}async revokedIds(){return new Set((await this.list()).filter(t=>t.status==="revoked").map(t=>t.shareId))}async load(){try{let t=await Ke(this.snapshotPath,"utf8"),r=JSON.parse(t);return Ue(r),r}catch(t){if(t.code==="ENOENT")return ze(this.now());throw t}}async mutate(t){await te(this.directory,{recursive:!0,mode:448});let r=W(this.lockPath,"xeno secure-share registry","1");try{let n=await this.load(),{snapshot:i,result:o}=t(n);return i!==n&&await We(this.snapshotPath,`${JSON.stringify(i,null,2)}
|
|
4
|
+
`),o}finally{r.release()}}};function ze(e){return re({schemaVersion:1,generation:0,updatedAt:e.toISOString(),records:[]})}function G(e,t,r){return re({schemaVersion:1,generation:e.generation+1,updatedAt:r.toISOString(),records:[...t].sort((n,i)=>n.shareId.localeCompare(i.shareId))})}function re(e){return{...e,checksum:{algorithm:"sha256",value:ee("sha256").update(w(e)).digest("hex")}}}function Ue(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new Error("Invalid secure-share registry snapshot");let{checksum:t,...r}=e,n=ee("sha256").update(w(r)).digest("hex");if(t?.algorithm!=="sha256"||t.value!==n)throw new Error("Secure-share registry checksum mismatch");let i=new Set;for(let o of e.records){if(o.shareId!==o.envelope?.payload?.shareId)throw new Error("Secure-share registry identity mismatch");if(i.has(o.shareId))throw new Error(`Duplicate secure-share registry record: ${o.shareId}`);i.add(o.shareId)}}async function We(e,t){await te(je(e),{recursive:!0,mode:448});let r=`${e}.${process.pid}.${Date.now()}.tmp`,n;try{n=await Be(r,"wx",384),await n.writeFile(t,"utf8"),await n.sync(),await n.close(),n=void 0,await M(r,e),await Je(e,384).catch(()=>{})}finally{n&&await n.close().catch(()=>{}),await Me(r).catch(()=>{})}}function w(e){return p(e)}function Q(e,t){let r=e.trim();if(!r||r.length>500||h(r))throw new Error(`${t} is invalid`);return r}export{Y as FileXenoShareRegistry,X as XENO_HANDOFF_SCHEMA_VERSION,m as XENO_SHARE_REGISTRY_SCHEMA_VERSION,E as XENO_SHARE_SCHEMA_VERSION,st as createXenoSecureShare,ct as createXenoSessionHandoff,ot as createXenoShareSigningIdentity,N as publicKeyFingerprint,T as redactXenoShareValue,xe as signSharePayload,at as verifyXenoSecureShare,dt as verifyXenoSessionHandoff};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/sharing/types.ts":{"bytes":5121,"imports":[],"format":"esm"},"src/sharing/redaction.ts":{"bytes":6716,"imports":[],"format":"esm"},"src/artifacts/hash.ts":{"bytes":1489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/utils/text-security.ts":{"bytes":809,"imports":[],"format":"esm"},"src/sharing/protocol.ts":{"bytes":19325,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"../utils/text-security.js"},{"path":"src/sharing/redaction.ts","kind":"import-statement","original":"./redaction.js"},{"path":"src/sharing/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/utils/fs.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/sharing/types.ts":{"bytes":5121,"imports":[],"format":"esm"},"src/sharing/redaction.ts":{"bytes":6716,"imports":[],"format":"esm"},"src/artifacts/hash.ts":{"bytes":1489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/utils/text-security.ts":{"bytes":809,"imports":[],"format":"esm"},"src/sharing/protocol.ts":{"bytes":19325,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"../utils/text-security.js"},{"path":"src/sharing/redaction.ts","kind":"import-statement","original":"./redaction.js"},{"path":"src/sharing/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/utils/fs.ts":{"bytes":13746,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/control-plane/lock.ts":{"bytes":2496,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/sharing/file-registry.ts":{"bytes":7359,"imports":[{"path":"node:crypto","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/fs.ts","kind":"import-statement","original":"../utils/fs.js"},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"},{"path":"src/control-plane/lock.ts","kind":"import-statement","original":"../control-plane/lock.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"../utils/text-security.js"},{"path":"src/sharing/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/sharing/index.ts":{"bytes":127,"imports":[{"path":"src/sharing/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/sharing/redaction.ts","kind":"import-statement","original":"./redaction.js"},{"path":"src/sharing/protocol.ts","kind":"import-statement","original":"./protocol.js"},{"path":"src/sharing/file-registry.ts","kind":"import-statement","original":"./file-registry.js"}],"format":"esm"}},"outputs":{"dist/sharing/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:crypto","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/promises","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/sharing/index.ts","inputs":{"src/sharing/index.ts":{"bytesInOutput":413},"src/sharing/types.ts":{"bytesInOutput":16},"src/sharing/redaction.ts":{"bytesInOutput":3216},"src/sharing/protocol.ts":{"bytesInOutput":9109},"src/artifacts/hash.ts":{"bytesInOutput":559},"src/utils/text-security.ts":{"bytesInOutput":179},"src/sharing/file-registry.ts":{"bytesInOutput":3490},"src/utils/fs.ts":{"bytesInOutput":318},"src/control-plane/lock.ts":{"bytesInOutput":1059}},"bytes":19260}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/sharing/types.ts":{"bytes":5121,"imports":[],"format":"esm"},"src/sharing/redaction.ts":{"bytes":6716,"imports":[],"format":"esm"},"src/artifacts/hash.ts":{"bytes":1489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/utils/text-security.ts":{"bytes":809,"imports":[],"format":"esm"},"src/sharing/protocol.ts":{"bytes":19325,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"../utils/text-security.js"},{"path":"src/sharing/redaction.ts","kind":"import-statement","original":"./redaction.js"},{"path":"src/sharing/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/utils/fs.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/sharing/types.ts":{"bytes":5121,"imports":[],"format":"esm"},"src/sharing/redaction.ts":{"bytes":6716,"imports":[],"format":"esm"},"src/artifacts/hash.ts":{"bytes":1489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/utils/text-security.ts":{"bytes":809,"imports":[],"format":"esm"},"src/sharing/protocol.ts":{"bytes":19325,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"../utils/text-security.js"},{"path":"src/sharing/redaction.ts","kind":"import-statement","original":"./redaction.js"},{"path":"src/sharing/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/utils/fs.ts":{"bytes":13746,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/control-plane/lock.ts":{"bytes":2496,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/sharing/file-registry.ts":{"bytes":7359,"imports":[{"path":"node:crypto","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/fs.ts","kind":"import-statement","original":"../utils/fs.js"},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"},{"path":"src/control-plane/lock.ts","kind":"import-statement","original":"../control-plane/lock.js"},{"path":"src/utils/text-security.ts","kind":"import-statement","original":"../utils/text-security.js"},{"path":"src/sharing/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/sharing/index.ts":{"bytes":127,"imports":[{"path":"src/sharing/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/sharing/redaction.ts","kind":"import-statement","original":"./redaction.js"},{"path":"src/sharing/protocol.ts","kind":"import-statement","original":"./protocol.js"},{"path":"src/sharing/file-registry.ts","kind":"import-statement","original":"./file-registry.js"}],"format":"esm"}},"outputs":{"dist/sharing/index.js":{"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"exports":["FileXenoShareRegistry","XENO_HANDOFF_SCHEMA_VERSION","XENO_SHARE_REGISTRY_SCHEMA_VERSION","XENO_SHARE_SCHEMA_VERSION","createXenoSecureShare","createXenoSessionHandoff","createXenoShareSigningIdentity","publicKeyFingerprint","redactXenoShareValue","signSharePayload","verifyXenoSecureShare","verifyXenoSessionHandoff"],"entryPoint":"src/sharing/index.ts","inputs":{"src/sharing/types.ts":{"bytesInOutput":16},"src/sharing/index.ts":{"bytesInOutput":0},"src/sharing/redaction.ts":{"bytesInOutput":3216},"src/sharing/protocol.ts":{"bytesInOutput":9080},"src/artifacts/hash.ts":{"bytesInOutput":559},"src/utils/text-security.ts":{"bytesInOutput":179},"src/sharing/file-registry.ts":{"bytesInOutput":3478},"src/utils/fs.ts":{"bytesInOutput":313},"src/control-plane/lock.ts":{"bytesInOutput":1041}},"bytes":18252}}}
|
package/dist/skills/index.d.cts
CHANGED
|
@@ -37,6 +37,12 @@ interface ToolDefinition {
|
|
|
37
37
|
additionalProperties?: boolean | Record<string, unknown>;
|
|
38
38
|
[keyword: string]: unknown;
|
|
39
39
|
};
|
|
40
|
+
grammar?: ToolInputGrammar;
|
|
41
|
+
}
|
|
42
|
+
interface ToolInputGrammar {
|
|
43
|
+
syntax: "gbnf";
|
|
44
|
+
definition: string;
|
|
45
|
+
inputField: string;
|
|
40
46
|
}
|
|
41
47
|
interface ImageUrlBlock {
|
|
42
48
|
type: "image_url";
|
package/dist/skills/index.d.ts
CHANGED
|
@@ -37,6 +37,12 @@ interface ToolDefinition {
|
|
|
37
37
|
additionalProperties?: boolean | Record<string, unknown>;
|
|
38
38
|
[keyword: string]: unknown;
|
|
39
39
|
};
|
|
40
|
+
grammar?: ToolInputGrammar;
|
|
41
|
+
}
|
|
42
|
+
interface ToolInputGrammar {
|
|
43
|
+
syntax: "gbnf";
|
|
44
|
+
definition: string;
|
|
45
|
+
inputField: string;
|
|
40
46
|
}
|
|
41
47
|
interface ImageUrlBlock {
|
|
42
48
|
type: "image_url";
|
package/dist/utils/index.cjs
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`,"utf-8")}async function
|
|
3
|
-
`,"utf-8"),await
|
|
4
|
-
`)?"CRLF":"LF"}function
|
|
5
|
-
`);return
|
|
6
|
-
`):
|
|
7
|
-
`)?/(^|[^\r])\n/.test(
|
|
8
|
-
`)){let r
|
|
9
|
-
`)}function
|
|
10
|
-
`)),nextIndex:
|
|
11
|
-
`)}function
|
|
12
|
-
${
|
|
13
|
-
`):process.stderr.write(`[${
|
|
14
|
-
`))}function
|
|
15
|
-
`):process.stderr.write(`[${
|
|
16
|
-
`))}function
|
|
17
|
-
`):process.stderr.write(`[${
|
|
18
|
-
`))}function
|
|
19
|
-
`):process.stderr.write(`[${
|
|
20
|
-
`))}function k(t){if(t==null)return"";if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}var Te=/^[A-Za-z0-9:._*-]{1,64}$/,Ce=/^[A-Za-z0-9_-][A-Za-z0-9 _-]{0,30}[A-Za-z0-9_-]$/,Ae=/^[0-9][0-9A-Za-z.+-]{0,40}$/;function ke(t){if(!t||typeof t!="object")throw new TypeError("requestContext must be an object");let e=Object.keys(t).filter(r=>r!=="surface"&&r!=="client");if(e.length>0)throw new TypeError(`requestContext does not accept: ${e.join(", ")}`);if(typeof t.surface!="string"||!Te.test(t.surface))throw new TypeError("requestContext.surface must match /^[A-Za-z0-9:._*-]{1,64}$/");if(t.client===void 0)return Object.freeze({surface:t.surface});let n=t.client;if(!n||typeof n!="object"||Object.keys(n).some(r=>r!=="name"&&r!=="version"))throw new TypeError("requestContext.client must be { name, version }");if(typeof n.name!="string"||!Ce.test(n.name))throw new TypeError("requestContext.client.name must be 2-32 characters of letters, digits, space, _ or -");if(typeof n.version!="string"||!Ae.test(n.version))throw new TypeError("requestContext.client.version must start with a digit, e.g. 1.2.3");return Object.freeze({surface:t.surface,client:Object.freeze({name:n.name,version:n.version})})}function Me(t){return t?{"X-Xeno-Surface":t.surface,...t.client?{"X-Xeno-Client":`${t.client.name}/${t.client.version}`}:{}}:{}}var w=class extends Error{statusCode;body;retryAfterMs;requestId;cfRay;constructor(e,n={}){super(e,n.cause!==void 0?{cause:n.cause}:void 0),this.name="ApiTransientError",this.statusCode=n.statusCode,this.retryAfterMs=n.retryAfterMs,this.requestId=n.requestId,this.cfRay=n.cfRay;for(let r of["code","category","retryable","providerCode","remedy"])n[r]!==void 0&&Object.defineProperty(this,r,{value:n[r],enumerable:!0,configurable:!0,writable:!1})}},M={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function _(t,e){let n=process.env[t],r=n?Number.parseInt(n,10):Number.NaN;return!Number.isFinite(r)||r<0?e:r}function _e(t={}){let e=Math.max(0,t.maxRetries??_("XENO_API_MAX_RETRIES",M.maxRetries)),n=Math.max(50,t.baseDelayMs??_("XENO_API_BASE_DELAY_MS",M.baseDelayMs)),r=Math.max(n,t.maxDelayMs??_("XENO_API_MAX_DELAY_MS",M.maxDelayMs)),o=Math.max(0,t.jitterMs??_("XENO_API_RETRY_JITTER_MS",M.jitterMs));return{maxRetries:e,baseDelayMs:n,maxDelayMs:r,jitterMs:o}}function Se(t,e,n){if(e.retryAfterMs&&e.retryAfterMs>0)return Math.min(e.retryAfterMs,n.maxDelayMs);let r=Math.min(n.baseDelayMs*Math.pow(2,t),n.maxDelayMs),o=Math.floor(Math.random()*n.jitterMs);return Math.min(r+o,n.maxDelayMs)}function nt(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("too many requests")||e.includes("429")}function ve(t){let e=t.toLowerCase();return e.includes("network")||e.includes("timeout")||e.includes("fetch failed")||e.includes("socket hang up")||e.includes("econnreset")||e.includes("eai_again")||e.includes("enotfound")||e.includes("econnrefused")||e.includes("tls")||e.includes("temporarily unavailable")}function N(t){if(t instanceof w)return{statusCode:t.statusCode,retryAfterMs:t.retryAfterMs,requestId:t.requestId,cfRay:t.cfRay};if(!(t instanceof Error))return{};let e=t;if(e.statusCode!==void 0||e.retryAfterMs!==void 0||e.requestId!==void 0||e.cfRay!==void 0)return{statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId,cfRay:e.cfRay};let n=t.message.toLowerCase();return nt(n)?{statusCode:429}:{}}var $="408|425|429|500|502|503|504";function rt(t){let e=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${$})\\b`,"i"),n=new RegExp(`\\b(?:${$})\\s+(?:internal|bad\\s+gateway|service\\s+unavailable|gateway\\s+time|request\\s+time|too\\s+early|too\\s+many)`,"i"),r=new RegExp(`^\\s*(?:${$})\\b`);return e.test(t)||n.test(t)||r.test(t)}function ot(t){if(t&&typeof t=="object"&&"retryable"in t)return t.retryable===!0;if(t instanceof w){let{statusCode:e}=N(t);if(e)return e===429||e>=500||e===408||e===409||e===425}if(t instanceof Error){let e=t.name?.toLowerCase()??"";return e==="aborterror"||e==="agentinterruptederror"||t.message.toLowerCase().includes("aborted")||t.message.toLowerCase().includes("interrupted")?!1:rt(t.message)?!0:nt(t.message)||ve(t.message.toLowerCase())}return!1}function $e(t){if(t.onAbort)return t.onAbort();let e=new Error("The operation was aborted");return e.name="AbortError",e}async function Ne(t,e={}){let n=_e(e),r;for(let o=0;o<=n.maxRetries;o++)try{if(e.signal?.aborted)throw $e(e);return e.onBeforeAttempt?.(o),await t()}catch(i){if(r=i,!(e.shouldRetry?e.shouldRetry(i,o):ot(i))||o===n.maxRetries)throw i;let f=N(i),c=Se(o,f,n),l=e.getDelayMs?.(i,o,c),E=typeof l=="number"&&l>=0?l:c;await new Promise(R=>setTimeout(R,E))}throw r}var it=(t,e)=>{if(!t)return 0;let n=e.toLowerCase(),r=n.includes("claude")?3.5:n.includes("gemini")?3.8:(/(^|[/_-])(gpt|o\d)/.test(n),4),o=[...t].filter(s=>s.codePointAt(0)>127).length,i=Math.ceil(t.length/r);return Math.max(1,i+Math.ceil(o*.35))},st=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:it,countImage:({detail:t})=>t==="high"?2e3:t==="low"?512:1200,safetyMarginRatio:t=>{let e=t.toLowerCase();return e.includes("claude")?.12:e.includes("gemini")?.14:/(^|[/_-])(gpt|o\d)/.test(e)?.1:.18}});function Oe(t,e,n=st){return{tokens:Math.max(0,Math.ceil(n.countText(t,e))),source:n.source,adapterId:n.id}}function at(t){return t?Math.ceil(t.length/4):0}function Le(t,e){if(!t||e<=0)return"";let n=e*4;if(t.length<=n)return t;let r=t.slice(0,n),o=r.lastIndexOf(" ");return o>n*.8&&(r=r.slice(0,o)),r+"..."}function Be(t,e){return at(t)<=e}function Pe(t,e){return Math.max(0,e-t)}var Ie={"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 De(t,e,n){let r=Ie[t];return r?e/1e6*r.input+n/1e6*r.output:0}function Fe(t){return t<=0?"$0.00":t<.001?"<$0.001":t<.01?`$${t.toFixed(4)}`:t<1?`$${t.toFixed(3)}`:`$${t.toFixed(2)}`}var ut=require("node:child_process");function je(t){let e=process.platform==="win32"?[{command:"clip.exe",args:[]}]:process.platform==="darwin"?[{command:"pbcopy",args:[]}]:[{command:"wl-copy",args:[]},{command:"xclip",args:["-selection","clipboard"]},{command:"xsel",args:["--clipboard","--input"]}],n=null;for(let r of e)try{let o=(0,ut.spawnSync)(r.command,r.args,{input:t,encoding:"utf8"});if(o.error){n=o.error.message;continue}if(o.status===0)return;n=o.stderr||o.stdout||`exit ${o.status}`}catch(o){n=o instanceof Error?o.message:String(o)}throw new Error(`Clipboard copy failed${n?`: ${n}`:""}`)}function lt(t){return t.replace(/\\/g,"/").toLowerCase()}var We=["golden","solution","answer","expected"],qe=["expected","golden","reference","answer","answers"],Xe=new Set([";","&&","||","|"]);function ft(t){return lt(t).replace(/^\.\/+/,"").split("/").map(e=>e.trim()).filter(e=>e.length>0)}function ze(t){return We.some(e=>t.includes(e))}function ct(t){return qe.some(e=>t.includes(e))}function dt(t){return t.split("::",1)[0]?.split("?",1)[0]?.split("#",1)[0]??t}function S(t){let e=t.trim().replace(/^[({]+/,"").replace(/[),;]+$/,"");return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e}function He(t){return t.match(/"[^"]*"|'[^']*'|&&|\|\||[;|]|[^\s;|&]+/g)?.map(S).filter(e=>e.length>0)??[]}function pt(t){let e=ft(t),n=dt(e.at(-1)??"");return ct(n)||e.some(r=>ct(r))}function gt(t){let e=lt(S(t));return!e||e==="/dev/null"||e.startsWith("/tmp/")||e.startsWith("tmp/")||e.startsWith("/var/tmp/")||e.startsWith("var/tmp/")?!1:e.startsWith("/app/")||e.startsWith("./")?!0:!e.startsWith("/")}function Je(t){return/[\\/]/.test(t)||/\.[A-Za-z0-9]{1,8}$/.test(t)}function Ye(t){let e=He(t);for(let n=0;n<e.length;n+=1){let r=e[n]?.toLowerCase();if(r!=="cp"&&r!=="mv"&&r!=="rsync"&&r!=="install")continue;let o=[];for(let s=n+1;s<e.length;s+=1){let f=e[s];if(!f||Xe.has(f))break;f!=="--"&&(f.startsWith("-")||o.push(f))}if(o.length<2)continue;let i=o.at(-1);if(gt(i)){for(let s of o.slice(0,-1))if(Je(s)&&pt(s))return{sourcePath:s,destinationPath:i,operation:r}}}return null}function Ue(t){let e=[/\bcat\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*>\s*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i,/\bdd\b[\s\S]*?\bif=(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))[\s\S]*?\bof=(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i];for(let n of e){let r=t.match(n);if(!r)continue;let o=S(r[1]??r[2]??r[3]??""),i=S(r[4]??r[5]??r[6]??"");if(!(!o||!i)&&pt(o)&>(i))return{sourcePath:o,destinationPath:i,operation:n.source.startsWith("\\bdd")?"dd":"redirect"}}return null}function O(){return process.env.XENO_BENCHMARK_MODE?.trim().toLowerCase()==="terminal-bench"}function L(t){let e=ft(t);if(e.includes("solution")||e.includes("xeno-audit")||e.includes(".xeno")&&e.includes("audit"))return!0;let n=dt(e.at(-1)??"");return e.includes("tests")&&ze(n)}function Ge(t){return O()?t.filter(e=>!L(e)):t}function Ke(t){return`Benchmark safety: access to verifier answer or benchmark trace artifacts is blocked (${t}). Use task inputs and verifier logic, not golden, solution, or agent audit files.`}function Ze(t){return t.split(/[\s"'`;|&]+/).map(e=>e.trim()).filter(e=>e.length>0&&/[\\/]/.test(e)).some(e=>L(e))}function Qe(t){if(!O())return null;let e=Ye(t)??Ue(t);return e?["[xeno guidance]",`Benchmark safety blocked ${e.operation} from reference-like source ${e.sourcePath} to protected destination ${e.destinationPath}.`,"Do not copy expected, golden, reference, or answer files over task inputs or submission artifacts to make validation pass.","If a previous check polluted an input, restore/regenerate the original source input, then rerun the actual script or program under test."].join(`
|
|
21
|
-
`):null}function
|
|
1
|
+
"use strict";var Ye=Object.create;var O=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var tt=(e,t)=>{for(var r in t)O(e,r,{get:t[r],enumerable:!0})},J=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Je(t))!et.call(e,o)&&o!==r&&O(e,o,{get:()=>t[o],enumerable:!(n=Ze(t,o))||n.enumerable});return e};var F=(e,t,r)=>(r=e!=null?Ye(Qe(e)):{},J(t||!e||!e.__esModule?O(r,"default",{value:e,enumerable:!0}):r,e)),rt=e=>J(O({},"__esModule",{value:!0}),e);var Gr={};tt(Gr,{ApiTransientError:()=>S,HOME_DIR:()=>Ht,IS_LINUX:()=>Ft,IS_MAC:()=>Xt,IS_WINDOWS:()=>v,LogLevel:()=>we,OS_VERSION:()=>zt,PLATFORM:()=>$,accountTextTokens:()=>hr,appendDurableLine:()=>ut,appendLine:()=>ct,benchmarkLeakError:()=>$r,buildToolResultBlock:()=>Ur,buildToolResultText:()=>Le,calculateCost:()=>xr,commandMentionsBenchmarkLeak:()=>Nr,conservativeTokenAccountingAdapter:()=>ve,copyTextToClipboard:()=>_r,createSafeRegex:()=>Qt,debug:()=>nr,decodeTextBuffer:()=>oe,deleteDir:()=>wt,deleteFile:()=>bt,detectLineEnding:()=>se,detectPreferredLineEnding:()=>ft,detectTextEncoding:()=>re,encodeTextBuffer:()=>ie,ensureDir:()=>M,error:()=>sr,estimateTokens:()=>Ae,estimateTokensForModel:()=>_e,existsSync:()=>yt,fetchPinnedEndpoint:()=>Kr,filterBenchmarkLeakPaths:()=>Mr,findSimilarFile:()=>mt,fitsInBudget:()=>br,formatCost:()=>Tr,getAgentHome:()=>Ut,getBenchmarkReferenceOverwriteHint:()=>Lr,getBoolean:()=>Jt,getConfigDir:()=>qt,getLogLevel:()=>rr,getNumber:()=>Zt,getProjectConfigDir:()=>Vt,getRetryErrorContext:()=>j,getShellName:()=>jt,getString:()=>Yt,getToolResultTransportContent:()=>Xr,hasDir:()=>ot,hasDisallowedAsciiControlCharacter:()=>qr,hasFile:()=>nt,hasFrontmatter:()=>At,hasMixedLineEndings:()=>dt,hasNonTextToolResultContent:()=>zr,hasTransientStatusMention:()=>xe,info:()=>or,isBenchmarkLeakPath:()=>K,isBenchmarkMode:()=>W,isGitRepo:()=>Wt,isGitRepoAsync:()=>Kt,isPathSafe:()=>pe,isRetryableError:()=>Te,listDirs:()=>Et,listFiles:()=>ht,normalizeLineEndings:()=>ae,normalizeXenoRequestContext:()=>dr,parseDocument:()=>_t,parseJsonLines:()=>Tt,pathIdentityKey:()=>Ot,readFileSafe:()=>it,readIfExists:()=>gt,readTextFile:()=>ce,remainingBudget:()=>wr,renameReplacingWithRetry:()=>te,safeJsonParse:()=>Rt,safeJsonStringify:()=>xt,safeRegexTest:()=>er,safeResolvePath:()=>It,setLogLevel:()=>tr,stringifyDocument:()=>vt,toTransportAssistantBlocks:()=>Hr,toolAssistantContentToText:()=>$e,toolResultContentToText:()=>Br,truncateToTokens:()=>Er,validateRegexPattern:()=>be,validateRequired:()=>Gt,warn:()=>ir,withRetry:()=>yr,writeAtomic:()=>ee,writeTextFile:()=>lt,xenoRequestContextHeaders:()=>lr});module.exports=rt(Gr);var C=require("node:fs"),T=require("node:fs"),f=F(require("node:fs/promises"),1),d=F(require("node:path"),1);function nt(e){try{return(0,T.existsSync)(e)&&(0,T.statSync)(e).isFile()}catch{return!1}}function ot(e){try{return(0,T.existsSync)(e)&&(0,T.statSync)(e).isDirectory()}catch{return!1}}function it(e,t=""){try{return(0,C.readFileSync)(e,"utf-8")}catch{return t}}async function M(e){await f.mkdir(e,{recursive:!0})}async function ee(e,t){let r=d.dirname(e);await M(r);let n=Math.random().toString(36).substring(2,15),o=`${e}.tmp.${process.pid}.${n}`;try{await f.writeFile(o,t),await te(o,e)}finally{try{await f.unlink(o)}catch{}}}var st=new Set(["EACCES","EBUSY","EPERM"]),at=[10,20,40,80,160,320,640];async function te(e,t){for(let r=0;;r+=1)try{await f.rename(e,t);return}catch(n){let o=n.code,i=at[r];if(process.platform!=="win32"||!o||!st.has(o)||i===void 0)throw n;await new Promise(s=>setTimeout(s,i))}}async function ct(e,t){let r=d.dirname(e);await M(r),await f.appendFile(e,t+`
|
|
2
|
+
`,"utf-8")}async function ut(e,t){let r=d.dirname(e);await M(r);let n=await f.open(e,"a");try{await n.writeFile(t+`
|
|
3
|
+
`,"utf-8"),await n.sync()}finally{await n.close()}}function re(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 ne(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 ne(e.subarray(2)).toString("utf16le");default:return e.toString("utf8")}}function ie(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]),ne(Buffer.from(e,"utf16le"))]);default:return Buffer.from(e,"utf8")}}function se(e){return e.includes(`\r
|
|
4
|
+
`)?"CRLF":"LF"}function ae(e,t){let r=e.replace(/\r\n/g,`
|
|
5
|
+
`);return t==="CRLF"?r.replace(/\n/g,`\r
|
|
6
|
+
`):r}function dt(e){return e.includes(`\r
|
|
7
|
+
`)?/(^|[^\r])\n/.test(e):!1}async function ce(e){let t=await f.readFile(e),r=re(t),n=oe(t,r);return{content:n,encoding:r,lineEnding:se(n),sizeBytes:t.length}}async function lt(e,t,r){let n=r?.preserveLineEndings?t:ae(t,r?.lineEnding??"LF");await ee(e,ie(n,r?.encoding??"utf8"))}async function ft(e,t){let r=new Set,n=d.resolve(e),o=t===void 0?void 0:d.resolve(t);if(o!==void 0){let i=d.relative(o,n);if(d.isAbsolute(i)||i===".."||i.startsWith(`..${d.sep}`))return"LF"}for(;!r.has(n);){r.add(n);try{let s=(0,C.readdirSync)(n,{withFileTypes:!0}).filter(a=>a.isFile()).map(a=>a.name).sort();for(let a of s){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),p=await ce(l);if(p.content.length>0)return p.lineEnding}catch{}}}catch{}if(o!==void 0&&d.relative(o,n)==="")break;let i=d.dirname(n);if(i===n)break;n=i}return"LF"}function pt(e,t,r){let n=[],o=[{dir:e,depth:0}],i=new Set;for(;o.length>0&&n.length<r;){let s=o.shift();if(!i.has(s.dir)){i.add(s.dir);try{let a=(0,C.readdirSync)(s.dir,{withFileTypes:!0});for(let c of a){let l=d.join(s.dir,c.name);if(c.isFile()){if(n.push(l),n.length>=r)break;continue}c.isDirectory()&&s.depth<t&&!c.name.startsWith(".")&&c.name!=="node_modules"&&o.push({dir:l,depth:s.depth+1})}}catch{}}}return n}function Q(e,t){let r=d.relative(e,t);return r===""||!r.startsWith("..")&&!d.isAbsolute(r)}function mt(e,t){try{let r=d.dirname(e),n=d.basename(e,d.extname(e)).toLowerCase(),o=d.basename(e).toLowerCase(),i=[r,d.dirname(r)],s=t!==void 0&&Q(t,e)?t:void 0,a=i.flatMap(l=>pt(l,2,500)).filter(l=>s===void 0||Q(s,l)),c=null;for(let l of a){let p=d.basename(l).toLowerCase(),u=d.basename(l,d.extname(l)).toLowerCase(),g=null;if(p===o?g=0:u===n?g=1:(p.includes(n)||n.includes(u))&&(g=2),g===null)continue;let _=d.relative(r,l).split(d.sep).length,h=g+_*.01;(!c||h<c.score)&&(c={filePath:l,score:h})}return c?.filePath??null}catch{}return null}async function gt(e){try{return await f.readFile(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function yt(e){return(0,T.existsSync)(e)}async function ht(e,t){try{let n=(await f.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 Et(e){try{return(await f.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 bt(e){try{await f.unlink(e)}catch(t){if(t.code!=="ENOENT")throw t}}async function wt(e){try{await f.rm(e,{recursive:!0,force:!0})}catch(t){if(t.code!=="ENOENT")throw t}}function Rt(e,t){try{return JSON.parse(e)}catch{return t}}function xt(e,t="{}"){try{return JSON.stringify(e)}catch{return t}}function Tt(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 _t(e){let t=Pt(e);return{frontmatter:t.frontmatter,content:t.content.trim()}}function vt(e,t){let r=Object.fromEntries(Object.entries(e).filter(([n,o])=>o!==void 0));return["---",fe(r),"---","",t].join(`
|
|
9
|
+
`)}function At(e){return e.trimStart().startsWith("---")}function Pt(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 i=n.slice(0,o.index),s=o[0],a=o.index+s.length;return{frontmatter:de(i),content:n.slice(a)}}function de(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 i=Ct(o,n+1);if(i.key==="<<")throw new Error("YAML merge keys are not supported.");if(i.value!==""){t[i.key]=le(i.value,n+1);continue}let s=kt(r,n+1);t[i.key]=s.value,n=s.nextIndex-1}return t}function kt(e,t){let r=[],n=t;for(;n<e.length;n+=1){let i=e[n];if(!i.trim()){r.push(i);continue}if(!/^\s/.test(i))break;r.push(i.replace(/^ {2}/,""))}let o=r.filter(i=>i.trim()&&!i.trimStart().startsWith("#"));return o.length===0?{value:{},nextIndex:n}:o.every(i=>i.trimStart().startsWith("- "))?{value:o.map((i,s)=>le(i.trimStart().slice(2),t+s+1)),nextIndex:n}:{value:de(r.join(`
|
|
10
|
+
`)),nextIndex:n}}function Ct(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 le(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 ue(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 ue(e,t);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${t}.`);return e}function ue(e,t){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${t}.`)}}function fe(e,t=""){return Object.entries(e).map(([r,n])=>St(r,n,t)).join(`
|
|
11
|
+
`)}function St(e,t,r){return Array.isArray(t)?`${r}${e}: ${JSON.stringify(t)}`:t&&typeof t=="object"?`${r}${e}:
|
|
12
|
+
${fe(t,`${r} `)}`:`${r}${e}: ${JSON.stringify(t)}`}var y=F(require("path"),1);function pe(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 It(e,t){if(y.isAbsolute(t))return y.resolve(t);if(!pe(e,t))throw new Error(`PathSecurity: Path traversal attempt detected: ${t}`);return y.resolve(e,t)}function Ot(e,t=process.platform){let r=y.resolve(e);return t==="win32"?r.toLowerCase():r}var w=require("node:os"),A=require("node:child_process"),he=require("node:fs"),E=require("node:path");var z=require("node:child_process"),Mt=5e3,me=128;function $t(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===me?{...n,terminated:!0,reason:"not-running",exitCode:me}:{...n,terminated:!1,reason:"failed",exitCode:t.status,detail:`${e} exited with code ${t.status??"unknown"}`}}var Nt=(e,t,r)=>new Promise(n=>{let o=!1,i={},s=c=>{o||(o=!0,i.timer&&clearTimeout(i.timer),n(c))},a;try{a=(0,z.spawn)(e,[...t],{stdio:"ignore",windowsHide:!0})}catch(c){s({status:null,timedOut:!1,error:c instanceof Error?c.message:String(c)});return}i.timer=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}s({status:null,timedOut:!0})},r),i.timer.unref?.(),a.once("error",c=>{s({status:null,timedOut:!1,error:c.code??c.message})}),a.once("close",c=>{s(c===null?{status:null,timedOut:!1,error:"no exit status"}:{status:c,timedOut:!1})})});function ge(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):Mt}function Lt(e,t){return{terminated:!1,reason:"failed",tool:e,exitCode:null,timeoutMs:t,detail:"pid is not a positive integer"}}function Dt(e){return["/PID",String(e),"/T","/F"]}async function ye(e,t={}){let r=ge(t.timeoutMs);return!Number.isSafeInteger(e)||e<=0?Lt("taskkill",r):Bt("taskkill","taskkill.exe",Dt(e),{timeoutMs:r,run:t.run})}async function Bt(e,t,r,n={}){let o=ge(n.timeoutMs),i;try{i=await(n.run??Nt)(t,r,o)}catch(s){i={status:null,timedOut:!1,error:s instanceof Error?s.message:String(s)}}return $t(e,i,o)}var $=(0,w.platform)(),v=$==="win32",Xt=$==="darwin",Ft=$==="linux",zt=(0,w.release)(),Ht=(0,w.homedir)();function Ut(){let e=process.env.XENO_AGENT_HOME?.trim();return e?(0,E.resolve)(e):(0,E.resolve)((0,w.homedir)(),".xeno-agent")}function qt(){let e=process.env.XENO_CONFIG_DIR?.trim();return e?(0,E.resolve)(e):(0,E.resolve)((0,w.homedir)(),".xeno-code")}function Vt(e){return(0,E.resolve)(e,".xeno-code")}function jt(){return v?"powershell":process.env.SHELL?.split("/").pop()??"bash"}var U=5e3,q=4096,H=["rev-parse","--is-inside-work-tree"];function Ee(){if(!v)return{file:"git",args:H};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,he.statSync)(o).isFile())continue}catch{continue}if(n!==".cmd"&&n!==".bat")return{file:o,args:H};if(/["%!\r\n\0]/.test(o))throw new Error("Git wrapper path cannot be represented safely");let i=process.env.SystemRoot??process.env.WINDIR;if(!i)throw new Error("Windows command interpreter is unavailable");return{file:(0,E.join)(i,"System32","cmd.exe"),args:["/d","/s","/c",`""${o}" rev-parse --is-inside-work-tree"`],windowsVerbatimArguments:!0}}}return{file:"git",args:H}}function Wt(e){try{let t=Ee();if(t.windowsVerbatimArguments){let r=(0,A.spawnSync)(t.file,t.args,{cwd:e,encoding:"utf8",windowsHide:!0,windowsVerbatimArguments:!0,timeout:U,maxBuffer:q,stdio:["ignore","pipe","ignore"]});return!r.error&&r.status===0&&r.stdout.trim()==="true"}return(0,A.execFileSync)(t.file,t.args,{cwd:e,encoding:"utf8",windowsHide:!0,timeout:U,maxBuffer:q,stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}function Kt(e){return new Promise(t=>{let r,n=!1,o={},i=0,s=[],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(v&&r.pid)ye(r.pid);else if(!v&&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=Ee();r=(0,A.spawn)(l.file,l.args,{cwd:e,windowsHide:!0,detached:!v,windowsVerbatimArguments:l.windowsVerbatimArguments,stdio:["ignore","pipe","ignore"]})}catch{a(!1);return}o.timer=setTimeout(c,U),r.stdout?.on("data",l=>{if(!n){if(i+=l.byteLength,i>q){c();return}s.push(Buffer.from(l))}}),r.once("error",()=>a(!1)),r.once("close",l=>a(l===0&&Buffer.concat(s).toString("utf8").trim()==="true"))})}function Gt(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 Yt(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 Zt(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 Jt(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 be(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 Qt(e,t,r=5e3){let n=be(e);if(n)throw new Error(n);try{return new RegExp(e,t)}catch(o){let i=o instanceof Error?o.message:String(o);throw new Error(`Invalid regex pattern: ${i}`)}}function er(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 we=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(we||{}),P=1;function tr(e){P=e}function rr(){return P}function R(){return new Date().toISOString()}function nr(e,t){P<=0&&(t!==void 0?process.stderr.write(`[${R()}] DEBUG: ${e} ${N(t)}
|
|
13
|
+
`):process.stderr.write(`[${R()}] DEBUG: ${e}
|
|
14
|
+
`))}function or(e,t){P<=1&&(t!==void 0?process.stderr.write(`[${R()}] INFO: ${e} ${N(t)}
|
|
15
|
+
`):process.stderr.write(`[${R()}] INFO: ${e}
|
|
16
|
+
`))}function ir(e,t){P<=2&&(t!==void 0?process.stderr.write(`[${R()}] WARN: ${e} ${N(t)}
|
|
17
|
+
`):process.stderr.write(`[${R()}] WARN: ${e}
|
|
18
|
+
`))}function sr(e,t){P<=3&&(t!==void 0?process.stderr.write(`[${R()}] ERROR: ${e} ${N(t)}
|
|
19
|
+
`):process.stderr.write(`[${R()}] ERROR: ${e}
|
|
20
|
+
`))}function N(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 ar=/^[A-Za-z0-9:._*-]{1,64}$/,cr=/^[A-Za-z0-9_-][A-Za-z0-9 _-]{0,30}[A-Za-z0-9_-]$/,ur=/^[0-9][0-9A-Za-z.+-]{0,40}$/;function dr(e){if(!e||typeof e!="object")throw new TypeError("requestContext must be an object");let t=Object.keys(e).filter(n=>n!=="surface"&&n!=="client");if(t.length>0)throw new TypeError(`requestContext does not accept: ${t.join(", ")}`);if(typeof e.surface!="string"||!ar.test(e.surface))throw new TypeError("requestContext.surface must match /^[A-Za-z0-9:._*-]{1,64}$/");if(e.client===void 0)return Object.freeze({surface:e.surface});let r=e.client;if(!r||typeof r!="object"||Object.keys(r).some(n=>n!=="name"&&n!=="version"))throw new TypeError("requestContext.client must be { name, version }");if(typeof r.name!="string"||!cr.test(r.name))throw new TypeError("requestContext.client.name must be 2-32 characters of letters, digits, space, _ or -");if(typeof r.version!="string"||!ur.test(r.version))throw new TypeError("requestContext.client.version must start with a digit, e.g. 1.2.3");return Object.freeze({surface:e.surface,client:Object.freeze({name:r.name,version:r.version})})}function lr(e){return e?{"X-Xeno-Surface":e.surface,...e.client?{"X-Xeno-Client":`${e.client.name}/${e.client.version}`}:{}}:{}}var S=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})}},L={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitterMs:300};function D(e,t){let r=process.env[e],n=r?Number.parseInt(r,10):Number.NaN;return!Number.isFinite(n)||n<0?t:n}function fr(e={}){let t=Math.max(0,e.maxRetries??D("XENO_API_MAX_RETRIES",L.maxRetries)),r=Math.max(50,e.baseDelayMs??D("XENO_API_BASE_DELAY_MS",L.baseDelayMs)),n=Math.max(r,e.maxDelayMs??D("XENO_API_MAX_DELAY_MS",L.maxDelayMs)),o=Math.max(0,e.jitterMs??D("XENO_API_RETRY_JITTER_MS",L.jitterMs));return{maxRetries:t,baseDelayMs:r,maxDelayMs:n,jitterMs:o}}function pr(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 Re(e){let t=e.toLowerCase();return t.includes("rate limit")||t.includes("too many requests")||t.includes("429")}function mr(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 j(e){if(e instanceof S)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 Re(r)?{statusCode:429}:{}}var V="408|425|429|500|502|503|504";function xe(e){let t=new RegExp(`(?:\\bstatus(?:[ _-]?code)?\\b\\s*[=:]?\\s*|\\bhttp\\b\\s*|\\bapi\\b\\s*|\\bcode\\b\\s*[=:]\\s*|\\berror\\b\\s*)(?:${V})\\b`,"i"),r=new RegExp(`\\b(?:${V})\\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*(?:${V})\\b`);return t.test(e)||r.test(e)||n.test(e)}function Te(e){if(e&&typeof e=="object"&&"retryable"in e)return e.retryable===!0;if(e instanceof S){let{statusCode:t}=j(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:xe(e.message)?!0:Re(e.message)||mr(e.message.toLowerCase())}return!1}function gr(e){if(e.onAbort)return e.onAbort();let t=new Error("The operation was aborted");return t.name="AbortError",t}async function yr(e,t={}){let r=fr(t),n;for(let o=0;o<=r.maxRetries;o++)try{if(t.signal?.aborted)throw gr(t);return t.onBeforeAttempt?.(o),await e()}catch(i){if(n=i,!(t.shouldRetry?t.shouldRetry(i,o):Te(i))||o===r.maxRetries)throw i;let a=j(i),c=pr(o,a,r),l=t.getDelayMs?.(i,o,c),p=typeof l=="number"&&l>=0?l:c;await new Promise(u=>setTimeout(u,p))}throw n}var _e=(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(s=>s.codePointAt(0)>127).length,i=Math.ceil(e.length/n);return Math.max(1,i+Math.ceil(o*.35))},ve=Object.freeze({id:"xeno-conservative-v1",source:"estimated",countText:_e,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 hr(e,t,r=ve){return{tokens:Math.max(0,Math.ceil(r.countText(e,t))),source:r.source,adapterId:r.id}}function Ae(e){return e?Math.ceil(e.length/4):0}function Er(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 br(e,t){return Ae(e)<=t}function wr(e,t){return Math.max(0,t-e)}var Rr={"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 xr(e,t,r){let n=Rr[e];return n?t/1e6*n.input+r/1e6*n.output:0}function Tr(e){return e<=0?"$0.00":e<.001?"<$0.001":e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}var Pe=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,Pe.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 Ce(e){return e.replace(/\\/g,"/").toLowerCase()}var vr=["golden","solution","answer","expected"],Ar=["expected","golden","reference","answer","answers"],Pr=new Set([";","&&","||","|"]);function Se(e){return Ce(e).replace(/^\.\/+/,"").split("/").map(t=>t.trim()).filter(t=>t.length>0)}function kr(e){return vr.some(t=>e.includes(t))}function ke(e){return Ar.some(t=>e.includes(t))}function Ie(e){return e.split("::",1)[0]?.split("?",1)[0]?.split("#",1)[0]??e}function B(e){let t=e.trim().replace(/^[({]+/,"").replace(/[),;]+$/,"");return(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1)),t}function Cr(e){return e.match(/"[^"]*"|'[^']*'|&&|\|\||[;|]|[^\s;|&]+/g)?.map(B).filter(t=>t.length>0)??[]}function Oe(e){let t=Se(e),r=Ie(t.at(-1)??"");return ke(r)||t.some(n=>ke(n))}function Me(e){let t=Ce(B(e));return!t||t==="/dev/null"||t.startsWith("/tmp/")||t.startsWith("tmp/")||t.startsWith("/var/tmp/")||t.startsWith("var/tmp/")?!1:t.startsWith("/app/")||t.startsWith("./")?!0:!t.startsWith("/")}function Sr(e){return/[\\/]/.test(e)||/\.[A-Za-z0-9]{1,8}$/.test(e)}function Ir(e){let t=Cr(e);for(let r=0;r<t.length;r+=1){let n=t[r]?.toLowerCase();if(n!=="cp"&&n!=="mv"&&n!=="rsync"&&n!=="install")continue;let o=[];for(let s=r+1;s<t.length;s+=1){let a=t[s];if(!a||Pr.has(a))break;a!=="--"&&(a.startsWith("-")||o.push(a))}if(o.length<2)continue;let i=o.at(-1);if(Me(i)){for(let s of o.slice(0,-1))if(Sr(s)&&Oe(s))return{sourcePath:s,destinationPath:i,operation:n}}}return null}function Or(e){let t=[/\bcat\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*>\s*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i,/\bdd\b[\s\S]*?\bif=(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))[\s\S]*?\bof=(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/i];for(let r of t){let n=e.match(r);if(!n)continue;let o=B(n[1]??n[2]??n[3]??""),i=B(n[4]??n[5]??n[6]??"");if(!(!o||!i)&&Oe(o)&&Me(i))return{sourcePath:o,destinationPath:i,operation:r.source.startsWith("\\bdd")?"dd":"redirect"}}return null}function W(){return process.env.XENO_BENCHMARK_MODE?.trim().toLowerCase()==="terminal-bench"}function K(e){let t=Se(e);if(t.includes("solution")||t.includes("xeno-audit")||t.includes(".xeno")&&t.includes("audit"))return!0;let r=Ie(t.at(-1)??"");return t.includes("tests")&&kr(r)}function Mr(e){return W()?e.filter(t=>!K(t)):e}function $r(e){return`Benchmark safety: access to verifier answer or benchmark trace artifacts is blocked (${e}). Use task inputs and verifier logic, not golden, solution, or agent audit files.`}function Nr(e){return e.split(/[\s"'`;|&]+/).map(t=>t.trim()).filter(t=>t.length>0&&/[\\/]/.test(t)).some(t=>K(t))}function Lr(e){if(!W())return null;let t=Ir(e)??Or(e);return t?["[xeno guidance]",`Benchmark safety blocked ${t.operation} from reference-like source ${t.sourcePath} to protected destination ${t.destinationPath}.`,"Do not copy expected, golden, reference, or answer files over task inputs or submission artifacts to make validation pass.","If a previous check polluted an input, restore/regenerate the original source input, then rerun the actual script or program under test."].join(`
|
|
21
|
+
`):null}function Dr(e){return/^data:([^;,]+)[;,]/i.exec(e.trim())?.[1]}function $e(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 ${Dr(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(`
|
|
22
22
|
|
|
23
|
-
`).trim()}function
|
|
24
|
-
`)}function
|
|
25
|
-
`)}}function rn(t){return Array.isArray(t)&&t.some(e=>e.type!=="text")}function on(t){return typeof t=="string"?ht(t):t}function sn(t,e){return{type:"tool_result",tool_use_id:t,content:xt(e),...e.assistantContent&&e.assistantContent.length>0?{assistant_content:e.assistantContent}:{},...e.assistantOnlyContent&&e.assistantOnlyContent.length>0?{assistant_only_content:e.assistantOnlyContent}:{},is_error:!e.success,...e.operation?{operation:e.operation}:{},...e.evidence&&e.evidence.length>0?{evidence:e.evidence}:{},...e.webContext?{web_context:e.webContext}:{},...e.retryable!==void 0?{retryable:e.retryable}:{}}}function an(t,e={}){for(let n of t){let r=n.codePointAt(0);if(r===127)return!0;if(!(r>31)&&!(r===9&&e.allowTab===!0)&&!((r===10||r===13)&&e.allowLineBreaks===!0))return!0}return!1}0&&(module.exports={ApiTransientError,HOME_DIR,IS_LINUX,IS_MAC,IS_WINDOWS,LogLevel,OS_VERSION,PLATFORM,accountTextTokens,appendDurableLine,appendLine,benchmarkLeakError,buildToolResultBlock,buildToolResultText,calculateCost,commandMentionsBenchmarkLeak,conservativeTokenAccountingAdapter,copyTextToClipboard,createSafeRegex,debug,decodeTextBuffer,deleteDir,deleteFile,detectLineEnding,detectPreferredLineEnding,detectTextEncoding,encodeTextBuffer,ensureDir,error,estimateTokens,estimateTokensForModel,existsSync,filterBenchmarkLeakPaths,findSimilarFile,fitsInBudget,formatCost,getAgentHome,getBenchmarkReferenceOverwriteHint,getBoolean,getConfigDir,getLogLevel,getNumber,getProjectConfigDir,getRetryErrorContext,getShellName,getString,getToolResultTransportContent,hasDir,hasDisallowedAsciiControlCharacter,hasFile,hasFrontmatter,hasMixedLineEndings,hasNonTextToolResultContent,hasTransientStatusMention,info,isBenchmarkLeakPath,isBenchmarkMode,isGitRepo,isPathSafe,isRetryableError,listDirs,listFiles,normalizeLineEndings,normalizeXenoRequestContext,parseDocument,parseJsonLines,pathIdentityKey,readFileSafe,readIfExists,readTextFile,remainingBudget,renameReplacingWithRetry,safeJsonParse,safeJsonStringify,safeRegexTest,safeResolvePath,setLogLevel,stringifyDocument,toTransportAssistantBlocks,toolAssistantContentToText,toolResultContentToText,truncateToTokens,validateRegexPattern,validateRequired,warn,withRetry,writeAtomic,writeTextFile,xenoRequestContextHeaders});
|
|
23
|
+
`).trim()}function Ne(e){let t=e.trim();return t.length>0?[{type:"text",text:t}]:[]}function Br(e){return typeof e=="string"?e:$e(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(`
|
|
24
|
+
`)}function Xr(e){let t=e.assistant_content&&e.assistant_content.length>0?e.assistant_content:typeof e.content=="string"?Ne(e.content):e.content,r=e.assistant_only_content??[],n=Fr(e),o=[...t,...r,...n?[n]:[]];return o.length>0?o:e.content}function Fr(e){let t=e.operation;if(!t)return null;let r=e.evidence??t.evidence??[],n=r.filter(i=>i.status==="verified").length,o=r.filter(i=>i.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(i=>!!i).join(`
|
|
25
|
+
`)}}function zr(e){return Array.isArray(e)&&e.some(t=>t.type!=="text")}function Hr(e){return typeof e=="string"?Ne(e):e}function Ur(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 qr(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"),I=require("node:net");var b="[redacted]";var Vr=[[/-----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 De(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function k(e,t=[]){if(!e)return e;let r=e,n=[...new Set([...t].filter(o=>typeof o=="string"&&o.length>=12))].sort((o,i)=>i.length-o.length);for(let o of n){r=r.replace(new RegExp(`(?<![A-Za-z0-9_-])${De(o)}(?![A-Za-z0-9_-])`,"g"),b);let i=encodeURIComponent(o);i!==o&&(r=r.replace(new RegExp(`(?<![A-Za-z0-9_-])${De(i)}(?![A-Za-z0-9_-])`,"g"),b))}for(let[o,i]of Vr)o.lastIndex=0,r=r.replace(o,i);return r}function G(e,t,r){try{Object.defineProperty(e,t,{value:r,writable:!0,configurable:!0,enumerable:!1})}catch{}}function Y(e,t=[],r=0){if(!(e instanceof Error)||r>6)return e;let n=[...t],o=k(e.message,n);if(o!==e.message&&G(e,"message",o),typeof e.stack=="string"){let s=k(e.stack,n);s!==e.stack&&G(e,"stack",s)}let i=e.cause;if(i instanceof Error)Y(i,n,r+1);else if(i!=null){let s;try{s=typeof i=="string"?i:JSON.stringify(i)??String(i)}catch{s=String(i)}let a=k(s,n);a!==s&&G(e,"cause",a)}for(let s of Object.keys(e)){let a=e[s];if(typeof a=="string"){let c=k(a,n);if(c!==a)try{e[s]=c}catch{}}}return e}var X=class extends Error{category;code;retryable;providerId;statusCode;retryAfterMs;requestId;providerCode;remedy;constructor(t,r){super(k(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),Y(this)}};var ze=new Set(["metadata.google.internal","metadata.azure.internal","instance-data.ec2.internal"]);function m(e){return new X(`Provider endpoint rejected: ${e}`,{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"})}function jr(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 Be(e){let t=jr(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];(0,I.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=x(e);return(0,I.isIP)(t)===4?Be(t):t==="::"||t==="::0"?"unspecified":t==="::1"?"loopback":t.startsWith("::ffff:")?Be(t.slice(7)):/^f[cd]/.test(t)?"private":/^fe[89ab]/.test(t)?"link-local":"public"}function Xe(e){return e==="example"||e.endsWith(".example")||e==="test"||e.endsWith(".test")||e==="invalid"||e.endsWith(".invalid")}function Wr(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(ze.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,""),i=(0,I.isIP)(o)?He(o):null;if(i==="link-local"||i==="unspecified")throw m(`${i} destinations are forbidden`);if(n==="public-https"&&(i==="private"||i==="loopback"||Wr(r.hostname)))throw m("private and loopback destinations require the local-network profile");if(n==="local-network"&&r.protocol==="http:"&&i==="public"&&!t.allowedHosts?.includes(r.hostname))throw m("local-network HTTP must resolve to loopback or a private address");return r}async function qe(e,t={}){let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(ze.has(r))throw m("cloud metadata destinations are forbidden");let n=new Set((t.allowedHosts??[]).map(s=>s.toLowerCase())),o=(0,I.isIP)(r)?[r]:Xe(r)?[]:t.resolveHostname?await t.resolveHostname(r):(await(0,Fe.lookup)(r,{all:!0,verbatim:!0})).map(s=>s.address);if(!o.length&&!Xe(r))throw m("DNS resolution returned no addresses");let i=t.profile??"public-https";for(let s of o){let a=He(s);if(a==="link-local"||a==="unspecified")throw m(`DNS resolved to a forbidden ${a} address`);if(i==="public-https"&&a!=="public"&&!n.has(r))throw m(`DNS resolved public endpoint to ${a} address ${s}`);if(i==="local-network"&&e.protocol==="http:"&&a==="public"&&!n.has(r))throw m(`local-network HTTP resolved to public address ${s}`)}return o}var Ve=require("node:http"),je=require("node:https"),Z=require("node:net"),We=require("node:events");function Ke(e,t,r){return{dispatch(n,o){let i,s=!1,a=u=>{s||(s=!0,i?.destroy(),o.onError(u))},c=t[0];if(!c||!(0,Z.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??{},p=(e.protocol==="https:"?je.request:Ve.request)(new URL(n.path,e.origin),{method:n.method,headers:l,agent:!1,rejectUnauthorized:!0,lookup:(u,g,_)=>{let h={address:c,family:(0,Z.isIP)(c)};typeof g=="object"&&g.all?_(null,[h]):_(null,c,h.family)}},u=>{i=u;let g=u.rawHeaders.map(h=>Buffer.from(h)),_=()=>u.resume();o.onHeaders(u.statusCode??500,g,_,u.statusMessage??"")===!1&&u.pause(),u.on("data",h=>{o.onData(h)||u.pause()}),u.on("end",()=>{s||(s=!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 p.on("socket",u=>{u.once("connect",()=>{if(!u.remoteAddress||x(u.remoteAddress)!==x(c)){p.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?.()})}),p.on("error",a),o.onConnect(u=>p.destroy(u??new Error("Provider request aborted"))),(async()=>{try{let u=n.body;if(typeof u=="string"||u instanceof Uint8Array)p.end(u);else{if(u)for await(let g of u){if(p.destroyed)return;p.write(g)||await(0,We.once)(p,"drain")}p.end()}}catch(u){p.destroy(u instanceof Error?u:new Error("Provider request body failed"))}})(),!0}}}async function Kr(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 i=await Ge(qe(o,r.policy),t.signal);if(!i.length)throw new Error("Pinned endpoint resolution returned no addresses.");if(r.authorizeAddress&&i.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 s=fetch(n,{...t,redirect:"manual",credentials:"omit",dispatcher:Ke(n,i)});s.then(c=>{t.signal?.aborted&&c.body?.cancel().catch(()=>{})},()=>{});let a=await Ge(s,t.signal);if(a.redirected)throw await a.body?.cancel(),new Error("Pinned endpoint transport followed a redirect without authorization.");return a}async function Ge(e,t){if(!t)return e;let r,n=new Promise((o,i)=>{r=()=>i(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,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,getLogLevel,getNumber,getProjectConfigDir,getRetryErrorContext,getShellName,getString,getToolResultTransportContent,hasDir,hasDisallowedAsciiControlCharacter,hasFile,hasFrontmatter,hasMixedLineEndings,hasNonTextToolResultContent,hasTransientStatusMention,info,isBenchmarkLeakPath,isBenchmarkMode,isGitRepo,isGitRepoAsync,isPathSafe,isRetryableError,listDirs,listFiles,normalizeLineEndings,normalizeXenoRequestContext,parseDocument,parseJsonLines,pathIdentityKey,readFileSafe,readIfExists,readTextFile,remainingBudget,renameReplacingWithRetry,safeJsonParse,safeJsonStringify,safeRegexTest,safeResolvePath,setLogLevel,stringifyDocument,toTransportAssistantBlocks,toolAssistantContentToText,toolResultContentToText,truncateToTokens,validateRegexPattern,validateRequired,warn,withRetry,writeAtomic,writeTextFile,xenoRequestContextHeaders});
|
package/dist/utils/index.d.cts
CHANGED
|
@@ -27,7 +27,7 @@ declare function writeTextFile(filePath: string, content: string, options?: {
|
|
|
27
27
|
lineEnding?: LineEnding;
|
|
28
28
|
preserveLineEndings?: boolean;
|
|
29
29
|
}): Promise<void>;
|
|
30
|
-
declare function detectPreferredLineEnding(baseDir: string): Promise<LineEnding>;
|
|
30
|
+
declare function detectPreferredLineEnding(baseDir: string, workspaceRoot?: string): Promise<LineEnding>;
|
|
31
31
|
declare function findSimilarFile(filePath: string, boundary?: string): string | null;
|
|
32
32
|
declare function readIfExists(filePath: string): Promise<string | null>;
|
|
33
33
|
declare function existsSync(filePath: string): boolean;
|
|
@@ -59,6 +59,7 @@ declare function getConfigDir(): string;
|
|
|
59
59
|
declare function getProjectConfigDir(cwd: string): string;
|
|
60
60
|
declare function getShellName(): string;
|
|
61
61
|
declare function isGitRepo(cwd: string): boolean;
|
|
62
|
+
declare function isGitRepoAsync(cwd: string): Promise<boolean>;
|
|
62
63
|
declare function validateRequired(params: Record<string, unknown>, required: string[]): string | null;
|
|
63
64
|
declare function getString(params: Record<string, unknown>, key: string, defaultValue?: string): string;
|
|
64
65
|
declare function getNumber(params: Record<string, unknown>, key: string, defaultValue?: number): number;
|
|
@@ -312,4 +313,15 @@ interface XenoAsciiControlCharacterPolicy {
|
|
|
312
313
|
allowLineBreaks?: boolean;
|
|
313
314
|
}
|
|
314
315
|
declare function hasDisallowedAsciiControlCharacter(value: string, policy?: XenoAsciiControlCharacterPolicy): boolean;
|
|
315
|
-
|
|
316
|
+
type DirectEndpointProfile = "public-https" | "local-network";
|
|
317
|
+
interface DirectEndpointPolicy {
|
|
318
|
+
profile?: DirectEndpointProfile;
|
|
319
|
+
allowedHosts?: string[];
|
|
320
|
+
resolveHostname?: (hostname: string) => Promise<string[]>;
|
|
321
|
+
}
|
|
322
|
+
interface PinnedEndpointFetchOptions {
|
|
323
|
+
policy?: DirectEndpointPolicy;
|
|
324
|
+
authorizeAddress?: (address: string, url: URL) => boolean;
|
|
325
|
+
}
|
|
326
|
+
declare function fetchPinnedEndpoint(url: string | URL, init: RequestInit, options?: PinnedEndpointFetchOptions): Promise<Response>;
|
|
327
|
+
export { ApiTransientError, type ApiTransientErrorClassification, HOME_DIR, IS_LINUX, IS_MAC, IS_WINDOWS, type LineEnding, LogLevel, OS_VERSION, PLATFORM, type ParsedDocument, type PinnedEndpointFetchOptions, type RetryErrorContext, type RetryOptions, type TextEncoding, type TextFileContents, type TokenAccountingAdapter, type TokenAccountingResult, type TokenAccountingSource, type TokenEstimator, type XenoAsciiControlCharacterPolicy, type XenoRequestContext, accountTextTokens, appendDurableLine, appendLine, benchmarkLeakError, buildToolResultBlock, buildToolResultText, calculateCost, 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, getLogLevel, getNumber, getProjectConfigDir, getRetryErrorContext, getShellName, getString, getToolResultTransportContent, hasDir, hasDisallowedAsciiControlCharacter, hasFile, hasFrontmatter, hasMixedLineEndings, hasNonTextToolResultContent, hasTransientStatusMention, info, isBenchmarkLeakPath, isBenchmarkMode, isGitRepo, isGitRepoAsync, isPathSafe, isRetryableError, listDirs, listFiles, normalizeLineEndings, normalizeXenoRequestContext, parseDocument, parseJsonLines, pathIdentityKey, readFileSafe, readIfExists, readTextFile, remainingBudget, renameReplacingWithRetry, safeJsonParse, safeJsonStringify, safeRegexTest, safeResolvePath, setLogLevel, stringifyDocument, toTransportAssistantBlocks, toolAssistantContentToText, toolResultContentToText, truncateToTokens, validateRegexPattern, validateRequired, warn, withRetry, writeAtomic, writeTextFile, xenoRequestContextHeaders };
|