@xenosystem/agent-cli 0.5.51 → 0.5.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +6 -6
- package/dist/metafile-esm.json +1 -1
- package/dist/sdk-build-identity.json +5 -5
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -524,7 +524,7 @@ ${m||"(no new output)"}`,operation:A??void 0,evidence:A?.evidence}}finally{a&&c.
|
|
|
524
524
|
`),n=t.endsWith(`
|
|
525
525
|
`)?t.slice(0,-1):t;return n.length===0?[]:n.split(`
|
|
526
526
|
`)}function Yfe(e){return e.endsWith(`
|
|
527
|
-
`)||e.endsWith("\r")}function Kfe(e){return/[\s"\\\t\r\n]/.test(e)?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\t/g,"\\t").replace(/\r/g,"\\r").replace(/\n/g,"\\n")}"`:e}function q6(e,t){qO(e);let n=uX(e),r=n,i=nme(n);if(t==="xeno")return{schema:n,dialect:t,canonicalSha256:i,projectedSha256:i,changes:[]};let o={dialect:t,root:r,pointers:new Map,anchors:new Map,changes:[],activeReferences:new Set};nM(r,"",o);let s=Ug(r,"#",o);if(!nv(s))throw new Ko(t,"#","provider tool root must remain an object schema");return Mmt(n,s,t),{schema:s,dialect:t,canonicalSha256:i,projectedSha256:nme(s),changes:o.changes}}function vx(e,t){return e.map(n=>{let r=q6(n.input_schema,t);return{definition:{...n,input_schema:r.schema},projection:r}})}function Ug(e,t,n){if(typeof e=="boolean"){if(n.dialect!=="google")return e;if(e)return{};throw new Ko(n.dialect,t,"false schemas are not representable by this provider")}if(typeof e.$ref=="string"){let i=Nmt(e.$ref,t,n);if(n.activeReferences.has(e.$ref))throw new Ko(n.dialect,t,`recursive reference ${e.$ref} cannot be serialized safely`);let o=Object.fromEntries(Object.entries(e).filter(([a])=>a!=="$ref"&&!dX.has(a)));if(Object.keys(o).length>0){if(n.dialect==="google")throw new Ko(n.dialect,t,"$ref siblings require an unsupported intersection");n.activeReferences.add(e.$ref);let a=Ug(i,`${t}/$ref`,n);n.activeReferences.delete(e.$ref);let c=Ug(o,t,n);return n.changes.push({path:t,keyword:"$ref",action:"transformed",reason:"inlined local reference with sibling intersection"}),{allOf:[a,c]}}n.activeReferences.add(e.$ref);let s=Ug(i,`${t}/$ref`,n);return n.activeReferences.delete(e.$ref),n.changes.push({path:t,keyword:"$ref",action:"transformed",reason:"inlined local reference"}),s}let r={};for(let[i,o]of Object.entries(e))if(i!=="$ref"){if(dX.has(i)||i.startsWith("x-")){i==="description"?r.description=o:n.changes.push({path:t,keyword:i,action:"omitted",reason:"provider wire metadata is not required for canonical validation"});continue}if(n.dialect==="google"&&!ZSe.has(i)){if(i==="const"){r.enum=[uX(o)],n.changes.push({path:t,keyword:i,action:"transformed",reason:"Google wire schema represents const as a single-value enum"});continue}if(i==="prefixItems")throw new Ko(n.dialect,t,"tuple prefixItems cannot preserve the provider structural contract");n.changes.push({path:t,keyword:i,action:"omitted",reason:"constraint remains enforced by canonical local validation"});continue}if(i==="type"&&n.dialect==="google"&&Array.isArray(o)){let s=o.filter(a=>a!=="null");if(s.length!==1||o.length!==2)throw new Ko(n.dialect,t,"type union cannot be represented without weakening structure");r.type=s[0],r.nullable=!0,n.changes.push({path:t,keyword:i,action:"transformed",reason:"nullable two-type union mapped to Google nullable"});continue}if(i==="properties"||i==="patternProperties"||i==="$defs"){if(!nv(o))throw new Ko(n.dialect,t,`${i} must be an object`);let s={};for(let[a,c]of Object.entries(o))s[a]=Ug(c,`${t}/${i}/${j6(a)}`,n);r[i]=s;continue}if(["items","contains","additionalProperties","not"].includes(i)){r[i]=Ug(o,`${t}/${i}`,n);continue}if(["prefixItems","allOf","anyOf","oneOf"].includes(i)){if(!Array.isArray(o))throw new Ko(n.dialect,t,`${i} must be an array`);r[i]=o.map((s,a)=>Ug(s,`${t}/${i}/${a}`,n));continue}r[i]=uX(o)}if(n.dialect==="google"){let i=e.type!==void 0||e.properties!==void 0||e.items!==void 0,o=r.type!==void 0||r.properties!==void 0||r.items!==void 0;if(!i&&(e.oneOf!==void 0||e.allOf!==void 0||e.not!==void 0)||i&&!o)throw new Ko(n.dialect,t,"minimum structural contract cannot be represented")}return r}function Mmt(e,t,n){if(t.type!=="object"||!nv(t.properties))throw new Ko(n,"#","root object/properties contract changed");let r=Object.keys(e.properties).sort(),i=Object.keys(t.properties).sort();if(JSON.stringify(r)!==JSON.stringify(i))throw new Ko(n,"#","root property identity changed");let o=[...e.required??[]].sort(),s=Array.isArray(t.required)?[...t.required].sort():[];if(JSON.stringify(o)!==JSON.stringify(s))throw new Ko(n,"#","root required-property contract changed")}function nM(e,t,n){if(n.pointers.set(t,e),typeof e!="boolean"){typeof e.$anchor=="string"&&n.anchors.set(e.$anchor,e);for(let r of["$defs","properties","patternProperties"]){let i=e[r];if(nv(i))for(let[o,s]of Object.entries(i))nM(s,`${t}/${r}/${j6(o)}`,n)}for(let r of["items","contains","additionalProperties","not"]){let i=e[r];(typeof i=="boolean"||nv(i))&&nM(i,`${t}/${r}`,n)}for(let r of["prefixItems","allOf","anyOf","oneOf"]){let i=e[r];Array.isArray(i)&&i.forEach((o,s)=>nM(o,`${t}/${r}/${s}`,n))}}}function Nmt(e,t,n){if(!e.startsWith("#"))throw new Ko(n.dialect,t,"remote references are forbidden");if(e==="#")return n.root;if(e.startsWith("#/")){let r=e.slice(1).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~")).map(j6).join("/"),i=n.pointers.get(r);if(i!==void 0)return i}else{let r=n.anchors.get(e.slice(1));if(r!==void 0)return r}throw new Ko(n.dialect,t,`unresolved reference ${e}`)}function nme(e){return Bmt("sha256").update(lX(e)).digest("hex")}function lX(e){return Array.isArray(e)?`[${e.map(lX).join(",")}]`:nv(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${lX(e[t])}`).join(",")}}`:JSON.stringify(e)}function uX(e){return JSON.parse(JSON.stringify(e))}function j6(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function nv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function H6(e,t=Date.now()){if(!e)return;let n=Number(e.trim());if(Number.isFinite(n)&&n>=0)return Math.ceil(n*1e3);let r=Date.parse(e);if(Number.isFinite(r))return Math.max(0,r-t)}function Omt(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e,n=t.error;if(typeof n=="string")return n;if(n&&typeof n=="object"){let r=n;if(typeof r.message=="string")return r.message;if(typeof r.type=="string")return r.type}return typeof t.message=="string"?t.message:""}function FG(e,t){return t.some(n=>e.includes(n))}function W6(e){let t=Omt(e.body).trim(),n=t.toLowerCase(),r=t?`: ${t.slice(0,1e3)}`:"",i={providerId:e.providerId,statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId};return e.statusCode===401?new jn(`Provider authentication failed${r}`,{...i,category:"authentication",code:"PROVIDER_AUTHENTICATION_FAILED"}):e.statusCode===403?new jn(`Provider authorization failed${r}`,{...i,category:"authorization",code:"PROVIDER_AUTHORIZATION_FAILED"}):FG(n,["api key not valid","invalid api key","api key expired","api_key_invalid","invalid authentication credentials","missing api key"])?new jn(`Provider authentication failed${r}`,{...i,category:"authentication",code:"PROVIDER_AUTHENTICATION_FAILED"}):e.statusCode===429?new jn(`Provider rate limit reached${r}`,{...i,category:"rate_limit",code:"PROVIDER_RATE_LIMITED",retryable:!0}):bSe(n)?new jn(`Provider context window exceeded${r}`,{...i,category:"context_overflow",code:"PROVIDER_CONTEXT_OVERFLOW"}):FG(n,["safety","content policy","blocked_reason","responsible_ai_policy_violation"])?new jn(`Provider safety policy refused the request${r}`,{...i,category:"safety_refusal",code:"PROVIDER_SAFETY_REFUSAL"}):e.statusCode===404||FG(n,["model not found","model does not exist","unsupported model"])?new jn(`Provider model is unavailable${r}`,{...i,category:"unsupported_model",code:"PROVIDER_MODEL_UNSUPPORTED"}):e.statusCode===408||e.statusCode===504?new jn(`Provider request timed out${r}`,{...i,category:"timeout",code:"PROVIDER_TIMEOUT",retryable:!0}):e.statusCode>=500||e.statusCode===409||e.statusCode===425?new jn(`Provider server error${r}`,{...i,category:"server",code:"PROVIDER_SERVER_ERROR",retryable:!0}):new jn(`Provider rejected the request with HTTP ${e.statusCode}${r}`,{...i,category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"})}function wn(e,t,n){return new jn(`Malformed ${e} response: ${t}`,{providerId:e,category:"malformed_response",code:"PROVIDER_MALFORMED_RESPONSE",...n!==void 0?{cause:n}:{}})}function rv(e,t){return $n("xeno.provider.capability_mismatches",1,{component:"provider_contract",provider:e,capability:t,error_code:"provider_capability_unsupported"}),new jn(`${e} does not advertise the required ${t} capability`,{providerId:e,category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"})}function js(e){return new jn(`Provider endpoint rejected: ${e}`,{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"})}function Lmt(e){let t=e.split(".");if(t.length!==4)return null;let n=t.map(r=>Number(r));return n.every(r=>Number.isInteger(r)&&r>=0&&r<=255)?n:null}function rme(e){let t=Lmt(e);if(!t)return"public";let[n,r]=t;return n===0?"unspecified":n===127?"loopback":n===169&&r===254?"link-local":n===10||n===172&&r>=16&&r<=31||n===192&&r===168?"private":"public"}function pX(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"").split("%")[0];ZD(t)===6&&(t=new URL(`http://[${t}]`).hostname.slice(1,-1));let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),i=Number.parseInt(n[2],16);return`${r>>8}.${r&255}.${i>>8}.${i&255}`}return t}function eCe(e){let t=pX(e);return ZD(t)===4?rme(t):t==="::"||t==="::0"?"unspecified":t==="::1"?"loopback":t.startsWith("::ffff:")?rme(t.slice(7)):/^f[cd]/.test(t)?"private":/^fe[89ab]/.test(t)?"link-local":"public"}function ime(e){return e==="example"||e.endsWith(".example")||e==="test"||e.endsWith(".test")||e==="invalid"||e.endsWith(".invalid")}function Qmt(e){return e==="localhost"||e.endsWith(".localhost")}function Ix(e,t={}){let n;try{n=new URL(e)}catch{throw js("the URL is invalid")}if(n.username||n.password)throw js("embedded credentials are forbidden");if(n.hash||n.search)throw js("base URLs cannot contain a query or fragment");if(!n.hostname||n.hostname.includes("%"))throw js("the hostname is empty or ambiguous");if(J6.has(n.hostname.toLowerCase()))throw js("cloud metadata destinations are forbidden");if(n.protocol!=="https:"&&n.protocol!=="http:")throw js(`scheme ${n.protocol} is unsupported`);let r=t.profile??"public-https";if(n.protocol==="http:"&&r!=="local-network")throw js("plain HTTP requires the explicit local-network profile");let i=n.hostname.replace(/^\[|\]$/g,""),o=ZD(i)?eCe(i):null;if(o==="link-local"||o==="unspecified")throw js(`${o} destinations are forbidden`);if(r==="public-https"&&(o==="private"||o==="loopback"||Qmt(n.hostname)))throw js("private and loopback destinations require the local-network profile");if(r==="local-network"&&n.protocol==="http:"&&o==="public"&&!t.allowedHosts?.includes(n.hostname))throw js("local-network HTTP must resolve to loopback or a private address");return n}async function G6(e,t={}){await tCe(e,t)}async function tCe(e,t={}){let n=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(J6.has(n))throw js("cloud metadata destinations are forbidden");let r=new Set((t.allowedHosts??[]).map(s=>s.toLowerCase())),i=ZD(n)?[n]:ime(n)?[]:t.resolveHostname?await t.resolveHostname(n):(await Dmt(n,{all:!0,verbatim:!0})).map(s=>s.address);if(!i.length&&!ime(n))throw js("DNS resolution returned no addresses");let o=t.profile??"public-https";for(let s of i){let a=eCe(s);if(a==="link-local"||a==="unspecified")throw js(`DNS resolved to a forbidden ${a} address`);if(o==="public-https"&&a!=="public"&&!r.has(n))throw js(`DNS resolved public endpoint to ${a} address ${s}`);if(o==="local-network"&&e.protocol==="http:"&&a==="public"&&!r.has(n))throw js(`local-network HTTP resolved to public address ${s}`)}return i}function jmt(e,t){return{dispatch(n,r){let i,o=!1,s=u=>{o||(o=!0,i?.destroy(),r.onError(u))},a=t[0];if(!a||!ome(a)||new URL(n.origin).origin!==e.origin)return queueMicrotask(()=>s(new Error("Provider connection has no authorized pinned address"))),!0;let c=n.headers??{},l=(e.protocol==="https:"?Umt:Fmt)(new URL(n.path,e.origin),{method:n.method,headers:c,agent:!1,rejectUnauthorized:!0,lookup:(u,d,p)=>{let f={address:a,family:ome(a)};typeof d=="object"&&d.all?p(null,[f]):p(null,a,f.family)}},u=>{i=u;let d=u.rawHeaders.map(f=>Buffer.from(f)),p=()=>u.resume();r.onHeaders(u.statusCode??500,d,p,u.statusMessage??"")===!1&&u.pause(),u.on("data",f=>{r.onData(f)||u.pause()}),u.on("end",()=>{o||(o=!0,r.onComplete(u.rawTrailers.map(f=>Buffer.from(f))))}),u.on("error",s),u.on("aborted",()=>s(new Error("Provider response was interrupted")))});return l.on("socket",u=>{u.once("connect",()=>{(!u.remoteAddress||pX(u.remoteAddress)!==pX(a))&&l.destroy(new Error("Provider socket did not connect to its authorized address"))})}),l.on("error",s),r.onConnect(u=>l.destroy(u??new Error("Provider request aborted"))),(async()=>{try{let u=n.body;if(typeof u=="string"||u instanceof Uint8Array)l.end(u);else{if(u)for await(let d of u){if(l.destroyed)return;l.write(d)||await qmt(l,"drain")}l.end()}}catch(u){l.destroy(u instanceof Error?u:new Error("Provider request body failed"))}})(),!0}}}function Hmt(e={}){for(let[t,n]of Object.entries(e))if(n!==void 0&&(!Number.isSafeInteger(n)||n<1))throw wn("provider-transport",`${t} must be a positive safe integer`);return{connectTimeoutMs:Math.max(100,e.connectTimeoutMs??qg.connectTimeoutMs),totalTimeoutMs:Math.max(100,e.totalTimeoutMs??qg.totalTimeoutMs),idleTimeoutMs:Math.max(100,e.idleTimeoutMs??qg.idleTimeoutMs),maxResponseBytes:Math.max(1024,e.maxResponseBytes??qg.maxResponseBytes),maxHeaderBytes:Math.max(1024,e.maxHeaderBytes??qg.maxHeaderBytes),maxEventBytes:Math.max(1024,e.maxEventBytes??qg.maxEventBytes)}}async function qC(e,t){let n,r=new Promise((i,o)=>{n=()=>o(new Error("Provider operation aborted")),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()});try{return await Promise.race([e,r])}finally{t.removeEventListener("abort",n)}}function KM(e,t,n,r){try{return e.decode(t,{stream:n})}catch{throw wn(r,"response is not valid UTF-8")}}function qG(e,t,n){let r=new jn(t==="cancelled"?"Provider request was cancelled":"Provider request timed out",{providerId:e,category:t,code:t==="cancelled"?"PROVIDER_CANCELLED":"PROVIDER_TIMEOUT",retryable:t==="timeout",...n!==void 0?{cause:n}:{}});return t==="cancelled"&&(r.name="AbortError"),r}function Wmt(e){let t=0;return e.forEach((n,r)=>{t+=Buffer.byteLength(r)+Buffer.byteLength(n)+4}),t}async function nCe(e,t,n,r){if(!e.body)return"";let i=e.body.getReader(),o=new TextDecoder("utf-8",{fatal:!0}),s=0,a="",c,l=()=>{c&&clearTimeout(c),c=setTimeout(()=>r.abort("idle-timeout"),n.idleTimeoutMs)};l();try{for(;;){let{value:u,done:d}=await qC(i.read(),r.signal);if(d)break;if(l(),s+=u.byteLength,s>n.maxResponseBytes)throw wn(t,`response exceeded ${n.maxResponseBytes} bytes`);a+=KM(o,u,!0,t)}return a+=KM(o,void 0,!1,t),a}finally{c&&clearTimeout(c),i.cancel().catch(()=>{}),i.releaseLock()}}async function rCe(e,t,n,r){let i=UG.now(),o=Hmt(n.limits);$n("xeno.provider.requests",1,{component:"provider_transport",provider:n.providerId,transport:"http"});let s=new AbortController,a=null,c=t.signal,l=()=>s.abort("caller");if(c?.aborted)throw qG(n.providerId,"cancelled");c?.addEventListener("abort",l,{once:!0});let u=setTimeout(()=>{a="total",s.abort("total-timeout")},o.totalTimeoutMs),d=setTimeout(()=>{a="connect",s.abort("connect-timeout")},o.connectTimeoutMs),p;try{let f=await qC(tCe(e,n.endpointPolicy),s.signal);if(s.signal.aborted)throw new Error("Provider request aborted before dispatch");let m={...t,signal:s.signal,redirect:"manual",dispatcher:jmt(e,f)},h=fetch(e,m);h.then(w=>{s.signal.aborted&&w.body?.cancel().catch(()=>{})},()=>{});let g=await qC(h,s.signal);if(p=g,clearTimeout(d),Wmt(g.headers)>o.maxHeaderBytes)throw wn(n.providerId,`response headers exceeded ${o.maxHeaderBytes} bytes`);if(g.redirected||g.status>=300&&g.status<400)throw new jn("Provider redirects are disabled",{providerId:n.providerId,category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED",statusCode:g.status});let A=g.headers.get("content-length");if(A&&/^\d+$/.test(A)&&Number(A)>o.maxResponseBytes)throw wn(n.providerId,`response exceeded ${o.maxResponseBytes} bytes`);if(!g.ok){let w=await nCe(g,n.providerId,o,s),b=w;try{b=w?JSON.parse(w):{}}catch{}throw W6({providerId:n.providerId,statusCode:g.status,body:b,retryAfterMs:H6(g.headers.get("retry-after")),requestId:g.headers.get("request-id")??g.headers.get("x-request-id")??void 0})}let y=await qC(r(g,s,o),s.signal);return $n("xeno.provider.request_results",1,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"success"}),Di("xeno.provider.request_duration_ms",UG.now()-i,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"success"}),y}catch(f){let m;throw f instanceof jn?m=f:c?.aborted||s.signal.reason==="caller"?m=qG(n.providerId,"cancelled",f):a||s.signal.reason==="idle-timeout"?m=qG(n.providerId,"timeout",f):m=new jn("Provider transport failed",{providerId:n.providerId,category:"transport",code:"PROVIDER_TRANSPORT_ERROR",retryable:!0,cause:f}),s.abort("request-failed"),p?.body&&!p.body.locked&&p.body.cancel().catch(()=>{}),$n("xeno.provider.request_results",1,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"error",category:m.category,error_code:m.code}),Di("xeno.provider.request_duration_ms",UG.now()-i,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"error",category:m.category}),m}finally{clearTimeout(d),clearTimeout(u),c?.removeEventListener("abort",l)}}async function iCe(e,t,n){return rCe(e,t,n,async(r,i,o)=>{let s=await nCe(r,n.providerId,o,i),a;try{a=s?JSON.parse(s):{}}catch(c){throw wn(n.providerId,"body is not valid JSON",c)}if(!a||typeof a!="object"||Array.isArray(a))throw wn(n.providerId,"JSON body must be an object");return a})}async function eL(e,t,n,r){return rCe(e,t,n,async(i,o,s)=>{if(!i.body)throw wn(n.providerId,"stream response has no body");let a=i.body.getReader(),c=new TextDecoder("utf-8",{fatal:!0}),l="",u=0,d="message",p=[],f,m=()=>{f&&clearTimeout(f),f=setTimeout(()=>o.abort("idle-timeout"),s.idleTimeoutMs)},h=async()=>{if(p.length===0){d="message";return}let g=p.join(`
|
|
527
|
+
`)||e.endsWith("\r")}function Kfe(e){return/[\s"\\\t\r\n]/.test(e)?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\t/g,"\\t").replace(/\r/g,"\\r").replace(/\n/g,"\\n")}"`:e}function q6(e,t){qO(e);let n=uX(e),r=n,i=nme(n);if(t==="xeno")return{schema:n,dialect:t,canonicalSha256:i,projectedSha256:i,changes:[]};let o={dialect:t,root:r,pointers:new Map,anchors:new Map,changes:[],activeReferences:new Set};nM(r,"",o);let s=Ug(r,"#",o);if(!nv(s))throw new Ko(t,"#","provider tool root must remain an object schema");return Mmt(n,s,t),{schema:s,dialect:t,canonicalSha256:i,projectedSha256:nme(s),changes:o.changes}}function vx(e,t){return e.map(n=>{let r=q6(n.input_schema,t);return{definition:{...n,input_schema:r.schema},projection:r}})}function Ug(e,t,n){if(typeof e=="boolean"){if(n.dialect!=="google")return e;if(e)return{};throw new Ko(n.dialect,t,"false schemas are not representable by this provider")}if(typeof e.$ref=="string"){let i=Nmt(e.$ref,t,n);if(n.activeReferences.has(e.$ref))throw new Ko(n.dialect,t,`recursive reference ${e.$ref} cannot be serialized safely`);let o=Object.fromEntries(Object.entries(e).filter(([a])=>a!=="$ref"&&!dX.has(a)));if(Object.keys(o).length>0){if(n.dialect==="google")throw new Ko(n.dialect,t,"$ref siblings require an unsupported intersection");n.activeReferences.add(e.$ref);let a=Ug(i,`${t}/$ref`,n);n.activeReferences.delete(e.$ref);let c=Ug(o,t,n);return n.changes.push({path:t,keyword:"$ref",action:"transformed",reason:"inlined local reference with sibling intersection"}),{allOf:[a,c]}}n.activeReferences.add(e.$ref);let s=Ug(i,`${t}/$ref`,n);return n.activeReferences.delete(e.$ref),n.changes.push({path:t,keyword:"$ref",action:"transformed",reason:"inlined local reference"}),s}let r={};for(let[i,o]of Object.entries(e))if(i!=="$ref"){if(dX.has(i)||i.startsWith("x-")){i==="description"?r.description=o:n.changes.push({path:t,keyword:i,action:"omitted",reason:"provider wire metadata is not required for canonical validation"});continue}if(n.dialect==="google"&&!ZSe.has(i)){if(i==="const"){r.enum=[uX(o)],n.changes.push({path:t,keyword:i,action:"transformed",reason:"Google wire schema represents const as a single-value enum"});continue}if(i==="prefixItems")throw new Ko(n.dialect,t,"tuple prefixItems cannot preserve the provider structural contract");n.changes.push({path:t,keyword:i,action:"omitted",reason:"constraint remains enforced by canonical local validation"});continue}if(i==="type"&&n.dialect==="google"&&Array.isArray(o)){let s=o.filter(a=>a!=="null");if(s.length!==1||o.length!==2)throw new Ko(n.dialect,t,"type union cannot be represented without weakening structure");r.type=s[0],r.nullable=!0,n.changes.push({path:t,keyword:i,action:"transformed",reason:"nullable two-type union mapped to Google nullable"});continue}if(i==="properties"||i==="patternProperties"||i==="$defs"){if(!nv(o))throw new Ko(n.dialect,t,`${i} must be an object`);let s={};for(let[a,c]of Object.entries(o))s[a]=Ug(c,`${t}/${i}/${j6(a)}`,n);r[i]=s;continue}if(["items","contains","additionalProperties","not"].includes(i)){r[i]=Ug(o,`${t}/${i}`,n);continue}if(["prefixItems","allOf","anyOf","oneOf"].includes(i)){if(!Array.isArray(o))throw new Ko(n.dialect,t,`${i} must be an array`);r[i]=o.map((s,a)=>Ug(s,`${t}/${i}/${a}`,n));continue}r[i]=uX(o)}if(n.dialect==="google"){let i=e.type!==void 0||e.properties!==void 0||e.items!==void 0,o=r.type!==void 0||r.properties!==void 0||r.items!==void 0;if(!i&&(e.oneOf!==void 0||e.allOf!==void 0||e.not!==void 0)||i&&!o)throw new Ko(n.dialect,t,"minimum structural contract cannot be represented")}return r}function Mmt(e,t,n){if(t.type!=="object"||!nv(t.properties))throw new Ko(n,"#","root object/properties contract changed");let r=Object.keys(e.properties).sort(),i=Object.keys(t.properties).sort();if(JSON.stringify(r)!==JSON.stringify(i))throw new Ko(n,"#","root property identity changed");let o=[...e.required??[]].sort(),s=Array.isArray(t.required)?[...t.required].sort():[];if(JSON.stringify(o)!==JSON.stringify(s))throw new Ko(n,"#","root required-property contract changed")}function nM(e,t,n){if(n.pointers.set(t,e),typeof e!="boolean"){typeof e.$anchor=="string"&&n.anchors.set(e.$anchor,e);for(let r of["$defs","properties","patternProperties"]){let i=e[r];if(nv(i))for(let[o,s]of Object.entries(i))nM(s,`${t}/${r}/${j6(o)}`,n)}for(let r of["items","contains","additionalProperties","not"]){let i=e[r];(typeof i=="boolean"||nv(i))&&nM(i,`${t}/${r}`,n)}for(let r of["prefixItems","allOf","anyOf","oneOf"]){let i=e[r];Array.isArray(i)&&i.forEach((o,s)=>nM(o,`${t}/${r}/${s}`,n))}}}function Nmt(e,t,n){if(!e.startsWith("#"))throw new Ko(n.dialect,t,"remote references are forbidden");if(e==="#")return n.root;if(e.startsWith("#/")){let r=e.slice(1).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~")).map(j6).join("/"),i=n.pointers.get(r);if(i!==void 0)return i}else{let r=n.anchors.get(e.slice(1));if(r!==void 0)return r}throw new Ko(n.dialect,t,`unresolved reference ${e}`)}function nme(e){return Bmt("sha256").update(lX(e)).digest("hex")}function lX(e){return Array.isArray(e)?`[${e.map(lX).join(",")}]`:nv(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${lX(e[t])}`).join(",")}}`:JSON.stringify(e)}function uX(e){return JSON.parse(JSON.stringify(e))}function j6(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function nv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function H6(e,t=Date.now()){if(!e)return;let n=Number(e.trim());if(Number.isFinite(n)&&n>=0)return Math.ceil(n*1e3);let r=Date.parse(e);if(Number.isFinite(r))return Math.max(0,r-t)}function Omt(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e,n=t.error;if(typeof n=="string")return n;if(n&&typeof n=="object"){let r=n;if(typeof r.message=="string")return r.message;if(typeof r.type=="string")return r.type}return typeof t.message=="string"?t.message:""}function FG(e,t){return t.some(n=>e.includes(n))}function W6(e){let t=Omt(e.body).trim(),n=t.toLowerCase(),r=t?`: ${t.slice(0,1e3)}`:"",i={providerId:e.providerId,statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId};return e.statusCode===401?new jn(`Provider authentication failed${r}`,{...i,category:"authentication",code:"PROVIDER_AUTHENTICATION_FAILED"}):e.statusCode===403?new jn(`Provider authorization failed${r}`,{...i,category:"authorization",code:"PROVIDER_AUTHORIZATION_FAILED"}):FG(n,["api key not valid","invalid api key","api key expired","api_key_invalid","invalid authentication credentials","missing api key"])?new jn(`Provider authentication failed${r}`,{...i,category:"authentication",code:"PROVIDER_AUTHENTICATION_FAILED"}):e.statusCode===429?new jn(`Provider rate limit reached${r}`,{...i,category:"rate_limit",code:"PROVIDER_RATE_LIMITED",retryable:!0}):bSe(n)?new jn(`Provider context window exceeded${r}`,{...i,category:"context_overflow",code:"PROVIDER_CONTEXT_OVERFLOW"}):FG(n,["safety","content policy","blocked_reason","responsible_ai_policy_violation"])?new jn(`Provider safety policy refused the request${r}`,{...i,category:"safety_refusal",code:"PROVIDER_SAFETY_REFUSAL"}):e.statusCode===404||FG(n,["model not found","model does not exist","unsupported model","unknown provider for model"])?new jn(`Provider model is unavailable${r}`,{...i,category:"unsupported_model",code:"PROVIDER_MODEL_UNSUPPORTED"}):e.statusCode===408||e.statusCode===504?new jn(`Provider request timed out${r}`,{...i,category:"timeout",code:"PROVIDER_TIMEOUT",retryable:!0}):e.statusCode>=500||e.statusCode===409||e.statusCode===425?new jn(`Provider server error${r}`,{...i,category:"server",code:"PROVIDER_SERVER_ERROR",retryable:!0}):new jn(`Provider rejected the request with HTTP ${e.statusCode}${r}`,{...i,category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"})}function wn(e,t,n){return new jn(`Malformed ${e} response: ${t}`,{providerId:e,category:"malformed_response",code:"PROVIDER_MALFORMED_RESPONSE",...n!==void 0?{cause:n}:{}})}function rv(e,t){return $n("xeno.provider.capability_mismatches",1,{component:"provider_contract",provider:e,capability:t,error_code:"provider_capability_unsupported"}),new jn(`${e} does not advertise the required ${t} capability`,{providerId:e,category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"})}function js(e){return new jn(`Provider endpoint rejected: ${e}`,{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"})}function Lmt(e){let t=e.split(".");if(t.length!==4)return null;let n=t.map(r=>Number(r));return n.every(r=>Number.isInteger(r)&&r>=0&&r<=255)?n:null}function rme(e){let t=Lmt(e);if(!t)return"public";let[n,r]=t;return n===0?"unspecified":n===127?"loopback":n===169&&r===254?"link-local":n===10||n===172&&r>=16&&r<=31||n===192&&r===168?"private":"public"}function pX(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"").split("%")[0];ZD(t)===6&&(t=new URL(`http://[${t}]`).hostname.slice(1,-1));let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),i=Number.parseInt(n[2],16);return`${r>>8}.${r&255}.${i>>8}.${i&255}`}return t}function eCe(e){let t=pX(e);return ZD(t)===4?rme(t):t==="::"||t==="::0"?"unspecified":t==="::1"?"loopback":t.startsWith("::ffff:")?rme(t.slice(7)):/^f[cd]/.test(t)?"private":/^fe[89ab]/.test(t)?"link-local":"public"}function ime(e){return e==="example"||e.endsWith(".example")||e==="test"||e.endsWith(".test")||e==="invalid"||e.endsWith(".invalid")}function Qmt(e){return e==="localhost"||e.endsWith(".localhost")}function Ix(e,t={}){let n;try{n=new URL(e)}catch{throw js("the URL is invalid")}if(n.username||n.password)throw js("embedded credentials are forbidden");if(n.hash||n.search)throw js("base URLs cannot contain a query or fragment");if(!n.hostname||n.hostname.includes("%"))throw js("the hostname is empty or ambiguous");if(J6.has(n.hostname.toLowerCase()))throw js("cloud metadata destinations are forbidden");if(n.protocol!=="https:"&&n.protocol!=="http:")throw js(`scheme ${n.protocol} is unsupported`);let r=t.profile??"public-https";if(n.protocol==="http:"&&r!=="local-network")throw js("plain HTTP requires the explicit local-network profile");let i=n.hostname.replace(/^\[|\]$/g,""),o=ZD(i)?eCe(i):null;if(o==="link-local"||o==="unspecified")throw js(`${o} destinations are forbidden`);if(r==="public-https"&&(o==="private"||o==="loopback"||Qmt(n.hostname)))throw js("private and loopback destinations require the local-network profile");if(r==="local-network"&&n.protocol==="http:"&&o==="public"&&!t.allowedHosts?.includes(n.hostname))throw js("local-network HTTP must resolve to loopback or a private address");return n}async function G6(e,t={}){await tCe(e,t)}async function tCe(e,t={}){let n=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(J6.has(n))throw js("cloud metadata destinations are forbidden");let r=new Set((t.allowedHosts??[]).map(s=>s.toLowerCase())),i=ZD(n)?[n]:ime(n)?[]:t.resolveHostname?await t.resolveHostname(n):(await Dmt(n,{all:!0,verbatim:!0})).map(s=>s.address);if(!i.length&&!ime(n))throw js("DNS resolution returned no addresses");let o=t.profile??"public-https";for(let s of i){let a=eCe(s);if(a==="link-local"||a==="unspecified")throw js(`DNS resolved to a forbidden ${a} address`);if(o==="public-https"&&a!=="public"&&!r.has(n))throw js(`DNS resolved public endpoint to ${a} address ${s}`);if(o==="local-network"&&e.protocol==="http:"&&a==="public"&&!r.has(n))throw js(`local-network HTTP resolved to public address ${s}`)}return i}function jmt(e,t){return{dispatch(n,r){let i,o=!1,s=u=>{o||(o=!0,i?.destroy(),r.onError(u))},a=t[0];if(!a||!ome(a)||new URL(n.origin).origin!==e.origin)return queueMicrotask(()=>s(new Error("Provider connection has no authorized pinned address"))),!0;let c=n.headers??{},l=(e.protocol==="https:"?Umt:Fmt)(new URL(n.path,e.origin),{method:n.method,headers:c,agent:!1,rejectUnauthorized:!0,lookup:(u,d,p)=>{let f={address:a,family:ome(a)};typeof d=="object"&&d.all?p(null,[f]):p(null,a,f.family)}},u=>{i=u;let d=u.rawHeaders.map(f=>Buffer.from(f)),p=()=>u.resume();r.onHeaders(u.statusCode??500,d,p,u.statusMessage??"")===!1&&u.pause(),u.on("data",f=>{r.onData(f)||u.pause()}),u.on("end",()=>{o||(o=!0,r.onComplete(u.rawTrailers.map(f=>Buffer.from(f))))}),u.on("error",s),u.on("aborted",()=>s(new Error("Provider response was interrupted")))});return l.on("socket",u=>{u.once("connect",()=>{(!u.remoteAddress||pX(u.remoteAddress)!==pX(a))&&l.destroy(new Error("Provider socket did not connect to its authorized address"))})}),l.on("error",s),r.onConnect(u=>l.destroy(u??new Error("Provider request aborted"))),(async()=>{try{let u=n.body;if(typeof u=="string"||u instanceof Uint8Array)l.end(u);else{if(u)for await(let d of u){if(l.destroyed)return;l.write(d)||await qmt(l,"drain")}l.end()}}catch(u){l.destroy(u instanceof Error?u:new Error("Provider request body failed"))}})(),!0}}}function Hmt(e={}){for(let[t,n]of Object.entries(e))if(n!==void 0&&(!Number.isSafeInteger(n)||n<1))throw wn("provider-transport",`${t} must be a positive safe integer`);return{connectTimeoutMs:Math.max(100,e.connectTimeoutMs??qg.connectTimeoutMs),totalTimeoutMs:Math.max(100,e.totalTimeoutMs??qg.totalTimeoutMs),idleTimeoutMs:Math.max(100,e.idleTimeoutMs??qg.idleTimeoutMs),maxResponseBytes:Math.max(1024,e.maxResponseBytes??qg.maxResponseBytes),maxHeaderBytes:Math.max(1024,e.maxHeaderBytes??qg.maxHeaderBytes),maxEventBytes:Math.max(1024,e.maxEventBytes??qg.maxEventBytes)}}async function qC(e,t){let n,r=new Promise((i,o)=>{n=()=>o(new Error("Provider operation aborted")),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()});try{return await Promise.race([e,r])}finally{t.removeEventListener("abort",n)}}function KM(e,t,n,r){try{return e.decode(t,{stream:n})}catch{throw wn(r,"response is not valid UTF-8")}}function qG(e,t,n){let r=new jn(t==="cancelled"?"Provider request was cancelled":"Provider request timed out",{providerId:e,category:t,code:t==="cancelled"?"PROVIDER_CANCELLED":"PROVIDER_TIMEOUT",retryable:t==="timeout",...n!==void 0?{cause:n}:{}});return t==="cancelled"&&(r.name="AbortError"),r}function Wmt(e){let t=0;return e.forEach((n,r)=>{t+=Buffer.byteLength(r)+Buffer.byteLength(n)+4}),t}async function nCe(e,t,n,r){if(!e.body)return"";let i=e.body.getReader(),o=new TextDecoder("utf-8",{fatal:!0}),s=0,a="",c,l=()=>{c&&clearTimeout(c),c=setTimeout(()=>r.abort("idle-timeout"),n.idleTimeoutMs)};l();try{for(;;){let{value:u,done:d}=await qC(i.read(),r.signal);if(d)break;if(l(),s+=u.byteLength,s>n.maxResponseBytes)throw wn(t,`response exceeded ${n.maxResponseBytes} bytes`);a+=KM(o,u,!0,t)}return a+=KM(o,void 0,!1,t),a}finally{c&&clearTimeout(c),i.cancel().catch(()=>{}),i.releaseLock()}}async function rCe(e,t,n,r){let i=UG.now(),o=Hmt(n.limits);$n("xeno.provider.requests",1,{component:"provider_transport",provider:n.providerId,transport:"http"});let s=new AbortController,a=null,c=t.signal,l=()=>s.abort("caller");if(c?.aborted)throw qG(n.providerId,"cancelled");c?.addEventListener("abort",l,{once:!0});let u=setTimeout(()=>{a="total",s.abort("total-timeout")},o.totalTimeoutMs),d=setTimeout(()=>{a="connect",s.abort("connect-timeout")},o.connectTimeoutMs),p;try{let f=await qC(tCe(e,n.endpointPolicy),s.signal);if(s.signal.aborted)throw new Error("Provider request aborted before dispatch");let m={...t,signal:s.signal,redirect:"manual",dispatcher:jmt(e,f)},h=fetch(e,m);h.then(w=>{s.signal.aborted&&w.body?.cancel().catch(()=>{})},()=>{});let g=await qC(h,s.signal);if(p=g,clearTimeout(d),Wmt(g.headers)>o.maxHeaderBytes)throw wn(n.providerId,`response headers exceeded ${o.maxHeaderBytes} bytes`);if(g.redirected||g.status>=300&&g.status<400)throw new jn("Provider redirects are disabled",{providerId:n.providerId,category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED",statusCode:g.status});let A=g.headers.get("content-length");if(A&&/^\d+$/.test(A)&&Number(A)>o.maxResponseBytes)throw wn(n.providerId,`response exceeded ${o.maxResponseBytes} bytes`);if(!g.ok){let w=await nCe(g,n.providerId,o,s),b=w;try{b=w?JSON.parse(w):{}}catch{}throw W6({providerId:n.providerId,statusCode:g.status,body:b,retryAfterMs:H6(g.headers.get("retry-after")),requestId:g.headers.get("request-id")??g.headers.get("x-request-id")??void 0})}let y=await qC(r(g,s,o),s.signal);return $n("xeno.provider.request_results",1,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"success"}),Di("xeno.provider.request_duration_ms",UG.now()-i,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"success"}),y}catch(f){let m;throw f instanceof jn?m=f:c?.aborted||s.signal.reason==="caller"?m=qG(n.providerId,"cancelled",f):a||s.signal.reason==="idle-timeout"?m=qG(n.providerId,"timeout",f):m=new jn("Provider transport failed",{providerId:n.providerId,category:"transport",code:"PROVIDER_TRANSPORT_ERROR",retryable:!0,cause:f}),s.abort("request-failed"),p?.body&&!p.body.locked&&p.body.cancel().catch(()=>{}),$n("xeno.provider.request_results",1,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"error",category:m.category,error_code:m.code}),Di("xeno.provider.request_duration_ms",UG.now()-i,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"error",category:m.category}),m}finally{clearTimeout(d),clearTimeout(u),c?.removeEventListener("abort",l)}}async function iCe(e,t,n){return rCe(e,t,n,async(r,i,o)=>{let s=await nCe(r,n.providerId,o,i),a;try{a=s?JSON.parse(s):{}}catch(c){throw wn(n.providerId,"body is not valid JSON",c)}if(!a||typeof a!="object"||Array.isArray(a))throw wn(n.providerId,"JSON body must be an object");return a})}async function eL(e,t,n,r){return rCe(e,t,n,async(i,o,s)=>{if(!i.body)throw wn(n.providerId,"stream response has no body");let a=i.body.getReader(),c=new TextDecoder("utf-8",{fatal:!0}),l="",u=0,d="message",p=[],f,m=()=>{f&&clearTimeout(f),f=setTimeout(()=>o.abort("idle-timeout"),s.idleTimeoutMs)},h=async()=>{if(p.length===0){d="message";return}let g=p.join(`
|
|
528
528
|
`);if(Buffer.byteLength(g)>s.maxEventBytes)throw wn(n.providerId,`stream event exceeded ${s.maxEventBytes} bytes`);await r({event:d,data:g}),d="message",p=[]};m();try{for(;;){let{value:g,done:A}=await qC(a.read(),o.signal);if(A)break;if(m(),u+=g.byteLength,u>s.maxResponseBytes)throw wn(n.providerId,`stream exceeded ${s.maxResponseBytes} bytes`);for(l+=KM(c,g,!0,n.providerId);;){let y=l.indexOf(`
|
|
529
529
|
`);if(y<0)break;let w=l.slice(0,y).replace(/\r$/,"");if(l=l.slice(y+1),!w)await h();else if(!w.startsWith(":")){let b=w.indexOf(":"),I=b<0?w:w.slice(0,b),v=b<0?"":w.slice(b+1).replace(/^ /,"");I==="event"?d=v:I==="data"&&p.push(v)}}}if(l+=KM(c,void 0,!1,n.providerId),l.trim())for(let g of l.split(/\r?\n/))g.startsWith("data:")?p.push(g.slice(5).replace(/^ /,"")):g.startsWith("event:")&&(d=g.slice(6).trim());await h()}finally{f&&clearTimeout(f),a.cancel().catch(()=>{}),a.releaseLock()}})}function oCe(e){let t=e.kind==="anthropic"?"https://api.anthropic.com":e.kind==="google"?"https://generativelanguage.googleapis.com":e.kind==="openai-responses"?"https://api.openai.com":null;if(!e.baseURL&&!t)throw new jn("Generic OpenAI-compatible providers require baseURL",{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"});let n=Ix(e.baseURL??t,{profile:e.endpointProfile,allowedHosts:e.allowedHosts,resolveHostname:e.resolveHostname});return n.pathname=n.pathname.replace(/\/$/,""),n}function vC(e,t){let n=new URL(e.toString());return n.pathname=`${n.pathname.replace(/\/$/,"")}/${t.replace(/^\//,"")}`,n}function sCe(e){let t=e.authentication??{type:"bearer"};if(t.type==="none"||!e.apiKey)return{};if(t.type==="bearer")return{authorization:`Bearer ${e.apiKey}`};let n=t.header.trim().toLowerCase(),r=new Set(["host","content-length","connection","transfer-encoding","cookie","set-cookie","proxy-authorization"]);if(!/^[a-z0-9-]{1,80}$/.test(n)||r.has(n))throw new jn("Generic provider authentication header is invalid",{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"});let i=t.prefix??"";if(/[\r\n]/.test(i))throw new jn("Generic provider authentication prefix is invalid",{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"});return{[n]:`${i}${e.apiKey}`}}function Jmt(e){let t;if(e.kind==="openai-compatible"){if(!e.capabilityProfile)throw new jn("Generic OpenAI-compatible providers require an explicit capabilityProfile",{category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"});t={...e.capabilityProfile};for(let n of["structuredOutput","promptCaching"])if(t[n])throw rv("direct-openai-compatible",n);if(!!e.streaming!=!!t.streaming)throw new jn("Generic endpoint streaming config must match capabilityProfile.streaming",{category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"})}else t={...mCe[e.kind],streaming:!!e.streaming,reasoningMetadata:e.kind==="anthropic"&&!!e.streaming};return{...t,vision:t.imageInput}}function Ex(e,t){return{providerId:t,endpointPolicy:{profile:e.endpointProfile,allowedHosts:e.allowedHosts,resolveHostname:e.resolveHostname},limits:e.transportLimits}}function aCe(e){let t=/^data:([^;,]+);base64,([a-z0-9+/=\r\n]+)$/i.exec(e);return t?{mediaType:t[1],data:t[2].replace(/\s/g,"")}:null}function Sx(e){let t=Array.isArray(e.assistant_content)?e.assistant_content:[],n=Array.isArray(e.assistant_only_content)?e.assistant_only_content:[];return[...t,...n].filter(r=>r?.type==="image_url")}function cCe(e){return e.filter(t=>t?.type==="image_url")}function lCe(e){return e.some(t=>Array.isArray(t.content)&&t.content.some(n=>n.type==="image_url"||n.type==="tool_result"&&Sx(n).length>0))}function sme(e){let t=aCe(e.image_url.url);return t?{type:"image",source:{type:"base64",media_type:t.mediaType,data:t.data}}:{type:"image",source:{type:"url",url:e.image_url.url}}}function Xmt(e){return e.map(t=>({role:t.role,content:typeof t.content=="string"?t.content:t.content.flatMap(n=>{if(n.type==="image_url")return[sme(n)];if(n.type==="text")return[n];if(n.type==="tool_use")return[{type:"tool_use",id:n.id,name:n.name,input:n.input}];let r=Sx(n),i=[{type:"text",text:Tm(n.content)}];return i.push(...r.map(sme)),[{type:"tool_result",tool_use_id:n.tool_use_id,content:i,is_error:n.is_error}]})}))}function zmt(e){return{type:"input_image",image_url:e.image_url.url,detail:e.image_url.detail??"auto"}}function Ymt(e){let t=[];for(let n of e){if(typeof n.content=="string"){t.push({role:n.role,content:n.content});continue}let r=n.content.filter(o=>o.type==="text").map(o=>o.text).join(`
|
|
530
530
|
`),i=[...cCe(n.content),...n.content.flatMap(o=>o.type==="tool_result"?Sx(o):[])];(r||i.length)&&t.push({role:n.role,content:[...r?[{type:"input_text",text:r}]:[],...i.map(zmt)]});for(let o of n.content)o.type==="tool_use"?t.push({type:"function_call",call_id:o.id,name:o.name,arguments:JSON.stringify(o.input)}):o.type==="tool_result"&&t.push({type:"function_call_output",call_id:o.tool_use_id,output:Tm(o.content)})}return t}function ame(e){let t=aCe(e.image_url.url);return t?{inlineData:{mimeType:t.mediaType,data:t.data}}:{fileData:{fileUri:e.image_url.url}}}function Kmt(e){let t=new Map;for(let n of e)if(Array.isArray(n.content))for(let r of n.content)r.type==="tool_use"&&t.set(r.id,r.name);return e.map(n=>typeof n.content=="string"?{role:n.role==="assistant"?"model":"user",parts:[{text:n.content}]}:{role:n.role==="assistant"?"model":"user",parts:n.content.flatMap(r=>{if(r.type==="image_url")return[ame(r)];if(r.type==="text")return[{text:r.text}];if(r.type==="tool_use")return[{functionCall:{id:r.id,name:r.name,args:r.input},...r.provider_metadata?.thoughtSignature?{thoughtSignature:r.provider_metadata.thoughtSignature}:{}}];let i=Tm(r.content);return[{functionResponse:{id:r.tool_use_id,name:t.get(r.tool_use_id)??"unknown_tool",response:r.is_error?{error:i}:{result:i}}},...Sx(r).map(ame)]})})}function uCe(e,t){let n=t?[{role:"system",content:t}]:[];for(let r of e){if(typeof r.content=="string"){n.push({role:r.role,content:r.content});continue}let i=r.content.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
@@ -2657,7 +2657,7 @@ public static class XenoProtectedWrite {
|
|
|
2657
2657
|
$request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
2658
2658
|
$result = [XenoProtectedWrite]::Run([string]$request.path, [Convert]::FromBase64String([string]$request.payload), [bool]$request.ifAbsent, [string]$request.operationId, [string]$request.operation, [int]$request.parentPid, [long]$request.parentBirth)
|
|
2659
2659
|
$result | ConvertTo-Json -Compress
|
|
2660
|
-
`});Kgt=z(()=>{"use strict";is(),Dme(),Dme(),kL="ai.xenostudio.xeno-agent.mcp",EL="xeno.host.state.encryption-key.v1",SC="aes-256-gcm",dm=32,oM=12,_X=16,Ab="b64:",sN="dpapi:v1:"}),NY=z(()=>{"use strict";gL(),agt(),KSe(),YSe(),G0(),ywe(),sO(),wv(),fO(),c0e(),fgt(),wgt(),Uz(),Ugt(),Xz(),e8(),Kgt()}),C0e={};Vnt(C0e,{createDelegatedXenoAgent:()=>ql});OY=z(()=>{"use strict";lY(),gY(),NY(),Tx(),x0e=[{tool:"Write",decision:"deny"},{tool:"Edit",decision:"deny"},{tool:"MemoryWrite",decision:"deny"},{tool:"Bash",decision:"deny"},{tool:"dispatch_agent",decision:"deny"}]});Tx=z(()=>{"use strict";EA(),Cm(),oY(),BCe(),AY(),FO(),NY(),BA(),S0=8192,C0=50});pv();Tp="0.9.34";ka();rs();DA=class{filePath;sessionId;labels;sequence=0;writeQueue=Promise.resolve();constructor(e){this.filePath=e.filePath,this.sessionId=e.sessionId,this.labels={run_id:e.runId,agent_id:e.agentId,parent_agent_id:e.parentAgentId,workspace:e.workspace,model:e.model,provider:e.provider}}get path(){return this.filePath}async append(e){let t=nAt(),n={id:t,sequence:this.sequence++,timestamp:new Date().toISOString(),session_id:e.session_id??this.sessionId,...this.labels,...e};return this.writeQueue=this.writeQueue.then(async()=>{await _B(this.filePath,JSON.stringify(n))}),await this.writeQueue,t}async read(e){let t=await fi(this.filePath);if(!t)return[];let n=lC(t);return e?.eventType&&(n=n.filter(r=>r.event_type===e.eventType)),e?.traceId&&(n=n.filter(r=>r.trace_id===e.traceId)),e?.limit!==void 0&&(n=n.slice(-Math.max(0,e.limit))),n}async tail(e=20){let t=Math.max(1,Math.min(e,500));return this.read({limit:t})}async exportJson(e){let t=await this.read();return await Li(e,JSON.stringify(t,null,2)),t.length}async flush(){await this.writeQueue}};twe();swe();_0e=1,LY=new Set(["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read"]),QY=new Set(["browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download","browser.record.start","browser.record.stop"]),FY=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),UY=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),QA=[...LY,...QY,...FY,...UY];Ue=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoAutomationError"}code;detail};e8();sAt=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,Ume=1048576;B0e=1,M0e=1,HY=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation"],WY=["draft","pending_review","approved","rejected","superseded","archived"],GY=["public","internal","confidential","restricted"],JY=["agent","tool","user","system","integration"],TL=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],PL=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];dO();Px=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(n=>({...n}))}},XY=class extends Error{constructor(e,t){super(`Artifact state cannot transition from ${e} to ${t}`),this.fromState=e,this.toState=t,this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},mAt={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},hAt="[\\u0000-\\u001f\\u007f]",gAt=new RegExp(hAt),N0e=/^[a-f0-9]{64}$/,AAt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,wAt=new Set(WY),yAt=new Set(GY),bAt=new Set(JY),vAt=new Set(HY),IAt=new Set(TL),kAt=new Set(PL);At=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoArtifactRepositoryError"}code;detail},BL=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(e={}){this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>(this.idCounter+=1,`${t}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),e.initialState&&this.hydrate(e.initialState)}exportState(){return{schemaVersion:1,records:[...this.records.values()].flatMap(t=>[...t.values()]).sort(Gme).map(t=>({artifact:GC(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(Rs(e),this.assertInitialState(e),e.revision!==1)throw new At("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:e.artifactId,revision:e.revision});if(this.records.has(e.artifactId))throw new At("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=GC(e),n=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),r={artifact:t,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,r]])),this.currentRevisions.set(t.artifactId,t.revision),$g(r)}async createRevision(e,t={}){Rs(e),this.assertInitialState(e);let n=this.getMutable(e.artifactId);this.assertVersion(n,t.expectedRecordVersion);let r=n.artifact.revision+1;if(e.revision!==r||e.predecessorRevision!==n.artifact.revision)throw new At("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:e.artifactId,currentRevision:n.artifact.revision,requestedRevision:e.revision});if(SAt(e,n.artifact))throw new At("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(n.artifact.state==="archived")throw new At("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){x0(n.artifact.state,"superseded");let a=this.now(),c=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});n.artifact.state="superseded",n.artifact.updatedAt=a,n.lifecycleEvents.push(c),n.recordVersion+=1}let i=GC(e),o=this.createLifecycleEvent({artifact:i,sequence:1,actor:t.actor??i.provenance.producer,fromState:null,toState:i.state,reason:t.reason??`revision-created-from-${n.artifact.revision}`}),s={artifact:i,recordVersion:1,lifecycleEvents:[o],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,s),this.currentRevisions.set(i.artifactId,i.revision),$g(s)}async get(e,t){let n=this.records.get(e);if(!n)return;let r=t??this.currentRevisions.get(e);if(r===void 0)return;let i=n.get(r);return i?$g(i):void 0}async require(e,t){let n=await this.get(e,t);if(!n)throw new At("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return n}async list(e={}){let t=[];for(let[n,r]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(n)))if(e.includeSuperseded)t.push(...r.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let o=r.get(i);o&&t.push(o)}}return t.filter(n=>CAt(n.artifact,e)).sort(Gme).map($g)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((n,r)=>n.artifact.revision-r.artifact.revision).map($g):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),x0(t.artifact.state,e.toState),e.toState==="approved"||e.toState==="rejected"){let o=e.reviewEventId?t.reviewEvents.find(a=>a.eventId===e.reviewEventId&&a.type==="decision-recorded"):void 0,s=$L(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new At("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${e.toState} requires a matching decision event`,{artifactId:e.artifactId,revision:t.artifact.revision});if(e.toState==="approved"&&s.unresolvedComments>0)throw new At("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let n=this.now(),r=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:r,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:n});return t.artifact.state=e.toState,t.artifact.updatedAt=n,t.lifecycleEvents.push(i),t.recordVersion+=1,$g(t)}async appendReviewEvent(e){let t=e.event,n=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(n,e.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new At("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(n,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new At("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let r={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=_L(r,n.artifact);if(i.length>0)throw new Px("XENO artifact review event validation failed",i);return n.reviewEvents.push(r),n.recordVersion+=1,$g(n)}getMutable(e,t){let n=this.records.get(e),r=t??this.currentRevisions.get(e),i=r===void 0?void 0:n?.get(r);if(!i)throw new At("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return i}assertVersion(e,t){if(t!==void 0&&t!==e.recordVersion)throw new At("ARTIFACT_CONFLICT",`Expected record version ${t}, found ${e.recordVersion}`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision,expectedRecordVersion:t,actualRecordVersion:e.recordVersion})}assertInitialState(e){if(e.state!=="draft"&&e.state!=="pending_review")throw new At("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:e.artifactId,revision:e.revision})}assertReviewCommentState(e,t){if(t.type==="comment-added"){if(e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.parentCommentId))throw new At("ARTIFACT_REVIEW_INVALID",`Parent comment ${t.parentCommentId} does not exist`);return}if(t.type!=="comment-resolved"&&t.type!=="comment-reopened")return;if(!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let n=xAt(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&n.resolved)throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!n.resolved)throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is not resolved`)}createLifecycleEvent(e){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:e.artifact.artifactId,revision:e.artifact.revision,sequence:e.sequence,recordedAt:e.recordedAt??this.now(),actor:{...e.actor},fromState:e.fromState,toState:e.toState,...e.reason?{reason:e.reason}:{},...e.reviewEventId?{reviewEventId:e.reviewEventId}:{}}}nextEventId(e){let t=this.idFactory(e);if(typeof t!="string"||t.trim().length===0||this.eventIds.has(t))throw new At("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${e} ID`);return this.eventIds.add(t),t}hydrate(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new At("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((n,r)=>n.artifact.artifactId.localeCompare(r.artifact.artifactId)||n.artifact.revision-r.artifact.revision);for(let n of t){let r=EAt(n,this.eventIds),i=this.records.get(r.artifact.artifactId);if(i||(i=new Map,this.records.set(r.artifact.artifactId,i)),i.has(r.artifact.revision))throw new At("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${r.artifact.artifactId}:${r.artifact.revision}`);i.set(r.artifact.revision,r),this.currentRevisions.set(r.artifact.artifactId,r.artifact.revision)}for(let[n,r]of this.records){let i=[...r.values()].sort((o,s)=>o.artifact.revision-s.artifact.revision);for(let o=0;o<i.length;o+=1){let s=i[o],a=o+1;if(s.artifact.revision!==a)throw new At("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new At("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new At("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new At("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${a} must be superseded`)}}}};MX=32*1024*1024,RAt=1024*1024*1024,TAt=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;Xme=16*1024*1024;Yme=3e4,Kme=1e3,ZY=class{adapter;leaseAuthority;durable;artifactRepository;now;executions=new Map;active=new Map;constructor(e){if(this.adapter=e.adapter,this.leaseAuthority=e.leaseAuthority,!!e.leaseAuthority==!!e.durable)throw new Error("Choose exactly one legacy or durable automation authority");this.durable=e.durable,this.artifactRepository=e.durable?.artifactRepository??e.artifactRepository,this.now=e.now??(()=>new Date().toISOString())}execute(e,t){e=structuredClone(e);let n=FAt(e),r=this.executions.get(e.operationId);if(r){if(r.fingerprint!==n)throw new Ue("AUTOMATION_OPERATION_CONFLICT",`Operation ${e.operationId} was already submitted with different authority or parameters`);if(this.durable){let a=this.durable;return a.assertCurrent(e).then(()=>r.promise).then(async c=>(await a.assertCurrent(e),structuredClone(c)))}return r.promise}if(this.active.size>=Kme)throw new Ue("AUTOMATION_OPERATION_CONFLICT","Automation active-operation capacity reached");let i=new AbortController,o=UAt(t,i);this.active.set(e.operationId,i);let s=(this.durable?KY(this.durable,e,n,a=>this.executeFresh(e,i.signal,a)):this.executeFresh(e,i.signal)).finally(()=>{o(),this.active.delete(e.operationId)});return this.executions.set(e.operationId,{fingerprint:n,promise:s}),this.durable&&s.then(()=>this.executions.delete(e.operationId),()=>this.executions.delete(e.operationId)),this.trimIdempotencyRecords(),s}async stop(e,t="human-stop"){let n=this.active.get(e);return n?(n.abort(new Error(t)),await this.adapter.stop?.(e,t),!0):!1}async executeFresh(e,t,n){qY(e),eB(t);let r=await this.adapter.manifest();RL(r);let i=zc(e.operation),o=VY(e),s=this.now(),a=await this.adapter.preflight(e,t);OAt(a,this.now()),aN(e,r,a.observedTarget),eB(t);let c=a.evidence??[];JC(c,o,"before");let l=await R0(this.artifactRepository,cN({request:e,manifest:r,policy:o,evidence:c,now:this.now}));if(eB(t),Date.parse(a.expiresAt)<=Date.parse(this.now()))throw new Ue("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let u=jY(e,a.observedTarget),d;if(this.durable){await this.durable.assertCurrent(e);let b=await this.durable.consume(n,e.capabilityLeaseId,e.expectedLeaseVersion,u);if(b.executionDisposition!=="dispatch-once"||b.replayed)throw vp();d=b.lease,await this.durable.assertCurrent(e)}else d=await this.leaseAuthority.consume(e.capabilityLeaseId,e.expectedLeaseVersion,u);let p={contractFingerprint:e.executionContract.fingerprint,lease:d,capabilityUse:u},f;try{eB(t),f=await this.adapter.execute(e,a,p,t)}catch(b){return s4({request:e,manifest:r,descriptorEffect:i.effect,target:a.observedTarget,lease:d,artifacts:l,startedAt:s,completedAt:this.now(),status:t.aborted?"cancelled":"error",code:t.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_ADAPTER_ERROR",message:t.aborted?"Automation operation was stopped":qAt(b)})}if(DAt(f),f.operationId!==void 0&&f.operationId!==e.operationId)throw new Ue("AUTOMATION_RESPONSE_INVALID","Adapter returned another operation identity");let m=LAt(a.observedTarget,f.observedTarget),h;try{aN(e,r,f.observedTarget)}catch(b){h=b instanceof Error?b:new Error(String(b))}let g=f.evidence??[];QAt(c,g);let A=[],y;try{JC(g,o,"after"),JC([...c,...g],o,"recording"),A=await R0(this.artifactRepository,cN({request:e,manifest:r,policy:o,evidence:g,now:this.now}))}catch(b){y=b instanceof Error?b:new Error(String(b))}let w=[...l,...A];return m||h?s4({request:e,manifest:r,descriptorEffect:i.effect,target:f.observedTarget,lease:d,artifacts:w,startedAt:f.startedAt,completedAt:f.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:m??h.message}):y?s4({request:e,manifest:r,descriptorEffect:i.effect,target:f.observedTarget,lease:d,artifacts:w,startedAt:f.startedAt,completedAt:f.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:y.message}):{operationId:e.operationId,status:f.status,effect:i.effect,startedAt:f.startedAt,completedAt:f.completedAt,adapter:D0e(r),target:structuredClone(f.observedTarget),...f.data!==void 0?{data:structuredClone(f.data)}:{},artifacts:w,lease:L0e(d),...f.error?{error:{...f.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>Kme;){let e=this.executions.keys().next().value;if(!e||this.active.has(e))break;this.executions.delete(e)}}};eK=class{constructor(e){this.database=e;try{if(e.exec("PRAGMA busy_timeout=0; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS automation_execution_schema(id INTEGER PRIMARY KEY CHECK(id=1),version INTEGER NOT NULL); INSERT OR IGNORE INTO automation_execution_schema VALUES(1,1);"),e.prepare("SELECT version FROM automation_execution_schema WHERE id=1").get()?.version!==1)throw Error("Unsupported automation execution journal");e.exec("CREATE TABLE IF NOT EXISTS automation_executions(id TEXT PRIMARY KEY,body TEXT NOT NULL)")}catch(t){throw e.close(),this.closed=!0,t}}database;closed=!1;async begin(e){return e=structuredClone(e),OX(e),Eb(e,["operationId","fingerprint","ownerToken"]),this.transaction(()=>{let t=this.read(e.operationId);if(t){if(t.fingerprint!==e.fingerprint)throw tB();return{claimed:!1,record:t}}let n=this.database.prepare("SELECT COUNT(*) AS count FROM automation_executions").get()?.count;if(typeof n!="number"||n>=1e5)throw Error("Automation journal capacity reached; explicit archival required");let r={schemaVersion:1,...e,outcome:{kind:"pending"}};return this.database.prepare("INSERT INTO automation_executions(id,body) VALUES(?,?)").run(e.operationId,Zme(r)),{claimed:!0,record:r}})}async get(e){if(typeof e!="string"||!e.trim()||e.length>1024)throw Error("Invalid automation journal identity");return this.transaction(()=>this.read(e))}async finish(e,t){e=structuredClone(e),t=structuredClone(t),OX(e),Eb(e,["operationId","fingerprint","ownerToken"]);let n={schemaVersion:1,...e,outcome:t};return DX(n),this.transaction(()=>{let r=this.read(e.operationId);if(!r||r.fingerprint!==e.fingerprint||r.ownerToken!==e.ownerToken)throw tB();if(r.outcome.kind!=="pending"){if(JSON.stringify(r.outcome)!==JSON.stringify(t))throw tB();return}this.database.prepare("UPDATE automation_executions SET body=? WHERE id=?").run(Zme(n),e.operationId)})}close(){this.closed||(this.closed=!0,this.database.close())}read(e){let t=this.database.prepare("SELECT CASE WHEN length(body)<=16384 THEN body ELSE NULL END AS body FROM automation_executions WHERE id=?").get(e);if(!t)return;if(typeof t.body!="string")throw Error("Corrupt automation journal size");let n=JSON.parse(t.body);if(DX(n),n.operationId!==e)throw tB();return n}async transaction(e){let t=Date.now()+1e3;for(;;){if(this.closed)throw Error("Automation journal closed");let n=!1;try{this.database.exec("BEGIN IMMEDIATE"),n=!0;let r=e();return this.database.exec("COMMIT"),r}catch(r){if(n)try{this.database.exec("ROLLBACK")}catch{}if(Date.now()>=t||!/SQLITE_BUSY|database is locked/.test(String(r)))throw r;await new Promise(i=>setTimeout(i,10))}}}};HAt=6e4,WAt=48*1024*1024,U0e=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(e){if(this.endpoint=GAt(e.baseUrl),this.token=JAt(e.token),this.timeoutMs=ehe(e.timeoutMs??HAt,1e3,3e5,"timeoutMs"),this.maxResponseBytes=ehe(e.maxResponseBytes??WAt,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=e.fetch??globalThis.fetch,typeof this.fetchImpl!="function")throw new Ue("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}preflight(e,t){return this.request("preflight","POST",e,t)}execute(e,t,n,r){return this.request("execute","POST",{request:e,preflight:t,grant:n},r)}async stop(e,t){await this.request("stop","POST",{operationId:e,reason:t.slice(0,512)})}async request(e,t,n,r){let i=new AbortController,o=YAt(r,i),s=setTimeout(()=>i.abort(new Error("automation transport timeout")),this.timeoutMs);s.unref?.();try{let a=new URL(e,this.endpoint),c=await this.fetchImpl(a,{method:t,redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.token}`,accept:"application/json",...t==="POST"?{"content-type":"application/json"}:{}},...t==="POST"?{body:JSON.stringify(n??{})}:{},signal:i.signal}),l=await XAt(c,this.maxResponseBytes);if(!c.ok){let u=zAt(l);throw new Ue("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${e}: ${u.message}`,{status:c.status,route:e,adapterCode:u.code})}if(!LX(l)||l.ok!==!0||!("result"in l))throw new Ue("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${e} envelope`);return l.result}catch(a){if(a instanceof Ue)throw a;let c=r?.aborted;throw new Ue(c?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",c?"Automation transport was stopped":`XENO Browser ${e} transport failed`,{route:e},{cause:a})}finally{clearTimeout(s),o()}}};_x=["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read","browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download"],ML=class{constructor(e){if(this.options=e,this.base=twt(e.baseUrl),this.fetchImpl=e.fetch??globalThis.fetch,this.timeoutMs=e.timeoutMs??6e4,!nwt(e.token))throw new Error("XENO browser control-plane token is invalid")}options;base;fetchImpl;timeoutMs;async manifest(){let e=await this.call("health",void 0),t=_x.filter(n=>e.verbs?.includes(the(n))??!1);return{protocolVersion:1,adapterId:this.options.driver==="extension"?"xeno-extension-native":"xeno-browser-native",adapterVersion:e.version??"unknown",platform:process.platform,architecture:process.arch,operations:t,targetBinding:"atomic-preflight",profileIsolation:this.options.driver==="browser"?"both":"none",supports:{accessibilitySnapshots:!0,screenshots:!0,recordings:!1,consoleInspection:!0,networkInspection:!0,storageInspection:t.includes("browser.storage.read"),pageErrorInspection:!0,visibleCoControl:!0,deterministicHandback:!0,immediateStop:!0,sensitiveRegionRedaction:!1},policyEnforcement:{domain:!0,scheme:!0,port:!0,redirect:!0,upload:t.includes("browser.upload"),download:t.includes("browser.download")},certified:!1,limitations:[`${this.options.driver==="extension"?"Extension":"Browser"} transport is policy-enforced but not release-certified`,"sensitive-region screenshot redaction is not available"]}}async preflight(e,t){ewt(e.operation);let n=await this.call("health",void 0,t);if(!n.verbs?.includes(the(e.operation)))throw new Error(`${this.options.driver} driver does not support ${e.operation}`);let r=ohe(n.activeTab),i=Sb(e.parameters.tabId)??e.declaredTarget?.tabId;if(i&&r&&i!==r)throw new Error(`Requested tab ${i} is not the active browser tab ${r}`);let o=nhe(e,r);rhe(e,o);let s=new Date;return{token:`${e.operationId}:${r??"unbound"}:${KAt()}`,preparedAt:s.toISOString(),expiresAt:new Date(s.getTime()+2e4).toISOString(),observedTarget:o,...j0e(e.operation)?{evidence:[await this.snapshotEvidence(e,"before",t)]}:{},adapterState:{activeTab:r??null,driver:this.options.driver}}}async execute(e,t,n,r){let i=new Date().toISOString(),o=await this.call("health",void 0,r),s=ohe(o.activeTab);if(t.observedTarget.tabId&&s!==t.observedTarget.tabId)throw new Error("Active browser tab changed after atomic preflight");rhe(e,t.observedTarget);try{let a=q0e(e.operation,e.parameters),c=await this.call(a.verb,a.params,r),l=nhe(e,s),u=e.operation==="browser.wait"||e.operation==="browser.tabs.list"?[]:[await this.resultEvidence(e,c,r)];return{status:"ok",startedAt:i,completedAt:new Date().toISOString(),observedTarget:l,data:iwt(c),...u.length?{evidence:u}:{}}}catch(a){let c={code:swt(a),message:owt(a),retryable:!1};return{status:awt(a),startedAt:i,completedAt:new Date().toISOString(),observedTarget:t.observedTarget,error:c,evidence:[{evidenceId:`${e.operationId}-after-failure`,phase:"after",kind:"browser-snapshot",title:`${e.operation} failed attempt`,mediaType:"application/json",content:{type:"text",text:JSON.stringify({error:c})},sensitivity:"restricted"}]}}}async stop(e,t){await this.call("stop",{})}async resultEvidence(e,t,n){return e.operation==="browser.screenshot"?ZAt(e,"after",t):this.snapshotEvidence(e,"after",n)}async snapshotEvidence(e,t,n){let r=await this.call("observe",{limit:1e3},n);return{evidenceId:`${e.operationId}-${t}`,phase:t,kind:"browser-snapshot",title:`${e.operation} ${t} state`,mediaType:"application/json",content:{type:"text",text:JSON.stringify(r)},sensitivity:"restricted"}}async call(e,t,n){let r=new AbortController,i=()=>r.abort(n?.reason);n?.aborted?i():n?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>r.abort(new Error("browser control-plane timeout")),this.timeoutMs);o.unref?.();try{let s=await this.fetchImpl(new URL(`/v1/browser/${e}`,this.base),{method:e==="health"?"GET":"POST",redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.options.token}`,accept:"application/json",...e==="health"?{}:{"content-type":"application/json"}},...e==="health"?{}:{body:JSON.stringify(t??{})},signal:r.signal}),a=await s.json();if(!s.ok||a.ok!==!0)throw Object.assign(new Error(a.error?.message??`Browser ${e} failed with HTTP ${s.status}`),{code:a.error?.code??`HTTP_${s.status}`,status:s.status});return a.result}finally{clearTimeout(o),n?.removeEventListener("abort",i)}}};NL=1,kwt="repository.v1.json",Ewt=5e3,Swt=20,Cwt=64*1024*1024,nK=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let t=e.snapshotFileName??kwt;if(che(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=fwt(e.directory),this.snapshotPath=pwt(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=a4(e.lockTimeoutMs,Ewt,100,6e4,"lockTimeoutMs"),this.lockRetryMs=a4(e.lockRetryMs,Swt,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=a4(e.maxSnapshotBytes,Cwt,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(t=>t.create(e))}async createRevision(e,t){return this.mutate(n=>n.createRevision(e,t))}async get(e,t){return(await this.load()).repository.get(e,t)}async require(e,t){return(await this.load()).repository.require(e,t)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(t=>t.transition(e))}async appendReviewEvent(e){return this.mutate(t=>t.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let t=await this.acquireLock();try{let n=await this.load(),r=await e(n.repository);return await this.persist(n),r}finally{t.release()}})}async enqueueMutation(e){let t=this.mutationTail.then(e,e);return this.mutationTail=t.then(()=>{},()=>{}),t}async acquireLock(){let e=Date.now(),t;for(;Date.now()-e<=this.lockTimeoutMs;)try{return FA(this.lockPath,`artifact-repository:${che(this.snapshotPath)}`,Tp)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;t=n,await _wt(this.lockRetryMs)}throw new At("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,n=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=uN(i)}if(!t&&(e||await Pwt(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),t=i,n=!0)}catch(i){throw e?new At("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,uN(i)])}):i}if(!t&&e)throw e;let r=t?.state??{schemaVersion:1,records:[]};return{repository:new BL({now:this.now,idFactory:i=>`${i}_${W0e()}`,initialState:r}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:n,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),n={schemaVersion:NL,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},r=Rwt(n),i=`${JSON.stringify(r,null,2)}
|
|
2660
|
+
`});Kgt=z(()=>{"use strict";is(),Dme(),Dme(),kL="ai.xenostudio.xeno-agent.mcp",EL="xeno.host.state.encryption-key.v1",SC="aes-256-gcm",dm=32,oM=12,_X=16,Ab="b64:",sN="dpapi:v1:"}),NY=z(()=>{"use strict";gL(),agt(),KSe(),YSe(),G0(),ywe(),sO(),wv(),fO(),c0e(),fgt(),wgt(),Uz(),Ugt(),Xz(),e8(),Kgt()}),C0e={};Vnt(C0e,{createDelegatedXenoAgent:()=>ql});OY=z(()=>{"use strict";lY(),gY(),NY(),Tx(),x0e=[{tool:"Write",decision:"deny"},{tool:"Edit",decision:"deny"},{tool:"MemoryWrite",decision:"deny"},{tool:"Bash",decision:"deny"},{tool:"dispatch_agent",decision:"deny"}]});Tx=z(()=>{"use strict";EA(),Cm(),oY(),BCe(),AY(),FO(),NY(),BA(),S0=8192,C0=50});pv();Tp="0.9.35";ka();rs();DA=class{filePath;sessionId;labels;sequence=0;writeQueue=Promise.resolve();constructor(e){this.filePath=e.filePath,this.sessionId=e.sessionId,this.labels={run_id:e.runId,agent_id:e.agentId,parent_agent_id:e.parentAgentId,workspace:e.workspace,model:e.model,provider:e.provider}}get path(){return this.filePath}async append(e){let t=nAt(),n={id:t,sequence:this.sequence++,timestamp:new Date().toISOString(),session_id:e.session_id??this.sessionId,...this.labels,...e};return this.writeQueue=this.writeQueue.then(async()=>{await _B(this.filePath,JSON.stringify(n))}),await this.writeQueue,t}async read(e){let t=await fi(this.filePath);if(!t)return[];let n=lC(t);return e?.eventType&&(n=n.filter(r=>r.event_type===e.eventType)),e?.traceId&&(n=n.filter(r=>r.trace_id===e.traceId)),e?.limit!==void 0&&(n=n.slice(-Math.max(0,e.limit))),n}async tail(e=20){let t=Math.max(1,Math.min(e,500));return this.read({limit:t})}async exportJson(e){let t=await this.read();return await Li(e,JSON.stringify(t,null,2)),t.length}async flush(){await this.writeQueue}};twe();swe();_0e=1,LY=new Set(["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read"]),QY=new Set(["browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download","browser.record.start","browser.record.stop"]),FY=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),UY=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),QA=[...LY,...QY,...FY,...UY];Ue=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoAutomationError"}code;detail};e8();sAt=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,Ume=1048576;B0e=1,M0e=1,HY=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation"],WY=["draft","pending_review","approved","rejected","superseded","archived"],GY=["public","internal","confidential","restricted"],JY=["agent","tool","user","system","integration"],TL=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],PL=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];dO();Px=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(n=>({...n}))}},XY=class extends Error{constructor(e,t){super(`Artifact state cannot transition from ${e} to ${t}`),this.fromState=e,this.toState=t,this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},mAt={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},hAt="[\\u0000-\\u001f\\u007f]",gAt=new RegExp(hAt),N0e=/^[a-f0-9]{64}$/,AAt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,wAt=new Set(WY),yAt=new Set(GY),bAt=new Set(JY),vAt=new Set(HY),IAt=new Set(TL),kAt=new Set(PL);At=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoArtifactRepositoryError"}code;detail},BL=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(e={}){this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>(this.idCounter+=1,`${t}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),e.initialState&&this.hydrate(e.initialState)}exportState(){return{schemaVersion:1,records:[...this.records.values()].flatMap(t=>[...t.values()]).sort(Gme).map(t=>({artifact:GC(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(Rs(e),this.assertInitialState(e),e.revision!==1)throw new At("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:e.artifactId,revision:e.revision});if(this.records.has(e.artifactId))throw new At("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=GC(e),n=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),r={artifact:t,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,r]])),this.currentRevisions.set(t.artifactId,t.revision),$g(r)}async createRevision(e,t={}){Rs(e),this.assertInitialState(e);let n=this.getMutable(e.artifactId);this.assertVersion(n,t.expectedRecordVersion);let r=n.artifact.revision+1;if(e.revision!==r||e.predecessorRevision!==n.artifact.revision)throw new At("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:e.artifactId,currentRevision:n.artifact.revision,requestedRevision:e.revision});if(SAt(e,n.artifact))throw new At("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(n.artifact.state==="archived")throw new At("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){x0(n.artifact.state,"superseded");let a=this.now(),c=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});n.artifact.state="superseded",n.artifact.updatedAt=a,n.lifecycleEvents.push(c),n.recordVersion+=1}let i=GC(e),o=this.createLifecycleEvent({artifact:i,sequence:1,actor:t.actor??i.provenance.producer,fromState:null,toState:i.state,reason:t.reason??`revision-created-from-${n.artifact.revision}`}),s={artifact:i,recordVersion:1,lifecycleEvents:[o],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,s),this.currentRevisions.set(i.artifactId,i.revision),$g(s)}async get(e,t){let n=this.records.get(e);if(!n)return;let r=t??this.currentRevisions.get(e);if(r===void 0)return;let i=n.get(r);return i?$g(i):void 0}async require(e,t){let n=await this.get(e,t);if(!n)throw new At("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return n}async list(e={}){let t=[];for(let[n,r]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(n)))if(e.includeSuperseded)t.push(...r.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let o=r.get(i);o&&t.push(o)}}return t.filter(n=>CAt(n.artifact,e)).sort(Gme).map($g)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((n,r)=>n.artifact.revision-r.artifact.revision).map($g):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),x0(t.artifact.state,e.toState),e.toState==="approved"||e.toState==="rejected"){let o=e.reviewEventId?t.reviewEvents.find(a=>a.eventId===e.reviewEventId&&a.type==="decision-recorded"):void 0,s=$L(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new At("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${e.toState} requires a matching decision event`,{artifactId:e.artifactId,revision:t.artifact.revision});if(e.toState==="approved"&&s.unresolvedComments>0)throw new At("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let n=this.now(),r=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:r,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:n});return t.artifact.state=e.toState,t.artifact.updatedAt=n,t.lifecycleEvents.push(i),t.recordVersion+=1,$g(t)}async appendReviewEvent(e){let t=e.event,n=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(n,e.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new At("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(n,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new At("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let r={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=_L(r,n.artifact);if(i.length>0)throw new Px("XENO artifact review event validation failed",i);return n.reviewEvents.push(r),n.recordVersion+=1,$g(n)}getMutable(e,t){let n=this.records.get(e),r=t??this.currentRevisions.get(e),i=r===void 0?void 0:n?.get(r);if(!i)throw new At("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return i}assertVersion(e,t){if(t!==void 0&&t!==e.recordVersion)throw new At("ARTIFACT_CONFLICT",`Expected record version ${t}, found ${e.recordVersion}`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision,expectedRecordVersion:t,actualRecordVersion:e.recordVersion})}assertInitialState(e){if(e.state!=="draft"&&e.state!=="pending_review")throw new At("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:e.artifactId,revision:e.revision})}assertReviewCommentState(e,t){if(t.type==="comment-added"){if(e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.parentCommentId))throw new At("ARTIFACT_REVIEW_INVALID",`Parent comment ${t.parentCommentId} does not exist`);return}if(t.type!=="comment-resolved"&&t.type!=="comment-reopened")return;if(!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let n=xAt(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&n.resolved)throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!n.resolved)throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is not resolved`)}createLifecycleEvent(e){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:e.artifact.artifactId,revision:e.artifact.revision,sequence:e.sequence,recordedAt:e.recordedAt??this.now(),actor:{...e.actor},fromState:e.fromState,toState:e.toState,...e.reason?{reason:e.reason}:{},...e.reviewEventId?{reviewEventId:e.reviewEventId}:{}}}nextEventId(e){let t=this.idFactory(e);if(typeof t!="string"||t.trim().length===0||this.eventIds.has(t))throw new At("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${e} ID`);return this.eventIds.add(t),t}hydrate(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new At("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((n,r)=>n.artifact.artifactId.localeCompare(r.artifact.artifactId)||n.artifact.revision-r.artifact.revision);for(let n of t){let r=EAt(n,this.eventIds),i=this.records.get(r.artifact.artifactId);if(i||(i=new Map,this.records.set(r.artifact.artifactId,i)),i.has(r.artifact.revision))throw new At("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${r.artifact.artifactId}:${r.artifact.revision}`);i.set(r.artifact.revision,r),this.currentRevisions.set(r.artifact.artifactId,r.artifact.revision)}for(let[n,r]of this.records){let i=[...r.values()].sort((o,s)=>o.artifact.revision-s.artifact.revision);for(let o=0;o<i.length;o+=1){let s=i[o],a=o+1;if(s.artifact.revision!==a)throw new At("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new At("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new At("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new At("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${a} must be superseded`)}}}};MX=32*1024*1024,RAt=1024*1024*1024,TAt=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;Xme=16*1024*1024;Yme=3e4,Kme=1e3,ZY=class{adapter;leaseAuthority;durable;artifactRepository;now;executions=new Map;active=new Map;constructor(e){if(this.adapter=e.adapter,this.leaseAuthority=e.leaseAuthority,!!e.leaseAuthority==!!e.durable)throw new Error("Choose exactly one legacy or durable automation authority");this.durable=e.durable,this.artifactRepository=e.durable?.artifactRepository??e.artifactRepository,this.now=e.now??(()=>new Date().toISOString())}execute(e,t){e=structuredClone(e);let n=FAt(e),r=this.executions.get(e.operationId);if(r){if(r.fingerprint!==n)throw new Ue("AUTOMATION_OPERATION_CONFLICT",`Operation ${e.operationId} was already submitted with different authority or parameters`);if(this.durable){let a=this.durable;return a.assertCurrent(e).then(()=>r.promise).then(async c=>(await a.assertCurrent(e),structuredClone(c)))}return r.promise}if(this.active.size>=Kme)throw new Ue("AUTOMATION_OPERATION_CONFLICT","Automation active-operation capacity reached");let i=new AbortController,o=UAt(t,i);this.active.set(e.operationId,i);let s=(this.durable?KY(this.durable,e,n,a=>this.executeFresh(e,i.signal,a)):this.executeFresh(e,i.signal)).finally(()=>{o(),this.active.delete(e.operationId)});return this.executions.set(e.operationId,{fingerprint:n,promise:s}),this.durable&&s.then(()=>this.executions.delete(e.operationId),()=>this.executions.delete(e.operationId)),this.trimIdempotencyRecords(),s}async stop(e,t="human-stop"){let n=this.active.get(e);return n?(n.abort(new Error(t)),await this.adapter.stop?.(e,t),!0):!1}async executeFresh(e,t,n){qY(e),eB(t);let r=await this.adapter.manifest();RL(r);let i=zc(e.operation),o=VY(e),s=this.now(),a=await this.adapter.preflight(e,t);OAt(a,this.now()),aN(e,r,a.observedTarget),eB(t);let c=a.evidence??[];JC(c,o,"before");let l=await R0(this.artifactRepository,cN({request:e,manifest:r,policy:o,evidence:c,now:this.now}));if(eB(t),Date.parse(a.expiresAt)<=Date.parse(this.now()))throw new Ue("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let u=jY(e,a.observedTarget),d;if(this.durable){await this.durable.assertCurrent(e);let b=await this.durable.consume(n,e.capabilityLeaseId,e.expectedLeaseVersion,u);if(b.executionDisposition!=="dispatch-once"||b.replayed)throw vp();d=b.lease,await this.durable.assertCurrent(e)}else d=await this.leaseAuthority.consume(e.capabilityLeaseId,e.expectedLeaseVersion,u);let p={contractFingerprint:e.executionContract.fingerprint,lease:d,capabilityUse:u},f;try{eB(t),f=await this.adapter.execute(e,a,p,t)}catch(b){return s4({request:e,manifest:r,descriptorEffect:i.effect,target:a.observedTarget,lease:d,artifacts:l,startedAt:s,completedAt:this.now(),status:t.aborted?"cancelled":"error",code:t.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_ADAPTER_ERROR",message:t.aborted?"Automation operation was stopped":qAt(b)})}if(DAt(f),f.operationId!==void 0&&f.operationId!==e.operationId)throw new Ue("AUTOMATION_RESPONSE_INVALID","Adapter returned another operation identity");let m=LAt(a.observedTarget,f.observedTarget),h;try{aN(e,r,f.observedTarget)}catch(b){h=b instanceof Error?b:new Error(String(b))}let g=f.evidence??[];QAt(c,g);let A=[],y;try{JC(g,o,"after"),JC([...c,...g],o,"recording"),A=await R0(this.artifactRepository,cN({request:e,manifest:r,policy:o,evidence:g,now:this.now}))}catch(b){y=b instanceof Error?b:new Error(String(b))}let w=[...l,...A];return m||h?s4({request:e,manifest:r,descriptorEffect:i.effect,target:f.observedTarget,lease:d,artifacts:w,startedAt:f.startedAt,completedAt:f.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:m??h.message}):y?s4({request:e,manifest:r,descriptorEffect:i.effect,target:f.observedTarget,lease:d,artifacts:w,startedAt:f.startedAt,completedAt:f.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:y.message}):{operationId:e.operationId,status:f.status,effect:i.effect,startedAt:f.startedAt,completedAt:f.completedAt,adapter:D0e(r),target:structuredClone(f.observedTarget),...f.data!==void 0?{data:structuredClone(f.data)}:{},artifacts:w,lease:L0e(d),...f.error?{error:{...f.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>Kme;){let e=this.executions.keys().next().value;if(!e||this.active.has(e))break;this.executions.delete(e)}}};eK=class{constructor(e){this.database=e;try{if(e.exec("PRAGMA busy_timeout=0; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS automation_execution_schema(id INTEGER PRIMARY KEY CHECK(id=1),version INTEGER NOT NULL); INSERT OR IGNORE INTO automation_execution_schema VALUES(1,1);"),e.prepare("SELECT version FROM automation_execution_schema WHERE id=1").get()?.version!==1)throw Error("Unsupported automation execution journal");e.exec("CREATE TABLE IF NOT EXISTS automation_executions(id TEXT PRIMARY KEY,body TEXT NOT NULL)")}catch(t){throw e.close(),this.closed=!0,t}}database;closed=!1;async begin(e){return e=structuredClone(e),OX(e),Eb(e,["operationId","fingerprint","ownerToken"]),this.transaction(()=>{let t=this.read(e.operationId);if(t){if(t.fingerprint!==e.fingerprint)throw tB();return{claimed:!1,record:t}}let n=this.database.prepare("SELECT COUNT(*) AS count FROM automation_executions").get()?.count;if(typeof n!="number"||n>=1e5)throw Error("Automation journal capacity reached; explicit archival required");let r={schemaVersion:1,...e,outcome:{kind:"pending"}};return this.database.prepare("INSERT INTO automation_executions(id,body) VALUES(?,?)").run(e.operationId,Zme(r)),{claimed:!0,record:r}})}async get(e){if(typeof e!="string"||!e.trim()||e.length>1024)throw Error("Invalid automation journal identity");return this.transaction(()=>this.read(e))}async finish(e,t){e=structuredClone(e),t=structuredClone(t),OX(e),Eb(e,["operationId","fingerprint","ownerToken"]);let n={schemaVersion:1,...e,outcome:t};return DX(n),this.transaction(()=>{let r=this.read(e.operationId);if(!r||r.fingerprint!==e.fingerprint||r.ownerToken!==e.ownerToken)throw tB();if(r.outcome.kind!=="pending"){if(JSON.stringify(r.outcome)!==JSON.stringify(t))throw tB();return}this.database.prepare("UPDATE automation_executions SET body=? WHERE id=?").run(Zme(n),e.operationId)})}close(){this.closed||(this.closed=!0,this.database.close())}read(e){let t=this.database.prepare("SELECT CASE WHEN length(body)<=16384 THEN body ELSE NULL END AS body FROM automation_executions WHERE id=?").get(e);if(!t)return;if(typeof t.body!="string")throw Error("Corrupt automation journal size");let n=JSON.parse(t.body);if(DX(n),n.operationId!==e)throw tB();return n}async transaction(e){let t=Date.now()+1e3;for(;;){if(this.closed)throw Error("Automation journal closed");let n=!1;try{this.database.exec("BEGIN IMMEDIATE"),n=!0;let r=e();return this.database.exec("COMMIT"),r}catch(r){if(n)try{this.database.exec("ROLLBACK")}catch{}if(Date.now()>=t||!/SQLITE_BUSY|database is locked/.test(String(r)))throw r;await new Promise(i=>setTimeout(i,10))}}}};HAt=6e4,WAt=48*1024*1024,U0e=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(e){if(this.endpoint=GAt(e.baseUrl),this.token=JAt(e.token),this.timeoutMs=ehe(e.timeoutMs??HAt,1e3,3e5,"timeoutMs"),this.maxResponseBytes=ehe(e.maxResponseBytes??WAt,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=e.fetch??globalThis.fetch,typeof this.fetchImpl!="function")throw new Ue("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}preflight(e,t){return this.request("preflight","POST",e,t)}execute(e,t,n,r){return this.request("execute","POST",{request:e,preflight:t,grant:n},r)}async stop(e,t){await this.request("stop","POST",{operationId:e,reason:t.slice(0,512)})}async request(e,t,n,r){let i=new AbortController,o=YAt(r,i),s=setTimeout(()=>i.abort(new Error("automation transport timeout")),this.timeoutMs);s.unref?.();try{let a=new URL(e,this.endpoint),c=await this.fetchImpl(a,{method:t,redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.token}`,accept:"application/json",...t==="POST"?{"content-type":"application/json"}:{}},...t==="POST"?{body:JSON.stringify(n??{})}:{},signal:i.signal}),l=await XAt(c,this.maxResponseBytes);if(!c.ok){let u=zAt(l);throw new Ue("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${e}: ${u.message}`,{status:c.status,route:e,adapterCode:u.code})}if(!LX(l)||l.ok!==!0||!("result"in l))throw new Ue("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${e} envelope`);return l.result}catch(a){if(a instanceof Ue)throw a;let c=r?.aborted;throw new Ue(c?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",c?"Automation transport was stopped":`XENO Browser ${e} transport failed`,{route:e},{cause:a})}finally{clearTimeout(s),o()}}};_x=["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read","browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download"],ML=class{constructor(e){if(this.options=e,this.base=twt(e.baseUrl),this.fetchImpl=e.fetch??globalThis.fetch,this.timeoutMs=e.timeoutMs??6e4,!nwt(e.token))throw new Error("XENO browser control-plane token is invalid")}options;base;fetchImpl;timeoutMs;async manifest(){let e=await this.call("health",void 0),t=_x.filter(n=>e.verbs?.includes(the(n))??!1);return{protocolVersion:1,adapterId:this.options.driver==="extension"?"xeno-extension-native":"xeno-browser-native",adapterVersion:e.version??"unknown",platform:process.platform,architecture:process.arch,operations:t,targetBinding:"atomic-preflight",profileIsolation:this.options.driver==="browser"?"both":"none",supports:{accessibilitySnapshots:!0,screenshots:!0,recordings:!1,consoleInspection:!0,networkInspection:!0,storageInspection:t.includes("browser.storage.read"),pageErrorInspection:!0,visibleCoControl:!0,deterministicHandback:!0,immediateStop:!0,sensitiveRegionRedaction:!1},policyEnforcement:{domain:!0,scheme:!0,port:!0,redirect:!0,upload:t.includes("browser.upload"),download:t.includes("browser.download")},certified:!1,limitations:[`${this.options.driver==="extension"?"Extension":"Browser"} transport is policy-enforced but not release-certified`,"sensitive-region screenshot redaction is not available"]}}async preflight(e,t){ewt(e.operation);let n=await this.call("health",void 0,t);if(!n.verbs?.includes(the(e.operation)))throw new Error(`${this.options.driver} driver does not support ${e.operation}`);let r=ohe(n.activeTab),i=Sb(e.parameters.tabId)??e.declaredTarget?.tabId;if(i&&r&&i!==r)throw new Error(`Requested tab ${i} is not the active browser tab ${r}`);let o=nhe(e,r);rhe(e,o);let s=new Date;return{token:`${e.operationId}:${r??"unbound"}:${KAt()}`,preparedAt:s.toISOString(),expiresAt:new Date(s.getTime()+2e4).toISOString(),observedTarget:o,...j0e(e.operation)?{evidence:[await this.snapshotEvidence(e,"before",t)]}:{},adapterState:{activeTab:r??null,driver:this.options.driver}}}async execute(e,t,n,r){let i=new Date().toISOString(),o=await this.call("health",void 0,r),s=ohe(o.activeTab);if(t.observedTarget.tabId&&s!==t.observedTarget.tabId)throw new Error("Active browser tab changed after atomic preflight");rhe(e,t.observedTarget);try{let a=q0e(e.operation,e.parameters),c=await this.call(a.verb,a.params,r),l=nhe(e,s),u=e.operation==="browser.wait"||e.operation==="browser.tabs.list"?[]:[await this.resultEvidence(e,c,r)];return{status:"ok",startedAt:i,completedAt:new Date().toISOString(),observedTarget:l,data:iwt(c),...u.length?{evidence:u}:{}}}catch(a){let c={code:swt(a),message:owt(a),retryable:!1};return{status:awt(a),startedAt:i,completedAt:new Date().toISOString(),observedTarget:t.observedTarget,error:c,evidence:[{evidenceId:`${e.operationId}-after-failure`,phase:"after",kind:"browser-snapshot",title:`${e.operation} failed attempt`,mediaType:"application/json",content:{type:"text",text:JSON.stringify({error:c})},sensitivity:"restricted"}]}}}async stop(e,t){await this.call("stop",{})}async resultEvidence(e,t,n){return e.operation==="browser.screenshot"?ZAt(e,"after",t):this.snapshotEvidence(e,"after",n)}async snapshotEvidence(e,t,n){let r=await this.call("observe",{limit:1e3},n);return{evidenceId:`${e.operationId}-${t}`,phase:t,kind:"browser-snapshot",title:`${e.operation} ${t} state`,mediaType:"application/json",content:{type:"text",text:JSON.stringify(r)},sensitivity:"restricted"}}async call(e,t,n){let r=new AbortController,i=()=>r.abort(n?.reason);n?.aborted?i():n?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>r.abort(new Error("browser control-plane timeout")),this.timeoutMs);o.unref?.();try{let s=await this.fetchImpl(new URL(`/v1/browser/${e}`,this.base),{method:e==="health"?"GET":"POST",redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.options.token}`,accept:"application/json",...e==="health"?{}:{"content-type":"application/json"}},...e==="health"?{}:{body:JSON.stringify(t??{})},signal:r.signal}),a=await s.json();if(!s.ok||a.ok!==!0)throw Object.assign(new Error(a.error?.message??`Browser ${e} failed with HTTP ${s.status}`),{code:a.error?.code??`HTTP_${s.status}`,status:s.status});return a.result}finally{clearTimeout(o),n?.removeEventListener("abort",i)}}};NL=1,kwt="repository.v1.json",Ewt=5e3,Swt=20,Cwt=64*1024*1024,nK=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let t=e.snapshotFileName??kwt;if(che(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=fwt(e.directory),this.snapshotPath=pwt(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=a4(e.lockTimeoutMs,Ewt,100,6e4,"lockTimeoutMs"),this.lockRetryMs=a4(e.lockRetryMs,Swt,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=a4(e.maxSnapshotBytes,Cwt,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(t=>t.create(e))}async createRevision(e,t){return this.mutate(n=>n.createRevision(e,t))}async get(e,t){return(await this.load()).repository.get(e,t)}async require(e,t){return(await this.load()).repository.require(e,t)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(t=>t.transition(e))}async appendReviewEvent(e){return this.mutate(t=>t.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let t=await this.acquireLock();try{let n=await this.load(),r=await e(n.repository);return await this.persist(n),r}finally{t.release()}})}async enqueueMutation(e){let t=this.mutationTail.then(e,e);return this.mutationTail=t.then(()=>{},()=>{}),t}async acquireLock(){let e=Date.now(),t;for(;Date.now()-e<=this.lockTimeoutMs;)try{return FA(this.lockPath,`artifact-repository:${che(this.snapshotPath)}`,Tp)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;t=n,await _wt(this.lockRetryMs)}throw new At("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,n=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=uN(i)}if(!t&&(e||await Pwt(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),t=i,n=!0)}catch(i){throw e?new At("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,uN(i)])}):i}if(!t&&e)throw e;let r=t?.state??{schemaVersion:1,records:[]};return{repository:new BL({now:this.now,idFactory:i=>`${i}_${W0e()}`,initialState:r}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:n,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),n={schemaVersion:NL,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},r=Rwt(n),i=`${JSON.stringify(r,null,2)}
|
|
2661
2661
|
`;if(Buffer.byteLength(i,"utf8")>this.maxSnapshotBytes)throw new At("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await G0e(this.directory,{recursive:!0,mode:448}),e.hasSnapshot&&!e.recoveredFromBackup&&e.sourceSnapshot&&await dhe(this.backupPath,`${JSON.stringify(e.sourceSnapshot,null,2)}
|
|
2662
2662
|
`),await dhe(this.snapshotPath,i)}async readSnapshot(e,t){let n;try{n=await J0e(e)}catch(r){if(!t&&QX(r,"ENOENT")||t&&QX(r,"ENOENT"))return;throw FX("Unable to inspect artifact repository snapshot",e,r)}if(!n.isFile()||n.size>this.maxSnapshotBytes)throw new At("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:e,sizeBytes:n.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let r=await lwt(e);if(r.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return xwt(JSON.parse(r.toString("utf8")),e)}catch(r){throw r instanceof At?r:FX("Unable to parse artifact repository snapshot",e,r,!0)}}};fO();e8();Mwt=8*1024*1024,Nwt=4;exe=[..._x],Kwt=exe.filter(e=>!["browser.storage.read","browser.upload","browser.download"].includes(e)),Zwt=QA.filter(e=>e.startsWith("computer.")),l4=6e4,OL=class{constructor(e){this.options=e,this.environment=e.environment??Bx()}options;leases=new wm({maximumDurationMs:l4,maximumUses:1});activeExecutors=new Map;environment;browserAdapter;computerAdapter;register(e){if(this.options.safeMode)return 0;let t=[];return qX(this.environment.browser)&&t.push(...ryt(this.environment.browser.driver)),jX(this.environment.computer)&&t.push(...Zwt),t.length===0?0:(e.registerAll(rK({runtime:this,operations:t})),t.length)}async execute(e){if(this.options.safeMode)throw new Error("Governed automation is disabled in safe mode");pyt(e);let t=zc(e.operation),n=this.options.profile(),r={runId:this.options.runId,agentId:this.options.agentId??"agent-main",...this.options.sessionId?{sessionId:this.options.sessionId}:{},turnId:e.authorization.turnId,...this.options.workspaceId?{workspaceId:this.options.workspaceId}:{}},i=lyt(e.operation,e.declaredTarget,this.environment),o=t.surface==="browser"?t.effect==="act"?"browser-act":"browser-read":t.effect==="act"?"computer-act":"computer-observe",s=t.effect==="act"?"external":"read",a=uyt(i),c=dyt(i),l=this.leases.request({subject:{...r,toolName:e.governingToolName,operationId:e.operationId},scope:{kind:o,effect:s,operations:[e.operation],...a?{resources:[a]}:{},...c?{destinations:[c]}:{},governingToolName:e.governingToolName},reason:`${e.operation} authorized by the CLI policy and permission layers`,requestedBy:{kind:"agent",id:r.agentId,profileFingerprint:n.fingerprint},durationMs:l4,requestTtlMs:3e4,maxUses:1,childInheritance:"none",policyFingerprints:[n.fingerprint]},n),u=this.leases.approve({leaseId:l.leaseId,expectedVersion:l.version,approvedBy:{kind:"integration",id:`xeno-${this.options.surface}-permission-engine`,displayName:`XENO ${this.options.surface.toUpperCase()} permission engine`},approvalContext:{surface:this.options.surface,turnId:e.authorization.turnId,messageId:e.authorization.toolCallId}}),d=await this.adapterFor(t.surface),p=Yz({contractId:`contract-${e.operationId}`,identity:r,policy:this.securityPolicy(),profile:n,...this.options.securityStatus?{adapterStatus:this.options.securityStatus}:{},filesystem:{readRoots:[KS(this.options.cwd())],writeRoots:[KS(this.options.cwd())],executeRoots:[KS(this.options.cwd())]},network:cyt(i,this.environment),browser:t.surface==="browser"?syt(t.effect,i,this.environment):{mode:"none"},computer:t.surface==="computer"?ayt(t.effect,this.environment):{mode:"none"},capabilityLeaseIds:[u.leaseId],expiresAt:new Date(Date.now()+l4).toISOString()});await this.audit({eventType:"automation_lease_approved",traceId:e.authorization.turnId,operation:e.operation,operationId:e.operationId,leaseId:u.leaseId,contractFingerprint:p.fingerprint,permissionReason:e.authorization.permission.reason});let f=new ZY({adapter:d,leaseAuthority:this.leases,artifactRepository:new nK({directory:KS(this.options.cwd(),".xeno","artifacts")})});this.activeExecutors.set(e.operationId,f),e.reportProgress?.({activity:"state",message:`Executing governed ${e.operation}`});try{let m=await f.execute({protocolVersion:1,operationId:e.operationId,idempotencyKey:e.idempotencyKey,requestedAt:new Date().toISOString(),identity:r,governingToolName:e.governingToolName,operation:e.operation,parameters:fyt(e.parameters),...i?{declaredTarget:i}:{},executionContract:p,capabilityLeaseId:u.leaseId,expectedLeaseVersion:u.version},e.signal);return await this.audit({eventType:m.status==="ok"?"automation_completed":"automation_failed",traceId:e.authorization.turnId,operation:e.operation,operationId:e.operationId,leaseId:u.leaseId,contractFingerprint:p.fingerprint,status:m.status,artifactIds:m.artifacts.map(h=>h.artifactId)}),m}catch(m){throw await this.audit({eventType:"automation_failed",traceId:e.authorization.turnId,operation:e.operation,operationId:e.operationId,leaseId:u.leaseId,contractFingerprint:p.fingerprint,status:m instanceof Error?m.name:"error"}),m}finally{this.activeExecutors.delete(e.operationId)}}async stop(e,t="human-stop"){let n=this.activeExecutors.get(e);return n?n.stop(e,t):!1}securityPolicy(){let e=this.options.securityPolicy?.();if(e)return e;let t=KS(this.options.cwd());return{allowedDirectories:[t],workingDirectory:t,capabilities:{terminal:!0,fileRead:!0,fileWrite:!0,appLaunch:!0},executionLevel:"policy-only",trustMode:"trusted-workspace",allowNetwork:!1}}adapterFor(e){if(e==="browser"){let n=this.environment.browser;if(!qX(n))throw new Error(nxe(n));return this.browserAdapter??=new ML({baseUrl:n.baseUrl,token:n.token,driver:n.driver}),this.browserAdapter}let t=this.environment.computer;if(!jX(t))throw new Error(rxe(t));return this.computerAdapter??=txe(t),this.computerAdapter}async audit(e){try{await this.options.onAudit?.(e)}catch{}}};dO();sK=class extends Error{code="EVIDENCE_GRAPH_INVALID";issues;constructor(e){super("XENO evidence graph validation failed"),this.name="XenoEvidenceGraphValidationError",this.issues=e.map(t=>({...t}))}},Ayt=new Set(["depends_on","decomposes","supersedes"]),wyt=new Set(TL),yyt=new Set(PL);axe=class{now;graph;constructor(e){if("schemaVersion"in e)Xg(e),this.now=()=>new Date().toISOString(),this.graph=rB(e);else{this.now=e.now??(()=>new Date().toISOString());let t=this.now();this.graph={schemaVersion:1,graphId:e.graphId,version:1,createdAt:t,updatedAt:t,nodes:[],edges:[]},Xg(this.graph)}}addNode(e){let t=rB(this.graph);return t.nodes.push(cxe(e)),this.touch(t),Xg(t),this.graph=t,this}addEdge(e){let t=rB(this.graph);return t.edges.push(lxe(e)),this.touch(t),Xg(t),this.graph=t,this}build(){return Xg(this.graph),rB(this.graph)}touch(e){e.version+=1,e.updatedAt=this.now()}};byt=16*1024*1024,vyt=5e3,Iyt=1e5,kyt=1e6,Eyt=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,Es=class extends Error{constructor(e,t){super(t===void 0?e:`${e} at diff line ${t}`),this.line=t,this.name="XenoDiffParseError"}line;code="XENO_DIFF_INVALID"};pN=class{repository;actor;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");if(!e.actor?.kind||!e.actor.id?.trim())throw new TypeError("Review actor is required");this.repository=e.repository,this.actor=structuredClone(e.actor),this.idFactory=e.idFactory??(()=>`comment_${Pyt()}`)}async addComment(e){let t=LL(e.body,"Review comment body",65536),n=await this.repository.require(e.artifactId,e.revision),r=fN(n,e),i=mN(this.idFactory(),"Comment ID"),o=_yt(e.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:"comment-added",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,commentId:i,body:t,...r?{anchor:r}:{},...o?{parentCommentId:o}:{}}})}async setCommentResolution(e){let t=mN(e.commentId,"Review comment ID"),n=yhe(e.reason,"Resolution reason",16*1024),r=await this.repository.require(e.artifactId,e.revision);return this.repository.appendReviewEvent({expectedRecordVersion:r.recordVersion,event:{type:e.resolved?"comment-resolved":"comment-reopened",artifactId:r.artifact.artifactId,artifactRevision:r.artifact.revision,artifactHash:r.artifact.content.hash,actor:this.actor,commentId:t,...n?{reason:n}:{}}})}async decide(e){let t=await this.repository.require(e.artifactId,e.revision);if(t.artifact.state!=="pending_review")throw new At("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${t.artifact.state}`);let n=fN(t,e),r=yhe(e.rationale,"Decision rationale",64*1024),i=await this.repository.appendReviewEvent({expectedRecordVersion:t.recordVersion,event:{type:"decision-recorded",artifactId:t.artifact.artifactId,artifactRevision:t.artifact.revision,artifactHash:t.artifact.content.hash,actor:this.actor,decision:e.decision,...r?{rationale:r}:{},...n?{scope:n}:{}}});if(n||e.decision==="changes_requested")return i;let o=i.reviewEvents.at(-1);if(!o||o.type!=="decision-recorded")throw new At("ARTIFACT_REVIEW_INVALID","Artifact decision event was not recorded");return this.repository.transition({artifactId:i.artifact.artifactId,revision:i.artifact.revision,expectedRecordVersion:i.recordVersion,toState:e.decision,actor:this.actor,reviewEventId:o.eventId,...r?{reason:r}:{}})}};lA="xeno.spec.v1",sv="xeno.spec-execution.v1",Zo=class extends Error{constructor(e){super(`XENO spec is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},pxe=class{repository;now;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");this.repository=e.repository,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(()=>$yt())}async create(e,t){if(e.revision!==1||e.predecessorRevision!==void 0)throw new Zo(["A new spec must begin at revision 1 without a predecessor"]);let n=hN(e,t);return await this.repository.create(n.requirements),await this.repository.create(n.design),await this.repository.create(n.taskGraph),await this.repository.create(n.plan),n}async revise(e,t){let n=tA(e.specId),r=await this.repository.require(n.plan);if(e.revision!==r.artifact.revision+1||e.predecessorRevision!==r.artifact.revision)throw new Zo([`Revision ${e.revision} must follow approved or reviewed revision ${r.artifact.revision}`]);let i=hN(e,t);return await this.repository.createRevision(i.requirements,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.design,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.taskGraph,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.plan,{actor:t.producer,reason:"spec-revised"}),i}async approve(e,t,n){return new pN({repository:this.repository,actor:t}).decide({artifactId:tA(e).plan,decision:"approved",...n?{rationale:n}:{}})}async reject(e,t,n){return new pN({repository:this.repository,actor:t}).decide({artifactId:tA(e).plan,decision:"rejected",rationale:n})}async startExecution(e,t){let n=await this.repository.require(tA(e).plan);if(n.artifact.state!=="approved")throw new Zo([`Spec ${e} must be approved before execution`]);let r=gN(n.artifact),i=this.now(),o={schemaVersion:sv,executionId:`spec_execution_${this.idFactory()}`,specId:r.specId,specRevision:r.revision,planArtifactId:n.artifact.artifactId,planHash:{...n.artifact.content.hash},state:"ready",createdAt:i,updatedAt:i,observedPaths:[],tasks:r.tasks.map(s=>({taskId:s.id,status:"pending",evidence:[],acceptanceEvidence:Object.fromEntries(s.acceptanceCriterionIds.map(a=>[a,[]]))}))};return this.repository.create(AN(o,{producer:t,identity:n.artifact.identity,sensitivity:n.artifact.sensitivity,accessPolicyId:n.artifact.accessPolicyId}))}async updateExecution(e,t,n){let r=await this.repository.require(e),i=dK(r.artifact),o=await this.repository.require(i.planArtifactId,i.specRevision);if(o.artifact.state!=="approved"||!T0(o.artifact.content.hash,i.planHash))throw new Zo(["Execution is no longer bound to the approved plan revision"]);let s=t(structuredClone(i));s.schemaVersion=sv,s.executionId=i.executionId,s.specId=i.specId,s.specRevision=i.specRevision,s.planArtifactId=i.planArtifactId,s.planHash={...i.planHash},s.createdAt=i.createdAt,s.updatedAt=this.now(),QL(s,gN(o.artifact));let a=AN(s,{producer:n,identity:r.artifact.identity,sensitivity:r.artifact.sensitivity,accessPolicyId:r.artifact.accessPolicyId},r.artifact.revision+1,r.artifact.revision);return this.repository.createRevision(a,{actor:n,reason:"spec-execution-updated"})}};dO();FL="xeno.review-report.v1",pK=["correctness","security","performance","api","tests","documentation"],fK=["source","test","trace","artifact","reproduction","benchmark"],es=class extends Error{constructor(e){super(`XENO review is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},gxe=class{reviewer;verifier;now;idFactory;constructor(e){if(typeof e?.reviewer!="function")throw new TypeError("Review agent executor is required");this.reviewer=e.reviewer,this.verifier=e.verifier,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${Lyt()}`)}async run(e){UL(e.pack),qL(e.target),yN(e.runId,"runId");let t=this.now(),n=await Promise.all(e.pack.dimensions.map(async(a,c)=>{let l=await this.reviewer({...e,dimension:a,reviewerSlot:c});return Uyt(l,a,e.pack.maxFindings),structuredClone(l)})),r=n.flatMap(a=>a.findings.map(c=>({finding:c,reviewerAgentId:a.reviewerAgentId})));if(r.length>e.pack.maxFindings)throw new es([`Reviewers returned ${r.length} findings, exceeding maxFindings ${e.pack.maxFindings}`]);let i=Qyt(r,this.idFactory);for(let a of i){let c=this.verifier?await Promise.all(Array.from({length:e.pack.verifierCount},async(f,m)=>{let h=await this.verifier({...e,finding:structuredClone(a),verifierSlot:m});return qyt(h),structuredClone(h)})):[];a.verifications=jyt(c),a.evidence=Ixe([...a.evidence,...a.verifications.flatMap(f=>f.evidence)]);let l=new Set(a.verifications.filter(f=>f.outcome==="reproduced").map(f=>f.verifierAgentId)).size,u=a.verifications.length>0&&a.verifications.every(f=>f.outcome==="rejected"),d=new Set(a.evidence.map(f=>f.producerId)).size;l>=e.pack.minimumVerifierReproductions?(a.state="verified",a.verificationBasis="verifier"):e.pack.allowIndependentEvidenceVerification&&d>=e.pack.minimumIndependentEvidenceProducers?(a.state="verified",a.verificationBasis="independent-evidence"):u?(a.state="rejected",a.verificationBasis="verifier"):(a.state="unverified",a.verificationBasis="none");let p=a.verifications.map(f=>f.confidence).filter(f=>f!==void 0);p.length>0&&(a.confidence=Rxe(Math.min(a.confidence,...p)))}i.sort(Vyt);let o=this.now(),s={schemaVersion:FL,reportId:yN(this.idFactory("report"),"reportId"),runId:e.runId,pack:structuredClone(e.pack),target:structuredClone(e.target),startedAt:t,completedAt:o,reviewers:n.map(a=>({agentId:a.reviewerAgentId,dimension:a.dimension,findingCount:a.findings.length})),findings:i,summary:Sxe(i)};return Wv(s),s}};Yyt=3e4,Kyt=64*1024,Zyt=/(^|_)(TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|COOKIE|AUTH|AUTHORIZATION)(_|$)/i,ebt=new Set(["PATH","Path","PATHEXT","SystemRoot","WINDIR","ComSpec","TMP","TEMP","HOME","USERPROFILE"]);wv();rbt=3e4,ibt=64*1024;Lxe=class{constructor(e,t={}){this.executor=e,this.options=t}executor;options;run(e,t){return WL(e,t,{...this.options,promptExecutor:this.executor})}},Qxe=class{constructor(e,t={}){this.executor=e,this.options=t}executor;options;run(e,t){return GL(e,t,{...this.options,agentExecutor:this.executor})}};Fxe=class{constructor(e,t={}){this.hooks=e,this.options=t}hooks;options;run(e){return JL(this.hooks,e,this.options)}},Uxe=class{constructor(e,t={}){this.config=e,this.options=t}config;options;run(e){let t=[...this.config.hooks??[],...this.config.events?.[e.event]??[]];return JL([...new Set(t)],e,this.options)}},qxe=class{constructor(e={}){this.options=e}options;run(e,t){return VL(e,t,this.options)}},jxe=class{constructor(e={}){this.options=e}options;run(e,t){return HL(e,t,this.options)}};EA();zC=class extends Error{code;expiresAt;constructor(e,t,n={}){super(e),this.name="XenoAuthError",this.code=t,n.expiresAt&&(this.expiresAt=n.expiresAt)}},fbt="XENO_API_KEY",AK=6e4;Cm();EA();rs();vbt="profiles.json",p4="default",Fx=class{data;filePath;constructor(){this.filePath=bbt(rr(),vbt),this.data=this.load()}listProfiles(){return[...this.data.profiles]}getActiveProfile(){let e=this.data.activeProfile??p4,t=this.data.profiles.find(n=>n.name===e);return t?{...t}:{name:p4}}getActiveProfileName(){return this.data.activeProfile??p4}switchProfile(e){if(!this.data.profiles.some(t=>t.name===e))throw new Error(`Profile "${e}" does not exist. Use listProfiles() to see available profiles.`);this.data.activeProfile=e,this.save()}createProfile(e){if(!e.name||!e.name.trim())throw new Error("Profile name cannot be empty.");let t=e.name.trim();if(t.length>64)throw new Error("Profile name too long (max 64 characters).");if(/[/\\:\0]/.test(t))throw new Error("Profile name cannot contain path separators (/ \\), colons, or null bytes.");if(t.startsWith(".")||t.startsWith("-"))throw new Error('Profile name cannot start with "." or "-".');let n={...e,name:t};if(this.data.profiles.some(r=>r.name===n.name))throw new Error(`Profile "${n.name}" already exists. Use updateProfile() to modify it.`);this.data.profiles.push(n),this.save()}deleteProfile(e){let t=this.data.profiles.findIndex(n=>n.name===e);if(t===-1)throw new Error(`Profile "${e}" does not exist.`);this.data.profiles.splice(t,1),this.data.activeProfile===e&&(this.data.activeProfile=null),this.save()}updateProfile(e,t){let n=this.data.profiles.findIndex(s=>s.name===e);if(n===-1)throw new Error(`Profile "${e}" does not exist.`);let r=this.data.profiles[n],{name:i,...o}=t;this.data.profiles[n]={...r,...o,name:r.name},this.save()}getProfile(e){let t=this.data.profiles.find(n=>n.name===e);return t?{...t}:void 0}reload(){this.data=this.load()}load(){if(!Ehe(this.filePath))return{activeProfile:null,profiles:[]};try{let e=wbt(this.filePath,"utf-8"),t=Er(e,{activeProfile:null,profiles:[]});return Array.isArray(t.profiles)?{activeProfile:typeof t.activeProfile=="string"?t.activeProfile:null,profiles:t.profiles.filter(n=>typeof n=="object"&&n!==null&&typeof n.name=="string")}:{activeProfile:null,profiles:[]}}catch{return{activeProfile:null,profiles:[]}}}save(){ex();let e=rr();Ehe(e)||Abt(e,{recursive:!0}),ybt(this.filePath,JSON.stringify(this.data,null,2)+`
|
|
2663
2663
|
`,"utf-8")}};rs();Cbt=[".xenocode",".xenocode.json"];EA();rs();SO();w8();oY();CCe();xCe();RCe();gCe();ICe();kCe();SCe();BA();Obt={Read:{avgMs:500,p95Ms:900},Glob:{avgMs:1800,p95Ms:3200},Grep:{avgMs:2200,p95Ms:4e3},LS:{avgMs:900,p95Ms:1600},Edit:{avgMs:450,p95Ms:900},Write:{avgMs:450,p95Ms:900}},xhe=.7;BCe();yCe();bCe();Bv();cx();UA=class{checkpointManager;lastCheckpointAt=0;constructor(e){this.checkpointManager=e}async checkInterval(e){return e.length-this.lastCheckpointAt>=10?(await this.checkpointManager.create({trigger:"auto",messages:e,description:`Auto-checkpoint at ${e.length} messages`}),this.lastCheckpointAt=e.length,!0):!1}async checkBeforeDangerous(e,t,n){return Jc.isDangerousOperation(e,t)?(await this.checkpointManager.create({trigger:"pre_dangerous",messages:n,description:`Before ${e}`}),!0):!1}};lY();MCe();gY();AY();FO();Xke();ZCe();N8();vK=class Kxe{index;byId=new Map;constructor(t={}){this.index=new lx({maxDocuments:t.maxEpisodes??5e3})}async add(t){this.byId.set(t.id,t),await this.index.addDocument(t.id,jbt(t),{kind:"episode",outcome:t.outcome})}async recall(t,n=5,r=.1){let i=await this.index.search(t,n,r),o=[];for(let s of i){let a=this.byId.get(s.id);a&&o.push({episode:a,score:s.score})}return o}get(t){return this.byId.get(t)}all(){return[...this.byId.values()]}get size(){return this.byId.size}toJSON(){return this.all()}static async fromEpisodes(t,n={}){let r=new Kxe(n);for(let i of t)await r.add(i);return r}};N8();IK=class Zxe{index;byId=new Map;constructor(t={}){this.index=new lx({maxDocuments:t.maxSkills??5e3})}async add(t){this.byId.set(t.id,t),await this.index.addDocument(t.id,Vbt(t),{kind:"skill",name:t.name})}async recall(t,n=5,r=.1){let i=await this.index.search(t,n,r),o=[];for(let s of i){let a=this.byId.get(s.id);a&&o.push({skill:a,score:s.score})}return o}nextVersion(t){let n=0;for(let r of this.byId.values())r.name===t&&r.version>n&&(n=r.version);return n+1}get(t){return this.byId.get(t)}all(){return[...this.byId.values()]}get size(){return this.byId.size}toJSON(){return this.all()}static async fromSkills(t,n={}){let r=new Zxe(n);for(let i of t)await r.add(i);return r}};Wbt=`You distill REUSABLE SKILLS from a completed agent task.
|
|
@@ -2878,7 +2878,7 @@ ${Re}${X.compose(nQ(),X.bold)("\u2717")} ${bR(e)}
|
|
|
2878
2878
|
`)}function oI(){return`
|
|
2879
2879
|
${Re}${ke("Goodbye.")}
|
|
2880
2880
|
`}var $Tt,p1e,nQ,en,ke,IR,bR,BTt,kR,MTt,OTt,DTt,U,Re,w1e,cZ,S,pZ,g1e,vR,as=Ie(()=>{"use strict";ha();Ca();s1e();eQ();$Tt=new id(process.stdout),p1e=new id(process.stderr),nQ=()=>Sr(),en=e=>nQ()(e),ke=X.dim,IR=X.bold,bR=e=>nQ()(e),BTt="\u25A0",kR="\u2514",MTt={open:"\x1B[4m",close:"\x1B[24m"};OTt={Read:e=>Kc()(e),ReadImage:e=>Kc()(e),Glob:e=>Kc()(e),Grep:e=>Kc()(e),ElfAnalyze:e=>Kc()(e),MemoryRead:e=>Kc()(e),Write:e=>yR()(e),Edit:e=>yR()(e),MemoryWrite:e=>yR()(e),Bash:e=>rZ()(e),GitStatus:e=>Kc()(e),GitDiff:e=>Kc()(e),GitLog:e=>Kc()(e),GitBranch:e=>Kc()(e),GitCommit:e=>rZ()(e),WebSearch:e=>X.cyan(e),WebFetch:e=>X.cyan(e),TaskOutput:e=>Kc()(e),TaskInput:e=>X.cyan(e),TaskStop:e=>HA()(e)};DTt={Edit:"Update",Glob:"Search",Grep:"Search",WebSearch:"Web Search",WebFetch:"Web Fetch"};U={accent:en,purple:bR,cyan:bR,dim:ke,bold:IR,red:bR,green:bR},Re=" ",w1e=1e3,cZ=3;S={moveTo:(e,t)=>`\x1B[${e};${t}H`,saveCursor:()=>"\x1B[s",restoreCursor:()=>"\x1B[u",setScrollRegion:(e,t)=>`\x1B[${e};${t}r`,resetScrollRegion:()=>"\x1B[r",eraseLine:()=>"\x1B[2K",clearScreen:()=>"\x1B[2J\x1B[3J\x1B[H",showCursor:()=>"\x1B[?25h",hideCursor:()=>"\x1B[?25l",disableWrap:()=>"\x1B[?7l",enableWrap:()=>"\x1B[?7h",enableMouseReporting:()=>"\x1B[?1000h\x1B[?1006h",disableMouseReporting:()=>"\x1B[?1006l\x1B[?1000l",enableBracketedPaste:()=>"\x1B[?2004h",disableBracketedPaste:()=>"\x1B[?2004l"};pZ=class{atLineStart=!0;writeFn;constructor(t){this.writeFn=t??(n=>{$Tt.writeOrdered(n,"stream")})}write(t){let n="";for(let r of t)this.atLineStart&&(n+=Re,this.atLineStart=!1),n+=r,r===`
|
|
2881
|
-
`&&(this.atLineStart=!0);this.writeFn(n)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},g1e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],vR=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,n){this.writeFn=t??(r=>{p1e.writeFrame(r,"spinner")}),this.clearFn=n??(()=>{p1e.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let n=g1e[this.frameIndex%g1e.length],r=`${en(n)} ${ke(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${r}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});var he,gi=Ie(()=>{"use strict";he="0.5.51"});import{readFileSync as u_t}from"node:fs";import{WebContextClient as d_t}from"@xenosystem/web-context-client";function f_t(e=process.env){let t=e.XENO_WEB_CONTEXT_TOKEN?.trim();if(t)return t;let n=e.XENO_WEB_CONTEXT_TOKEN_FILE?.trim();if(n){let r=u_t(n,"utf8").trim();if(r)return r}throw Object.assign(new Error("XENO Web Context is not configured. Set XENO_WEB_CONTEXT_TOKEN or XENO_WEB_CONTEXT_TOKEN_FILE."),{code:"WEB_CONTEXT_NOT_CONFIGURED"})}function $Z(e=process.env){return new d_t({baseUrl:e.XENO_WEB_CONTEXT_URL?.trim()||p_t,token:f_t(e)})}function Y1e(e=process.env){return{client:new _Z(e),createRequest:nD({actor:{id:"xeno-agent-cli",kind:"agent"},scope:{kind:"local-profile",profileId:"pending-token-scope"},classification:"public",purposePrefix:"xeno-agent-cli:chat",budget:{durationMs:12e4,maxAttempts:3,maxConcurrency:4,maxBytes:1e7,maxPages:100,maxRedirects:8,maxProviderCostUsd:0}})}}var p_t,_Z,BZ=Ie(()=>{"use strict";at();p_t="http://127.0.0.1:8080";_Z=class{constructor(t){this.env=t}env;client;tenantId;async search(t){return this.getClient().search(await this.bindTenant(t))}async scrapeAndWait(t,n){return this.getClient().scrapeAndWait(await this.bindTenant(t),n)}getClient(){return this.client??=$Z(this.env),this.client}async bindTenant(t){this.tenantId??=this.getClient().account().then(r=>r.tenantId);let n=await this.tenantId;return{...t,scope:{kind:"tenant",tenantId:n}}}}});var K1e=Ie(()=>{"use strict"});function Z1e(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(t.success===!1)return typeof t.error=="string";if(t.success!==!0||!t.snapshot||typeof t.snapshot!="object"||Array.isArray(t.snapshot))return!1;let n=t.snapshot,r=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,i=(o,s,a,c=!1)=>Array.isArray(o)&&o.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&typeof l[s]=="string"&&r(l[a])&&(!c||l.cost===null));return n.source==="local-runtime-journal"&&n.billingStatus==="unavailable"&&n.totalCost===null&&typeof n.observedAt=="string"&&Number.isFinite(Date.parse(n.observedAt))&&r(n.totalTokens)&&r(n.totalRequests)&&r(n.unmeasuredRequests)&&n.unmeasuredRequests<=n.totalRequests&&i(n.dailyUsage,"label","value")&&i(n.weeklyUsage,"label","value")&&i(n.monthlyUsage,"label","value")&&i(n.costByModel,"model","tokens",!0)&&i(n.topAgents,"name","tokens",!0)}var e$e=Ie(()=>{"use strict"});var t$e=Ie(()=>{"use strict"});function n$e(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.success===!1?typeof t.error=="string":t.success===!0&&t.source==="local-runtime-journal"&&typeof t.observedAt=="string"&&Number.isFinite(Date.parse(t.observedAt))&&typeof t.complete=="boolean"&&(t.complete?t.nextCursor===null:typeof t.nextCursor=="string"&&t.nextCursor.length>0&&t.nextCursor.length<=4096)&&Array.isArray(t.entries)&&t.entries.length<=1e4&&t.entries.every(n=>n&&typeof n=="object"&&["id","timestamp","action","actor","target","details"].every(r=>typeof n[r]=="string")&&Number.isFinite(Date.parse(n.timestamp)))}var r$e=Ie(()=>{"use strict"});function o$e(e){return!MZ(e)||typeof e.success!="boolean"||e.error!==void 0&&(typeof e.error!="string"||e.error.length>1e3)?!1:e.success?e.content!==void 0&&(typeof e.content!="string"||e.content.length>128e3)||e.loadedModel!==void 0&&!i$e(e.loadedModel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length>1e3||!e.models.every(t=>MZ(t)&&i$e(t.id)&&typeof t.name=="string"&&t.name.length<=512&&(t.contextWindowTokens===void 0||Number.isSafeInteger(t.contextWindowTokens)&&t.contextWindowTokens>0)))||e.usage!==void 0&&(!MZ(e.usage)||!["inputTokens","outputTokens"].every(t=>Number.isSafeInteger(e.usage[t])&&(e.usage[t]??-1)>=0))?!1:e.content!==void 0||e.models!==void 0||e.loadedModel!==void 0:typeof e.error=="string"&&!!e.error}var MZ,i$e,s$e=Ie(()=>{"use strict";MZ=e=>!!e&&typeof e=="object"&&!Array.isArray(e),i$e=e=>typeof e=="string"&&e.length>0&&e.length<=512&&!/[\x00-\x1f\x7f]/.test(e)});var VMn,a$e=Ie(()=>{"use strict";VMn=new TextEncoder});var c$e=Ie(()=>{"use strict"});var l$e=Ie(()=>{"use strict"});var u$e=Ie(()=>{"use strict"});var d$e=Ie(()=>{"use strict"});var p$e=Ie(()=>{"use strict"});var f$e=Ie(()=>{"use strict";p$e()});var m$e=Ie(()=>{"use strict"});var h$e=Ie(()=>{"use strict"});var g$e=Ie(()=>{"use strict"});var m_t,A$e=Ie(()=>{"use strict";mI();m_t=1024*1024});import{WEB_JOB_PROGRESS_OPERATIONS as ZMn,WEB_JOB_PROGRESS_SCHEMA as eNn,WEB_JOB_PROGRESS_SCHEMA_VERSION as tNn,WEB_JOB_PROGRESS_STATES as nNn,TERMINAL_WEB_JOB_STATES as rNn,isTerminalWebJobState as iNn,isWebJobProgress as oNn,parseWebJobProgress as sNn}from"@xenosystem/web-context-client/progress";function y_t(e){return typeof e=="string"&&h_t.includes(e)}function w$e(e){return so(e)?Bn(e.clientId)&&Bn(e.clientVersion)&&Bn(e.instanceId)&&y_t(e.surface):!1}function b$e(e){return!so(e)||!so(e.protocol)||!so(e.host)||!so(e.storage)?!1:Number.isInteger(e.protocol.current)&&S_t(e.protocol.supported)&&Bn(e.host.instanceId)&&Bn(e.host.version)&&(e.host.authority==="primary"||e.host.authority==="diagnostic-read-only")&&(e.host.processBoundary==="in-process"||e.host.processBoundary==="per-user-service")&&e.storage.owner==="xeno-agent-host"&&Number.isInteger(e.storage.schemaVersion)&&Number.isInteger(e.storage.eventSchemaVersion)&&w$e(e.surface)}function NZ(e){return!so(e)||!Bn(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(k_t)}function b_t(e){return!so(e)||!so(e.event)?!1:Bn(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&Bn(e.timestamp)&&Bn(e.conversationId)&&Bn(e.requestId)&&Bn(e.type)&&Bn(e.source)}function v$e(e){return!so(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(b_t)}function I$e(e){return!so(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&Bn(e.conversationId)&&Bn(e.requestId)&&Bn(e.adapterId)&&so(e.selection)&&Bn(e.selection.providerId)&&Bn(e.selection.catalogRevision):Bn(e.code)&&Bn(e.safeError)}function k$e(e){return!so(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&Bn(e.conversationId)&&Bn(e.requestId):Bn(e.code)&&Bn(e.safeError)}function E$e(e){return so(e)&&Bn(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&v_t(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e}function v_t(e){return typeof e=="string"&&w_t.includes(e)}function S$e(e,t,n){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new qi("surface_mismatch",`Agent host acknowledged ${e.surface.surface}/${e.surface.instanceId} instead of ${t.surface}/${t.instanceId}.`);if(e.protocol.current<n.min||e.protocol.current>n.max||n.max<e.protocol.supported.min||n.min>e.protocol.supported.max)throw new qi("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${n.min}-${n.max}.`)}function I_t(e){return!(!so(e)||e.chatExecution!==void 0&&!NR(e.chatExecution)||e.durableResume!==void 0&&!NR(e.durableResume)||e.nativeTuiAttach!==void 0&&!NR(e.nativeTuiAttach)||e.reconciliation!==void 0&&!NR(e.reconciliation)||e.modelSwitchInPlace!==void 0&&!NR(e.modelSwitchInPlace)||e.resumeCompatibilityKey!==void 0&&typeof e.resumeCompatibilityKey!="string")}function NR(e){return so(e)?(e.status==="available"||e.status==="degraded"||e.status==="blocked"||e.status==="unsupported")&&(e.source==="provider"||e.source==="host"||e.source==="policy")&&(e.reason===void 0||typeof e.reason=="string")&&(e.version===void 0||typeof e.version=="string"):!1}function k_t(e){return so(e)?Bn(e.id)&&typeof e.kind=="string"&&g_t.includes(e.kind)&&Bn(e.displayName)&&C$e(e.availability)&&so(e.capabilities)&&(e.providerSession===void 0||I_t(e.providerSession))&&Array.isArray(e.models)&&e.models.every(E_t)&&Bn(e.catalogRevision):!1}function E_t(e){return so(e)&&Bn(e.id)&&Bn(e.displayName)&&C$e(e.availability)&&(e.reasoningOptions===void 0||Array.isArray(e.reasoningOptions)&&e.reasoningOptions.every(t=>so(t)&&Bn(t.id)&&Bn(t.label)&&(t.runtimeModelId===void 0||Bn(t.runtimeModelId))&&(t.runtimeReasoningEffort===void 0||typeof t.runtimeReasoningEffort=="string"&&/^[a-z][a-z0-9_-]{0,79}$/i.test(t.runtimeReasoningEffort))&&(t.isDefault===void 0||typeof t.isDefault=="boolean")))}function C$e(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function S_t(e){return so(e)&&Number.isInteger(e.min)&&Number.isInteger(e.max)&&typeof e.min=="number"&&typeof e.max=="number"&&e.min>0&&e.max>=e.min}function Bn(e){return typeof e=="string"&&e.trim().length>0}function so(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function x$e(e){for(let t of x_t)for(let n of C_t)if(e===`${t}tool.${n}`)return n;return null}function KA(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n:void 0}function R$e(e){let t=e.event;return KA(t,"toolName")||KA(t,"tool")||KA(t,"name")||KA(t,"title")||KA(t,"kind")}function T$e(e){let t=e.event;return KA(t,"toolCallId")||KA(t,"tool_call_id")}function P$e(e){let t=e.event;for(let n of["rawInput","input","arguments","parameters","args"]){let r=t?.[n];if(r&&typeof r=="object"&&!Array.isArray(r))return r}}function _$e(e){let t=e.event;for(let n of["rawOutput","output","result","content"]){let r=t?.[n];if(typeof r=="string")return r.length>0?r:void 0;if(r!=null)try{let i=JSON.stringify(r);if(i&&i!=="{}"&&i!=="[]")return i}catch{}}}function $$e(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var hI,y$e,h_t,g_t,A_t,aNn,w_t,qi,C_t,x_t,mI=Ie(()=>{"use strict";K1e();e$e();t$e();r$e();s$e();a$e();c$e();l$e();u$e();d$e();f$e();m$e();h$e();g$e();A$e();hI=1,y$e=1,h_t=["standalone-desktop","hub-embed","shell-embed","embed-preview","panel-embed","headless-client"],g_t=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"],A_t=["workspace.usage","workspace.audit","inference.request","workspace.schedule","workspace.backup","workspace.environment","account.request","workforce.request","workspace.notifications","workspace.rules","workspace.browser","workspace.browser.session","host.handshake","providers.list","providers.refresh","runtime.events.list","workspace.lifecycle.apply","state.workspaces.load","state.workspaces.save","state.conversations.load","state.conversations.save","state.conversations.delete","workspace.access.grant","coordination.held.list","coordination.held.release","coordination.policy.set","coordination.state.get","coordination.action","workspace.application.grant","workspace.directory.list","workspace.file.read","workspace.file.write","workspace.command.run","workspace.terminal.start","workspace.terminal.stop","workspace.pty.start","workspace.pty.snapshot","workspace.pty.input","workspace.pty.resize","workspace.pty.clear","workspace.pty.stop","conversation.open","conversation.resume","xeno.tui.attach","provider.lanes.list","provider.lanes.get","provider.lanes.select","provider.native.attach","provider.native.detach","provider.native.reattach","provider.native.stop","provider.reconcile","turn.start","turn.cancel","turn.steer","context.inject","turn.queue","turn.queue.list","run.observation.snapshot","run.observation.change","run.observation.overlaps","fleet.view","fleet.route","fleet.plan","subagent.run.create","subagent.run.list","subagent.run.cancel","subagent.scheduler.status","subagent.scheduler.recover","session.list","session.attach","session.detach","session.snapshot","session.input","session.takeover","session.release","session.setMode","acp.agents.list","acp.agents.addPreset","acp.agents.remove","acp.capabilitySnapshot.get","acp.command.invoke","intake.sources.list","intake.items.list","intake.item.claim","intake.item.release","intake.item.dispatch","knowledge.list","knowledge.record","knowledge.forget","knowledge.context","turn.queue.drop","elicitation.choose-directory.answer","elicitation.workspace-placement.answer","elicitation.permission.answer","turn.resume","acp.provider.approve","permissions.rules.list","permissions.rules.revoke","elicitation.ask-user.answer","sdk.sessions.list","sdk.sessions.show","sdk.sessions.attach","sdk.sessions.detach","sdk.sessions.delete","sdk.sessions.clean","sdk.checkpoints.list","sdk.checkpoints.restore","sdk.checkpoints.delete","sdk.tasks.output","sdk.tasks.stop","engineering.git.status","engineering.git.diff","engineering.git.stage","engineering.git.unstage","engineering.git.commit","engineering.git.branch","engineering.git.push","engineering.git.pr.create","engineering.landing.enqueue","engineering.landing.remove","engineering.landing.status","engineering.landing.land","engineering.landing.verify","engineering.checks.discover","engineering.checks.run","engineering.background.start","engineering.background.list","engineering.background.output","engineering.background.stop","engineering.runs.list","engineering.diagnostics","engineering.patches.list","engineering.patches.enqueue","engineering.patches.update","engineering.patches.review","engineering.checkpoints.list","engineering.checkpoints.compare","engineering.checkpoints.restore","engineering.sessions.list","engineering.runtime.timeline"],aNn=new Set(A_t),w_t=["host.ready","provider.catalog.changed","state.workspaces.changed","runtime.event.appended","turn.execution.completed","turn.execution.failed","turn.execution.abandoned","elicitation.choose-directory.requested","elicitation.workspace-placement.requested","elicitation.permission.requested","elicitation.ask-user.requested","task.changed","workspace.terminal.data","workspace.terminal.exit","workspace.pty.data","workspace.pty.exit","coordination.event","run.observation","session.event","provider.lane.created","provider.lane.selected","provider.lane.resumed","provider.lane.invalidated","provider.writer.acquired","provider.writer.renewed","provider.writer.released","provider.writer.recovery_classified","provider.native_tui.started","provider.native_tui.detached","provider.native_tui.exited","provider.reconciliation.started","provider.reconciliation.completed","provider.reconciliation.failed","provider.portable_context.acknowledged_partial"],qi=class extends Error{code;constructor(t,n){super(n),this.name="AgentHostProtocolError",this.code=t}};C_t=["started","updated","completed","failed","cancelled"],x_t=["","acp."]});import{createHash as R_t}from"node:crypto";import{setTimeout as T_t}from"node:timers/promises";function $_t(e,t){return`subrun-${R_t("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}async function B_t(e,t,n){return((await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}))?.events??[]).map(i=>{let o=String(i.type??"").toLowerCase();if(!o.includes("text")&&!o.includes("message")&&!o.includes("delta"))return"";let s=i.event??{};return typeof s.text=="string"?s.text:typeof s.delta=="string"?s.delta:""}).join("")}function M_t(e,t,n,r){let i=new Set,o=typeof r.onToolStart=="function"||typeof r.onToolEnd=="function",s=a=>{try{a()}catch{}};return async function(){if(!o)return;let c=await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}).catch(()=>null);for(let l of c?.events??[]){let u=x$e(String(l.type??""));if(!u)continue;let d=`${T$e(l)??l.id}:${u}`;if(i.has(d))continue;i.add(d);let p=R$e(l)??"unknown";if(u==="started"&&r.onToolStart){let m=r.onToolStart;s(()=>m(p,P$e(l)??{}))}let f=$$e(u);if(f!==null&&r.onToolEnd){let m=r.onToolEnd;s(()=>m(p,{success:f,output:_$e(l)??""}))}}}}function B$e(e){let t=e.pollIntervalMs??250;return async n=>{let r=n.task,i=$_t(e.rootTraceId,r.id),o={lastTraceId:null,tokenUsage:{input:0,output:0,total:0},async run(s){let a=Math.max(1e3,e.deadline-Date.now()),c={parentConversationId:e.parentConversationId,...e.parentRequestId===void 0?{}:{parentRequestId:e.parentRequestId},parentAgentId:e.parentAgentId,childConversationId:i,childAgentId:r.role?`delegated-${r.role}`:"delegated-branch",workspaceId:e.workspaceId,teamId:e.teamId,objective:s,...r.role===void 0?{}:{role:r.role},policy:{maxRuntimeMs:a}},l=await e.client.createSubagentRun(c);if(!l?.success||!l.run)throw new Error(l?.safeError??"The Agent host refused to create a subagent run for this delegated branch.");let u=l.run.id;o.lastTraceId=u;let d=M_t(e.client,i,u,{onToolStart:n.onToolStart,onToolEnd:n.onToolEnd});for(;;){if(e.signal?.aborted){await e.client.cancelSubagentRun({runId:u}).catch(()=>{});let h=new Error("Delegated branch was cancelled.");throw h.name="AgentInterruptedError",h}let f=((await e.client.listSubagentRuns({parentConversationId:e.parentConversationId}))?.runs??[]).find(h=>h.id===u),m=String(f?.status??"");if(P_t.has(m)){if(__t.has(m))throw new Error(f?.error??`The delegated branch ended as '${m}' without reporting a reason.`);await d();let h=await B_t(e.client,i,u);if(h.length===0)throw new Error(`The delegated branch reported '${m}' but produced no readable output. Its runtime events carry no text for this run id.`);return h}if(Date.now()>=e.deadline)throw await e.client.cancelSubagentRun({runId:u}).catch(()=>{}),new Error("The delegated branch exceeded the time this run was given to wait.");await d(),await T_t(t,void 0,{signal:e.signal})}}};return o}}var P_t,__t,M$e=Ie(()=>{"use strict";mI();P_t=new Set(["completed","succeeded","failed","cancelled","error"]),__t=new Set(["failed","cancelled","error"])});import{execFile as N$e,execFileSync as OZ}from"node:child_process";import{promisify as O$e}from"node:util";import{createHash as N_t}from"node:crypto";import{existsSync as O_t,readFileSync as DZ,readlinkSync as D_t}from"node:fs";import{hostname as ZA}from"node:os";function wQ(e){return Number.isInteger(e)&&e>0}function Q_t(e){return N_t("sha256").update(e).digest("hex")}function DR(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${Q_t(t)}`:void 0}function AQ(){if(process.platform==="linux")try{return DZ("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function Fp(e){if(typeof e!="number"||!wQ(e))return"dead";try{return process.kill(e,0),"live"}catch(t){return t.code==="ESRCH"?"dead":"unknown"}}function LZ(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function D$e(e){return["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",["$ErrorActionPreference = 'Stop'",`$items = @(Get-Process -Id @(${e.join(", ")}) -ErrorAction SilentlyContinue)`,"$out = @($items | ForEach-Object { $path = try { [string]$_.Path } catch { '' }; [pscustomobject]@{ pid = [int]$_.Id; startedAt = $_.StartTime.ToUniversalTime().ToString('o'); executable = $path } })","$out | ConvertTo-Json -Compress"].join("; ")]}function L$e(e){let t=new Map;try{if(!e)return t;let n=JSON.parse(e);for(let r of Array.isArray(n)?n:[n]){let i=Number(r.pid),o=LZ(String(r.startedAt??""));!wQ(i)||!o||t.set(i,{pid:i,processStartedAt:o,hostname:ZA(),...DR(r.executable)?{executableFingerprint:DR(r.executable)}:{},confidence:"observed"})}}catch{return t}return t}function F_t(e){if(!e.length)return new Map;try{return L$e(OZ("powershell.exe",D$e(e),{encoding:"utf8",windowsHide:!0,timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim())}catch{return new Map}}function U_t(){if(OR)return OR;try{let e=Number.parseInt(OZ("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);OR=Number.isFinite(e)&&e>0?e:100}catch{OR=100}return OR}function q_t(){try{let e=/^btime\s+(\d+)$/m.exec(DZ("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function j_t(e){try{let t=DZ(`/proc/${e}/stat`,"utf8"),n=t.lastIndexOf(")");if(n<0)return null;let r=t.slice(n+2).trim().split(/\s+/),i=Number(r[19]),o=q_t();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/U_t())*1e3).toISOString(),a;try{a=D_t(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:ZA(),...AQ()?{bootId:AQ()}:{},...DR(a)?{executableFingerprint:DR(a)}:{},confidence:"observed"}}catch{return null}}function Q$e(e){let t=new Map;if(process.platform==="linux"){for(let n of e){let r=j_t(n);r&&t.set(n,r)}return t}for(let n of e)try{let r=OZ("ps",["-p",String(n),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=LZ(r);if(!i)continue;t.set(n,{pid:n,processStartedAt:i,hostname:ZA(),confidence:"observed"})}catch{continue}return t}function LR(e){let t=[...new Set(e.filter(wQ))],n=t.includes(process.pid),r=n?t.filter(o=>o!==process.pid):t,i=process.platform==="win32"?F_t(r):Q$e(r);return n&&i.set(process.pid,zm()),i}function F$e(e){return LR([e]).get(e)??null}async function U$e(e,t){t?.throwIfAborted();let n=[...new Set(e.filter(wQ))],r=n.filter(o=>o!==process.pid),i=new Map;if(process.platform==="win32"&&r.length)try{let o=await O$e(N$e)("powershell.exe",D$e(r),{encoding:"utf8",windowsHide:!0,timeout:1e4,maxBuffer:1048576,signal:t});i=L$e(o.stdout.trim())}catch{t?.throwIfAborted()}else if(process.platform==="linux")i=Q$e(r);else if(process.platform!=="win32")for(let o of r){t?.throwIfAborted();try{let{stdout:s}=await O$e(N$e)("ps",["-p",String(o),"-o","lstart="],{encoding:"utf8",timeout:2e3,signal:t,env:{...process.env,LC_ALL:"C"},maxBuffer:4096}),a=LZ(s.trim());a&&i.set(o,{pid:o,processStartedAt:a,hostname:ZA(),confidence:"observed"})}catch{t?.throwIfAborted()}}return t?.throwIfAborted(),n.includes(process.pid)&&i.set(process.pid,zm()),i}function yQ(e,t=new Date,n=!1){return(n?F$e(e):null)??{pid:e,processStartedAt:t.toISOString(),hostname:ZA(),confidence:"degraded"}}function zm(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:ZA(),...AQ()?{bootId:AQ()}:{},...O_t(process.execPath)?{executableFingerprint:DR(process.execPath)}:{},confidence:"self"}}function Lo(e,t=F$e){if(e.hostname!==ZA())return{status:"remote",expected:e,reason:"Process belongs to another host."};if(Fp(e.pid)==="dead")return{status:"dead",expected:e,reason:"Process ID is not live."};let n=t(e.pid);if(!n)return{status:"degraded",expected:e,reason:"Creation time could not be observed."};let r=Date.parse(e.processStartedAt),i=Date.parse(n.processStartedAt);return!Number.isFinite(r)||!Number.isFinite(i)||Math.abs(r-i)>L_t?{status:"mismatch",expected:e,observed:n,reason:"Process creation time does not match."}:e.bootId&&n.bootId&&e.bootId!==n.bootId?{status:"mismatch",expected:e,observed:n,reason:"Host boot identity does not match."}:e.executableFingerprint&&n.executableFingerprint&&e.executableFingerprint!==n.executableFingerprint?{status:"mismatch",expected:e,observed:n,reason:"Executable identity does not match."}:{status:"live",expected:e,observed:n}}var L_t,OR,sd=Ie(()=>{"use strict";L_t=3e3});import{createHash as V_t,randomBytes as H_t}from"node:crypto";import{chmodSync as W_t,existsSync as G_t,mkdirSync as j$e,readFileSync as J_t,renameSync as X_t,unlinkSync as V$e,writeFileSync as z_t}from"node:fs";import{dirname as Y_t,join as QR}from"node:path";function H$e(){return Qc()}function K_t(e){return V_t("sha256").update(e).digest("hex").slice(0,16)}function Mn(){return QR(H$e(),"daemon")}function QZ(){return QR(Mn(),"daemon.json")}function W$e(){return QR(Mn(),"daemon.lock")}function gI(){return QR(Mn(),"daemon.log")}function FZ(){let e=K_t(H$e());return process.platform==="win32"?{transport:"named-pipe",endpoint:`\\\\.\\pipe\\xeno-agent-daemon-${e}`}:{transport:"unix-socket",endpoint:QR(Mn(),"daemon.sock")}}function bQ(){j$e(Mn(),{recursive:!0})}function G$e(){return H_t(32).toString("base64url")}function q$e(e){if(process.platform!=="win32")try{W_t(e,384)}catch{}}function UZ(){try{let e=QZ(),t=J_t(e,"utf8"),n=JSON.parse(t);if(!n||n.schemaVersion!==1||n.protocolVersion!==1||n.transport!=="named-pipe"&&n.transport!=="unix-socket"||typeof n.endpoint!="string"||typeof n.authToken!="string"||!Number.isSafeInteger(n.pid)||typeof n.startedAt!="string"||typeof n.cliVersion!="string"||typeof n.logPath!="string")throw new Error("daemon state schema is invalid");return n}catch(e){if(e.code==="ENOENT")return null;throw new Error(`Daemon state is corrupt or unreadable: ${e instanceof Error?e.message:String(e)}`)}}function J$e(e){let t=QZ();j$e(Y_t(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;z_t(n,JSON.stringify(e,null,2)+`
|
|
2881
|
+
`&&(this.atLineStart=!0);this.writeFn(n)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},g1e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],vR=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,n){this.writeFn=t??(r=>{p1e.writeFrame(r,"spinner")}),this.clearFn=n??(()=>{p1e.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let n=g1e[this.frameIndex%g1e.length],r=`${en(n)} ${ke(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${r}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});var he,gi=Ie(()=>{"use strict";he="0.5.52"});import{readFileSync as u_t}from"node:fs";import{WebContextClient as d_t}from"@xenosystem/web-context-client";function f_t(e=process.env){let t=e.XENO_WEB_CONTEXT_TOKEN?.trim();if(t)return t;let n=e.XENO_WEB_CONTEXT_TOKEN_FILE?.trim();if(n){let r=u_t(n,"utf8").trim();if(r)return r}throw Object.assign(new Error("XENO Web Context is not configured. Set XENO_WEB_CONTEXT_TOKEN or XENO_WEB_CONTEXT_TOKEN_FILE."),{code:"WEB_CONTEXT_NOT_CONFIGURED"})}function $Z(e=process.env){return new d_t({baseUrl:e.XENO_WEB_CONTEXT_URL?.trim()||p_t,token:f_t(e)})}function Y1e(e=process.env){return{client:new _Z(e),createRequest:nD({actor:{id:"xeno-agent-cli",kind:"agent"},scope:{kind:"local-profile",profileId:"pending-token-scope"},classification:"public",purposePrefix:"xeno-agent-cli:chat",budget:{durationMs:12e4,maxAttempts:3,maxConcurrency:4,maxBytes:1e7,maxPages:100,maxRedirects:8,maxProviderCostUsd:0}})}}var p_t,_Z,BZ=Ie(()=>{"use strict";at();p_t="http://127.0.0.1:8080";_Z=class{constructor(t){this.env=t}env;client;tenantId;async search(t){return this.getClient().search(await this.bindTenant(t))}async scrapeAndWait(t,n){return this.getClient().scrapeAndWait(await this.bindTenant(t),n)}getClient(){return this.client??=$Z(this.env),this.client}async bindTenant(t){this.tenantId??=this.getClient().account().then(r=>r.tenantId);let n=await this.tenantId;return{...t,scope:{kind:"tenant",tenantId:n}}}}});var K1e=Ie(()=>{"use strict"});function Z1e(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(t.success===!1)return typeof t.error=="string";if(t.success!==!0||!t.snapshot||typeof t.snapshot!="object"||Array.isArray(t.snapshot))return!1;let n=t.snapshot,r=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,i=(o,s,a,c=!1)=>Array.isArray(o)&&o.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&typeof l[s]=="string"&&r(l[a])&&(!c||l.cost===null));return n.source==="local-runtime-journal"&&n.billingStatus==="unavailable"&&n.totalCost===null&&typeof n.observedAt=="string"&&Number.isFinite(Date.parse(n.observedAt))&&r(n.totalTokens)&&r(n.totalRequests)&&r(n.unmeasuredRequests)&&n.unmeasuredRequests<=n.totalRequests&&i(n.dailyUsage,"label","value")&&i(n.weeklyUsage,"label","value")&&i(n.monthlyUsage,"label","value")&&i(n.costByModel,"model","tokens",!0)&&i(n.topAgents,"name","tokens",!0)}var e$e=Ie(()=>{"use strict"});var t$e=Ie(()=>{"use strict"});function n$e(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.success===!1?typeof t.error=="string":t.success===!0&&t.source==="local-runtime-journal"&&typeof t.observedAt=="string"&&Number.isFinite(Date.parse(t.observedAt))&&typeof t.complete=="boolean"&&(t.complete?t.nextCursor===null:typeof t.nextCursor=="string"&&t.nextCursor.length>0&&t.nextCursor.length<=4096)&&Array.isArray(t.entries)&&t.entries.length<=1e4&&t.entries.every(n=>n&&typeof n=="object"&&["id","timestamp","action","actor","target","details"].every(r=>typeof n[r]=="string")&&Number.isFinite(Date.parse(n.timestamp)))}var r$e=Ie(()=>{"use strict"});function o$e(e){return!MZ(e)||typeof e.success!="boolean"||e.error!==void 0&&(typeof e.error!="string"||e.error.length>1e3)?!1:e.success?e.content!==void 0&&(typeof e.content!="string"||e.content.length>128e3)||e.loadedModel!==void 0&&!i$e(e.loadedModel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length>1e3||!e.models.every(t=>MZ(t)&&i$e(t.id)&&typeof t.name=="string"&&t.name.length<=512&&(t.contextWindowTokens===void 0||Number.isSafeInteger(t.contextWindowTokens)&&t.contextWindowTokens>0)))||e.usage!==void 0&&(!MZ(e.usage)||!["inputTokens","outputTokens"].every(t=>Number.isSafeInteger(e.usage[t])&&(e.usage[t]??-1)>=0))?!1:e.content!==void 0||e.models!==void 0||e.loadedModel!==void 0:typeof e.error=="string"&&!!e.error}var MZ,i$e,s$e=Ie(()=>{"use strict";MZ=e=>!!e&&typeof e=="object"&&!Array.isArray(e),i$e=e=>typeof e=="string"&&e.length>0&&e.length<=512&&!/[\x00-\x1f\x7f]/.test(e)});var VMn,a$e=Ie(()=>{"use strict";VMn=new TextEncoder});var c$e=Ie(()=>{"use strict"});var l$e=Ie(()=>{"use strict"});var u$e=Ie(()=>{"use strict"});var d$e=Ie(()=>{"use strict"});var p$e=Ie(()=>{"use strict"});var f$e=Ie(()=>{"use strict";p$e()});var m$e=Ie(()=>{"use strict"});var h$e=Ie(()=>{"use strict"});var g$e=Ie(()=>{"use strict"});var m_t,A$e=Ie(()=>{"use strict";mI();m_t=1024*1024});import{WEB_JOB_PROGRESS_OPERATIONS as ZMn,WEB_JOB_PROGRESS_SCHEMA as eNn,WEB_JOB_PROGRESS_SCHEMA_VERSION as tNn,WEB_JOB_PROGRESS_STATES as nNn,TERMINAL_WEB_JOB_STATES as rNn,isTerminalWebJobState as iNn,isWebJobProgress as oNn,parseWebJobProgress as sNn}from"@xenosystem/web-context-client/progress";function y_t(e){return typeof e=="string"&&h_t.includes(e)}function w$e(e){return so(e)?Bn(e.clientId)&&Bn(e.clientVersion)&&Bn(e.instanceId)&&y_t(e.surface):!1}function b$e(e){return!so(e)||!so(e.protocol)||!so(e.host)||!so(e.storage)?!1:Number.isInteger(e.protocol.current)&&S_t(e.protocol.supported)&&Bn(e.host.instanceId)&&Bn(e.host.version)&&(e.host.authority==="primary"||e.host.authority==="diagnostic-read-only")&&(e.host.processBoundary==="in-process"||e.host.processBoundary==="per-user-service")&&e.storage.owner==="xeno-agent-host"&&Number.isInteger(e.storage.schemaVersion)&&Number.isInteger(e.storage.eventSchemaVersion)&&w$e(e.surface)}function NZ(e){return!so(e)||!Bn(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(k_t)}function b_t(e){return!so(e)||!so(e.event)?!1:Bn(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&Bn(e.timestamp)&&Bn(e.conversationId)&&Bn(e.requestId)&&Bn(e.type)&&Bn(e.source)}function v$e(e){return!so(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(b_t)}function I$e(e){return!so(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&Bn(e.conversationId)&&Bn(e.requestId)&&Bn(e.adapterId)&&so(e.selection)&&Bn(e.selection.providerId)&&Bn(e.selection.catalogRevision):Bn(e.code)&&Bn(e.safeError)}function k$e(e){return!so(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&Bn(e.conversationId)&&Bn(e.requestId):Bn(e.code)&&Bn(e.safeError)}function E$e(e){return so(e)&&Bn(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&v_t(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e}function v_t(e){return typeof e=="string"&&w_t.includes(e)}function S$e(e,t,n){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new qi("surface_mismatch",`Agent host acknowledged ${e.surface.surface}/${e.surface.instanceId} instead of ${t.surface}/${t.instanceId}.`);if(e.protocol.current<n.min||e.protocol.current>n.max||n.max<e.protocol.supported.min||n.min>e.protocol.supported.max)throw new qi("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${n.min}-${n.max}.`)}function I_t(e){return!(!so(e)||e.chatExecution!==void 0&&!NR(e.chatExecution)||e.durableResume!==void 0&&!NR(e.durableResume)||e.nativeTuiAttach!==void 0&&!NR(e.nativeTuiAttach)||e.reconciliation!==void 0&&!NR(e.reconciliation)||e.modelSwitchInPlace!==void 0&&!NR(e.modelSwitchInPlace)||e.resumeCompatibilityKey!==void 0&&typeof e.resumeCompatibilityKey!="string")}function NR(e){return so(e)?(e.status==="available"||e.status==="degraded"||e.status==="blocked"||e.status==="unsupported")&&(e.source==="provider"||e.source==="host"||e.source==="policy")&&(e.reason===void 0||typeof e.reason=="string")&&(e.version===void 0||typeof e.version=="string"):!1}function k_t(e){return so(e)?Bn(e.id)&&typeof e.kind=="string"&&g_t.includes(e.kind)&&Bn(e.displayName)&&C$e(e.availability)&&so(e.capabilities)&&(e.providerSession===void 0||I_t(e.providerSession))&&Array.isArray(e.models)&&e.models.every(E_t)&&Bn(e.catalogRevision):!1}function E_t(e){return so(e)&&Bn(e.id)&&Bn(e.displayName)&&C$e(e.availability)&&(e.reasoningOptions===void 0||Array.isArray(e.reasoningOptions)&&e.reasoningOptions.every(t=>so(t)&&Bn(t.id)&&Bn(t.label)&&(t.runtimeModelId===void 0||Bn(t.runtimeModelId))&&(t.runtimeReasoningEffort===void 0||typeof t.runtimeReasoningEffort=="string"&&/^[a-z][a-z0-9_-]{0,79}$/i.test(t.runtimeReasoningEffort))&&(t.isDefault===void 0||typeof t.isDefault=="boolean")))}function C$e(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function S_t(e){return so(e)&&Number.isInteger(e.min)&&Number.isInteger(e.max)&&typeof e.min=="number"&&typeof e.max=="number"&&e.min>0&&e.max>=e.min}function Bn(e){return typeof e=="string"&&e.trim().length>0}function so(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function x$e(e){for(let t of x_t)for(let n of C_t)if(e===`${t}tool.${n}`)return n;return null}function KA(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n:void 0}function R$e(e){let t=e.event;return KA(t,"toolName")||KA(t,"tool")||KA(t,"name")||KA(t,"title")||KA(t,"kind")}function T$e(e){let t=e.event;return KA(t,"toolCallId")||KA(t,"tool_call_id")}function P$e(e){let t=e.event;for(let n of["rawInput","input","arguments","parameters","args"]){let r=t?.[n];if(r&&typeof r=="object"&&!Array.isArray(r))return r}}function _$e(e){let t=e.event;for(let n of["rawOutput","output","result","content"]){let r=t?.[n];if(typeof r=="string")return r.length>0?r:void 0;if(r!=null)try{let i=JSON.stringify(r);if(i&&i!=="{}"&&i!=="[]")return i}catch{}}}function $$e(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var hI,y$e,h_t,g_t,A_t,aNn,w_t,qi,C_t,x_t,mI=Ie(()=>{"use strict";K1e();e$e();t$e();r$e();s$e();a$e();c$e();l$e();u$e();d$e();f$e();m$e();h$e();g$e();A$e();hI=1,y$e=1,h_t=["standalone-desktop","hub-embed","shell-embed","embed-preview","panel-embed","headless-client"],g_t=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"],A_t=["workspace.usage","workspace.audit","inference.request","workspace.schedule","workspace.backup","workspace.environment","account.request","workforce.request","workspace.notifications","workspace.rules","workspace.browser","workspace.browser.session","host.handshake","providers.list","providers.refresh","runtime.events.list","workspace.lifecycle.apply","state.workspaces.load","state.workspaces.save","state.conversations.load","state.conversations.save","state.conversations.delete","workspace.access.grant","coordination.held.list","coordination.held.release","coordination.policy.set","coordination.state.get","coordination.action","workspace.application.grant","workspace.directory.list","workspace.file.read","workspace.file.write","workspace.command.run","workspace.terminal.start","workspace.terminal.stop","workspace.pty.start","workspace.pty.snapshot","workspace.pty.input","workspace.pty.resize","workspace.pty.clear","workspace.pty.stop","conversation.open","conversation.resume","xeno.tui.attach","provider.lanes.list","provider.lanes.get","provider.lanes.select","provider.native.attach","provider.native.detach","provider.native.reattach","provider.native.stop","provider.reconcile","turn.start","turn.cancel","turn.steer","context.inject","turn.queue","turn.queue.list","run.observation.snapshot","run.observation.change","run.observation.overlaps","fleet.view","fleet.route","fleet.plan","subagent.run.create","subagent.run.list","subagent.run.cancel","subagent.scheduler.status","subagent.scheduler.recover","session.list","session.attach","session.detach","session.snapshot","session.input","session.takeover","session.release","session.setMode","acp.agents.list","acp.agents.addPreset","acp.agents.remove","acp.capabilitySnapshot.get","acp.command.invoke","intake.sources.list","intake.items.list","intake.item.claim","intake.item.release","intake.item.dispatch","knowledge.list","knowledge.record","knowledge.forget","knowledge.context","turn.queue.drop","elicitation.choose-directory.answer","elicitation.workspace-placement.answer","elicitation.permission.answer","turn.resume","acp.provider.approve","permissions.rules.list","permissions.rules.revoke","elicitation.ask-user.answer","sdk.sessions.list","sdk.sessions.show","sdk.sessions.attach","sdk.sessions.detach","sdk.sessions.delete","sdk.sessions.clean","sdk.checkpoints.list","sdk.checkpoints.restore","sdk.checkpoints.delete","sdk.tasks.output","sdk.tasks.stop","engineering.git.status","engineering.git.diff","engineering.git.stage","engineering.git.unstage","engineering.git.commit","engineering.git.branch","engineering.git.push","engineering.git.pr.create","engineering.landing.enqueue","engineering.landing.remove","engineering.landing.status","engineering.landing.land","engineering.landing.verify","engineering.checks.discover","engineering.checks.run","engineering.background.start","engineering.background.list","engineering.background.output","engineering.background.stop","engineering.runs.list","engineering.diagnostics","engineering.patches.list","engineering.patches.enqueue","engineering.patches.update","engineering.patches.review","engineering.checkpoints.list","engineering.checkpoints.compare","engineering.checkpoints.restore","engineering.sessions.list","engineering.runtime.timeline"],aNn=new Set(A_t),w_t=["host.ready","provider.catalog.changed","state.workspaces.changed","runtime.event.appended","turn.execution.completed","turn.execution.failed","turn.execution.abandoned","elicitation.choose-directory.requested","elicitation.workspace-placement.requested","elicitation.permission.requested","elicitation.ask-user.requested","task.changed","workspace.terminal.data","workspace.terminal.exit","workspace.pty.data","workspace.pty.exit","coordination.event","run.observation","session.event","provider.lane.created","provider.lane.selected","provider.lane.resumed","provider.lane.invalidated","provider.writer.acquired","provider.writer.renewed","provider.writer.released","provider.writer.recovery_classified","provider.native_tui.started","provider.native_tui.detached","provider.native_tui.exited","provider.reconciliation.started","provider.reconciliation.completed","provider.reconciliation.failed","provider.portable_context.acknowledged_partial"],qi=class extends Error{code;constructor(t,n){super(n),this.name="AgentHostProtocolError",this.code=t}};C_t=["started","updated","completed","failed","cancelled"],x_t=["","acp."]});import{createHash as R_t}from"node:crypto";import{setTimeout as T_t}from"node:timers/promises";function $_t(e,t){return`subrun-${R_t("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}async function B_t(e,t,n){return((await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}))?.events??[]).map(i=>{let o=String(i.type??"").toLowerCase();if(!o.includes("text")&&!o.includes("message")&&!o.includes("delta"))return"";let s=i.event??{};return typeof s.text=="string"?s.text:typeof s.delta=="string"?s.delta:""}).join("")}function M_t(e,t,n,r){let i=new Set,o=typeof r.onToolStart=="function"||typeof r.onToolEnd=="function",s=a=>{try{a()}catch{}};return async function(){if(!o)return;let c=await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}).catch(()=>null);for(let l of c?.events??[]){let u=x$e(String(l.type??""));if(!u)continue;let d=`${T$e(l)??l.id}:${u}`;if(i.has(d))continue;i.add(d);let p=R$e(l)??"unknown";if(u==="started"&&r.onToolStart){let m=r.onToolStart;s(()=>m(p,P$e(l)??{}))}let f=$$e(u);if(f!==null&&r.onToolEnd){let m=r.onToolEnd;s(()=>m(p,{success:f,output:_$e(l)??""}))}}}}function B$e(e){let t=e.pollIntervalMs??250;return async n=>{let r=n.task,i=$_t(e.rootTraceId,r.id),o={lastTraceId:null,tokenUsage:{input:0,output:0,total:0},async run(s){let a=Math.max(1e3,e.deadline-Date.now()),c={parentConversationId:e.parentConversationId,...e.parentRequestId===void 0?{}:{parentRequestId:e.parentRequestId},parentAgentId:e.parentAgentId,childConversationId:i,childAgentId:r.role?`delegated-${r.role}`:"delegated-branch",workspaceId:e.workspaceId,teamId:e.teamId,objective:s,...r.role===void 0?{}:{role:r.role},policy:{maxRuntimeMs:a}},l=await e.client.createSubagentRun(c);if(!l?.success||!l.run)throw new Error(l?.safeError??"The Agent host refused to create a subagent run for this delegated branch.");let u=l.run.id;o.lastTraceId=u;let d=M_t(e.client,i,u,{onToolStart:n.onToolStart,onToolEnd:n.onToolEnd});for(;;){if(e.signal?.aborted){await e.client.cancelSubagentRun({runId:u}).catch(()=>{});let h=new Error("Delegated branch was cancelled.");throw h.name="AgentInterruptedError",h}let f=((await e.client.listSubagentRuns({parentConversationId:e.parentConversationId}))?.runs??[]).find(h=>h.id===u),m=String(f?.status??"");if(P_t.has(m)){if(__t.has(m))throw new Error(f?.error??`The delegated branch ended as '${m}' without reporting a reason.`);await d();let h=await B_t(e.client,i,u);if(h.length===0)throw new Error(`The delegated branch reported '${m}' but produced no readable output. Its runtime events carry no text for this run id.`);return h}if(Date.now()>=e.deadline)throw await e.client.cancelSubagentRun({runId:u}).catch(()=>{}),new Error("The delegated branch exceeded the time this run was given to wait.");await d(),await T_t(t,void 0,{signal:e.signal})}}};return o}}var P_t,__t,M$e=Ie(()=>{"use strict";mI();P_t=new Set(["completed","succeeded","failed","cancelled","error"]),__t=new Set(["failed","cancelled","error"])});import{execFile as N$e,execFileSync as OZ}from"node:child_process";import{promisify as O$e}from"node:util";import{createHash as N_t}from"node:crypto";import{existsSync as O_t,readFileSync as DZ,readlinkSync as D_t}from"node:fs";import{hostname as ZA}from"node:os";function wQ(e){return Number.isInteger(e)&&e>0}function Q_t(e){return N_t("sha256").update(e).digest("hex")}function DR(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${Q_t(t)}`:void 0}function AQ(){if(process.platform==="linux")try{return DZ("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function Fp(e){if(typeof e!="number"||!wQ(e))return"dead";try{return process.kill(e,0),"live"}catch(t){return t.code==="ESRCH"?"dead":"unknown"}}function LZ(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function D$e(e){return["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",["$ErrorActionPreference = 'Stop'",`$items = @(Get-Process -Id @(${e.join(", ")}) -ErrorAction SilentlyContinue)`,"$out = @($items | ForEach-Object { $path = try { [string]$_.Path } catch { '' }; [pscustomobject]@{ pid = [int]$_.Id; startedAt = $_.StartTime.ToUniversalTime().ToString('o'); executable = $path } })","$out | ConvertTo-Json -Compress"].join("; ")]}function L$e(e){let t=new Map;try{if(!e)return t;let n=JSON.parse(e);for(let r of Array.isArray(n)?n:[n]){let i=Number(r.pid),o=LZ(String(r.startedAt??""));!wQ(i)||!o||t.set(i,{pid:i,processStartedAt:o,hostname:ZA(),...DR(r.executable)?{executableFingerprint:DR(r.executable)}:{},confidence:"observed"})}}catch{return t}return t}function F_t(e){if(!e.length)return new Map;try{return L$e(OZ("powershell.exe",D$e(e),{encoding:"utf8",windowsHide:!0,timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim())}catch{return new Map}}function U_t(){if(OR)return OR;try{let e=Number.parseInt(OZ("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);OR=Number.isFinite(e)&&e>0?e:100}catch{OR=100}return OR}function q_t(){try{let e=/^btime\s+(\d+)$/m.exec(DZ("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function j_t(e){try{let t=DZ(`/proc/${e}/stat`,"utf8"),n=t.lastIndexOf(")");if(n<0)return null;let r=t.slice(n+2).trim().split(/\s+/),i=Number(r[19]),o=q_t();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/U_t())*1e3).toISOString(),a;try{a=D_t(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:ZA(),...AQ()?{bootId:AQ()}:{},...DR(a)?{executableFingerprint:DR(a)}:{},confidence:"observed"}}catch{return null}}function Q$e(e){let t=new Map;if(process.platform==="linux"){for(let n of e){let r=j_t(n);r&&t.set(n,r)}return t}for(let n of e)try{let r=OZ("ps",["-p",String(n),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=LZ(r);if(!i)continue;t.set(n,{pid:n,processStartedAt:i,hostname:ZA(),confidence:"observed"})}catch{continue}return t}function LR(e){let t=[...new Set(e.filter(wQ))],n=t.includes(process.pid),r=n?t.filter(o=>o!==process.pid):t,i=process.platform==="win32"?F_t(r):Q$e(r);return n&&i.set(process.pid,zm()),i}function F$e(e){return LR([e]).get(e)??null}async function U$e(e,t){t?.throwIfAborted();let n=[...new Set(e.filter(wQ))],r=n.filter(o=>o!==process.pid),i=new Map;if(process.platform==="win32"&&r.length)try{let o=await O$e(N$e)("powershell.exe",D$e(r),{encoding:"utf8",windowsHide:!0,timeout:1e4,maxBuffer:1048576,signal:t});i=L$e(o.stdout.trim())}catch{t?.throwIfAborted()}else if(process.platform==="linux")i=Q$e(r);else if(process.platform!=="win32")for(let o of r){t?.throwIfAborted();try{let{stdout:s}=await O$e(N$e)("ps",["-p",String(o),"-o","lstart="],{encoding:"utf8",timeout:2e3,signal:t,env:{...process.env,LC_ALL:"C"},maxBuffer:4096}),a=LZ(s.trim());a&&i.set(o,{pid:o,processStartedAt:a,hostname:ZA(),confidence:"observed"})}catch{t?.throwIfAborted()}}return t?.throwIfAborted(),n.includes(process.pid)&&i.set(process.pid,zm()),i}function yQ(e,t=new Date,n=!1){return(n?F$e(e):null)??{pid:e,processStartedAt:t.toISOString(),hostname:ZA(),confidence:"degraded"}}function zm(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:ZA(),...AQ()?{bootId:AQ()}:{},...O_t(process.execPath)?{executableFingerprint:DR(process.execPath)}:{},confidence:"self"}}function Lo(e,t=F$e){if(e.hostname!==ZA())return{status:"remote",expected:e,reason:"Process belongs to another host."};if(Fp(e.pid)==="dead")return{status:"dead",expected:e,reason:"Process ID is not live."};let n=t(e.pid);if(!n)return{status:"degraded",expected:e,reason:"Creation time could not be observed."};let r=Date.parse(e.processStartedAt),i=Date.parse(n.processStartedAt);return!Number.isFinite(r)||!Number.isFinite(i)||Math.abs(r-i)>L_t?{status:"mismatch",expected:e,observed:n,reason:"Process creation time does not match."}:e.bootId&&n.bootId&&e.bootId!==n.bootId?{status:"mismatch",expected:e,observed:n,reason:"Host boot identity does not match."}:e.executableFingerprint&&n.executableFingerprint&&e.executableFingerprint!==n.executableFingerprint?{status:"mismatch",expected:e,observed:n,reason:"Executable identity does not match."}:{status:"live",expected:e,observed:n}}var L_t,OR,sd=Ie(()=>{"use strict";L_t=3e3});import{createHash as V_t,randomBytes as H_t}from"node:crypto";import{chmodSync as W_t,existsSync as G_t,mkdirSync as j$e,readFileSync as J_t,renameSync as X_t,unlinkSync as V$e,writeFileSync as z_t}from"node:fs";import{dirname as Y_t,join as QR}from"node:path";function H$e(){return Qc()}function K_t(e){return V_t("sha256").update(e).digest("hex").slice(0,16)}function Mn(){return QR(H$e(),"daemon")}function QZ(){return QR(Mn(),"daemon.json")}function W$e(){return QR(Mn(),"daemon.lock")}function gI(){return QR(Mn(),"daemon.log")}function FZ(){let e=K_t(H$e());return process.platform==="win32"?{transport:"named-pipe",endpoint:`\\\\.\\pipe\\xeno-agent-daemon-${e}`}:{transport:"unix-socket",endpoint:QR(Mn(),"daemon.sock")}}function bQ(){j$e(Mn(),{recursive:!0})}function G$e(){return H_t(32).toString("base64url")}function q$e(e){if(process.platform!=="win32")try{W_t(e,384)}catch{}}function UZ(){try{let e=QZ(),t=J_t(e,"utf8"),n=JSON.parse(t);if(!n||n.schemaVersion!==1||n.protocolVersion!==1||n.transport!=="named-pipe"&&n.transport!=="unix-socket"||typeof n.endpoint!="string"||typeof n.authToken!="string"||!Number.isSafeInteger(n.pid)||typeof n.startedAt!="string"||typeof n.cliVersion!="string"||typeof n.logPath!="string")throw new Error("daemon state schema is invalid");return n}catch(e){if(e.code==="ENOENT")return null;throw new Error(`Daemon state is corrupt or unreadable: ${e instanceof Error?e.message:String(e)}`)}}function J$e(e){let t=QZ();j$e(Y_t(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;z_t(n,JSON.stringify(e,null,2)+`
|
|
2882
2882
|
`,{encoding:"utf8",mode:384}),q$e(n),X_t(n,t),q$e(t)}function vQ(){try{V$e(QZ())}catch{}}function X$e(){if(process.platform==="win32")return;let{endpoint:e}=FZ();if(G_t(e))try{V$e(e)}catch{}}function Xs(e){return Fp(e)!=="dead"}var ko=Ie(()=>{"use strict";Rg();sd()});import{existsSync as Z_t,linkSync as e1t,mkdirSync as t1t,readFileSync as n1t,rmSync as jZ,statSync as r1t,writeFileSync as i1t}from"node:fs";import{hostname as z$e}from"node:os";import{dirname as o1t}from"node:path";import{randomUUID as s1t}from"node:crypto";function a1t(){return new Date().toISOString()}function qZ(e){try{return JSON.parse(n1t(e,"utf8"))}catch{return null}}function c1t(e){if(e.hostname!==z$e())return!0;let t=Date.parse(e.acquiredAt);if(Number.isFinite(t)&&Date.now()-t<3e4)return!0;if(!Xs(e.pid))return!1;if(e.processIdentity){let n=Lo(e.processIdentity);return n.status==="live"||n.status==="degraded"||n.status==="remote"}return!0}function Y$e(e,t){t1t(o1t(e),{recursive:!0});let n=`${e}.${process.pid}.${s1t()}.tmp`;i1t(n,JSON.stringify(t,null,2)+`
|
|
2883
2883
|
`,{encoding:"utf8",flag:"wx"});try{e1t(n,e)}finally{jZ(n,{force:!0})}}function l1t(e){try{return Date.now()-r1t(e).mtimeMs<3e4}catch{return!1}}function u1t(e,t){return e?.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}function FR(e,t){return Object.assign(new Error(`${e} is already locked ${t}.`),{code:"CONTROL_PLANE_LOCK_BUSY"})}function Up(e){return e instanceof Error&&"code"in e&&e.code==="CONTROL_PLANE_LOCK_BUSY"}function d1t(e,t,n){try{Y$e(e,t)}catch(r){throw r.code==="EEXIST"?FR(n,"by another contender"):r}}function p1t(e,t){let n=qZ(e);n?.pid!==t.pid||n.hostname!==t.hostname||n.processStartedAt!==t.processStartedAt||jZ(e,{force:!0})}function Eo(e,t,n){let r=a1t(),i=zm(),o={schemaVersion:1,name:t,pid:process.pid,hostname:z$e(),processStartedAt:i.processStartedAt,processIdentity:i,version:n,acquiredAt:r,updatedAt:r};try{Y$e(e,o)}catch(s){if(s.code!=="EEXIST")throw s;let c=qZ(e);if(c&&c1t(c))throw FR(t,`by PID ${c.pid} on ${c.hostname}`);if(c){if(!u1t(qZ(e),c))throw FR(t,"while ownership was changing")}else{if(!Z_t(e))throw FR(t,"while ownership was changing");if(l1t(e))throw FR(t,"by an owner whose record is still being published")}jZ(e,{force:!0}),d1t(e,o,t)}return{record:o,release:()=>{p1t(e,o)}}}var qp=Ie(()=>{"use strict";ko();sd()});import{createHash as nBe,randomBytes as f1t,randomUUID as rBe}from"node:crypto";import{closeSync as iBe,existsSync as WZ,fstatSync as m1t,fsyncSync as h1t,mkdirSync as GZ,openSync as oBe,readFileSync as HZ,readSync as g1t,renameSync as A1t,writeFileSync as sBe}from"node:fs";import{cpus as w1t}from"node:os";import{dirname as aBe,isAbsolute as y1t,join as yI,resolve as b1t}from"node:path";function qR(e,t,n=1,r=Number.MAX_SAFE_INTEGER){let i=typeof e=="number"?e:Number.parseInt(String(e??""),10);return Number.isFinite(i)?Math.min(r,Math.max(n,Math.trunc(i))):t}function k1t(e,t,n=0,r=Number.MAX_SAFE_INTEGER){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.min(r,Math.max(n,i)):t}function AI(e,t){return t===void 0?e:Math.min(e,t)}function UR(e,t){return{maxConcurrency:AI(e.maxConcurrency,t?.maxConcurrency),maxCredentialConcurrency:AI(e.maxCredentialConcurrency,t?.maxCredentialConcurrency),maxRequestsPerWindow:AI(e.maxRequestsPerWindow,t?.maxRequestsPerWindow),maxTokensPerWindow:AI(e.maxTokensPerWindow,t?.maxTokensPerWindow),windowMs:t?.windowMs===void 0?e.windowMs:Math.max(1e3,t.windowMs)}}function E1t(e={}){let t=e.env??process.env,n=Math.max(1,e.cpuCount??w1t().length),r=Math.min(Math.max(1,n-2),v1t),i=qR(t.XENO_WORKFLOW_GLOBAL_CONCURRENCY,r,1,VZ),s=t.XENO_WORKFLOW_TRUSTED_CONCURRENCY_OVERRIDE==="1"?i:Math.min(r,i);s=AI(s,e.user?.globalConcurrency),s=AI(s,e.managed?.globalConcurrency),s=qR(s,r,1,VZ);let a={maxConcurrency:Math.min(s,8),maxCredentialConcurrency:Math.min(s,4),maxRequestsPerWindow:120,maxTokensPerWindow:2e6,windowMs:6e4},c=UR(a,e.user?.providerDefault),l=UR(c,e.managed?.providerDefault),u=new Set([...Object.keys(e.user?.providers??{}),...Object.keys(e.managed?.providers??{})]),d=Object.fromEntries([...u].map(f=>[f,UR(UR(l,e.user?.providers?.[f]),e.managed?.providers?.[f])])),p=(f,m,h=1,g=Number.MAX_SAFE_INTEGER)=>{let A=m,y=e.user?.[f],w=e.managed?.[f];return typeof y=="number"&&(A=Math.min(A,y)),typeof w=="number"&&(A=Math.min(A,w)),qR(A,m,h,g)};return{schemaVersion:1,productHardConcurrency:VZ,globalConcurrency:s,perRunConcurrency:p("perRunConcurrency",s,1,s),perParentConcurrency:p("perParentConcurrency",s,1,s),reservedPrioritySlots:Math.min(2,Math.max(0,s-1)),maxQueueLength:p("maxQueueLength",4096,1,65536),maxQueueWaitMs:p("maxQueueWaitMs",5*6e4,1e3,1440*6e4),maxAttemptsPerLogicalChild:p("maxAttemptsPerLogicalChild",3,1,100),maxAttemptsPerRun:p("maxAttemptsPerRun",1e3,1,1e4),maxReservedTokens:p("maxReservedTokens",4e6,1,Number.MAX_SAFE_INTEGER),maxReservedCostUsd:k1t(Math.min(e.user?.maxReservedCostUsd??500,e.managed?.maxReservedCostUsd??500),500,.01,1e6),leaseTtlMs:p("leaseTtlMs",4e3,2e3,5*6e4),heartbeatIntervalMs:p("heartbeatIntervalMs",1e3,250,6e4),maxStarvationMs:p("maxStarvationMs",3e4,1e3,60*6e4),providerDefault:l,providers:d}}function Z$e(e,t){if(!WZ(e)){if(t)throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy file not found: ${e}`);return}try{let n=JSON.parse(HZ(e,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("policy root must be an object");return n}catch(n){throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy is invalid: ${e}: ${n instanceof Error?n.message:String(n)}`)}}function S1t(e=process.env){let t=aBe(Mn()),n=e.XENO_WORKFLOW_RESOURCE_POLICY?.trim(),r=e.XENO_MANAGED_WORKFLOW_RESOURCE_POLICY?.trim(),i=a=>y1t(a)?a:b1t(a),o=Z$e(n?i(n):yI(t,"resource-policy.json"),!!n),s=r?Z$e(i(r),!0):void 0;return E1t({env:e,user:o,managed:s})}function So(e){return new Date(e).toISOString()}function C1t(e){return{schemaVersion:1,revision:0,nextFencingToken:1,updatedAt:So(e),permits:[],queue:[],attempts:[],usage:[],providerRates:[],effects:[]}}function x1t(e){let t=e,n=p=>!!(p&&typeof p=="object"&&!Array.isArray(p)),r=p=>typeof p=="string"&&p.length>0&&p.length<=512,i=p=>typeof p=="string"&&Number.isFinite(Date.parse(p)),o=p=>n(p)&&Number.isInteger(p.pid)&&Number(p.pid)>0&&r(p.hostname)&&i(p.processStartedAt),s=p=>n(p)&&r(p.permitId)&&r(p.requestId)&&r(p.operationId)&&r(p.runId)&&r(p.providerId)&&r(p.logicalChildId)&&r(p.attemptId)&&r(p.idempotencyKey)&&Number.isInteger(p.fencingToken)&&Number(p.fencingToken)>0&&o(p.owner)&&i(p.acquiredAt)&&i(p.heartbeatAt)&&i(p.expiresAt)&&Number.isFinite(p.reservedTokens)&&Number(p.reservedTokens)>=0&&Number.isFinite(p.reservedCostUsd)&&Number(p.reservedCostUsd)>=0,a=p=>n(p)&&r(p.requestId)&&r(p.operationId)&&r(p.runId)&&r(p.providerId)&&r(p.logicalChildId)&&r(p.attemptId)&&r(p.idempotencyKey)&&o(p.owner)&&i(p.enqueuedAt)&&i(p.updatedAt),c=p=>n(p)&&r(p.runId)&&r(p.logicalChildId)&&r(p.attemptId)&&r(p.idempotencyKey)&&r(p.state)&&i(p.startedAt),l=p=>n(p)&&r(p.runId)&&Number.isFinite(p.tokens)&&Number(p.tokens)>=0&&Number.isFinite(p.costUsd)&&Number(p.costUsd)>=0&&Number.isInteger(p.attempts)&&Number(p.attempts)>=0&&i(p.updatedAt),u=p=>n(p)&&r(p.providerId)&&i(p.timestamp)&&Number.isFinite(p.tokens)&&Number(p.tokens)>=0,d=p=>n(p)&&r(p.effectKey)&&r(p.idempotencyKey)&&r(p.permitId)&&Number.isInteger(p.fencingToken)&&Number(p.fencingToken)>0&&r(p.state)&&i(p.claimedAt);return!!(t&&t.schemaVersion===1&&Number.isInteger(t.revision)&&Number(t.revision)>=0&&Number.isInteger(t.nextFencingToken)&&Number(t.nextFencingToken)>0&&i(t.updatedAt)&&Array.isArray(t.permits)&&t.permits.every(s)&&Array.isArray(t.queue)&&t.queue.every(a)&&Array.isArray(t.attempts)&&t.attempts.every(c)&&Array.isArray(t.usage)&&t.usage.every(l)&&Array.isArray(t.providerRates)&&t.providerRates.every(u)&&Array.isArray(t.effects)&&t.effects.every(d))}function R1t(e,t){GZ(aBe(e),{recursive:!0});let n=`${e}.${process.pid}.${rBe()}.tmp`,r=oBe(n,"wx",384);try{sBe(r,JSON.stringify(t,null,2)+`
|
|
2884
2884
|
`,"utf8"),h1t(r)}finally{iBe(r)}A1t(n,e)}function T1t(e,t,n){let r=Date.parse(e.requestedAt??""),i=Number.isFinite(r)?r:t,o=Date.parse(e.queueDeadlineAt??"");return{requestedAt:So(i),deadlineAt:So(Number.isFinite(o)?Math.min(o,i+n):i+n)}}function cBe(e,t){return UR(e.providerDefault,e.providers[t])}function eBe(e,t,n){let r=Math.max(0,t-Date.parse(e.enqueuedAt));return I1t[e.priorityClass]+Math.floor(r/n.maxStarvationMs)*1001}function P1t(e,t,n){return[...e].sort((r,i)=>eBe(i,t,n)-eBe(r,t,n)||Date.parse(r.enqueuedAt)-Date.parse(i.enqueuedAt)||r.requestId.localeCompare(i.requestId))}function _1t(e,t){return e.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt}function wI(e){return Number.isFinite(e)?Math.max(0,Number(e)):0}function tBe(e,t,n,r){let i=e.permits;if(i.length>=n.globalConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"global_concurrency"};if(!(t.priorityClass==="control"||t.priorityClass==="foreground"||t.priorityClass==="reconciliation"||t.priorityClass==="terminal")&&i.length>=Math.max(0,n.globalConcurrency-n.reservedPrioritySlots))return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"reserved_priority_capacity"};let s=Math.min(n.perRunConcurrency,qR(t.runConcurrencyLimit,n.perRunConcurrency,1,n.globalConcurrency));if(i.filter(b=>b.runId===t.runId).length>=s)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"run_concurrency"};if(t.parentId&&i.filter(b=>b.parentId===t.parentId).length>=n.perParentConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"parent_concurrency"};let a=cBe(n,t.providerId);if(i.filter(b=>b.providerId===t.providerId).length>=a.maxConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"provider_concurrency"};if(t.credentialFingerprint&&i.filter(b=>b.providerId===t.providerId&&b.credentialFingerprint===t.credentialFingerprint).length>=a.maxCredentialConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"credential_concurrency"};if(i.some(b=>b.logicalChildId===t.logicalChildId))return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"logical_child_active"};let c=new Set(e.attempts.filter(b=>b.logicalChildId===t.logicalChildId).map(b=>b.attemptId));if(!c.has(t.attemptId)&&c.size>=n.maxAttemptsPerLogicalChild)return{code:"WORKFLOW_ATTEMPT_LIMIT",reason:"logical_child_attempt_limit"};let l=new Set(e.attempts.filter(b=>b.runId===t.runId).map(b=>b.attemptId)),u=Math.min(n.maxAttemptsPerRun,qR(t.runAttemptLimit,n.maxAttemptsPerRun,1,n.maxAttemptsPerRun));if(!l.has(t.attemptId)&&l.size>=u)return{code:"WORKFLOW_ATTEMPT_LIMIT",reason:"run_attempt_limit"};let d=wI(t.reservedTokens);if(i.reduce((b,I)=>b+I.reservedTokens,0)+d>n.maxReservedTokens)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"global_token_reservation"};let f=wI(t.reservedCostUsd);if(i.reduce((b,I)=>b+I.reservedCostUsd,0)+f>n.maxReservedCostUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"global_cost_reservation"};let h=e.usage.find(b=>b.runId===t.runId),g=i.filter(b=>b.runId===t.runId).reduce((b,I)=>b+I.reservedTokens,0);if(t.runTokenLimit!==void 0&&(h?.tokens??0)+g+d>t.runTokenLimit)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"run_token_limit"};let A=i.filter(b=>b.runId===t.runId).reduce((b,I)=>b+I.reservedCostUsd,0);if(t.runCostLimitUsd!==void 0&&(h?.costUsd??0)+A+f>t.runCostLimitUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"run_cost_limit"};let y=r-a.windowMs,w=e.providerRates.filter(b=>b.providerId===t.providerId&&Date.parse(b.timestamp)>=y&&(!t.credentialFingerprint||b.credentialFingerprint===t.credentialFingerprint));return w.length>=a.maxRequestsPerWindow?{reason:"provider_request_rate"}:w.reduce((b,I)=>b+I.tokens,0)+d>a.maxTokensPerWindow?{reason:"provider_token_rate"}:{}}function $1t(e){for(let[t,n]of Object.entries({requestId:e.requestId,operationId:e.operationId,runId:e.runId,providerId:e.providerId,logicalChildId:e.logicalChildId,attemptId:e.attemptId,idempotencyKey:e.idempotencyKey}))if(typeof n!="string"||!n.trim()||n.length>512)throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE",`Invalid resource request field: ${t}.`);if(e.credentialFingerprint&&!/^(?:cred_)?sha256_[a-f0-9]{32,64}$/i.test(e.credentialFingerprint))throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE","credentialFingerprint must be a scoped SHA-256 fingerprint.")}function Ym(e,t){let n=String(e??"default").trim().toLowerCase().split(/[/:]/,1)[0]||"default",r=t?.trim()?nBe("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16):"default";return`${n}@${r}`}function JZ(e){let t=nBe("sha256");return t.update(e.salt),t.update("\0"),t.update(e.providerId),t.update("\0"),t.update(e.endpoint?.trim().toLowerCase()??""),t.update("\0"),t.update(e.credential),`cred_sha256_${t.digest("hex")}`}function XZ(e=yI(Mn(),"governor")){let t=yI(e,"credential-salt.bin");if(GZ(e,{recursive:!0}),WZ(t))return HZ(t);let n=f1t(32);try{return sBe(t,n,{flag:"wx",mode:384}),n}catch{return HZ(t)}}function bI(e,t=process.env,n){let r=e.split("@",1)[0]?.toLowerCase(),o=(r==="anthropic"||r==="claude"?["ANTHROPIC_API_KEY","XENO_API_KEY"]:r==="openai"||r==="gpt"?["OPENAI_API_KEY","XENO_API_KEY"]:r==="google"||r==="gemini"?["GOOGLE_API_KEY","GEMINI_API_KEY","XENO_API_KEY"]:["XENO_API_KEY","ANTHROPIC_API_KEY","OPENAI_API_KEY","GOOGLE_API_KEY","GEMINI_API_KEY"]).map(s=>t[s]?.trim()).find(Boolean);return o?JZ({providerId:e,endpoint:n,credential:o,salt:XZ()}):void 0}function IQ(e){return{XENO_RESOURCE_PERMIT_ID:e.permitId,XENO_RESOURCE_FENCING_TOKEN:String(e.fencingToken),XENO_RESOURCE_OPERATION_ID:e.operationId,XENO_RESOURCE_IDEMPOTENCY_KEY:e.idempotencyKey}}function zZ(e=process.env){let t=e.XENO_RESOURCE_PERMIT_ID?.trim(),n=Number.parseInt(e.XENO_RESOURCE_FENCING_TOKEN??"",10);return t&&Number.isInteger(n)&&n>0?{permitId:t,fencingToken:n}:null}function Km(e,t,n=process.env){if(n.XENO_RESOURCE_OPERATION_ID?.trim()!==e)return;let r=zZ(n);if(!t||!r||t.permitId!==r.permitId||t.fencingToken!==r.fencingToken)throw new cs("WORKER_LEASE_EXPIRED","Worker state write rejected because its fencing token is stale.");new Zr().assertFence(r.permitId,r.fencingToken)}var VZ,v1t,K$e,cs,I1t,Zr,jp=Ie(()=>{"use strict";gi();nI();ko();qp();sd();VZ=64,v1t=16,K$e=16*1024*1024,cs=class extends Error{constructor(n,r){super(r);this.code=n;this.name="WorkflowResourceError"}code},I1t={control:1e3,foreground:900,reconciliation:850,terminal:800,"app-server":700,workflow:500,background:400,scheduled:300};Zr=class{policy;rootDir;ledgerPath;lockPath;now;owner;fault;constructor(t={}){this.rootDir=t.rootDir??yI(Mn(),"governor"),this.ledgerPath=yI(this.rootDir,"resource-ledger.json"),this.lockPath=yI(this.rootDir,"resource-ledger.lock"),this.policy=t.policy??S1t(),this.now=t.now??Date.now,this.owner=t.owner??zm,this.fault=t.fault,GZ(this.rootDir,{recursive:!0})}acquire(t){$1t(t);let n=0,r=this.withLedger((a,c)=>{this.cleanupExpired(a,c);let l=a.permits.find(I=>I.requestId===t.requestId||I.attemptId===t.attemptId);if(l)return n=a.permits.length,{value:{status:"active",permit:l,reason:"attempt_already_active"},changed:!0};let u=T1t(t,c,this.policy.maxQueueWaitMs);if(c>Date.parse(u.deadlineAt))return{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!1};let d=a.queue.find(I=>I.requestId===t.requestId);if(d&&c>Date.parse(d.queueDeadlineAt??u.deadlineAt))return a.queue=a.queue.filter(I=>I.requestId!==t.requestId),{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!0};if(!d&&a.queue.length>=this.policy.maxQueueLength)return{value:{status:"rejected",code:"WORKFLOW_QUEUE_FULL",reason:"The host workflow queue is full."},changed:!1};let p=t.owner??this.owner(),f=d?{...d,...t,owner:d.owner,updatedAt:So(c)}:{...t,owner:p,requestedAt:u.requestedAt,queueDeadlineAt:u.deadlineAt,enqueuedAt:So(c),updatedAt:So(c)};d?a.queue=a.queue.map(I=>I.requestId===f.requestId?f:I):a.queue.push(f);let m=P1t(a.queue,c,this.policy),h,g={};for(let I of m){let v=tBe(a,I,this.policy,c);if(I.requestId===f.requestId&&(g=v),!v.reason){h=I;break}}if(g.code==="WORKFLOW_ATTEMPT_LIMIT"||g.code==="WORKFLOW_TOKEN_LIMIT"||g.code==="WORKFLOW_COST_LIMIT")return a.queue=a.queue.filter(I=>I.requestId!==f.requestId),{value:{status:"rejected",code:g.code,reason:g.reason??"resource_limit"},changed:!0};if(!h||h.requestId!==f.requestId){let I=a.permits.map(x=>Date.parse(x.expiresAt)).filter(Number.isFinite).sort((x,C)=>x-C)[0],v=cBe(this.policy,f.providerId),k=a.providerRates.filter(x=>x.providerId===f.providerId&&(!f.credentialFingerprint||x.credentialFingerprint===f.credentialFingerprint)).map(x=>Date.parse(x.timestamp)+v.windowMs).filter(x=>Number.isFinite(x)&&x>c).sort((x,C)=>x-C)[0],R=[I,k].filter(x=>typeof x=="number").sort((x,C)=>x-C)[0];return{value:{status:"queued",request:f,reason:g.reason??"waiting_for_fair_turn",...R?{estimatedEligibleAt:So(R)}:{}},changed:!0}}let A=tBe(a,f,this.policy,c);if(A.reason)return A.code==="WORKFLOW_ATTEMPT_LIMIT"||A.code==="WORKFLOW_TOKEN_LIMIT"||A.code==="WORKFLOW_COST_LIMIT"?(a.queue=a.queue.filter(I=>I.requestId!==f.requestId),{value:{status:"rejected",code:A.code,reason:A.reason},changed:!0}):{value:{status:"queued",request:f,reason:A.reason},changed:!0};let y=So(c),w={permitId:`permit_${rBe()}`,requestId:f.requestId,operationId:f.operationId,surface:f.surface,priorityClass:f.priorityClass,runId:f.runId,...f.parentId?{parentId:f.parentId}:{},providerId:f.providerId,...f.credentialFingerprint?{credentialFingerprint:f.credentialFingerprint}:{},logicalChildId:f.logicalChildId,attemptId:f.attemptId,idempotencyKey:f.idempotencyKey,fencingToken:a.nextFencingToken++,owner:f.owner,acquiredAt:y,heartbeatAt:y,expiresAt:So(c+this.policy.leaseTtlMs),reservedTokens:wI(f.reservedTokens),reservedCostUsd:wI(f.reservedCostUsd),lastDurableSequence:0};a.queue=a.queue.filter(I=>I.requestId!==f.requestId),a.permits.push(w),n=a.permits.length;let b=a.attempts.find(I=>I.attemptId===f.attemptId);return b?Object.assign(b,{state:"active",permitId:w.permitId,endedAt:void 0,outcome:void 0}):a.attempts.push({runId:f.runId,logicalChildId:f.logicalChildId,attemptId:f.attemptId,idempotencyKey:f.idempotencyKey,state:"active",permitId:w.permitId,startedAt:y}),a.providerRates.push({providerId:f.providerId,...f.credentialFingerprint?{credentialFingerprint:f.credentialFingerprint}:{},timestamp:y,tokens:w.reservedTokens}),this.fault?.("acquire.before_commit"),{value:{status:"acquired",permit:w},changed:!0,afterCommit:()=>this.fault?.("acquire.after_commit")}}),i=r.status==="rejected"?r.code:r.status==="acquired"?"admitted":r.reason;Nr("xeno.workflow.admission_results",1,{component:"resource_governor",provider:t.providerId,state:r.status,reason:i,...r.status==="rejected"?{error_code:r.code}:{}}),(i==="provider_request_rate"||i==="provider_token_rate"||i==="provider_concurrency"||i==="credential_concurrency")&&Nr("xeno.workflow.provider_throttles",1,{component:"resource_governor",provider:t.providerId,reason:i});let o=Date.parse((r.status==="queued"?r.request.requestedAt:t.requestedAt)??""),s=r.status==="acquired"||r.status==="active"?Date.parse(r.permit.acquiredAt):this.now();return Number.isFinite(o)&&Number.isFinite(s)&&ss("xeno.workflow.queue_wait_ms",Math.max(0,s-o),{component:"resource_governor",provider:t.providerId,state:r.status}),n>0&&ss("xeno.workflow.active_concurrency",n,{component:"resource_governor",provider:t.providerId}),r}heartbeat(t){return this.withLedger((n,r)=>{let i=this.currentPermit(n,t.permitId,t.fencingToken,r),o=t.owner??this.owner();if(!_1t(i.owner,o))throw new cs("WORKER_IDENTITY_MISMATCH","Permit heartbeat came from a different worker identity.");return i.heartbeatAt=So(r),i.expiresAt=So(r+this.policy.leaseTtlMs),i.lastDurableSequence=Math.max(i.lastDurableSequence,Math.max(0,t.lastDurableSequence??0)),{value:{...i},changed:!0}})}assertFence(t,n){return this.withLedger((r,i)=>({value:{...this.currentPermit(r,t,n,i)},changed:!1}))}transfer(t,n,r){return this.withLedger((i,o)=>{let s=this.currentPermit(i,t,n,o);return s.owner=r,s.heartbeatAt=So(o),s.expiresAt=So(o+this.policy.leaseTtlMs),{value:{...s},changed:!0}})}settle(t){return this.withLedger((n,r)=>{let i=n.permits.find(c=>c.permitId===t.permitId);if(!i)return{value:!1,changed:!1};if(i.fencingToken!==t.fencingToken||Date.parse(i.expiresAt)<=r)throw new cs("WORKER_LEASE_EXPIRED","The worker fencing token is stale.");n.permits=n.permits.filter(c=>c.permitId!==i.permitId);let o=n.attempts.find(c=>c.attemptId===i.attemptId);o&&Object.assign(o,{state:"settled",endedAt:So(r),outcome:t.outcome});let s=n.usage.find(c=>c.runId===i.runId),a={runId:i.runId,tokens:(s?.tokens??0)+wI(t.actualTokens),costUsd:(s?.costUsd??0)+wI(t.actualCostUsd),attempts:(s?.attempts??0)+1,updatedAt:So(r)};return n.usage=[...n.usage.filter(c=>c.runId!==i.runId),a],{value:!0,changed:!0}})}settleOperation(t,n,r=0,i=0){let o=this.snapshot().permits.find(s=>s.operationId===t);return o?this.settle({permitId:o.permitId,fencingToken:o.fencingToken,outcome:n,actualTokens:r,actualCostUsd:i}):!1}cancelQueued(t){return this.withLedger(n=>{let r=n.queue.some(i=>i.requestId===t);return n.queue=n.queue.filter(i=>i.requestId!==t),{value:r,changed:r}})}claimEffect(t){return this.withLedger((n,r)=>{let i=this.currentPermit(n,t.permitId,t.fencingToken,r),o=n.effects.find(s=>s.effectKey===t.effectKey||s.idempotencyKey===i.idempotencyKey);return o?{value:o.permitId===i.permitId&&o.fencingToken===i.fencingToken&&o.state==="claimed",changed:!1}:(n.effects.push({effectKey:t.effectKey,idempotencyKey:i.idempotencyKey,permitId:i.permitId,fencingToken:i.fencingToken,state:"claimed",claimedAt:So(r)}),{value:!0,changed:!0})})}commitEffect(t){return this.withLedger((n,r)=>{this.currentPermit(n,t.permitId,t.fencingToken,r);let i=n.effects.find(o=>o.effectKey===t.effectKey);return!i||i.permitId!==t.permitId||i.fencingToken!==t.fencingToken?{value:!1,changed:!1}:i.state==="committed"?{value:!0,changed:!1}:(i.state="committed",i.committedAt=So(r),{value:!0,changed:!0})})}reconcile(t){let n=this.withLedger((r,i)=>{let o=[...r.permits],s=[...r.queue],a=t??LR(o.map(h=>h.owner.pid)),c=new Set,l=new Set;for(let h of o){let g=Lo(h.owner,A=>a.get(A)??null);g.status==="mismatch"&&c.add(h.permitId),(g.status==="degraded"||g.status==="remote")&&l.add(h.permitId)}this.cleanupExpired(r,i,c);let u=new Set(r.permits.map(h=>h.permitId)),d=o.filter(h=>!u.has(h.permitId)&&!c.has(h.permitId)),p=o.filter(h=>c.has(h.permitId)),f=new Set(r.queue.map(h=>h.requestId)),m=s.filter(h=>!f.has(h.requestId));return{value:{expiredPermits:d,identityMismatches:p,expiredQueue:m,livePermits:r.permits.length,degradedPermits:r.permits.filter(h=>l.has(h.permitId)).length},changed:d.length>0||p.length>0||m.length>0}});return ss("xeno.worker.live_leases",n.livePermits,{component:"resource_governor",operation:"reconcile"}),ss("xeno.worker.degraded_leases",n.degradedPermits,{component:"resource_governor",operation:"reconcile"}),n.expiredPermits.length>0&&Nr("xeno.worker.lease_expirations",n.expiredPermits.length,{component:"resource_governor",operation:"reconcile"}),n.identityMismatches.length>0&&Nr("xeno.worker.identity_mismatches",n.identityMismatches.length,{component:"resource_governor",operation:"reconcile"}),n}snapshot(){return this.withLedger(t=>({value:structuredClone(t),changed:!1}))}cleanupExpired(t,n,r=new Set){let i=new Set(t.permits.filter(s=>Date.parse(s.expiresAt)<=n||r.has(s.permitId)).map(s=>s.permitId));if(i.size>0){t.permits=t.permits.filter(s=>!i.has(s.permitId));for(let s of t.attempts)s.permitId&&i.has(s.permitId)&&s.state==="active"&&(s.state="expired",s.endedAt=So(n),s.outcome=r.has(s.permitId)?"WORKER_IDENTITY_MISMATCH":"WORKER_LEASE_EXPIRED")}t.queue=t.queue.filter(s=>Date.parse(s.queueDeadlineAt??s.updatedAt)>n);let o=Math.max(this.policy.providerDefault.windowMs,...Object.values(this.policy.providers).map(s=>s.windowMs??0));if(t.providerRates=t.providerRates.filter(s=>Date.parse(s.timestamp)>n-o),t.attempts.length>2e4){let s=t.attempts.filter(c=>c.state==="active"),a=t.attempts.filter(c=>c.state!=="active").slice(-Math.max(0,2e4-s.length));t.attempts=[...a,...s]}t.effects.length>2e4&&(t.effects=t.effects.slice(-2e4)),t.usage.length>1e4&&(t.usage=t.usage.slice(-1e4))}currentPermit(t,n,r,i){let o=t.permits.find(s=>s.permitId===n);if(!o||Date.parse(o.expiresAt)<=i||o.fencingToken!==r)throw new cs("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out.");return o}readLedger(t){if(!WZ(this.ledgerPath))return C1t(t);let n;try{n=oBe(this.ledgerPath,"r");let r=m1t(n).size;if(!Number.isSafeInteger(r)||r>K$e)throw new Error(`ledger exceeds the ${K$e} byte limit`);let i=Buffer.alloc(r),o=0;for(;o<r;){let c=g1t(n,i,o,r-o,o);if(c===0)throw new Error("Resource ledger changed during read");o+=c}let s=i.toString("utf8"),a=JSON.parse(s);if(!x1t(a))throw new Error("Unsupported resource ledger schema.");return a}catch(r){throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource ledger is unreadable and was not overwritten: ${r instanceof Error?r.message:String(r)}`)}finally{n!==void 0&&iBe(n)}}withLedger(t){let n=Date.now()+5e3,r=new Int32Array(new SharedArrayBuffer(4)),i,o;for(;!i&&Date.now()<=n;)try{i=Eo(this.lockPath,"workflow-resource-governor",he)}catch(s){if(o=s,!(s instanceof Error)||!s.message.includes("is already locked"))break;Atomics.wait(r,0,0,10)}if(!i)throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE",o instanceof Error?o.message:String(o??"Resource governor lock unavailable."));try{let s=this.now(),a=this.readLedger(s),c=t(a,s);return c.changed&&(a.revision+=1,a.updatedAt=So(s),R1t(this.ledgerPath,a)),c.afterCommit?.(),c.value}finally{i.release()}}}});import{createHash as B1t,randomUUID as M1t}from"node:crypto";import{setTimeout as N1t}from"node:timers/promises";function O1t(){return`delegation-${Date.now().toString(36)}-${M1t().slice(0,8)}`}function D1t(e){return async t=>(await ql({cwd:e.cwd,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:t.task.maxTokens,maxIterations:t.task.maxIterations,parentSystemPrompt:e.parentSystemPrompt,parentExecutionMode:e.parentExecutionMode,subagentRole:t.task.role,permissionEngine:e.permissionEngine,toolRegistry:e.createToolRegistry?.(),...e.auditLogger?{session:{auditLogger:e.auditLogger}}:{},onIteration:t.onIteration,onToolStart:t.onToolStart,onToolWillExecute:t.onToolWillExecute,onToolEnd:t.onToolEnd})).agent}async function L1t(e){for(;;){if(e.signal?.aborted){e.governor.cancelQueued(e.request.requestId);let n=new Error("Delegated branch admission was cancelled.");throw n.name="AgentInterruptedError",n}let t=e.governor.acquire(e.request);if(t.status==="acquired")return t.permit;if(t.status==="active")throw new cs("WORKFLOW_CONCURRENCY_LIMIT","Delegated branch attempt is already active.");if(t.status==="rejected")throw new cs(t.code,t.reason);if(Date.now()>=e.deadline)throw e.governor.cancelQueued(e.request.requestId),new cs("WORKFLOW_QUEUE_EXPIRED","Delegated branch exceeded its admission deadline.");await N1t(50,void 0,{signal:e.signal})}}function Q1t(e,t,n){let r=e.run.bind(e),i=!1,o=a=>{i||(i=!0,t.settle({permitId:n.permitId,fencingToken:n.fencingToken,outcome:a,actualTokens:e.tokenUsage.total}))};e.run=async a=>{try{let c=await r(a);return o("completed"),c}catch(c){throw o(c instanceof Error&&c.name==="AgentInterruptedError"?"cancelled":"failed"),c}};let s=e;if(s.cancelCurrentTurn){let a=s.cancelCurrentTurn.bind(s);s.cancelCurrentTurn=()=>(o("cancelled"),a())}else if(s.cancel){let a=s.cancel.bind(s);s.cancel=()=>(o("cancelled"),a())}return e}async function jR(e){let t=new Zr,n=e.rootTraceId??O1t(),r=Ym(e.model,e.baseURL),i=e.apiKey?JZ({providerId:r,endpoint:e.baseURL,credential:e.apiKey,salt:XZ()}):bI(r,process.env,e.baseURL),o=e.createBranchAgent??D1t(e),s=Date.now()+e.timeoutMs,a=async c=>{let l=c.task,u=`${n}:${l.id}`,d=`${u}:attempt-1`,p=B1t("sha256").update(`${n}\0${l.id}\0${l.prompt}`).digest("hex"),f=await L1t({governor:t,request:{requestId:`admit:${u}:attempt-1`,operationId:u,surface:"delegated-branch",priorityClass:"foreground",runId:n,parentId:n,providerId:r,...i?{credentialFingerprint:i}:{},logicalChildId:u,attemptId:d,idempotencyKey:p,reservedTokens:l.maxTokens,runConcurrencyLimit:e.branchPolicy?.maxConcurrentBranches,runAttemptLimit:e.branchPolicy?.roles?.length,runTokenLimit:e.maxTotalTokens,queueDeadlineAt:new Date(s).toISOString()},deadline:s,signal:l.signal??e.signal});if(!t.claimEffect({permitId:f.permitId,fencingToken:f.fencingToken,effectKey:`delegated:${f.operationId}`}))throw t.settle({permitId:f.permitId,fencingToken:f.fencingToken,outcome:"duplicate_branch_suppressed"}),new cs("WORKFLOW_CONCURRENCY_LIMIT","Duplicate delegated branch execution was suppressed.");try{let m=await o(c);return t.commitEffect({permitId:f.permitId,fencingToken:f.fencingToken,effectKey:`delegated:${f.operationId}`}),Q1t(m,t,f)}catch(m){throw t.settle({permitId:f.permitId,fencingToken:f.fencingToken,outcome:"branch_creation_failed"}),m}};if(e.hostDelegation){if(e.createBranchAgent)throw new Error("Host-routed delegation and a local createBranchAgent are mutually exclusive: the branch either executes on the Agent host or in this process. Pass one.");if(typeof e.onToolWillExecute=="function")throw new Error("Host-routed delegation cannot honour onToolWillExecute: it delays tool execution until it resolves, and a branch running on the Agent host does not wait for this process. A hook that cannot delay is not the hook you asked for, so it is refused rather than silently downgraded. Remove it to delegate on the host, or run without host delegation.");if(typeof e.onIteration=="function")throw new Error("Host-routed delegation cannot report onIteration: the host mints no iteration-bearing runtime event, so there is nothing to read \u2014 unlike onToolStart/onToolEnd, which now fire. Remove onIteration to delegate on the host, or run without host delegation.");return R2({...e,rootTraceId:n,createBranchAgent:B$e({...e.hostDelegation,rootTraceId:n,deadline:s,...e.signal===void 0?{}:{signal:e.signal}})})}return R2({...e,rootTraceId:n,createBranchAgent:a})}var lBe=Ie(()=>{"use strict";at();M$e();jp();at()});import{renameSync as F1t}from"node:fs";function ew(e,t){for(let n=0;;n++)try{F1t(e,t);return}catch(r){if(n>=10||!["EPERM","EACCES","EBUSY"].includes(r.code??""))throw r;Atomics.wait(U1t,0,0,Math.min(25,(n+1)*5))}}var U1t,kQ=Ie(()=>{"use strict";U1t=new Int32Array(new SharedArrayBuffer(4))});import{closeSync as q1t,fstatSync as j1t,openSync as V1t,readSync as H1t}from"node:fs";function vI(e){let t;try{t=V1t(e,"r")}catch(n){if(n.code==="ENOENT")return{text:"",startOffset:0,endOffset:0,totalBytes:0};throw n}try{let n=j1t(t);if(!n.isFile()||!Number.isSafeInteger(n.size))throw new Error("Output preview requires a regular file of supported size.");let r=n.size,i=Math.max(0,r-W1t),o=Buffer.allocUnsafe(r-i),s=0;for(;s<o.length;){let u=H1t(t,o,s,o.length-s,i+s);if(u===0)throw new Error("Output changed during preview; retry.");s+=u}let a=0;if(i>0)for(;a<Math.min(3,o.length)&&(o[a]&192)===128;)a++;let c=i+a,l;try{l=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(o.subarray(a),{stream:!0})}catch{throw new Error("Output preview contains invalid UTF-8; inspect the persisted output as bytes.")}return{text:l,startOffset:c,endOffset:c+Buffer.byteLength(l,"utf8"),totalBytes:r}}finally{q1t(t)}}var W1t,EQ=Ie(()=>{"use strict";W1t=64*1024});import*as oc from"node:fs/promises";import*as Zm from"node:path";import{homedir as e$t,platform as t$t,release as n$t}from"node:os";import{spawnSync as s$t}from"node:child_process";async function G1t(e){await oc.mkdir(e,{recursive:!0})}async function ei(e,t){let n=Zm.dirname(e);await G1t(n);let r=Math.random().toString(36).substring(2,15),i=`${e}.tmp.${process.pid}.${r}`;try{await oc.writeFile(i,t),await z1t(i,e)}finally{try{await oc.unlink(i)}catch{}}}async function z1t(e,t){for(let n=0;;n+=1)try{await oc.rename(e,t);return}catch(r){let i=r.code,o=X1t[n];if(process.platform!=="win32"||!i||!J1t.has(i)||o===void 0)throw r;await new Promise(s=>setTimeout(s,o))}}function dBe(e,t){try{return JSON.parse(e)}catch{return t}}function YZ(e){let t=Y1t(e);return{frontmatter:t.frontmatter,content:t.content.trim()}}function Y1t(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return{frontmatter:{},content:e};let n=t.search(/\r?\n/);if(n<0||t.slice(0,n).trim()!=="---")return{frontmatter:{},content:e};let r=t.slice(n+(t[n]==="\r"?2:1)),i=r.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!i||i.index===void 0)throw new Error("YAML frontmatter is not closed.");let o=r.slice(0,i.index),s=i[0],a=i.index+s.length;return{frontmatter:pBe(o),content:r.slice(a)}}function pBe(e){let t={},n=e.split(/\r?\n/);for(let r=0;r<n.length;r+=1){let i=n[r];if(!i.trim()||i.trimStart().startsWith("#"))continue;if(/^\s/.test(i))throw new Error(`Unexpected indentation at line ${r+1}.`);let o=Z1t(i,r+1);if(o.key==="<<")throw new Error("YAML merge keys are not supported.");if(o.value!==""){t[o.key]=fBe(o.value,r+1);continue}let s=K1t(n,r+1);t[o.key]=s.value,r=s.nextIndex-1}return t}function K1t(e,t){let n=[],r=t;for(;r<e.length;r+=1){let o=e[r];if(!o.trim()){n.push(o);continue}if(!/^\s/.test(o))break;n.push(o.replace(/^ {2}/,""))}let i=n.filter(o=>o.trim()&&!o.trimStart().startsWith("#"));return i.length===0?{value:{},nextIndex:r}:i.every(o=>o.trimStart().startsWith("- "))?{value:i.map((o,s)=>fBe(o.trimStart().slice(2),t+s+1)),nextIndex:r}:{value:pBe(n.join(`
|
|
@@ -2946,7 +2946,7 @@ foreach ($id in $ids) {
|
|
|
2946
2946
|
`),a=s.length===0?[]:s.split(`
|
|
2947
2947
|
`);if(a.length>o)throw new Ta(`Unified diff exceeds ${o} lines`);let c=[],l,u=0,d=(m,h)=>{if(l&&iOe(l,c),c.length>=r)throw new Ta(`Unified diff exceeds ${r} files`);return l={oldPath:m,newPath:h,status:"modified",binary:!1,headerLines:[],hunks:[]},l};for(let m=0;m<a.length;m+=1){let h=a[m];if(h.startsWith("diff --git ")){let[g,A]=ELt(h.slice(11),m+1);d(g,A).headerLines.push(h);continue}if(h.startsWith("--- ")){(!l||l.hunks.length>0)&&(l=d()),l.oldPath=oOe(h.slice(4)),l.headerLines.push(h);continue}if(h.startsWith("+++ ")){l||(l=d()),l.newPath=oOe(h.slice(4)),l.headerLines.push(h);continue}if(h.startsWith("@@ ")){if(!l)throw new Ta("Hunk appears before a file header",m+1);if(u>=i)throw new Ta(`Unified diff exceeds ${i} hunks`,m+1);let g=kLt.exec(h);if(!g)throw new Ta("Malformed unified diff hunk header",m+1);let A=Number(g[1]),y=g[2]===void 0?1:Number(g[2]),w=Number(g[3]),b=g[4]===void 0?1:Number(g[4]),I=[],v=A,k=w,R=0,x=0,C=m+1;for(;C<a.length;C+=1){let D=a[C],V=v-A===y,B=k-w===b;if(V&&B&&D.length===0||D.startsWith("diff --git ")||D.startsWith("@@ ")||D.startsWith("--- ")&&a[C+1]?.startsWith("+++ "))break;if(D.startsWith("+"))I.push({kind:"addition",text:D.slice(1),newLine:k}),k+=1,R+=1;else if(D.startsWith("-"))I.push({kind:"deletion",text:D.slice(1),oldLine:v}),v+=1,x+=1;else if(D.startsWith(" "))I.push({kind:"context",text:D.slice(1),oldLine:v,newLine:k}),v+=1,k+=1;else if(D==="\")I.push({kind:"no-newline",text:D});else{if(D.length===0&&C===a.length-1)break;throw new Ta("Unexpected line inside unified diff hunk",C+1)}}let P=I.filter(D=>D.kind==="context"||D.kind==="deletion").length,N=I.filter(D=>D.kind==="context"||D.kind==="addition").length;if(P!==y||N!==b)throw new Ta(`Hunk line counts do not match header (expected -${y}/+${b}, observed -${P}/+${N})`,m+1);let $=h,_=Qr(JSON.stringify({oldPath:l.oldPath??null,newPath:l.newPath??null,header:$,lines:I})).value.slice(0,32);l.hunks.push({hunkId:_,header:$,...g[5]?{section:g[5]}:{},oldStart:A,oldLines:y,newStart:w,newLines:b,additions:R,deletions:x,lines:I}),u+=1,m=C-1;continue}if(!l){if(h.trim().length===0)continue;throw new Ta("Content appears before the first diff file header",m+1)}l.headerLines.push(h),h.startsWith("new file mode ")?l.status="added":h.startsWith("deleted file mode ")?l.status="deleted":h.startsWith("rename from ")?(l.status="renamed",l.oldPath=Aw(h.slice(12))):h.startsWith("rename to ")?(l.status="renamed",l.newPath=Aw(h.slice(10))):h.startsWith("copy from ")?(l.status="copied",l.oldPath=Aw(h.slice(10))):h.startsWith("copy to ")?(l.status="copied",l.newPath=Aw(h.slice(8))):(h.startsWith("Binary files ")||h==="GIT binary patch")&&(l.binary=!0,l.status="binary")}l&&iOe(l,c);let p=c.reduce((m,h)=>m+h.additions,0),f=c.reduce((m,h)=>m+h.deletions,0);return{schemaVersion:1,mode:t.mode??"working-tree",...t.repositoryId?{repositoryId:t.repositoryId}:{},...t.baseRef?{baseRef:t.baseRef}:{},...t.headRef?{headRef:t.headRef}:{},files:c,additions:p,deletions:f,rawDiff:s}}function OF(e,t){let n=TOe(e,{mode:t.mode,repositoryId:t.repositoryId,baseRef:t.baseRef,headRef:t.headRef}),r=n,i=pc(r),o=[t.identity?.runId,t.identity?.turnId,t.identity?.taskId,t.repositoryId,t.mode].filter(Boolean).join(":"),s=t.kind??"diff",a=t.artifactId??`${s}_${Qr(`${o}:${n.rawDiff}`).value.slice(0,24)}`,c=t.revision??1,l={schemaVersion:1,artifactId:a,revision:c,kind:s,title:t.title??`${xLt(n.mode)} diff (${n.files.length} files)`,...t.description?{description:t.description}:{},state:"pending_review",createdAt:t.createdAt??new Date().toISOString(),mediaType:`application/vnd.xeno.${s}+json`,sensitivity:t.sensitivity??"internal",...t.identity?{identity:structuredClone(t.identity)}:{},content:{hash:Iw(r),sizeBytes:ROe.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i},redactedPreview:`${n.files.length} files, +${n.additions}/-${n.deletions}`},provenance:{producer:{...t.producer}},anchors:n.files.flatMap(u=>[{kind:"file",path:u.displayPath,...t.repositoryId?{repositoryId:t.repositoryId}:{}},...u.hunks.map(d=>({kind:"diff-hunk",path:u.displayPath,hunkId:d.hunkId,artifactId:a,revision:c}))]),...c>1?{predecessorRevision:t.predecessorRevision??c-1}:{},...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.diff.mode":n.mode,"xeno.diff.files":n.files.length,"xeno.diff.additions":n.additions,"xeno.diff.deletions":n.deletions}};return mh(l),l}function hh(e){if(mh(e),e.kind!=="diff"&&e.kind!=="patch")throw new TypeError("Artifact is not a diff or patch");if(e.content.storage.type!=="inline"||typeof e.content.storage.text!="string")throw new TypeError("Diff artifact content is not available inline");let t;try{t=JSON.parse(e.content.storage.text)}catch(r){throw new Ta(`Diff artifact JSON is malformed: ${RLt(r).message}`)}if(!CLt(t))throw new Ta("Diff artifact document is invalid");let n=TOe(t.rawDiff,{mode:t.mode,repositoryId:t.repositoryId,baseRef:t.baseRef,headRef:t.headRef});if(pc(n)!==pc(t))throw new Ta("Diff artifact document does not match its raw diff");return n}function iOe(e,t){if(!e.oldPath&&!e.newPath)throw new Ta("Diff file has no path");e.oldPath||(e.status="added"),e.newPath||(e.status="deleted"),e.binary&&(e.status="binary");let n=e.hunks.reduce((i,o)=>i+o.additions,0),r=e.hunks.reduce((i,o)=>i+o.deletions,0);t.push({...e.oldPath?{oldPath:e.oldPath}:{},...e.newPath?{newPath:e.newPath}:{},displayPath:e.newPath??e.oldPath,status:e.status,additions:n,deletions:r,binary:e.binary,headerLines:[...e.headerLines],hunks:structuredClone(e.hunks)})}function ELt(e,t){let n=SLt(e);if(n.length!==2)throw new Ta("Malformed diff --git path pair",t);return[Aw(n[0]),Aw(n[1])]}function SLt(e){let t=[],n=0;for(;n<e.length;){for(;e[n]===" ";)n+=1;if(n>=e.length)break;if(e[n]==='"'){let r='"';n+=1;let i=!1;for(;n<e.length;){let o=e[n];if(r+=o,n+=1,!i&&o==='"')break;i=!i&&o==="\\",o!=="\\"&&(i=!1)}t.push(POe(r))}else{let r=e.indexOf(" ",n);if(r===-1){t.push(e.slice(n));break}t.push(e.slice(n,r)),n=r+1}}return t}function POe(e){return!e.startsWith('"')||!e.endsWith('"')?e:e.slice(1,-1).replace(/\\([\\"tnr]|[0-7]{1,3})/g,(t,n)=>n==="t"?" ":n==="n"?`
|
|
2948
2948
|
`:n==="r"?"\r":n==="\\"?"\\":n==='"'?'"':String.fromCharCode(Number.parseInt(n,8)))}function oOe(e){let t=e.split(" ",1)[0].trim();if(t!=="/dev/null")return Aw(POe(t))}function Aw(e){let t=e.replace(/\\/g,"/");return t.startsWith("a/")||t.startsWith("b/")?t.slice(2):t}function CLt(e){return!sOe(e)||e.schemaVersion!==1||!["working-tree","staged","turn","commit","preview"].includes(String(e.mode))||!Array.isArray(e.files)||!Number.isSafeInteger(e.additions)||!Number.isSafeInteger(e.deletions)||typeof e.rawDiff!="string"?!1:e.files.every(t=>sOe(t)&&typeof t.displayPath=="string"&&Array.isArray(t.headerLines)&&Array.isArray(t.hunks))}function sOe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function RF(e,t,n,r,i){if(e===void 0)return t;if(!Number.isInteger(e)||e<n||e>r)throw new TypeError(`${i} must be an integer between ${n} and ${r}`);return e}function xLt(e){return e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" ")}function RLt(e){return e instanceof Error?e:new Error(String(e))}function aOe(e,t){if((t.line!==void 0||t.hunkId!==void 0)&&!t.file)throw ef("Line and hunk anchors require a file");if(t.line!==void 0&&t.hunkId!==void 0)throw ef("Line and hunk anchors cannot be combined");if(!t.file)return;let n=PLt(t.file);if(t.line!==void 0&&(!Number.isInteger(t.line)||t.line<1))throw ef("Review line must be a positive integer");if(e.artifact.kind==="diff"||e.artifact.kind==="patch"){let r=hh(e.artifact).files.find(i=>i.displayPath===n);if(!r)throw ef(`File ${n} is not present in this artifact`);if(t.hunkId&&!r.hunks.some(i=>i.hunkId===t.hunkId))throw ef(`Hunk ${t.hunkId} is not present in ${n}`)}return t.hunkId?{kind:"diff-hunk",path:n,hunkId:_F(t.hunkId,"Hunk ID"),artifactId:e.artifact.artifactId,revision:e.artifact.revision}:t.line!==void 0?{kind:"source-line",path:n,startLine:t.line}:{kind:"file",path:n}}function PLt(e){let t=DF(e,"Artifact review file",4096).replace(/\\/g,"/").replace(/^\.\//,"");if(t.startsWith("../")||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").some(n=>n===".."||n.length===0))throw ef("Artifact review file anchors must be repository-relative paths");return t}function DF(e,t,n){let r=typeof e=="string"?e.trim():"";if(!r)throw ef(`${t} cannot be empty`);if(r.length>n)throw ef(`${t} exceeds ${n} characters`);return r}function cOe(e,t,n){if(e!==void 0)return DF(e,t,n)}function _F(e,t){let n=DF(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(n))throw ef(`${t} contains unsupported characters`);return n}function _Lt(e,t){return e===void 0?void 0:_F(e,t)}function ef(e){return new St("ARTIFACT_REVIEW_INVALID",e)}function ww(e){let t=NLt(e,"specId");return{plan:`spec_${t}_plan`,requirements:`spec_${t}_requirements`,design:`spec_${t}_design`,taskGraph:`spec_${t}_task_graph`}}function BLt(e){let t=[];e?.schemaVersion!==yw&&t.push(`schemaVersion must be ${yw}`),JT(e?.specId,"specId",t),(!Number.isInteger(e?.revision)||e.revision<1)&&t.push("revision must be a positive integer"),Jl(e?.title,"title",t),Jl(e?.problem,"problem",t),BF(e?.createdAt,"createdAt",t),BF(e?.updatedAt,"updatedAt",t),e?.predecessorRevision!==void 0&&(!Number.isInteger(e.predecessorRevision)||e.predecessorRevision!==e.revision-1)&&t.push("predecessorRevision must be the immediately preceding revision");let n=TF(e?.requirements,"requirement",t),r=TF(e?.tasks,"task",t),i=new Set,o=[...Array.isArray(e?.acceptanceCriteria)?e.acceptanceCriteria:[],...Array.isArray(e?.requirements)?e.requirements.flatMap(c=>Array.isArray(c.acceptanceCriteria)?c.acceptanceCriteria:[]):[]];for(let c of o){JT(c?.id,"acceptance criterion id",t),Jl(c?.text,`acceptance criterion ${c?.id??"?"}`,t),i.has(c?.id)&&t.push(`Duplicate acceptance criterion: ${c?.id}`),i.add(c?.id);for(let l of c?.requiredEvidenceKinds??[])JT(l,"required evidence kind",t)}for(let c of e?.requirements??[])Jl(c?.text,`requirement ${c?.id??"?"}`,t),["must","should","could"].includes(c?.priority)||t.push(`Requirement ${c?.id??"?"} has invalid priority`),(!Array.isArray(c?.acceptanceCriteria)||c.acceptanceCriteria.length===0)&&t.push(`Requirement ${c?.id??"?"} needs at least one acceptance criterion`);Jl(e?.design?.summary,"design summary",t);let s=TF(e?.design?.decisions,"design decision",t),a=TF(e?.design?.risks,"risk",t);for(let c of e?.design?.decisions??[]){Jl(c?.decision,`design decision ${c?.id??"?"}`,t),Jl(c?.rationale,`design rationale ${c?.id??"?"}`,t);for(let l of c?.requirementIds??[])n.has(l)||t.push(`Design decision ${c.id} references unknown requirement ${l}`)}for(let c of e?.design?.risks??[])Jl(c?.description,`risk ${c?.id??"?"}`,t),Jl(c?.mitigation,`risk mitigation ${c?.id??"?"}`,t),["low","medium","high","critical"].includes(c?.impact)||t.push(`Risk ${c?.id??"?"} has invalid impact`);for(let c of e?.tasks??[]){Jl(c?.title,`task title ${c?.id??"?"}`,t),Jl(c?.description,`task description ${c?.id??"?"}`,t);for(let l of c?.dependsOn??[])r.has(l)||t.push(`Task ${c.id} depends on unknown task ${l}`),l===c.id&&t.push(`Task ${c.id} cannot depend on itself`);for(let l of c?.requirementIds??[])n.has(l)||t.push(`Task ${c.id} references unknown requirement ${l}`);for(let l of c?.acceptanceCriterionIds??[])i.has(l)||t.push(`Task ${c.id} references unknown acceptance criterion ${l}`);for(let l of c?.expectedPaths??[])MOe(l)||t.push(`Task ${c.id} has unsafe expected path ${l}`)}return OLt(e?.tasks??[])&&t.push("Task dependency graph contains a cycle"),[...new Set(t)]}function Bee(e){let t=BLt(e);if(t.length>0)throw new Ys(t)}function lOe(e,t){Bee(e);let n=ww(e.specId),r=e.revision,i={...t,createdAt:e.updatedAt,state:"draft"},o=HT({artifactId:n.requirements,revision:r,predecessorRevision:e.predecessorRevision,kind:"requirements",title:`${e.title} - requirements`,value:{schemaVersion:yw,specId:e.specId,revision:r,problem:e.problem,requirements:e.requirements,acceptanceCriteria:e.acceptanceCriteria},context:i}),s=HT({artifactId:n.design,revision:r,predecessorRevision:e.predecessorRevision,kind:"design",title:`${e.title} - design`,value:{schemaVersion:yw,specId:e.specId,revision:r,design:e.design,...e.sourceBaseline?{sourceBaseline:e.sourceBaseline}:{}},context:i}),a=HT({artifactId:n.taskGraph,revision:r,predecessorRevision:e.predecessorRevision,kind:"task-graph",title:`${e.title} - task graph`,value:{schemaVersion:yw,specId:e.specId,revision:r,tasks:e.tasks},context:i}),c=[o,s,a].map(u=>({relation:"decomposes",target:{type:"artifact",id:u.artifactId,revision:u.revision}})),l=HT({artifactId:n.plan,revision:r,predecessorRevision:e.predecessorRevision,kind:"plan",title:e.title,description:e.problem,value:e,context:{...t,createdAt:e.updatedAt,state:"pending_review"},relationships:c,extensions:{"xeno.spec.id":e.specId,"xeno.spec.revision":e.revision,"xeno.spec.requirements_hash":o.content.hash.value,"xeno.spec.design_hash":s.content.hash.value,"xeno.spec.task_graph_hash":a.content.hash.value}});return{document:structuredClone(e),plan:l,requirements:o,design:s,taskGraph:a}}function bw(e){if(e.kind!=="plan"||e.mediaType!=="application/vnd.xeno.spec+json")throw new Ys([`Artifact ${e.artifactId} is not a XENO spec plan`]);let t=BOe(e);if(Bee(t),t.revision!==e.revision)throw new Ys(["Spec and artifact revisions differ"]);if(!XT(Iw(t),e.content.hash))throw new Ys(["Spec artifact content hash is invalid"]);return structuredClone(t)}function uOe(e,t,n=1,r){let i=structuredClone(e);return HT({artifactId:e.executionId,revision:n,predecessorRevision:r,kind:"custom:xeno.spec-execution",title:`Execution of ${e.specId} revision ${e.specRevision}`,description:`Execution state: ${e.state}`,value:i,context:{...t,createdAt:e.updatedAt,state:e.state==="completed"?"pending_review":"draft"},relationships:[{relation:"implements",target:{type:"artifact",id:e.planArtifactId,revision:e.specRevision}}],extensions:{"xeno.spec.execution_state":e.state,"xeno.spec.plan_hash":e.planHash.value}})}function YT(e){if(e.kind!=="custom:xeno.spec-execution")throw new Ys([`Artifact ${e.artifactId} is not a spec execution`]);let t=BOe(e);if(t.schemaVersion!==$F||t.executionId!==e.artifactId)throw new Ys(["Spec execution identity or schema is invalid"]);if(!XT(Iw(t),e.content.hash))throw new Ys(["Spec execution content hash is invalid"]);return structuredClone(t)}function _Oe(e,t){let n=[];e.schemaVersion!==$F&&n.push("Execution schema is invalid"),(e.specId!==t.specId||e.specRevision!==t.revision)&&n.push("Execution is bound to the wrong spec revision");let r=new Map(t.tasks.map(o=>[o.id,o])),i=new Set;for(let o of e.tasks){i.has(o.taskId)&&n.push(`Duplicate execution task ${o.taskId}`),i.add(o.taskId);let s=r.get(o.taskId);if(!s){n.push(`Unknown execution task ${o.taskId}`);continue}for(let a of s.acceptanceCriterionIds)Array.isArray(o.acceptanceEvidence?.[a])||n.push(`Task ${o.taskId} is missing acceptance evidence slot ${a}`)}for(let o of r.keys())i.has(o)||n.push(`Execution is missing task ${o}`);for(let o of e.observedPaths)DLt(o)||n.push(`Unsafe observed path ${o}`);if(BF(e.createdAt,"execution createdAt",n),BF(e.updatedAt,"execution updatedAt",n),n.length>0)throw new Ys([...new Set(n)])}function $Oe(e,t,n,r,i=new Date().toISOString()){Bee(e),_Oe(n,e);let o=[];(!XT(t,r)||!XT(n.planHash,r))&&o.push({code:"PLAN_HASH_MISMATCH",severity:"error",message:"Execution is not bound to the approved plan content hash"});let s=new Map(e.tasks.map(l=>[l.id,l])),a=new Map(n.tasks.map(l=>[l.taskId,l]));for(let l of n.tasks){let u=s.get(l.taskId);if(!u){o.push({code:"UNKNOWN_TASK",severity:"error",taskId:l.taskId,message:`Unknown task ${l.taskId}`});continue}if(l.status==="completed"){l.evidence.length===0&&o.push({code:"MISSING_TASK_EVIDENCE",severity:"error",taskId:u.id,message:`Completed task ${u.id} has no evidence`});for(let d of u.dependsOn??[])a.get(d)?.status!=="completed"&&o.push({code:"DEPENDENCY_INCOMPLETE",severity:"error",taskId:u.id,message:`Task ${u.id} completed before dependency ${d}`});for(let d of u.acceptanceCriterionIds)(l.acceptanceEvidence[d]??[]).length===0&&o.push({code:"MISSING_ACCEPTANCE_EVIDENCE",severity:"error",taskId:u.id,criterionId:d,message:`Completed task ${u.id} has no evidence for ${d}`})}}let c=e.tasks.flatMap(l=>l.expectedPaths??[]);for(let l of n.observedPaths)c.some(u=>LLt(l,u))||o.push({code:"UNKNOWN_PATH",severity:"warning",path:l,message:`Observed path ${l} is outside the approved task plan`});return{schemaVersion:"xeno.spec-drift.v1",specId:e.specId,specRevision:e.revision,executionId:n.executionId,checkedAt:i,drifted:o.length>0,findings:o}}function HT(e){let t=e.value,n=pc(t);return{schemaVersion:1,artifactId:e.artifactId,revision:e.revision,kind:e.kind,title:e.title,...e.description?{description:e.description}:{},state:e.context.state,createdAt:e.context.createdAt??new Date().toISOString(),mediaType:MLt(e.kind),sensitivity:e.context.sensitivity??"internal",...e.context.identity?{identity:structuredClone(e.context.identity)}:{},content:{hash:Iw(t),sizeBytes:Buffer.byteLength(n,"utf8"),encoding:"utf8",storage:{type:"inline",text:n},redactedPreview:e.title},provenance:{producer:structuredClone(e.context.producer)},...e.relationships?.length?{relationships:structuredClone(e.relationships)}:{},...e.predecessorRevision!==void 0?{predecessorRevision:e.predecessorRevision}:{},...e.context.accessPolicyId?{accessPolicyId:e.context.accessPolicyId}:{},...e.extensions?{extensions:structuredClone(e.extensions)}:{}}}function MLt(e){return e==="plan"?"application/vnd.xeno.spec+json":e==="custom:xeno.spec-execution"?"application/vnd.xeno.spec-execution+json":`application/vnd.xeno.spec-${e}+json`}function BOe(e){let t=e.content.storage;if(t.type!=="inline"||typeof t.text!="string")throw new Ys(["Spec artifacts require inline JSON content"]);try{return JSON.parse(t.text)}catch(n){throw new Ys([`Spec artifact JSON is invalid: ${n instanceof Error?n.message:String(n)}`])}}function TF(e,t,n){let r=new Set;(!Array.isArray(e)||e.length===0)&&n.push(`${t} list cannot be empty`);for(let i of e??[])JT(i?.id,`${t} id`,n),r.has(i?.id??"")&&n.push(`Duplicate ${t}: ${i?.id}`),i?.id&&r.add(i.id);return r}function JT(e,t,n){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(e))&&n.push(`${t} must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}`)}function Jl(e,t,n){(typeof e!="string"||e.trim().length===0||e.length>64*1024)&&n.push(`${t} must be non-empty and no longer than 65536 characters`)}function BF(e,t,n){(typeof e!="string"||!e.includes("T")||!Number.isFinite(Date.parse(e)))&&n.push(`${t} must be an ISO 8601 timestamp`)}function NLt(e,t){let n=[];if(JT(e,t,n),n.length>0)throw new Ys(n);return e}function OLt(e){let t=new Map(e.map(o=>[o.id,o])),n=new Set,r=new Set,i=o=>{if(n.has(o))return!0;if(r.has(o))return!1;n.add(o);for(let s of t.get(o)?.dependsOn??[])if(i(s))return!0;return n.delete(o),r.add(o),!1};return e.some(o=>i(o.id))}function MOe(e){let t=e.replace(/\\/gu,"/");return t.length>0&&t.length<=4096&&!t.startsWith("/")&&!/^[A-Za-z]:/u.test(t)&&!t.split("/").includes("..")}function DLt(e){return MOe(e)&&!e.includes("*")}function LLt(e,t){let n=e.replace(/\\/gu,"/"),r=t.replace(/\\/gu,"/");if(r.endsWith("/**")){let i=r.slice(0,-3).replace(/\/$/u,"");return n===i||n.startsWith(`${i}/`)}if(r.endsWith("/*")){let i=r.slice(0,-2).replace(/\/$/u,""),o=n.startsWith(`${i}/`)?n.slice(i.length+1):"";return o.length>0&&!o.includes("/")}return n===r}function XT(e,t){return e.algorithm===t.algorithm&&e.value===t.value}function DOe(e="xeno-production-review"){return{schemaVersion:"xeno.review-pack.v1",packId:e,version:"1.0.0",dimensions:["correctness","security","performance","api","tests","documentation"],verifierCount:1,minimumVerifierReproductions:1,allowIndependentEvidenceVerification:!1,minimumIndependentEvidenceProducers:2,maxFindings:256}}function LOe(e){let t=[];e?.schemaVersion!=="xeno.review-pack.v1"&&t.push("Review pack schemaVersion must be xeno.review-pack.v1"),Xl(e?.packId,"packId",t),(typeof e?.version!="string"||!/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/u.test(e.version))&&t.push("Review pack version must be semantic version text"),(!Array.isArray(e?.dimensions)||e.dimensions.length===0)&&t.push("Review pack needs at least one dimension"),new Set(e?.dimensions??[]).size!==(e?.dimensions??[]).length&&t.push("Review pack dimensions must be unique");for(let n of e?.dimensions??[])JOe(n)||t.push(`Invalid review dimension ${n}`);if((!Number.isInteger(e?.verifierCount)||e.verifierCount<0||e.verifierCount>8)&&t.push("verifierCount must be 0 through 8"),(!Number.isInteger(e?.minimumVerifierReproductions)||e.minimumVerifierReproductions<1||e.minimumVerifierReproductions>Math.max(1,e.verifierCount))&&t.push("minimumVerifierReproductions must be positive and no greater than verifierCount"),(!Number.isInteger(e?.minimumIndependentEvidenceProducers)||e.minimumIndependentEvidenceProducers<2)&&t.push("minimumIndependentEvidenceProducers must be at least 2"),(!Number.isInteger(e?.maxFindings)||e.maxFindings<1||e.maxFindings>2048)&&t.push("maxFindings must be 1 through 2048"),t.length>0)throw new zl(t)}function QOe(e){let t=[];if(Xl(e?.artifactId,"target artifactId",t),(!Number.isInteger(e?.revision)||e.revision<1)&&t.push("Target revision must be positive"),vw(e?.title,"target title",t),(e?.contentHash?.algorithm!=="sha256"||!/^[a-f0-9]{64}$/u.test(e?.contentHash?.value??""))&&t.push("Target contentHash must be lowercase sha256"),t.length>0)throw new zl(t)}function FOe(e){let t=[];e?.schemaVersion!==NOe&&t.push("Review report schemaVersion is invalid"),Xl(e?.reportId,"reportId",t),Xl(e?.runId,"runId",t),NF(e?.startedAt,"startedAt",t),NF(e?.completedAt,"completedAt",t),Date.parse(e?.completedAt)<Date.parse(e?.startedAt)&&t.push("completedAt cannot precede startedAt");try{LOe(e.pack)}catch(o){t.push(o instanceof Error?o.message:String(o))}try{QOe(e.target)}catch(o){t.push(o instanceof Error?o.message:String(o))}let n=new Set,r=new Set;for(let o of e?.findings??[])Xl(o?.findingId,"findingId",t),n.has(o.findingId)&&t.push(`Duplicate findingId ${o.findingId}`),n.add(o.findingId),/^[a-f0-9]{64}$/u.test(o?.fingerprint??"")||t.push(`Finding ${o.findingId} has invalid fingerprint`),r.has(o.fingerprint)&&t.push(`Duplicate finding fingerprint ${o.fingerprint}`),r.add(o.fingerprint),vw(o?.title,`finding ${o.findingId} title`,t),vw(o?.summary,`finding ${o.findingId} summary`,t),GOe(o?.severity)||t.push(`Finding ${o.findingId} has invalid severity`),(!Number.isFinite(o?.confidence)||o.confidence<0||o.confidence>1)&&t.push(`Finding ${o.findingId} has invalid confidence`),o?.state==="verified"&&o.verificationBasis==="none"&&t.push(`Finding ${o.findingId} cannot be verified without a basis`),o?.state!=="verified"&&o.verificationBasis==="independent-evidence"&&t.push(`Finding ${o.findingId} has inconsistent evidence verification`);let i=WOe(e?.findings??[]);if((i.total!==e?.summary?.total||i.verified!==e?.summary?.verified||i.unverified!==e?.summary?.unverified||i.rejected!==e?.summary?.rejected||Object.keys(i.bySeverity).some(o=>i.bySeverity[o]!==e?.summary?.bySeverity?.[o]))&&t.push("Review report summary is inconsistent"),t.length>0)throw new zl([...new Set(t)])}function UOe(e,t){FOe(e);let n=e,r=pc(n),i=t.artifactId??`review_${Qr(`${e.runId}:${e.target.artifactId}:${e.target.contentHash.value}`).value.slice(0,24)}`,o={schemaVersion:1,artifactId:i,revision:1,kind:"review-report",title:`Review of ${e.target.title}`,description:`${e.summary.verified} verified, ${e.summary.unverified} unverified, ${e.summary.rejected} rejected findings`,state:"pending_review",createdAt:t.createdAt??e.completedAt,mediaType:"application/vnd.xeno.review-report+json",sensitivity:t.sensitivity??"internal",...t.identity?{identity:structuredClone(t.identity)}:{},content:{hash:Iw(n),sizeBytes:Buffer.byteLength(r,"utf8"),encoding:"utf8",storage:{type:"inline",text:r},redactedPreview:`${e.summary.total} findings; ${e.summary.verified} verified`},provenance:{producer:structuredClone(t.producer),sourceArtifactIds:[e.target.artifactId],attributes:{reviewPackId:e.pack.packId,reviewPackVersion:e.pack.version}},relationships:[{relation:"reviews",target:{type:"artifact",id:e.target.artifactId,revision:e.target.revision}}],anchors:VOe(e.findings.flatMap(s=>s.anchors)),...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.review.pack":e.pack.packId,"xeno.review.verified":e.summary.verified,"xeno.review.unverified":e.summary.unverified,"xeno.review.rejected":e.summary.rejected}};return mh(o),o}function qLt(e,t){let n=new Map;for(let r of e){qOe(r.finding),MF(r.reviewerAgentId,"reviewerAgentId");let i=jLt(r.finding),o=n.get(i)??[];o.push(structuredClone(r)),n.set(i,o)}return[...n.entries()].map(([r,i])=>{let o=[...i].sort((a,c)=>HI(c.finding.severity)-HI(a.finding.severity))[0],s=jOe(i.flatMap(a=>a.finding.evidence));return{findingId:MF(t("finding"),"findingId"),fingerprint:r,ruleIds:[...new Set(i.flatMap(a=>a.finding.ruleId?[a.finding.ruleId]:[]))].sort(),dimensions:[...new Set(i.map(a=>a.finding.dimension))].sort(),reviewerAgentIds:[...new Set(i.map(a=>a.reviewerAgentId))].sort(),title:o.finding.title,summary:o.finding.summary,severity:i.reduce((a,c)=>HI(c.finding.severity)>HI(a)?c.finding.severity:a,o.finding.severity),confidence:XOe(Math.max(...i.map(a=>a.finding.confidence))),state:"unverified",verificationBasis:"none",anchors:VOe(i.flatMap(a=>a.finding.anchors)),evidence:s,verifications:[],...o.finding.remediation?{remediation:o.finding.remediation}:{},duplicateProposalCount:i.length}})}function jLt(e){let t=e.anchors.map(HOe).sort();return Iw({ruleId:e.ruleId??"",title:JLt(e.title),anchors:t}).value}function VLt(e,t,n){let r=[];Xl(e?.reviewerAgentId,"reviewerAgentId",r),e?.dimension!==t&&r.push(`Reviewer returned dimension ${e?.dimension} for requested ${t}`),NF(e?.completedAt,"reviewer completedAt",r),(!Array.isArray(e?.findings)||e.findings.length>n)&&r.push("Reviewer finding list is invalid or exceeds maxFindings");for(let i of e?.findings??[]){try{qOe(i)}catch(o){r.push(o instanceof Error?o.message:String(o))}i.dimension!==t&&r.push(`Finding dimension ${i.dimension} differs from reviewer dimension ${t}`)}if(r.length>0)throw new zl([...new Set(r)])}function qOe(e){let t=[];JOe(e?.dimension)||t.push(`Invalid finding dimension ${e?.dimension}`),vw(e?.title,"finding title",t),vw(e?.summary,"finding summary",t),GOe(e?.severity)||t.push(`Invalid finding severity ${e?.severity}`),(!Number.isFinite(e?.confidence)||e.confidence<0||e.confidence>1)&&t.push("Finding confidence must be 0 through 1"),(!Array.isArray(e?.anchors)||e.anchors.length===0)&&t.push("Finding needs at least one source or artifact anchor"),Array.isArray(e?.evidence)||t.push("Finding evidence must be an array");for(let n of e?.evidence??[])Mee(n,t);if(e?.ruleId!==void 0&&Xl(e.ruleId,"ruleId",t),t.length>0)throw new zl([...new Set(t)])}function HLt(e){let t=[];Xl(e?.verifierAgentId,"verifierAgentId",t),["reproduced","rejected","inconclusive"].includes(e?.outcome)||t.push("Verifier outcome is invalid"),vw(e?.rationale,"verifier rationale",t),NF(e?.completedAt,"verifier completedAt",t),Array.isArray(e?.evidence)||t.push("Verifier evidence must be an array");for(let n of e?.evidence??[])Mee(n,t);if(e?.outcome==="reproduced"&&(e?.evidence?.length??0)===0&&t.push("A reproduced finding requires verifier evidence"),e?.confidence!==void 0&&(!Number.isFinite(e.confidence)||e.confidence<0||e.confidence>1)&&t.push("Verifier confidence must be 0 through 1"),t.length>0)throw new zl([...new Set(t)])}function Mee(e,t){Xl(e?.evidenceId,"evidenceId",t),Xl(e?.producerId,"evidence producerId",t),vw(e?.summary,"evidence summary",t),(typeof e?.kind!="string"||!(ULt.includes(e.kind)||_ee(e.kind)))&&t.push(`Invalid evidence kind ${e?.kind}`)}function jOe(e){let t=new Map;for(let n of e){let r=[];if(Mee(n,r),r.length>0)throw new zl(r);let i=t.get(n.evidenceId);if(i&&pc(i)!==pc(n))throw new zl([`Conflicting evidence ID ${n.evidenceId}`]);t.set(n.evidenceId,structuredClone(n))}return[...t.values()].sort((n,r)=>n.evidenceId.localeCompare(r.evidenceId))}function WLt(e){let t=new Map;for(let n of e){if(t.has(n.verifierAgentId))throw new zl([`Verifier ${n.verifierAgentId} returned more than one result for a finding`]);t.set(n.verifierAgentId,structuredClone(n))}return[...t.values()].sort((n,r)=>n.verifierAgentId.localeCompare(r.verifierAgentId))}function VOe(e){let t=new Map;for(let n of e)t.set(HOe(n),structuredClone(n));return[...t.entries()].sort(([n],[r])=>n.localeCompare(r)).map(([,n])=>n)}function HOe(e){return pc(e)}function WOe(e){let t={info:0,low:0,medium:0,high:0,critical:0};for(let n of e)t[n.severity]+=1;return{total:e.length,verified:e.filter(n=>n.state==="verified").length,unverified:e.filter(n=>n.state==="unverified").length,rejected:e.filter(n=>n.state==="rejected").length,bySeverity:t}}function GLt(e,t){return HI(t.severity)-HI(e.severity)||+(t.state==="verified")-+(e.state==="verified")||e.fingerprint.localeCompare(t.fingerprint)}function HI(e){return{info:0,low:1,medium:2,high:3,critical:4}[e]}function GOe(e){return typeof e=="string"&&["info","low","medium","high","critical"].includes(e)}function JOe(e){return typeof e=="string"&&(FLt.includes(e)||_ee(e))}function JLt(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function XOe(e){return Math.max(0,Math.min(1,Number(e.toFixed(6))))}function Xl(e,t,n){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u.test(e))&&n.push(`${t} has an invalid identifier`)}function MF(e,t){let n=[];if(Xl(e,t,n),n.length>0)throw new zl(n);return e}function vw(e,t,n){(typeof e!="string"||e.trim().length===0||e.length>64*1024)&&n.push(`${t} must be non-empty and no longer than 65536 characters`)}function NF(e,t,n){(typeof e!="string"||!e.includes("T")||!Number.isFinite(Date.parse(e)))&&n.push(`${t} must be an ISO 8601 timestamp`)}function zOe(e,t){let n=zLt(e),r=e.files.map(s=>s.patch).filter(s=>!!s);if(e.files.length>0&&r.length===e.files.length&&r.every(s=>s.startsWith("diff --git ")))try{let s=OF(r.join(`
|
|
2949
|
-
`),{artifactId:t.artifactId??`turn_diff_${e.turnId}`,revision:t.revision??1,createdAt:t.createdAt??e.completedAt,title:`Turn ${e.turnId} changes`,producer:t.producer,identity:{...t.identity?structuredClone(t.identity):{},turnId:t.identity?.turnId??e.turnId},sensitivity:t.sensitivity??"internal",...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},mode:"turn"}),a={...s,state:t.state??s.state,extensions:{...s.extensions??{},"xeno.legacy.turnDiffSummary":n}};return mh(a),a}catch{}let i=pc(n),o={schemaVersion:1,artifactId:t.artifactId??`turn_diff_${e.turnId}`,revision:t.revision??1,kind:"diff",title:`Turn ${e.turnId} changes`,state:t.state??"pending_review",createdAt:t.createdAt??e.completedAt,mediaType:"application/vnd.xeno.turn-diff+json",sensitivity:t.sensitivity??"internal",identity:{...t.identity?structuredClone(t.identity):{},turnId:t.identity?.turnId??e.turnId},content:{hash:Iw(n),sizeBytes:XLt.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i}},provenance:{producer:{...t.producer}},anchors:e.files.map(s=>({kind:"custom:source-file",data:{path:s.path}})),...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.legacy.turnDiffSummary":n}};return mh(o),o}function zLt(e){return JSON.parse(JSON.stringify(e))}var dOe,EDt,SDt,CDt,xDt,pOe,fOe,TDt,PDt,$ee,_Dt,$Dt,BDt,MDt,mOe,NDt,ODt,DDt,LDt,QDt,FDt,UDt,SQn,CQn,St,wOe,lLt,SOe,uLt,dLt,pLt,fLt,COe,yLt,bLt,vLt,ILt,kLt,Ta,WI,yw,$F,Ys,zT,NOe,FLt,ULt,zl,OOe,gh=Ie(()=>{"use strict";dOe=1,EDt=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation"],SDt=["draft","pending_review","approved","rejected","superseded","archived"],CDt=["public","internal","confidential","restricted"],xDt=["agent","tool","user","system","integration"],pOe=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],fOe=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];TDt=/^[a-z0-9][a-z0-9._/-]{0,127}$/,PDt="custom:";$ee=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(n=>({...n}))}},_Dt=class extends Error{constructor(e,t){super(`Artifact state cannot transition from ${e} to ${t}`),this.fromState=e,this.toState=t,this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},$Dt={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},BDt="[\\u0000-\\u001f\\u007f]",MDt=new RegExp(BDt),mOe=/^[a-f0-9]{64}$/,NDt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ODt=new Set(SDt),DDt=new Set(CDt),LDt=new Set(xDt),QDt=new Set(EDt),FDt=new Set(pOe),UDt=new Set(fOe);SQn=new Set(pOe),CQn=new Set(fOe),St=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoArtifactRepositoryError"}code;detail},wOe=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(e={}){this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>(this.idCounter+=1,`${t}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),e.initialState&&this.hydrate(e.initialState)}exportState(){return{schemaVersion:1,records:[...this.records.values()].flatMap(t=>[...t.values()]).sort(KNe).map(t=>({artifact:GT(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(mh(e),this.assertInitialState(e),e.revision!==1)throw new St("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:e.artifactId,revision:e.revision});if(this.records.has(e.artifactId))throw new St("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=GT(e),n=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),r={artifact:t,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,r]])),this.currentRevisions.set(t.artifactId,t.revision),hw(r)}async createRevision(e,t={}){mh(e),this.assertInitialState(e);let n=this.getMutable(e.artifactId);this.assertVersion(n,t.expectedRecordVersion);let r=n.artifact.revision+1;if(e.revision!==r||e.predecessorRevision!==n.artifact.revision)throw new St("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:e.artifactId,currentRevision:n.artifact.revision,requestedRevision:e.revision});if(HDt(e,n.artifact))throw new St("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(n.artifact.state==="archived")throw new St("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){Ree(n.artifact.state,"superseded");let a=this.now(),c=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});n.artifact.state="superseded",n.artifact.updatedAt=a,n.lifecycleEvents.push(c),n.recordVersion+=1}let i=GT(e),o=this.createLifecycleEvent({artifact:i,sequence:1,actor:t.actor??i.provenance.producer,fromState:null,toState:i.state,reason:t.reason??`revision-created-from-${n.artifact.revision}`}),s={artifact:i,recordVersion:1,lifecycleEvents:[o],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,s),this.currentRevisions.set(i.artifactId,i.revision),hw(s)}async get(e,t){let n=this.records.get(e);if(!n)return;let r=t??this.currentRevisions.get(e);if(r===void 0)return;let i=n.get(r);return i?hw(i):void 0}async require(e,t){let n=await this.get(e,t);if(!n)throw new St("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return n}async list(e={}){let t=[];for(let[n,r]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(n)))if(e.includeSuperseded)t.push(...r.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let o=r.get(i);o&&t.push(o)}}return t.filter(n=>WDt(n.artifact,e)).sort(KNe).map(hw)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((n,r)=>n.artifact.revision-r.artifact.revision).map(hw):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),Ree(t.artifact.state,e.toState),e.toState==="approved"||e.toState==="rejected"){let o=e.reviewEventId?t.reviewEvents.find(a=>a.eventId===e.reviewEventId&&a.type==="decision-recorded"):void 0,s=AOe(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new St("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${e.toState} requires a matching decision event`,{artifactId:e.artifactId,revision:t.artifact.revision});if(e.toState==="approved"&&s.unresolvedComments>0)throw new St("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let n=this.now(),r=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:r,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:n});return t.artifact.state=e.toState,t.artifact.updatedAt=n,t.lifecycleEvents.push(i),t.recordVersion+=1,hw(t)}async appendReviewEvent(e){let t=e.event,n=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(n,e.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new St("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(n,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new St("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let r={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=gOe(r,n.artifact);if(i.length>0)throw new $ee("XENO artifact review event validation failed",i);return n.reviewEvents.push(r),n.recordVersion+=1,hw(n)}getMutable(e,t){let n=this.records.get(e),r=t??this.currentRevisions.get(e),i=r===void 0?void 0:n?.get(r);if(!i)throw new St("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return i}assertVersion(e,t){if(t!==void 0&&t!==e.recordVersion)throw new St("ARTIFACT_CONFLICT",`Expected record version ${t}, found ${e.recordVersion}`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision,expectedRecordVersion:t,actualRecordVersion:e.recordVersion})}assertInitialState(e){if(e.state!=="draft"&&e.state!=="pending_review")throw new St("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:e.artifactId,revision:e.revision})}assertReviewCommentState(e,t){if(t.type==="comment-added"){if(e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.parentCommentId))throw new St("ARTIFACT_REVIEW_INVALID",`Parent comment ${t.parentCommentId} does not exist`);return}if(t.type!=="comment-resolved"&&t.type!=="comment-reopened")return;if(!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let n=GDt(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&n.resolved)throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!n.resolved)throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is not resolved`)}createLifecycleEvent(e){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:e.artifact.artifactId,revision:e.artifact.revision,sequence:e.sequence,recordedAt:e.recordedAt??this.now(),actor:{...e.actor},fromState:e.fromState,toState:e.toState,...e.reason?{reason:e.reason}:{},...e.reviewEventId?{reviewEventId:e.reviewEventId}:{}}}nextEventId(e){let t=this.idFactory(e);if(typeof t!="string"||t.trim().length===0||this.eventIds.has(t))throw new St("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${e} ID`);return this.eventIds.add(t),t}hydrate(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new St("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((n,r)=>n.artifact.artifactId.localeCompare(r.artifact.artifactId)||n.artifact.revision-r.artifact.revision);for(let n of t){let r=VDt(n,this.eventIds),i=this.records.get(r.artifact.artifactId);if(i||(i=new Map,this.records.set(r.artifact.artifactId,i)),i.has(r.artifact.revision))throw new St("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${r.artifact.artifactId}:${r.artifact.revision}`);i.set(r.artifact.revision,r),this.currentRevisions.set(r.artifact.artifactId,r.artifact.revision)}for(let[n,r]of this.records){let i=[...r.values()].sort((o,s)=>o.artifact.revision-s.artifact.revision);for(let o=0;o<i.length;o+=1){let s=i[o],a=o+1;if(s.artifact.revision!==a)throw new St("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new St("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new St("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new St("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${a} must be superseded`)}}}};lLt="0.9.34",SOe=1,uLt="repository.v1.json",dLt=5e3,pLt=20,fLt=64*1024*1024,COe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let t=e.snapshotFileName??uLt;if(eOe(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=KDt(e.directory),this.snapshotPath=YDt(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Eee(e.lockTimeoutMs,dLt,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Eee(e.lockRetryMs,pLt,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Eee(e.maxSnapshotBytes,fLt,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(t=>t.create(e))}async createRevision(e,t){return this.mutate(n=>n.createRevision(e,t))}async get(e,t){return(await this.load()).repository.get(e,t)}async require(e,t){return(await this.load()).repository.require(e,t)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(t=>t.transition(e))}async appendReviewEvent(e){return this.mutate(t=>t.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let t=await this.acquireLock();try{let n=await this.load(),r=await e(n.repository);return await this.persist(n),r}finally{t.release()}})}async enqueueMutation(e){let t=this.mutationTail.then(e,e);return this.mutationTail=t.then(()=>{},()=>{}),t}async acquireLock(){let e=Date.now(),t;for(;Date.now()-e<=this.lockTimeoutMs;)try{return cLt(this.lockPath,`artifact-repository:${eOe(this.snapshotPath)}`,lLt)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;t=n,await wLt(this.lockRetryMs)}throw new St("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,n=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=PF(i)}if(!t&&(e||await ALt(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),t=i,n=!0)}catch(i){throw e?new St("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,PF(i)])}):i}if(!t&&e)throw e;let r=t?.state??{schemaVersion:1,records:[]};return{repository:new wOe({now:this.now,idFactory:i=>`${i}_${yOe()}`,initialState:r}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:n,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),n={schemaVersion:SOe,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},r=hLt(n),i=`${JSON.stringify(r,null,2)}
|
|
2949
|
+
`),{artifactId:t.artifactId??`turn_diff_${e.turnId}`,revision:t.revision??1,createdAt:t.createdAt??e.completedAt,title:`Turn ${e.turnId} changes`,producer:t.producer,identity:{...t.identity?structuredClone(t.identity):{},turnId:t.identity?.turnId??e.turnId},sensitivity:t.sensitivity??"internal",...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},mode:"turn"}),a={...s,state:t.state??s.state,extensions:{...s.extensions??{},"xeno.legacy.turnDiffSummary":n}};return mh(a),a}catch{}let i=pc(n),o={schemaVersion:1,artifactId:t.artifactId??`turn_diff_${e.turnId}`,revision:t.revision??1,kind:"diff",title:`Turn ${e.turnId} changes`,state:t.state??"pending_review",createdAt:t.createdAt??e.completedAt,mediaType:"application/vnd.xeno.turn-diff+json",sensitivity:t.sensitivity??"internal",identity:{...t.identity?structuredClone(t.identity):{},turnId:t.identity?.turnId??e.turnId},content:{hash:Iw(n),sizeBytes:XLt.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i}},provenance:{producer:{...t.producer}},anchors:e.files.map(s=>({kind:"custom:source-file",data:{path:s.path}})),...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.legacy.turnDiffSummary":n}};return mh(o),o}function zLt(e){return JSON.parse(JSON.stringify(e))}var dOe,EDt,SDt,CDt,xDt,pOe,fOe,TDt,PDt,$ee,_Dt,$Dt,BDt,MDt,mOe,NDt,ODt,DDt,LDt,QDt,FDt,UDt,SQn,CQn,St,wOe,lLt,SOe,uLt,dLt,pLt,fLt,COe,yLt,bLt,vLt,ILt,kLt,Ta,WI,yw,$F,Ys,zT,NOe,FLt,ULt,zl,OOe,gh=Ie(()=>{"use strict";dOe=1,EDt=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation"],SDt=["draft","pending_review","approved","rejected","superseded","archived"],CDt=["public","internal","confidential","restricted"],xDt=["agent","tool","user","system","integration"],pOe=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],fOe=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];TDt=/^[a-z0-9][a-z0-9._/-]{0,127}$/,PDt="custom:";$ee=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(n=>({...n}))}},_Dt=class extends Error{constructor(e,t){super(`Artifact state cannot transition from ${e} to ${t}`),this.fromState=e,this.toState=t,this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},$Dt={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},BDt="[\\u0000-\\u001f\\u007f]",MDt=new RegExp(BDt),mOe=/^[a-f0-9]{64}$/,NDt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ODt=new Set(SDt),DDt=new Set(CDt),LDt=new Set(xDt),QDt=new Set(EDt),FDt=new Set(pOe),UDt=new Set(fOe);SQn=new Set(pOe),CQn=new Set(fOe),St=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoArtifactRepositoryError"}code;detail},wOe=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(e={}){this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>(this.idCounter+=1,`${t}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),e.initialState&&this.hydrate(e.initialState)}exportState(){return{schemaVersion:1,records:[...this.records.values()].flatMap(t=>[...t.values()]).sort(KNe).map(t=>({artifact:GT(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(mh(e),this.assertInitialState(e),e.revision!==1)throw new St("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:e.artifactId,revision:e.revision});if(this.records.has(e.artifactId))throw new St("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=GT(e),n=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),r={artifact:t,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,r]])),this.currentRevisions.set(t.artifactId,t.revision),hw(r)}async createRevision(e,t={}){mh(e),this.assertInitialState(e);let n=this.getMutable(e.artifactId);this.assertVersion(n,t.expectedRecordVersion);let r=n.artifact.revision+1;if(e.revision!==r||e.predecessorRevision!==n.artifact.revision)throw new St("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:e.artifactId,currentRevision:n.artifact.revision,requestedRevision:e.revision});if(HDt(e,n.artifact))throw new St("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(n.artifact.state==="archived")throw new St("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){Ree(n.artifact.state,"superseded");let a=this.now(),c=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});n.artifact.state="superseded",n.artifact.updatedAt=a,n.lifecycleEvents.push(c),n.recordVersion+=1}let i=GT(e),o=this.createLifecycleEvent({artifact:i,sequence:1,actor:t.actor??i.provenance.producer,fromState:null,toState:i.state,reason:t.reason??`revision-created-from-${n.artifact.revision}`}),s={artifact:i,recordVersion:1,lifecycleEvents:[o],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,s),this.currentRevisions.set(i.artifactId,i.revision),hw(s)}async get(e,t){let n=this.records.get(e);if(!n)return;let r=t??this.currentRevisions.get(e);if(r===void 0)return;let i=n.get(r);return i?hw(i):void 0}async require(e,t){let n=await this.get(e,t);if(!n)throw new St("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return n}async list(e={}){let t=[];for(let[n,r]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(n)))if(e.includeSuperseded)t.push(...r.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let o=r.get(i);o&&t.push(o)}}return t.filter(n=>WDt(n.artifact,e)).sort(KNe).map(hw)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((n,r)=>n.artifact.revision-r.artifact.revision).map(hw):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),Ree(t.artifact.state,e.toState),e.toState==="approved"||e.toState==="rejected"){let o=e.reviewEventId?t.reviewEvents.find(a=>a.eventId===e.reviewEventId&&a.type==="decision-recorded"):void 0,s=AOe(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new St("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${e.toState} requires a matching decision event`,{artifactId:e.artifactId,revision:t.artifact.revision});if(e.toState==="approved"&&s.unresolvedComments>0)throw new St("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let n=this.now(),r=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:r,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:n});return t.artifact.state=e.toState,t.artifact.updatedAt=n,t.lifecycleEvents.push(i),t.recordVersion+=1,hw(t)}async appendReviewEvent(e){let t=e.event,n=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(n,e.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new St("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(n,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new St("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let r={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=gOe(r,n.artifact);if(i.length>0)throw new $ee("XENO artifact review event validation failed",i);return n.reviewEvents.push(r),n.recordVersion+=1,hw(n)}getMutable(e,t){let n=this.records.get(e),r=t??this.currentRevisions.get(e),i=r===void 0?void 0:n?.get(r);if(!i)throw new St("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return i}assertVersion(e,t){if(t!==void 0&&t!==e.recordVersion)throw new St("ARTIFACT_CONFLICT",`Expected record version ${t}, found ${e.recordVersion}`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision,expectedRecordVersion:t,actualRecordVersion:e.recordVersion})}assertInitialState(e){if(e.state!=="draft"&&e.state!=="pending_review")throw new St("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:e.artifactId,revision:e.revision})}assertReviewCommentState(e,t){if(t.type==="comment-added"){if(e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.parentCommentId))throw new St("ARTIFACT_REVIEW_INVALID",`Parent comment ${t.parentCommentId} does not exist`);return}if(t.type!=="comment-resolved"&&t.type!=="comment-reopened")return;if(!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let n=GDt(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&n.resolved)throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!n.resolved)throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is not resolved`)}createLifecycleEvent(e){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:e.artifact.artifactId,revision:e.artifact.revision,sequence:e.sequence,recordedAt:e.recordedAt??this.now(),actor:{...e.actor},fromState:e.fromState,toState:e.toState,...e.reason?{reason:e.reason}:{},...e.reviewEventId?{reviewEventId:e.reviewEventId}:{}}}nextEventId(e){let t=this.idFactory(e);if(typeof t!="string"||t.trim().length===0||this.eventIds.has(t))throw new St("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${e} ID`);return this.eventIds.add(t),t}hydrate(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new St("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((n,r)=>n.artifact.artifactId.localeCompare(r.artifact.artifactId)||n.artifact.revision-r.artifact.revision);for(let n of t){let r=VDt(n,this.eventIds),i=this.records.get(r.artifact.artifactId);if(i||(i=new Map,this.records.set(r.artifact.artifactId,i)),i.has(r.artifact.revision))throw new St("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${r.artifact.artifactId}:${r.artifact.revision}`);i.set(r.artifact.revision,r),this.currentRevisions.set(r.artifact.artifactId,r.artifact.revision)}for(let[n,r]of this.records){let i=[...r.values()].sort((o,s)=>o.artifact.revision-s.artifact.revision);for(let o=0;o<i.length;o+=1){let s=i[o],a=o+1;if(s.artifact.revision!==a)throw new St("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new St("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new St("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new St("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${a} must be superseded`)}}}};lLt="0.9.35",SOe=1,uLt="repository.v1.json",dLt=5e3,pLt=20,fLt=64*1024*1024,COe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let t=e.snapshotFileName??uLt;if(eOe(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=KDt(e.directory),this.snapshotPath=YDt(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Eee(e.lockTimeoutMs,dLt,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Eee(e.lockRetryMs,pLt,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Eee(e.maxSnapshotBytes,fLt,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(t=>t.create(e))}async createRevision(e,t){return this.mutate(n=>n.createRevision(e,t))}async get(e,t){return(await this.load()).repository.get(e,t)}async require(e,t){return(await this.load()).repository.require(e,t)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(t=>t.transition(e))}async appendReviewEvent(e){return this.mutate(t=>t.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let t=await this.acquireLock();try{let n=await this.load(),r=await e(n.repository);return await this.persist(n),r}finally{t.release()}})}async enqueueMutation(e){let t=this.mutationTail.then(e,e);return this.mutationTail=t.then(()=>{},()=>{}),t}async acquireLock(){let e=Date.now(),t;for(;Date.now()-e<=this.lockTimeoutMs;)try{return cLt(this.lockPath,`artifact-repository:${eOe(this.snapshotPath)}`,lLt)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;t=n,await wLt(this.lockRetryMs)}throw new St("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,n=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=PF(i)}if(!t&&(e||await ALt(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),t=i,n=!0)}catch(i){throw e?new St("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,PF(i)])}):i}if(!t&&e)throw e;let r=t?.state??{schemaVersion:1,records:[]};return{repository:new wOe({now:this.now,idFactory:i=>`${i}_${yOe()}`,initialState:r}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:n,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),n={schemaVersion:SOe,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},r=hLt(n),i=`${JSON.stringify(r,null,2)}
|
|
2950
2950
|
`;if(Buffer.byteLength(i,"utf8")>this.maxSnapshotBytes)throw new St("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await bOe(this.directory,{recursive:!0,mode:448}),e.hasSnapshot&&!e.recoveredFromBackup&&e.sourceSnapshot&&await rOe(this.backupPath,`${JSON.stringify(e.sourceSnapshot,null,2)}
|
|
2951
2951
|
`),await rOe(this.snapshotPath,i)}async readSnapshot(e,t){let n;try{n=await vOe(e)}catch(r){if(!t&&Tee(r,"ENOENT")||t&&Tee(r,"ENOENT"))return;throw Pee("Unable to inspect artifact repository snapshot",e,r)}if(!n.isFile()||n.size>this.maxSnapshotBytes)throw new St("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:e,sizeBytes:n.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let r=await JDt(e);if(r.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return mLt(JSON.parse(r.toString("utf8")),e)}catch(r){throw r instanceof St?r:Pee("Unable to parse artifact repository snapshot",e,r,!0)}}};yLt=16*1024*1024,bLt=5e3,vLt=1e5,ILt=1e6,kLt=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,Ta=class extends Error{constructor(e,t){super(t===void 0?e:`${e} at diff line ${t}`),this.line=t,this.name="XenoDiffParseError"}line;code="XENO_DIFF_INVALID"};WI=class{repository;actor;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");if(!e.actor?.kind||!e.actor.id?.trim())throw new TypeError("Review actor is required");this.repository=e.repository,this.actor=structuredClone(e.actor),this.idFactory=e.idFactory??(()=>`comment_${TLt()}`)}async addComment(e){let t=DF(e.body,"Review comment body",65536),n=await this.repository.require(e.artifactId,e.revision),r=aOe(n,e),i=_F(this.idFactory(),"Comment ID"),o=_Lt(e.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:"comment-added",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,commentId:i,body:t,...r?{anchor:r}:{},...o?{parentCommentId:o}:{}}})}async setCommentResolution(e){let t=_F(e.commentId,"Review comment ID"),n=cOe(e.reason,"Resolution reason",16*1024),r=await this.repository.require(e.artifactId,e.revision);return this.repository.appendReviewEvent({expectedRecordVersion:r.recordVersion,event:{type:e.resolved?"comment-resolved":"comment-reopened",artifactId:r.artifact.artifactId,artifactRevision:r.artifact.revision,artifactHash:r.artifact.content.hash,actor:this.actor,commentId:t,...n?{reason:n}:{}}})}async decide(e){let t=await this.repository.require(e.artifactId,e.revision);if(t.artifact.state!=="pending_review")throw new St("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${t.artifact.state}`);let n=aOe(t,e),r=cOe(e.rationale,"Decision rationale",64*1024),i=await this.repository.appendReviewEvent({expectedRecordVersion:t.recordVersion,event:{type:"decision-recorded",artifactId:t.artifact.artifactId,artifactRevision:t.artifact.revision,artifactHash:t.artifact.content.hash,actor:this.actor,decision:e.decision,...r?{rationale:r}:{},...n?{scope:n}:{}}});if(n||e.decision==="changes_requested")return i;let o=i.reviewEvents.at(-1);if(!o||o.type!=="decision-recorded")throw new St("ARTIFACT_REVIEW_INVALID","Artifact decision event was not recorded");return this.repository.transition({artifactId:i.artifact.artifactId,revision:i.artifact.revision,expectedRecordVersion:i.recordVersion,toState:e.decision,actor:this.actor,reviewEventId:o.eventId,...r?{reason:r}:{}})}};yw="xeno.spec.v1",$F="xeno.spec-execution.v1",Ys=class extends Error{constructor(e){super(`XENO spec is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},zT=class{repository;now;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");this.repository=e.repository,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(()=>$Lt())}async create(e,t){if(e.revision!==1||e.predecessorRevision!==void 0)throw new Ys(["A new spec must begin at revision 1 without a predecessor"]);let n=lOe(e,t);return await this.repository.create(n.requirements),await this.repository.create(n.design),await this.repository.create(n.taskGraph),await this.repository.create(n.plan),n}async revise(e,t){let n=ww(e.specId),r=await this.repository.require(n.plan);if(e.revision!==r.artifact.revision+1||e.predecessorRevision!==r.artifact.revision)throw new Ys([`Revision ${e.revision} must follow approved or reviewed revision ${r.artifact.revision}`]);let i=lOe(e,t);return await this.repository.createRevision(i.requirements,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.design,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.taskGraph,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.plan,{actor:t.producer,reason:"spec-revised"}),i}async approve(e,t,n){return new WI({repository:this.repository,actor:t}).decide({artifactId:ww(e).plan,decision:"approved",...n?{rationale:n}:{}})}async reject(e,t,n){return new WI({repository:this.repository,actor:t}).decide({artifactId:ww(e).plan,decision:"rejected",rationale:n})}async startExecution(e,t){let n=await this.repository.require(ww(e).plan);if(n.artifact.state!=="approved")throw new Ys([`Spec ${e} must be approved before execution`]);let r=bw(n.artifact),i=this.now(),o={schemaVersion:$F,executionId:`spec_execution_${this.idFactory()}`,specId:r.specId,specRevision:r.revision,planArtifactId:n.artifact.artifactId,planHash:{...n.artifact.content.hash},state:"ready",createdAt:i,updatedAt:i,observedPaths:[],tasks:r.tasks.map(s=>({taskId:s.id,status:"pending",evidence:[],acceptanceEvidence:Object.fromEntries(s.acceptanceCriterionIds.map(a=>[a,[]]))}))};return this.repository.create(uOe(o,{producer:t,identity:n.artifact.identity,sensitivity:n.artifact.sensitivity,accessPolicyId:n.artifact.accessPolicyId}))}async updateExecution(e,t,n){let r=await this.repository.require(e),i=YT(r.artifact),o=await this.repository.require(i.planArtifactId,i.specRevision);if(o.artifact.state!=="approved"||!XT(o.artifact.content.hash,i.planHash))throw new Ys(["Execution is no longer bound to the approved plan revision"]);let s=t(structuredClone(i));s.schemaVersion=$F,s.executionId=i.executionId,s.specId=i.specId,s.specRevision=i.specRevision,s.planArtifactId=i.planArtifactId,s.planHash={...i.planHash},s.createdAt=i.createdAt,s.updatedAt=this.now(),_Oe(s,bw(o.artifact));let a=uOe(s,{producer:n,identity:r.artifact.identity,sensitivity:r.artifact.sensitivity,accessPolicyId:r.artifact.accessPolicyId},r.artifact.revision+1,r.artifact.revision);return this.repository.createRevision(a,{actor:n,reason:"spec-execution-updated"})}};NOe="xeno.review-report.v1",FLt=["correctness","security","performance","api","tests","documentation"],ULt=["source","test","trace","artifact","reproduction","benchmark"],zl=class extends Error{constructor(e){super(`XENO review is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},OOe=class{reviewer;verifier;now;idFactory;constructor(e){if(typeof e?.reviewer!="function")throw new TypeError("Review agent executor is required");this.reviewer=e.reviewer,this.verifier=e.verifier,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${QLt()}`)}async run(e){LOe(e.pack),QOe(e.target),MF(e.runId,"runId");let t=this.now(),n=await Promise.all(e.pack.dimensions.map(async(a,c)=>{let l=await this.reviewer({...e,dimension:a,reviewerSlot:c});return VLt(l,a,e.pack.maxFindings),structuredClone(l)})),r=n.flatMap(a=>a.findings.map(c=>({finding:c,reviewerAgentId:a.reviewerAgentId})));if(r.length>e.pack.maxFindings)throw new zl([`Reviewers returned ${r.length} findings, exceeding maxFindings ${e.pack.maxFindings}`]);let i=qLt(r,this.idFactory);for(let a of i){let c=this.verifier?await Promise.all(Array.from({length:e.pack.verifierCount},async(f,m)=>{let h=await this.verifier({...e,finding:structuredClone(a),verifierSlot:m});return HLt(h),structuredClone(h)})):[];a.verifications=WLt(c),a.evidence=jOe([...a.evidence,...a.verifications.flatMap(f=>f.evidence)]);let l=new Set(a.verifications.filter(f=>f.outcome==="reproduced").map(f=>f.verifierAgentId)).size,u=a.verifications.length>0&&a.verifications.every(f=>f.outcome==="rejected"),d=new Set(a.evidence.map(f=>f.producerId)).size;l>=e.pack.minimumVerifierReproductions?(a.state="verified",a.verificationBasis="verifier"):e.pack.allowIndependentEvidenceVerification&&d>=e.pack.minimumIndependentEvidenceProducers?(a.state="verified",a.verificationBasis="independent-evidence"):u?(a.state="rejected",a.verificationBasis="verifier"):(a.state="unverified",a.verificationBasis="none");let p=a.verifications.map(f=>f.confidence).filter(f=>f!==void 0);p.length>0&&(a.confidence=XOe(Math.min(a.confidence,...p)))}i.sort(GLt);let o=this.now(),s={schemaVersion:NOe,reportId:MF(this.idFactory("report"),"reportId"),runId:e.runId,pack:structuredClone(e.pack),target:structuredClone(e.target),startedAt:t,completedAt:o,reviewers:n.map(a=>({agentId:a.reviewerAgentId,dimension:a.dimension,findingCount:a.findings.length})),findings:i,summary:WOe(i)};return FOe(s),s}}});import{existsSync as WF,mkdirSync as b2t,readFileSync as v2t,readdirSync as I2t,writeFileSync as k2t}from"node:fs";import{basename as E2t,dirname as S2t,join as ZI,parse as C2t,resolve as x2t}from"node:path";import{homedir as ADe,platform as $2t,release as B2t}from"node:os";import{resolve as mDe}from"node:path";import{createHash as K2t}from"node:crypto";function R2t(e){let t=T2t(e);return{frontmatter:t.frontmatter,content:t.content.trim()}}function T2t(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return{frontmatter:{},content:e};let n=t.search(/\r?\n/);if(n<0||t.slice(0,n).trim()!=="---")return{frontmatter:{},content:e};let r=t.slice(n+(t[n]==="\r"?2:1)),i=r.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!i||i.index===void 0)throw new Error("YAML frontmatter is not closed.");let o=r.slice(0,i.index),s=i[0],a=i.index+s.length;return{frontmatter:hDe(o),content:r.slice(a)}}function hDe(e){let t={},n=e.split(/\r?\n/);for(let r=0;r<n.length;r+=1){let i=n[r];if(!i.trim()||i.trimStart().startsWith("#"))continue;if(/^\s/.test(i))throw new Error(`Unexpected indentation at line ${r+1}.`);let o=_2t(i,r+1);if(o.key==="<<")throw new Error("YAML merge keys are not supported.");if(o.value!==""){t[o.key]=gDe(o.value,r+1);continue}let s=P2t(n,r+1);t[o.key]=s.value,r=s.nextIndex-1}return t}function P2t(e,t){let n=[],r=t;for(;r<e.length;r+=1){let o=e[r];if(!o.trim()){n.push(o);continue}if(!/^\s/.test(o))break;n.push(o.replace(/^ {2}/,""))}let i=n.filter(o=>o.trim()&&!o.trimStart().startsWith("#"));return i.length===0?{value:{},nextIndex:r}:i.every(o=>o.trimStart().startsWith("- "))?{value:i.map((o,s)=>gDe(o.trimStart().slice(2),t+s+1)),nextIndex:r}:{value:hDe(n.join(`
|
|
2952
2952
|
`)),nextIndex:r}}function _2t(e,t){let n=e.indexOf(":");if(n<=0)throw new Error(`Invalid YAML line ${t}.`);let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!r)throw new Error(`Invalid YAML key at line ${t}.`);return{key:r,value:i}}function gDe(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 fDe(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 fDe(e,t);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${t}.`);return e}function fDe(e,t){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${t}.`)}}function M2t(){let e=process.env.XENO_AGENT_HOME?.trim();return e?mDe(e):mDe(ADe(),".xeno-agent")}function O2t(){return M2t()}function Hee(e=O2t()){return ZI(e,"agents")}function wDe(e){return x2t(e)}function D2t(e){let t=S2t(e);return t===e?e:t}function yDe(e=process.cwd()){let t=wDe(e),n=[],r=t;for(;;){let o=ZI(r,".claude","agents"),s=ZI(r,".xeno","agents");n.push({...WF(o)?{claude:o}:{},...WF(s)?{xeno:s}:{}});let a=D2t(r);if(a===r)break;r=a}n.reverse();let i=[];for(let o of n)o.claude&&i.push(o.claude),o.xeno&&i.push(o.xeno);return i}function bDe(e=process.cwd()){return ZI(wDe(e),".xeno","agents")}function L2t(e){return WF(e)?I2t(e,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.toLowerCase().endsWith(".md")).map(t=>ZI(e,t.name)).sort((t,n)=>t.localeCompare(n)):[]}function YI(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function KI(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean):typeof e=="string"?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Q2t(e){if(typeof e=="boolean")return e;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(["1","true","yes","on"].includes(t))return!0;if(["0","false","no","off"].includes(t))return!1}function F2t(e){return C2t(E2t(e)).name.toLowerCase()}function Wee(e){return N2t.test(e)}function U2t(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function q2t(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="inherit")return"inherit";if(t==="none"||t==="off"||t==="disabled")return"none";if(t==="read"||t==="readonly"||t==="read-only")return"readOnly";if(t==="default"||t==="standard")return"default";if(t==="full"||t==="fullaccess"||t==="full-access")return"fullAccess"}function j2t(e){if(e===void 0)return;if(typeof e=="string"||Array.isArray(e)){let o=KI(e);return o.length>0?{allow:o}:void 0}if(!U2t(e))return;let t=KI(e.allow),n=KI(e.deny),r=q2t(e.mode),i={};return r&&(i.mode=r),t.length>0&&(i.allow=t),n.length>0&&(i.deny=n),Object.keys(i).length>0?i:void 0}function V2t(e){let t=Q2t(e.worktree??e.defaultWorktreeIsolation);if(t===!0)return"worktree";if(t===!1)return"none";let n=YI(e.isolation)?.toLowerCase();if(n==="worktree")return"worktree";if(n==="none"||n==="off"||n==="disabled")return"none"}function vDe(e){let t=[];return Wee(e.name)||t.push(`Invalid agent name "${e.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`),e.prompt.trim().length===0&&t.push("Agent definition body is empty."),t}function H2t(e,t,n){let r=v2t(e,"utf8"),i=R2t(r),o=i.frontmatter,s=F2t(e),a=YI(o.name)?.toLowerCase()??s,c=i.content.trim(),l=vDe({name:a,prompt:c});if(l.length>0)throw new Error(l.join(" "));let u=YI(o.description),d=YI(o.model),p=YI(o.color),f=YI(o.memory??o.memoryScope),m=V2t(o),h=j2t(o.tools);return{name:a,scope:t,path:e,...u?{description:u}:{},...d?{model:d}:{},...p?{color:p}:{},...f?{memory:f}:{},...m?{isolation:m}:{},tags:KI(o.tags),skills:KI(o.skills),hooks:KI(o.hooks),prompt:c,active:!0,priority:n,...h?{toolPolicy:h}:{}}}function qF(e,t,n,r,i){for(let o of L2t(e))try{r.push(H2t(o,t,n))}catch(s){i.push({path:o,scope:t,message:s instanceof Error?s.message:String(s)})}}function W2t(e){let t=new Map;for(let n of e){let r=t.get(n.name);(!r||n.priority>r.priority)&&t.set(n.name,n)}return t}function G2t(e,t){let n=t.get(e.name),r=n?.path===e.path;return{name:e.name,scope:e.scope,path:e.path,...e.description?{description:e.description}:{},...e.model?{model:e.model}:{},...e.color?{color:e.color}:{},...e.memory?{memory:e.memory}:{},...e.isolation?{isolation:e.isolation}:{},tags:e.tags,skills:e.skills,hooks:e.hooks,prompt:e.prompt,active:r,...e.toolPolicy?{toolPolicy:e.toolPolicy}:{},...!r&&n?{shadowedBy:{name:n.name,scope:n.scope,path:n.path}}:{}}}function hd(e=process.cwd(),t={}){let n=t.cwd??e,r=t.userDir??Hee(t.agentHome),i=t.projectDirs??yDe(n),o=t.pluginDirs??[],s=t.builtInDirs??[],a=[],c=[];t.includeUser!==!1&&qF(r,"user",0,a,c),t.includeProject!==!1&&i.forEach((d,p)=>qF(d,"project",100+p,a,c)),t.includePlugins&&o.forEach((d,p)=>qF(d,"plugin",1e3+p,a,c)),t.includeBuiltIns&&s.forEach((d,p)=>qF(d,"built-in",2e3+p,a,c));let l=W2t(a),u=a.map(d=>G2t(d,l));return u.sort((d,p)=>{if(d.active!==p.active)return d.active?-1:1;let f=d.name.localeCompare(p.name);return f!==0?f:d.path.localeCompare(p.path)}),{definitions:u,issues:c,searchPaths:{...t.includeUser!==!1?{user:r}:{},project:t.includeProject===!1?[]:i,plugin:t.includePlugins?o:[],builtIn:t.includeBuiltIns?s:[]}}}function ek(e,t=process.cwd(),n={}){let r=e.trim().toLowerCase(),i=hd(t,n);return{definition:i.definitions.find(o=>o.active&&o.name===r)??null,scan:i}}function jF(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(n=>n.trim()).filter(Boolean)));return t.length>0?t:void 0}function X2t(e,t){if(!e&&!t)return;if(!e)return jF(t);if(!t)return jF(e);let n=new Set(t);return jF(e.filter(r=>n.has(r)))}function z2t(e,t){let n={none:0,readOnly:1,default:2,fullAccess:3,inherit:4},r=t??"inherit",i=e??"inherit";return n[r]<=n[i]?r:i}function jee(e,t={}){let n=e.toolPolicy??{},r={mode:z2t(n.mode,t.mode)},i=X2t(t.allow,n.allow),o=jF([...t.deny??[],...n.deny??[]]);return i&&(r.allow=i),o&&(r.deny=o),r}function Y2t(e){return{name:`custom-agent:${e.name}`,order:20,provide(){let t=["","","# Custom Agent",`Active agent: ${e.name}`,`Definition scope: ${e.scope}`,`Definition path: ${e.path}`];return e.description&&t.push(`Description: ${e.description}`),t.push("",e.prompt),t.join(`
|
|
@@ -4194,7 +4194,7 @@ ${r}`}}import{execFileSync as rQe}from"node:child_process";function Gqt(){let e=
|
|
|
4194
4194
|
`),i.model||i.baseURL||i.apiKey||i.maxTokens||i.permissionMode||i.plugins&&i.plugins.length>0||i.mcpServers&&i.mcpServers.length>0||n.onOutput(` (no settings configured)
|
|
4195
4195
|
`),n.onOutput(`
|
|
4196
4196
|
`),{handled:!0}}function Th(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/1e3),r=Math.floor(n/3600),i=Math.floor(n%3600/60),o=n%60;return r>0?`${r}h ${i}m ${o}s`:i>0?`${i}m ${o}s`:`${o}s`}function mQe(e){let t=["Last Session Summary",`- model: ${e.model}`,`- mode: ${e.mode??"unknown"}`,`- status: ${e.status??"unknown"}`,`- started: ${e.startedAt}`,`- ended: ${e.endedAt}`,`- duration: ${Th(e.durationMs)}`,`- tokens: ${e.tokenUsage.input.toLocaleString()} in / ${e.tokenUsage.output.toLocaleString()} out / ${e.tokenUsage.total.toLocaleString()} total`,`- estimated cost: ${nw(e.estimatedCostUsd)}`];return e.sessionId&&t.splice(1,0,`- session: ${e.sessionId}`),e.role&&t.splice(e.sessionId?2:1,0,`- role: ${e.role}`),e.messageCount!==void 0&&t.push(`- messages: ${e.messageCount}`),t.join(`
|
|
4197
|
-
`)}function Ejt(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function jU(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${Ejt(e.targetPrompt)}"`,n=await e.checkpointManager.create({trigger:"manual",messages:e.messages,description:t});if(e.sessionManager){let r=[n.id,...e.sessionManager.meta.checkpoints.filter(i=>i!==n.id)];await e.sessionManager.updateMeta({checkpoints:r}),await e.sessionManager.transcript.append({type:"checkpoint",data:{id:n.id,action:"create",name:t,trigger:"manual",messageCount:e.messages.length}})}return n.id}Mr();gi();var Sjt={"0.5.51":["Picks up SDK 0.9.34, which fixes provider error classification: a bad API key returning HTTP 400 was reported as a missing model capability rather than an authentication failure.","That told you your model lacked a feature when your key was simply wrong. Found by a live provider canary - offline tests prove what we send, never how we read what comes back."],"0.5.50":["Picks up SDK 0.9.33, which fixes a permission-rule wildcard that could span a carriage return: Bash(command:git*) matched 'git status\\rrm -rf /', so a prefix rule an operator wrote as a constraint could authorize a composed command.","On a terminal a carriage return returns the cursor to column zero, so an approval preview could display one command while the shell received a second one. A single * now stops at every line terminator and ** remains strictly broader."],"0.5.49":["Picks up SDK 0.9.32, which fixes a single-writer violation: a live session owner whose heartbeat stalled could be treated as stale and have its lock taken by a second writer.","A long tool call, a paused debugger or a saturated event loop no longer risks losing session ownership; a genuinely dead owner is still reclaimed immediately."],"0.5.48":["xeno handoff status gains --since-revision and --wait-ms: a caller passes the revision it already saw and the command returns when the session actually moves, instead of re-reading the whole session in a loop.","A wait that reaches its deadline exits 2 rather than 1, so an unchanged session reads as a retryable observation rather than a failure."],"0.5.47":["xeno sessions show gains --history and --cursor: recent transcript activity is read in a bounded window with a continuation cursor, instead of loading an entire transcript to display the last few entries.","New xeno agents wait <run-ids...> waits for the first of several background runs to reach a terminal state, or every run with --all. A deadline exits 2 rather than 1, so a caller can tell a timeout from a failure.","New xeno mcp resource-templates lists parameterized resources a connected MCP server offers; servers without template support are unaffected.","AskUser questions can now be cancelled, so an unanswered question no longer holds a turn open indefinitely (via SDK 0.9.31)."],"0.5.46":["Sessions can be branched: xeno sessions fork <id> creates a new session from an existing one without changing the original, carrying its transcript history and linking back to its parent, so both lines of work stay resumable.","Sessions can be titled, pinned and archived: xeno sessions title, pin and archive. Pinned sessions lead every listing regardless of activity, and archiving retains the transcript rather than deleting it.","xeno sessions list gains --archived, and shows titles and pin state inline."],"0.5.45":["The top-level xeno ctx-viz command now exposes the same bounded live tool inventory as the interactive TUI, with cursor paging and permission-safe metadata.","Inventory output clearly separates registered tools from request-loaded schemas and never grants execution authority."],"0.5.44":["File tools now complete reliably in standalone and packaged CLI processes, including guarded Edit and Write results after permission approval.","Durable interrupted-session recovery now preserves receipt-before-status crash ordering and requires explicit respawn for fresh input.","Worker stop, lease revocation, permission approval, workflow recovery, and goal-budget controls are qualified through the unsigned Windows candidate package.","Synced Agent SDK 0.9.28 with the awaited tool-operation liveness repair and recovery contracts."],"0.5.43":["Provider-native Codex and Claude continuations can be attached from the XENO provider cockpit without replacing the XENO TUI; exact provider session identity, workspace, and ownership survive detach, reattach, and Interface handoff.","The native terminal path mirrors user messages into the owning graphical conversation and keeps XENO application system instructions out of provider-visible chat text.","Synced XENO ACP 0.2.13 and Agent Interface 0.1.23 after the earlier immutable candidates were published without moving their npm latest tags."],"0.5.42":["Durable Web Context operations now render the canonical typed evidence progress stream in human and NDJSON modes without inventing counters.","SIGINT and external abort request exactly one service-side cancellation and report whether the durable job reached a confirmed terminal state.","Synced Web Context 0.1.1, Agent SDK 0.9.25, and Agent Interface 0.1.22 for the negotiated ACP v2 evidence contract."],"0.5.41":["Durable compaction now flushes the recoverable session snapshot before mutating resident history, so repeated long-context cycles and crash recovery retain completed turns.","Chat and non-interactive run paths bind the real host parent-session identity before delegating, keeping nested work and results attached to the correct resumable conversation.","Execution handoff preserves writer fencing and live ownership across A-to-B-to-C resume while Loop continuation remains unbounded by default.","Synced the public Agent SDK 0.9.24 and Agent Interface 0.1.21 registry packages for the qualified Goal / Loop / Handoff contract."],"0.5.40":["Added durable Goal records with explicit criteria, milestones, delegated tasks, progress, steering, and evidence-gated completion.","Added distinct scheduled, development, and goal-continuation loops that are unbounded by default, persist every iteration, survive restart, and remain recoverable after an iteration failure.","Added live, heartbeat-backed execution handoff across resumed terminals with atomic A-to-B-to-C transfer and immediate source fencing; one-shot commands cannot impersonate a live owner.","Handoff now flushes and relinquishes the source session-writer lock before printing the resume command, so the target can resume the same transcript without either terminal deleting or rewriting the other's lock state.","Synced Agent SDK 0.9.23 and Agent Interface 0.1.20 for the shared Goal / Loop / Handoff runtime contract."],"0.5.39":["Added XENO Web Context search, fetch, render, map, crawl, extract, job wait/cancel/resume, and Browser handoff commands with canonical evidence metadata.","Preserved Chat and Agent session mode/workspace identity across CLI and Interface resume paths.","Synced Agent SDK 0.9.22 and Agent Interface 0.1.19 for the typed Web Context runtime event contract."],"0.5.38":["Corrective Agent Interface handoff: explicit Chat, Agent, and resume launch intent now wins over restored persisted desktop tabs after session hydration.","`xeno agent --interface` preserves the exact granted workspace even when the desktop has existing Chat history, while `xeno chat --interface` remains Chat-only with no project grant.","Synced the Agent Interface client and contract packages to the installable 0.1.18 release."],"0.5.37":["`xeno chat --interface` opens the canonical desktop surface as XENO Chat with Chat-only authority and no project grant.","`xeno agent --interface` opens the same surface as XENO Agent and grants the exact current local workspace.","Synced the Agent Interface client and contract packages to 0.1.16."],"0.5.36":["`xeno chat` and `xeno agent` now launch the same canonical XENO terminal interface while preserving their invoked identity: Chat is branded XENO CHAT and Agent is branded XENO AGENT.","Chat mode owns a private managed workspace and cannot be promoted to Agent authority by saved settings or `--mode`; Agent mode keeps the explicit local-workspace and full-capability contract.","Windows Terminal multiline paste remains one editable composer item and submits as one persisted user message, including fragmented bracketed-paste frames.","Synced the Agent Interface client and contract packages to 0.1.15 and the Agent SDK to 0.9.21."],"0.5.35":["The provider cockpit now exposes durable provider lanes, exact native attach and detach, explicit stop and reconcile controls, and persists whether each Agent session is Chat mode or Agent mode.","The status bar shows the active provider lane, and non-interactive provider, lane, attach, and reconcile commands expose the same control plane to scripts.","The local release gate now builds the native Windows XENO PTY before integration tests and typechecks the complete test surface from a clean checkout.","Synced the Agent Interface client and contract packages to 0.1.12 and the Agent SDK to 0.9.18."],"0.5.34":["Windows multiline-paste recovery now keys off the actual win32 runtime even when terminal TTY capability probing reports an inconclusive profile.","Input diagnostics now record the runtime platform, terminal profile, and stdin/stdout TTY state so real-terminal evidence explains which paste path ran."],"0.5.33":["Windows Terminal multiline paste now remains one editable composer message even when Windows omits bracketed-paste markers because virtual-terminal input is unavailable.","Real bracketed-paste frames still retain stateful fragmented-stream handling, and an ordinary Enter remains a submit after the short paste-boundary grace period.","Synced the Agent Interface client and contract packages to 0.1.11 and the Agent SDK to 0.9.17."],"0.5.32":["Recent-session state now stays inside XENO_AGENT_HOME and uses durable per-workspace updates, preventing Windows EPERM contention and lost concurrent session entries.","PowerShell command completion now drains the final stdout pipe data before settling, so successful commands cannot intermittently return empty output."],"0.5.31":["Windows Terminal bracketed-paste mode is now explicitly negotiated for the full composer lifetime, correcting 0.5.30's incomplete decoder-only repair.","Native TUI and external-editor handoffs release terminal paste mode before transfer and restore it only after XENO regains terminal ownership.","`--interface` now waits for an exact nonce-bound acknowledgement from the desktop renderer instead of reporting success when an older app merely spawned and ignored the resume request.","Managed finite operations can continue beyond the generic three-turn safety cap, recent-session writes are serialized across processes, and background commands receive privacy-safe semantic fallback labels."],"0.5.30":["Multiline terminal pastes now remain one editable composer message even when Windows Terminal fragments the bracketed-paste frame across multiple input chunks.","Complete bracketed-paste frames are handled before generic Escape sequences, and their terminal markers never leak into the submitted prompt."],"0.5.29":["ACP provider cockpit: resume durable Codex, Claude, and compatible provider lanes without replaying the XENO transcript into a new native session.","Attach, detach, reattach, stop, and reconcile native provider TUIs with one-writer ownership between the XENO TUI, Agent Interface, and provider terminal.","`--interface` handoff now preserves the selected conversation host binding and exact provider continuation identity.","Background work uses semantic task names, and continuation checkpoints retain the original objective instead of ending a live operation at an arbitrary automatic-turn boundary.","Synced Agent Interface client/contract to 0.1.8 and @xenosystem/agent-sdk to 0.9.14."],"0.5.28":["The root `xeno --help` output now exposes `--interface` and `--resume [id]`, so terminal-to-desktop session handoff is discoverable at the exact command surface where it is used."],"0.5.27":["Open the XENO Agent Interface from the terminal with `xeno --interface`, resuming an exact session ID or the latest session in the current workspace.","Long-running background commands now stay alive while active, preserve native PowerShell syntax, and display meaningful task names.","Short follow-through messages such as do it and proceed now retain implementation authority, while nested continuations preserve the original objective.","Synced @xenosystem/agent-sdk to 0.9.13."],"0.5.26":["Terminal bracketed paste & multi-line input: bracketed paste frames are cleanly decoded, collapsed into `[Pasted text #N +N lines]` tokens for large blocks, and submitted with full uncorrupted text without escape code dropouts.","Dynamic terminal reflow: turn receipts, turn dividers, and prompt bubbles adapt smoothly to window resize events without clipping."],"0.5.25":["Interactive `/status`, `/config`, `/usage`, `/stats`, `/settings` multi-tab modal with live search, keyboard cycling, and instant ~/.xeno/config.json persistence.","Live 52-week session activity heatmap, longest/current streak metrics, active days summary, lifetime token metrics, and favorite model analytics.","Real-time git workspace analytics including active branch, ahead/behind counts, working tree diff additions/deletions, and live turn API elapsed times.","Turn receipt visual polish with right-margin padding and formatted recap indentation.","Interactive `/handoff` command: switch seamlessly between specialist agents with prompt context and intent transfer.","Zero-config `.claude/agents/*.md` & `.xeno/agents/*.md` discovery with level-ordered priority shadowing.","Host mid-turn steering (`turn.steer`) and subagent wire payload artifacts integration.","Synced @xenosystem/agent-sdk to 0.9.12 with enhanced offline grace monetization validation.","xeno-rt: resolved Qwen 3.8 / 3.5 MTP NextN architecture prefixes and prevented layer 32 recurrent tensor probe failure."],"0.5.24":["Published with exact matching CLI_VERSION literal, guarded by verify:version in CI.","Synced @xenosystem/agent-sdk to 0.9.11, pulling model-aware context budgets from live gateway `/v1/models` catalog.","`/import` now immediately triggers context reconstruction turns rather than pausing at the input prompt."],"0.5.23":["Model-aware context budget: queries gateway `/v1/models` catalog for authoritative `context_window` limits.","Context compaction request byte budget scaled to prevent false refusals on large toolsets."],"0.5.22":["`/context` divided by a hardcoded 200,000 regardless of which model you are on. That figure is XENO's window and nobody else's: on a 128,000-token OpenAI model the gauge read about 12% where the truth was 19%, and near the limit it said \"Context is healthy\" with compaction imminent; on Google's 1,000,000-token window it pegged at 100% from a fifth of the way in and warned permanently. It now divides by the budget the SDK actually resolved for the run.","The gauge also says how well it knows that number. A configured budget is exact and prints a plain percentage; a provider profile is one window for every model that provider serves, so it prints `~62%` and labels itself approximate. Before any turn has reported, it says the 200,000 is an assumption rather than presenting it as fact.","The numerator was always right and is unchanged: it sums the messages currently in context, so it falls when a compaction drops them. Only the denominator was asserted rather than resolved."],"0.5.21":["Security: undici 6.27.0 -> 6.28.0, closing a cookie-injection advisory. This repo had 12 open alerts and this was the ONLY one that reaches shipped code \u2014 the five rated HIGH are all build and test tooling. Fixing by severity rank would have addressed the wrong thing first.","Worktree cleanup could delete THROUGH a junction. That is the failure that destroyed two repositories on 2026-08-03: on Windows a recursive delete follows a junction and removes the target, and npm creates one for every file: dependency. Cleanup now clears the reparse point itself and never the thing it points at.","Worktree cleanup had also decayed into a no-op \u2014 its filter excluded every orphan it existed to remove, so it ran, reported success, and cleaned nothing. And a reparse-point scan that hits its cap now REFUSES rather than returning a short list, because a truncated scan that looks complete is how the delete above becomes safe-looking.","The control-plane `list()` was not a read: it wrote once per stale record, every time anything listed runs. Listing is now free of side effects.","`/import` brings a session from another agent CLI into XENO and continues it \u2014 including agy stores, where the obvious store turned out not to be the best source. `--imported` shows what is on disk and says plainly that it persists. The source transcript is never touched, and that is enforced rather than intended.","Delegated branches now run on the Agent host under XENO_AGENT_ATTACH, report tool progress while they work, and the CLI reads the HOST's audit rather than only its own. Previously a host-routed branch was silent until it finished, and a refusal blamed a missing stream that in fact existed.","`xeno host status` now reports WHICH lanes the host offers and why a blocked one is blocked \u2014 including whose environment the blockage is about, which was the part that made the old message useless.","Pinned to @xenosystem/agent-sdk 0.9.10. The pin had been two releases stale, so work that shipped in 0.9.9 reached nobody. 0.9.10 also reports how full an agent's context is: turn.completed carries the RESIDENT token count, not the cumulative billing counter, and context.pressure arrives after every model response. The obvious field re-adds the whole prompt each turn \u2014 measured live, three one-word turns reported 3049, 6106 then 9171 tokens while the context grew by about eight.","Budget accounting no longer reads the entire run store when no budget cap is configured."],"0.5.20":["Pinned to @xenosystem/agent-sdk 0.9.8. The SDK's ownership policy still labelled this CLI by a scope retired in 8363d30c, which had failed the release smoke on every run since 2026-08-13 \u2014 the mismatch was never in this repo, so the fix was a repin rather than a workaround.","The release smoke now derives how strict it should be from the release trust policy: while no signing identity is approved it holds the engineering bar, and it tightens by itself the moment one lands. It previously demanded a signature no ordinary CI run could produce, and had failed for long enough to read as background noise.","First test coverage of the native manifest signing path, which had never executed once. Signer and verifier each carry their own copy of the canonical-JSON serializer and cannot import each other, so a drift as small as key ordering would have invalidated every release signature \u2014 and would have surfaced on release day, looking like a key problem.","Windows: temporary-directory cleanup no longer loses a race with exiting child processes, and the certification matrix checks out correctly on Windows ARM. `force: true` suppresses ENOENT, not EPERM, so the previous cleanup looked defensive and was not.","Groundwork for interactive Ctrl+C on Windows: the native addon can now raise a real console interrupt. Writing 0x03 into a ConPTY does not raise a signal, which is why Ctrl+C has never worked there. NOT yet wired \u2014 the console attach succeeds and the event is raised, and a ConPTY client still does not observe it."],"0.5.19":["The CLI did nothing at all on Linux and macOS. Its entry point did not resolve symlinks, so every npx and global install ran the wrong path and exited silently \u2014 the install looked successful and the binary did nothing. Fixed.","Agent permission decisions now reach an actual human on both rails, rather than being resolved without one.","A remote run that is read-only now says so, instead of failing silently and leaving you to work out why nothing changed.","The version the binary REPORTS is now bound to the version npm publishes, and a test enforces it. They had drifted: 0.5.18 was published as a package whose `--version` said 0.5.17.","\u26A0\uFE0F 0.5.18 exists on npm and was published from a branch that was never merged. It is superseded by this release, which is cut from `main`. If you installed 0.5.18, upgrade."],"0.5.17":["The CLI now ships as @xenosystem/agent-cli. The former name @xeno-corporation/xeno-agent-cli is deprecated on npm and receives no further releases; the `xeno`, `xeno-agent` and `xeno-code` binaries are unchanged, so nothing in your shell or scripts has to change.","The exact SDK pin moves with it: the CLI is bound to @xenosystem/agent-sdk 0.8.12. 0.8.11 was never published under either name and cannot be \u2014 GitLab evaluates .gitlab-ci.yml as it exists at the tag, and tag sdk-v0.8.11 predates that pipeline.","This release cannot be installed until @xenosystem/agent-sdk 0.8.12 is live on the registry; the release pipeline fails closed on --require-dependencies-published until it is."],"0.5.16":["Windows 11 ARM64 containment certification now performs architecture-neutral MXC host preparation with the reviewed x64 helper through operating-system emulation while keeping the contained runtime native ARM64.","The CLI is bound exactly to SDK 0.8.11, whose host-preparation reports distinguish the host architecture from the reviewed setup-helper architecture and retain timeout diagnostics."],"0.5.15":["macOS and Linux standalone diagnostics now report their verified POSIX process-group lifecycle independently from the stronger process-hardened sandbox level, preserving truthful security status while certifying full-tree cancellation, timeout, and shutdown behavior.","Generated Harbor benchmark and audit workspaces are excluded from source control, keeping Windows ARM64 checkouts below platform path limits and removing 9,938 generated artifacts from release candidates."],"0.5.14":["Windows 11 24H2 containment admission now uses the authoritative non-server NT client build floor instead of rejecting current Azure and GitHub Windows 11 images whose legacy registry ProductName still says Windows 10.","Windows Server remains fail-closed, pre-26100 clients remain ineligible, and both x64 and ARM64 host identities have regression coverage."],"0.5.13":["Hosted Windows x64 containment certification now fails closed unless the runner is Windows 11 24H2 or newer, the platform supported by Microsoft MXC, instead of treating Windows Server runner failures as product failures.","The certification matrix accepts a protected XENO_WINDOWS_X64_RUNNER label for an ephemeral Windows 11 x64 runner while keeping all other hosted platform rows unchanged.","Containment failure reports preserve bounded head-and-tail diagnostics through SDK 0.8.10 so the actionable trailing Win32 or MXC error is retained."],"0.5.12":["Windows MXC containment now launches its unrestricted host from the prepared system-drive temporary directory, outside directories whose DACLs are mutated by the contained policy, and certification captures official redacted MXC diagnostics.","Internal background session workers no longer start a competing global reconciler, preventing slower macOS hosts from quarantining a healthy turn between transcript append and checkpoint commit.","The interactive attach/input/stop smoke now follows the actual persisted inbox sequence and records worker logs on failure; the CLI is bound exactly to SDK 0.8.9."],"0.5.11":["Windows x64 containment certification now launches the MXC host and contained runtime with working-directory and temporary paths on the prepared system drive, matching split-drive GitHub runners.","The CLI is bound exactly to SDK 0.8.8, preserving the passing Linux, macOS, and Windows ARM64 conformance behavior while repairing Windows x64 ProcessContainer startup."],"0.5.10":["Linux containment certification now keeps disposable fixtures under the OS-private temporary mount instead of GitHub's workspace-projected runner directory, preserving the unlisted-filesystem boundary probe.","Windows certification retains the MXC-prepared system-drive fixture root required by hosted runners whose workspace and default temp directory use another volume."],"0.5.9":["Windows containment certification now creates its disposable fixtures on the MXC-prepared system drive, including hosted runners whose workspace and default temp directory live on another volume.","Standalone Windows certification now performs the same explicit host preparation and temporary-root binding as the native package matrix."],"0.5.8":["Native containment certification now compiles its macOS UI-policy probe against the stable libsystem_sandbox ABI without depending on private SDK headers.","Windows certification now distinguishes MXC's persistent per-policy DACL requirement from its explicit one-time host-preparation warnings."],"0.5.7":["The immutable CLI candidate now binds SDK 0.8.5 to the exact canonical Linux npm tarball bytes used by certification."],"0.5.6":["Windows containment certification now performs Microsoft MXC's explicit idempotent host preparation before AppContainer+DACL conformance.","macOS ARM64 certification now records behavioral Seatbelt evidence for pasteboard, WindowServer, LaunchServices, and HID isolation."],"0.5.5":["Native certification now resolves the SDK candidate artifact from the same workspace path on Bash and PowerShell runners.","SDK containment assets retain executable package modes on Linux and macOS, with a source regression check for every reviewed Unix binary."],"0.5.4":["Native engineering certification jobs now download the exact SDK tarball produced by the successful parent gate before installing dependencies.","The six-platform matrix remains source-bound to one immutable CLI tag and one immutable SDK candidate artifact."],"0.5.3":["Candidate packaging accepts both npm 11 array-form and npm 12 package-keyed JSON, with explicit diagnostics for malformed output.","Hosted SDK packaging now parses a bounded JSON file instead of relying on a large shell variable or an obsolete npm output shape."],"0.5.2":["Hosted certification now caps SDK declaration generation at two concurrent entry points and cleans declaration output in isolated bounded-memory workers.","SDK build subprocess failures now report their terminating signal or exit status instead of producing a silent hosted-run failure."],"0.5.1":["Hosted certification now builds the exact SDK candidate in bounded declaration groups, preventing parallel TypeScript declaration generation from exhausting GitHub-hosted runner resources.","Post-freeze readiness now distinguishes exact candidate tags verified at the candidate commit from collisions in release, registry, feed, and service namespaces."],"0.5.0":["Agent Profiles now provide enforceable Assistant, SWE, Reviewer, Writer, Research, Product, CI, DevOps, and Legal Research identities with bounded tools, permissions, skills, hooks, memory, isolation, and external-action authority.","The XENO Artifact Protocol adds durable plans, patches, diffs, reviews, screenshots, recordings, reports, provenance, approvals, and evidence relationships shared across local, hosted, and Hub workflows.","Secure Execution Contracts and capability leases now make filesystem, network, secret, process, device, browser, and external-action authority explicit and auditable.","Skills v2 adds standards-compatible SKILL.md discovery, progressive loading, bundled resources, invocation policy, version identity, and compatibility with XENO, .agents, and Claude skill locations.","MCP now supports current Streamable HTTP sessions and OAuth discovery while retaining compatible stdio and legacy SSE connections.","Browser, computer-use, hosted-agent, semantic-index, production-review, spec-planning, secure-sharing, and provider-onboarding surfaces are integrated through the shared platform contracts.","The retained TUI now presents stable grouped tool activity, live task and subagent status, candidate-bound edit previews, context-pressure and compaction state, and clearer turn completion receipts.","Six-product candidate certification now binds the SDK, XENO Use, XENO Browser, Agents API, CLI, and Hub to exact source identities, versions, tags, evidence, and protected release gates."],"0.4.45":["This transitional release is engineering-tested but not GA-certified: native PTY artifacts are unsigned and remain disabled by default until the Azure signing identity is approved; ordinary CLI and pipe-mode commands remain available.","App Server v2 now provides durable threads and turns, typed clients, permission ownership and expiry, bounded replay and backpressure, authenticated HTTP access, and additive v1 compatibility.","The terminal renderer now uses committed retained frames, bounded coalescing, one normal write per frame, a responsive 50-agent footer, accessibility modes, and a native terminal compatibility matrix.","Release certification now fails closed on six native architectures, platform and manifest signatures, reproducible package payloads, SBOMs, provenance attestations, independent approvals, npm OIDC publication, and public clean-install verification.","Long chat prompts now soft-wrap into a growing six-row composer with Unicode-safe editing, visual Up/Down navigation, file-panel parity, and a temporary XENO_INPUT_SOFT_WRAP=0 rollback switch.","Long-running model-authored shell commands now use managed operations: Ctrl+B promotes the same process, finite background work waits without model polling, and durable continuations resume exactly once after terminal output arrives.","ReadImage now uses Xeno's dependency-free owned raster codec for bounded PNG, BMP, Netpbm, and core-SVG previews; /processes and doctor expose task control, process-tree containment, operation-schema, and codec status.","Dynamic workflows now expose first-class run limits and terminal reducer summaries in run records and inspect JSON.","Background agent sessions now deliver durable completion, failure, stop, and request-keyed needs-input notifications to interactive parent chats and bounded headless runs without clobbering prompt drafts.","Workflow orchestration includes grouped phase/child progress, parent-chat completion notifications, WorkflowWait, /workflows drill-down, watch JSONL snapshots, and ultracode workflow prompts.","Workflow starts now support plan preview and exact-definition approval memory, scheduler ticks are serialized, and workflow lifecycle metrics are available through the OTel usage export.","Tool activity now uses semantic Update and Search labels, contextual line-numbered edit previews, expandable read/search/shell output, and accurate failure rendering.","Interactive chat now blocks repeated inspections and unrequested mutations on short questions, gives explicit research a larger typo-tolerant evidence budget, and reserves a tool-free final-answer turn when work limits are reached."],"0.4.44":["Markdown source links now render as clickable terminal links in supported terminals, with visible URLs preserved when links are disabled."],"0.4.43":["New background agents now appear in the footer immediately after launch, and the footer can show up to eight agent sessions."],"0.4.42":["Background agent footer rows now fit the common three-agent fanout without hiding the first agent on compact terminals.","Completed background agent sessions now close after BackgroundAgentJoin returns their result to the main agent."],"0.4.41":["Completed background agent footer rows now keep a fixed runtime instead of continuing to count upward."],"0.4.40":["One-shot background agent sessions now mark done after returning their result, while user-follow-up sessions stay idle for continued chat."],"0.4.39":["Background agent session activity now uses concise status labels like Thinking instead of showing the full task prompt."],"0.4.38":["Opened background agent sessions now show their own session activity line while keeping main-agent tool progress isolated."],"0.4.37":["Opened background agent sessions no longer show the main agent's active tool progress line."],"0.4.36":["Opened background agent sessions now render the same main-chat transcript surface for user messages, assistant messages, tool calls, and tool results."],"0.4.35":["Background agent session chat now includes tool calls and tool results in its visible history."],"0.4.34":["Opening a footer background agent now switches the main chat surface into that agent session instead of showing a separate info panel.","Child-session input now queues messages to that agent while Esc returns to the main chat."],"0.4.33":["Background agent footer rows now repaint immediately during active turns.","Remembered background-agent approvals now apply to later background-agent launches."],"0.4.32":["Startup release-note hints now sit directly under the note text and render dimmed in the side panel."],"0.4.31":["Unread release notes now render beside the startup XENO AGENT header on wide terminals."],"0.4.30":["BackgroundAgentList now only reports current-chat footer sessions so old workspace agents do not hide missing new deployments."],"0.4.29":["Background agent footer markers now use filled and empty squares.","Opening a background agent from the footer now shows its session chat with transcript and message input."],"0.4.28":["First-run default model is now gpt-5.5 while saved user model choices are preserved.","Number keys in the model picker now type into search instead of selecting by index.","Model selections made with /model now persist as the user's saved default."],"0.4.27":["Background agent footer rows are now scoped to the current chat session."],"0.4.26":["Background agent rows now sit below the status line and inherit the live chat model."],"0.4.25":["Legacy BackgroundAgent calls now create footer-visible interactive background sessions."],"0.4.24":["Model picker support now has a `xeno models --json` command, share export proof, and GitHub review artifact contracts."],"0.4.23":["Model picker and /model listings now refresh Xeno API model availability before switching."],"0.4.22":["Hook review now shows command-hook hashes and supports trust, disable, and explain commands.","Expanded lifecycle hooks now cover permission decisions, stop failures, and delegated subagent start/stop events.","Set XENO_STATUS_LINE_COMMAND to replace the TUI status line with a cached command output.","Rewind now saves the abandoned conversation branch as a manual checkpoint before restoring.","Interactive chat now supports Ctrl+R history search, Ctrl+G prompt editing, /vim input mode, and /copy answer/block/diff clipboard copy.","/theme is now a discoverable alias for /color with user/project custom theme files, and /processes stop-all stops running background tasks."],"0.4.20":["Shell completions now include the current control-plane commands, flags, statuses, scopes, and usage groups.","The local app-server browser page now includes prompt and process controls on top of advanced JSON-RPC.","Published CLI and SDK packages now include GitHub repository metadata.","Docs now call out the temporary GitHub Actions startup_failure blocker while local gates remain authoritative."],"0.1.0":["Persistent shell sessions now preserve cwd and shell state across Bash calls.","Delegated planner, explorer, executor, and reviewer branches now support staged and parallel policies.","MCP now supports stdio and SSE transports, prompt discovery, resource reads, and live tool sync.","Notebook, ask-user, and memory tools are available in the shared agent runtime.","CLI operator workflows now include doctor, bug-report, config editing, cost summaries, and runtime inspection."]};function ene(e=he){return Sjt[e]??[]}function Cjt(e=he){let t=ht().lastReleaseNotesSeen;return ene(e).length>0&&t!==e}function yk(e=he){hi({lastReleaseNotesSeen:e})}function VU(e){let t=e??he,n=ene(t);return n.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...n.map(r=>`- ${r}`)].join(`
|
|
4197
|
+
`)}function Ejt(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function jU(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${Ejt(e.targetPrompt)}"`,n=await e.checkpointManager.create({trigger:"manual",messages:e.messages,description:t});if(e.sessionManager){let r=[n.id,...e.sessionManager.meta.checkpoints.filter(i=>i!==n.id)];await e.sessionManager.updateMeta({checkpoints:r}),await e.sessionManager.transcript.append({type:"checkpoint",data:{id:n.id,action:"create",name:t,trigger:"manual",messageCount:e.messages.length}})}return n.id}Mr();gi();var Sjt={"0.5.52":["Picks up SDK 0.9.35: a model the gateway cannot route was classified as a retryable server error, so a permanently wrong model id would be retried on a backoff loop forever.","A model that is temporarily unavailable stays retryable, so only the unroutable case changed. Found by a live provider conformance run against the XENO gateway."],"0.5.51":["Picks up SDK 0.9.34, which fixes provider error classification: a bad API key returning HTTP 400 was reported as a missing model capability rather than an authentication failure.","That told you your model lacked a feature when your key was simply wrong. Found by a live provider canary - offline tests prove what we send, never how we read what comes back."],"0.5.50":["Picks up SDK 0.9.33, which fixes a permission-rule wildcard that could span a carriage return: Bash(command:git*) matched 'git status\\rrm -rf /', so a prefix rule an operator wrote as a constraint could authorize a composed command.","On a terminal a carriage return returns the cursor to column zero, so an approval preview could display one command while the shell received a second one. A single * now stops at every line terminator and ** remains strictly broader."],"0.5.49":["Picks up SDK 0.9.32, which fixes a single-writer violation: a live session owner whose heartbeat stalled could be treated as stale and have its lock taken by a second writer.","A long tool call, a paused debugger or a saturated event loop no longer risks losing session ownership; a genuinely dead owner is still reclaimed immediately."],"0.5.48":["xeno handoff status gains --since-revision and --wait-ms: a caller passes the revision it already saw and the command returns when the session actually moves, instead of re-reading the whole session in a loop.","A wait that reaches its deadline exits 2 rather than 1, so an unchanged session reads as a retryable observation rather than a failure."],"0.5.47":["xeno sessions show gains --history and --cursor: recent transcript activity is read in a bounded window with a continuation cursor, instead of loading an entire transcript to display the last few entries.","New xeno agents wait <run-ids...> waits for the first of several background runs to reach a terminal state, or every run with --all. A deadline exits 2 rather than 1, so a caller can tell a timeout from a failure.","New xeno mcp resource-templates lists parameterized resources a connected MCP server offers; servers without template support are unaffected.","AskUser questions can now be cancelled, so an unanswered question no longer holds a turn open indefinitely (via SDK 0.9.31)."],"0.5.46":["Sessions can be branched: xeno sessions fork <id> creates a new session from an existing one without changing the original, carrying its transcript history and linking back to its parent, so both lines of work stay resumable.","Sessions can be titled, pinned and archived: xeno sessions title, pin and archive. Pinned sessions lead every listing regardless of activity, and archiving retains the transcript rather than deleting it.","xeno sessions list gains --archived, and shows titles and pin state inline."],"0.5.45":["The top-level xeno ctx-viz command now exposes the same bounded live tool inventory as the interactive TUI, with cursor paging and permission-safe metadata.","Inventory output clearly separates registered tools from request-loaded schemas and never grants execution authority."],"0.5.44":["File tools now complete reliably in standalone and packaged CLI processes, including guarded Edit and Write results after permission approval.","Durable interrupted-session recovery now preserves receipt-before-status crash ordering and requires explicit respawn for fresh input.","Worker stop, lease revocation, permission approval, workflow recovery, and goal-budget controls are qualified through the unsigned Windows candidate package.","Synced Agent SDK 0.9.28 with the awaited tool-operation liveness repair and recovery contracts."],"0.5.43":["Provider-native Codex and Claude continuations can be attached from the XENO provider cockpit without replacing the XENO TUI; exact provider session identity, workspace, and ownership survive detach, reattach, and Interface handoff.","The native terminal path mirrors user messages into the owning graphical conversation and keeps XENO application system instructions out of provider-visible chat text.","Synced XENO ACP 0.2.13 and Agent Interface 0.1.23 after the earlier immutable candidates were published without moving their npm latest tags."],"0.5.42":["Durable Web Context operations now render the canonical typed evidence progress stream in human and NDJSON modes without inventing counters.","SIGINT and external abort request exactly one service-side cancellation and report whether the durable job reached a confirmed terminal state.","Synced Web Context 0.1.1, Agent SDK 0.9.25, and Agent Interface 0.1.22 for the negotiated ACP v2 evidence contract."],"0.5.41":["Durable compaction now flushes the recoverable session snapshot before mutating resident history, so repeated long-context cycles and crash recovery retain completed turns.","Chat and non-interactive run paths bind the real host parent-session identity before delegating, keeping nested work and results attached to the correct resumable conversation.","Execution handoff preserves writer fencing and live ownership across A-to-B-to-C resume while Loop continuation remains unbounded by default.","Synced the public Agent SDK 0.9.24 and Agent Interface 0.1.21 registry packages for the qualified Goal / Loop / Handoff contract."],"0.5.40":["Added durable Goal records with explicit criteria, milestones, delegated tasks, progress, steering, and evidence-gated completion.","Added distinct scheduled, development, and goal-continuation loops that are unbounded by default, persist every iteration, survive restart, and remain recoverable after an iteration failure.","Added live, heartbeat-backed execution handoff across resumed terminals with atomic A-to-B-to-C transfer and immediate source fencing; one-shot commands cannot impersonate a live owner.","Handoff now flushes and relinquishes the source session-writer lock before printing the resume command, so the target can resume the same transcript without either terminal deleting or rewriting the other's lock state.","Synced Agent SDK 0.9.23 and Agent Interface 0.1.20 for the shared Goal / Loop / Handoff runtime contract."],"0.5.39":["Added XENO Web Context search, fetch, render, map, crawl, extract, job wait/cancel/resume, and Browser handoff commands with canonical evidence metadata.","Preserved Chat and Agent session mode/workspace identity across CLI and Interface resume paths.","Synced Agent SDK 0.9.22 and Agent Interface 0.1.19 for the typed Web Context runtime event contract."],"0.5.38":["Corrective Agent Interface handoff: explicit Chat, Agent, and resume launch intent now wins over restored persisted desktop tabs after session hydration.","`xeno agent --interface` preserves the exact granted workspace even when the desktop has existing Chat history, while `xeno chat --interface` remains Chat-only with no project grant.","Synced the Agent Interface client and contract packages to the installable 0.1.18 release."],"0.5.37":["`xeno chat --interface` opens the canonical desktop surface as XENO Chat with Chat-only authority and no project grant.","`xeno agent --interface` opens the same surface as XENO Agent and grants the exact current local workspace.","Synced the Agent Interface client and contract packages to 0.1.16."],"0.5.36":["`xeno chat` and `xeno agent` now launch the same canonical XENO terminal interface while preserving their invoked identity: Chat is branded XENO CHAT and Agent is branded XENO AGENT.","Chat mode owns a private managed workspace and cannot be promoted to Agent authority by saved settings or `--mode`; Agent mode keeps the explicit local-workspace and full-capability contract.","Windows Terminal multiline paste remains one editable composer item and submits as one persisted user message, including fragmented bracketed-paste frames.","Synced the Agent Interface client and contract packages to 0.1.15 and the Agent SDK to 0.9.21."],"0.5.35":["The provider cockpit now exposes durable provider lanes, exact native attach and detach, explicit stop and reconcile controls, and persists whether each Agent session is Chat mode or Agent mode.","The status bar shows the active provider lane, and non-interactive provider, lane, attach, and reconcile commands expose the same control plane to scripts.","The local release gate now builds the native Windows XENO PTY before integration tests and typechecks the complete test surface from a clean checkout.","Synced the Agent Interface client and contract packages to 0.1.12 and the Agent SDK to 0.9.18."],"0.5.34":["Windows multiline-paste recovery now keys off the actual win32 runtime even when terminal TTY capability probing reports an inconclusive profile.","Input diagnostics now record the runtime platform, terminal profile, and stdin/stdout TTY state so real-terminal evidence explains which paste path ran."],"0.5.33":["Windows Terminal multiline paste now remains one editable composer message even when Windows omits bracketed-paste markers because virtual-terminal input is unavailable.","Real bracketed-paste frames still retain stateful fragmented-stream handling, and an ordinary Enter remains a submit after the short paste-boundary grace period.","Synced the Agent Interface client and contract packages to 0.1.11 and the Agent SDK to 0.9.17."],"0.5.32":["Recent-session state now stays inside XENO_AGENT_HOME and uses durable per-workspace updates, preventing Windows EPERM contention and lost concurrent session entries.","PowerShell command completion now drains the final stdout pipe data before settling, so successful commands cannot intermittently return empty output."],"0.5.31":["Windows Terminal bracketed-paste mode is now explicitly negotiated for the full composer lifetime, correcting 0.5.30's incomplete decoder-only repair.","Native TUI and external-editor handoffs release terminal paste mode before transfer and restore it only after XENO regains terminal ownership.","`--interface` now waits for an exact nonce-bound acknowledgement from the desktop renderer instead of reporting success when an older app merely spawned and ignored the resume request.","Managed finite operations can continue beyond the generic three-turn safety cap, recent-session writes are serialized across processes, and background commands receive privacy-safe semantic fallback labels."],"0.5.30":["Multiline terminal pastes now remain one editable composer message even when Windows Terminal fragments the bracketed-paste frame across multiple input chunks.","Complete bracketed-paste frames are handled before generic Escape sequences, and their terminal markers never leak into the submitted prompt."],"0.5.29":["ACP provider cockpit: resume durable Codex, Claude, and compatible provider lanes without replaying the XENO transcript into a new native session.","Attach, detach, reattach, stop, and reconcile native provider TUIs with one-writer ownership between the XENO TUI, Agent Interface, and provider terminal.","`--interface` handoff now preserves the selected conversation host binding and exact provider continuation identity.","Background work uses semantic task names, and continuation checkpoints retain the original objective instead of ending a live operation at an arbitrary automatic-turn boundary.","Synced Agent Interface client/contract to 0.1.8 and @xenosystem/agent-sdk to 0.9.14."],"0.5.28":["The root `xeno --help` output now exposes `--interface` and `--resume [id]`, so terminal-to-desktop session handoff is discoverable at the exact command surface where it is used."],"0.5.27":["Open the XENO Agent Interface from the terminal with `xeno --interface`, resuming an exact session ID or the latest session in the current workspace.","Long-running background commands now stay alive while active, preserve native PowerShell syntax, and display meaningful task names.","Short follow-through messages such as do it and proceed now retain implementation authority, while nested continuations preserve the original objective.","Synced @xenosystem/agent-sdk to 0.9.13."],"0.5.26":["Terminal bracketed paste & multi-line input: bracketed paste frames are cleanly decoded, collapsed into `[Pasted text #N +N lines]` tokens for large blocks, and submitted with full uncorrupted text without escape code dropouts.","Dynamic terminal reflow: turn receipts, turn dividers, and prompt bubbles adapt smoothly to window resize events without clipping."],"0.5.25":["Interactive `/status`, `/config`, `/usage`, `/stats`, `/settings` multi-tab modal with live search, keyboard cycling, and instant ~/.xeno/config.json persistence.","Live 52-week session activity heatmap, longest/current streak metrics, active days summary, lifetime token metrics, and favorite model analytics.","Real-time git workspace analytics including active branch, ahead/behind counts, working tree diff additions/deletions, and live turn API elapsed times.","Turn receipt visual polish with right-margin padding and formatted recap indentation.","Interactive `/handoff` command: switch seamlessly between specialist agents with prompt context and intent transfer.","Zero-config `.claude/agents/*.md` & `.xeno/agents/*.md` discovery with level-ordered priority shadowing.","Host mid-turn steering (`turn.steer`) and subagent wire payload artifacts integration.","Synced @xenosystem/agent-sdk to 0.9.12 with enhanced offline grace monetization validation.","xeno-rt: resolved Qwen 3.8 / 3.5 MTP NextN architecture prefixes and prevented layer 32 recurrent tensor probe failure."],"0.5.24":["Published with exact matching CLI_VERSION literal, guarded by verify:version in CI.","Synced @xenosystem/agent-sdk to 0.9.11, pulling model-aware context budgets from live gateway `/v1/models` catalog.","`/import` now immediately triggers context reconstruction turns rather than pausing at the input prompt."],"0.5.23":["Model-aware context budget: queries gateway `/v1/models` catalog for authoritative `context_window` limits.","Context compaction request byte budget scaled to prevent false refusals on large toolsets."],"0.5.22":["`/context` divided by a hardcoded 200,000 regardless of which model you are on. That figure is XENO's window and nobody else's: on a 128,000-token OpenAI model the gauge read about 12% where the truth was 19%, and near the limit it said \"Context is healthy\" with compaction imminent; on Google's 1,000,000-token window it pegged at 100% from a fifth of the way in and warned permanently. It now divides by the budget the SDK actually resolved for the run.","The gauge also says how well it knows that number. A configured budget is exact and prints a plain percentage; a provider profile is one window for every model that provider serves, so it prints `~62%` and labels itself approximate. Before any turn has reported, it says the 200,000 is an assumption rather than presenting it as fact.","The numerator was always right and is unchanged: it sums the messages currently in context, so it falls when a compaction drops them. Only the denominator was asserted rather than resolved."],"0.5.21":["Security: undici 6.27.0 -> 6.28.0, closing a cookie-injection advisory. This repo had 12 open alerts and this was the ONLY one that reaches shipped code \u2014 the five rated HIGH are all build and test tooling. Fixing by severity rank would have addressed the wrong thing first.","Worktree cleanup could delete THROUGH a junction. That is the failure that destroyed two repositories on 2026-08-03: on Windows a recursive delete follows a junction and removes the target, and npm creates one for every file: dependency. Cleanup now clears the reparse point itself and never the thing it points at.","Worktree cleanup had also decayed into a no-op \u2014 its filter excluded every orphan it existed to remove, so it ran, reported success, and cleaned nothing. And a reparse-point scan that hits its cap now REFUSES rather than returning a short list, because a truncated scan that looks complete is how the delete above becomes safe-looking.","The control-plane `list()` was not a read: it wrote once per stale record, every time anything listed runs. Listing is now free of side effects.","`/import` brings a session from another agent CLI into XENO and continues it \u2014 including agy stores, where the obvious store turned out not to be the best source. `--imported` shows what is on disk and says plainly that it persists. The source transcript is never touched, and that is enforced rather than intended.","Delegated branches now run on the Agent host under XENO_AGENT_ATTACH, report tool progress while they work, and the CLI reads the HOST's audit rather than only its own. Previously a host-routed branch was silent until it finished, and a refusal blamed a missing stream that in fact existed.","`xeno host status` now reports WHICH lanes the host offers and why a blocked one is blocked \u2014 including whose environment the blockage is about, which was the part that made the old message useless.","Pinned to @xenosystem/agent-sdk 0.9.10. The pin had been two releases stale, so work that shipped in 0.9.9 reached nobody. 0.9.10 also reports how full an agent's context is: turn.completed carries the RESIDENT token count, not the cumulative billing counter, and context.pressure arrives after every model response. The obvious field re-adds the whole prompt each turn \u2014 measured live, three one-word turns reported 3049, 6106 then 9171 tokens while the context grew by about eight.","Budget accounting no longer reads the entire run store when no budget cap is configured."],"0.5.20":["Pinned to @xenosystem/agent-sdk 0.9.8. The SDK's ownership policy still labelled this CLI by a scope retired in 8363d30c, which had failed the release smoke on every run since 2026-08-13 \u2014 the mismatch was never in this repo, so the fix was a repin rather than a workaround.","The release smoke now derives how strict it should be from the release trust policy: while no signing identity is approved it holds the engineering bar, and it tightens by itself the moment one lands. It previously demanded a signature no ordinary CI run could produce, and had failed for long enough to read as background noise.","First test coverage of the native manifest signing path, which had never executed once. Signer and verifier each carry their own copy of the canonical-JSON serializer and cannot import each other, so a drift as small as key ordering would have invalidated every release signature \u2014 and would have surfaced on release day, looking like a key problem.","Windows: temporary-directory cleanup no longer loses a race with exiting child processes, and the certification matrix checks out correctly on Windows ARM. `force: true` suppresses ENOENT, not EPERM, so the previous cleanup looked defensive and was not.","Groundwork for interactive Ctrl+C on Windows: the native addon can now raise a real console interrupt. Writing 0x03 into a ConPTY does not raise a signal, which is why Ctrl+C has never worked there. NOT yet wired \u2014 the console attach succeeds and the event is raised, and a ConPTY client still does not observe it."],"0.5.19":["The CLI did nothing at all on Linux and macOS. Its entry point did not resolve symlinks, so every npx and global install ran the wrong path and exited silently \u2014 the install looked successful and the binary did nothing. Fixed.","Agent permission decisions now reach an actual human on both rails, rather than being resolved without one.","A remote run that is read-only now says so, instead of failing silently and leaving you to work out why nothing changed.","The version the binary REPORTS is now bound to the version npm publishes, and a test enforces it. They had drifted: 0.5.18 was published as a package whose `--version` said 0.5.17.","\u26A0\uFE0F 0.5.18 exists on npm and was published from a branch that was never merged. It is superseded by this release, which is cut from `main`. If you installed 0.5.18, upgrade."],"0.5.17":["The CLI now ships as @xenosystem/agent-cli. The former name @xeno-corporation/xeno-agent-cli is deprecated on npm and receives no further releases; the `xeno`, `xeno-agent` and `xeno-code` binaries are unchanged, so nothing in your shell or scripts has to change.","The exact SDK pin moves with it: the CLI is bound to @xenosystem/agent-sdk 0.8.12. 0.8.11 was never published under either name and cannot be \u2014 GitLab evaluates .gitlab-ci.yml as it exists at the tag, and tag sdk-v0.8.11 predates that pipeline.","This release cannot be installed until @xenosystem/agent-sdk 0.8.12 is live on the registry; the release pipeline fails closed on --require-dependencies-published until it is."],"0.5.16":["Windows 11 ARM64 containment certification now performs architecture-neutral MXC host preparation with the reviewed x64 helper through operating-system emulation while keeping the contained runtime native ARM64.","The CLI is bound exactly to SDK 0.8.11, whose host-preparation reports distinguish the host architecture from the reviewed setup-helper architecture and retain timeout diagnostics."],"0.5.15":["macOS and Linux standalone diagnostics now report their verified POSIX process-group lifecycle independently from the stronger process-hardened sandbox level, preserving truthful security status while certifying full-tree cancellation, timeout, and shutdown behavior.","Generated Harbor benchmark and audit workspaces are excluded from source control, keeping Windows ARM64 checkouts below platform path limits and removing 9,938 generated artifacts from release candidates."],"0.5.14":["Windows 11 24H2 containment admission now uses the authoritative non-server NT client build floor instead of rejecting current Azure and GitHub Windows 11 images whose legacy registry ProductName still says Windows 10.","Windows Server remains fail-closed, pre-26100 clients remain ineligible, and both x64 and ARM64 host identities have regression coverage."],"0.5.13":["Hosted Windows x64 containment certification now fails closed unless the runner is Windows 11 24H2 or newer, the platform supported by Microsoft MXC, instead of treating Windows Server runner failures as product failures.","The certification matrix accepts a protected XENO_WINDOWS_X64_RUNNER label for an ephemeral Windows 11 x64 runner while keeping all other hosted platform rows unchanged.","Containment failure reports preserve bounded head-and-tail diagnostics through SDK 0.8.10 so the actionable trailing Win32 or MXC error is retained."],"0.5.12":["Windows MXC containment now launches its unrestricted host from the prepared system-drive temporary directory, outside directories whose DACLs are mutated by the contained policy, and certification captures official redacted MXC diagnostics.","Internal background session workers no longer start a competing global reconciler, preventing slower macOS hosts from quarantining a healthy turn between transcript append and checkpoint commit.","The interactive attach/input/stop smoke now follows the actual persisted inbox sequence and records worker logs on failure; the CLI is bound exactly to SDK 0.8.9."],"0.5.11":["Windows x64 containment certification now launches the MXC host and contained runtime with working-directory and temporary paths on the prepared system drive, matching split-drive GitHub runners.","The CLI is bound exactly to SDK 0.8.8, preserving the passing Linux, macOS, and Windows ARM64 conformance behavior while repairing Windows x64 ProcessContainer startup."],"0.5.10":["Linux containment certification now keeps disposable fixtures under the OS-private temporary mount instead of GitHub's workspace-projected runner directory, preserving the unlisted-filesystem boundary probe.","Windows certification retains the MXC-prepared system-drive fixture root required by hosted runners whose workspace and default temp directory use another volume."],"0.5.9":["Windows containment certification now creates its disposable fixtures on the MXC-prepared system drive, including hosted runners whose workspace and default temp directory live on another volume.","Standalone Windows certification now performs the same explicit host preparation and temporary-root binding as the native package matrix."],"0.5.8":["Native containment certification now compiles its macOS UI-policy probe against the stable libsystem_sandbox ABI without depending on private SDK headers.","Windows certification now distinguishes MXC's persistent per-policy DACL requirement from its explicit one-time host-preparation warnings."],"0.5.7":["The immutable CLI candidate now binds SDK 0.8.5 to the exact canonical Linux npm tarball bytes used by certification."],"0.5.6":["Windows containment certification now performs Microsoft MXC's explicit idempotent host preparation before AppContainer+DACL conformance.","macOS ARM64 certification now records behavioral Seatbelt evidence for pasteboard, WindowServer, LaunchServices, and HID isolation."],"0.5.5":["Native certification now resolves the SDK candidate artifact from the same workspace path on Bash and PowerShell runners.","SDK containment assets retain executable package modes on Linux and macOS, with a source regression check for every reviewed Unix binary."],"0.5.4":["Native engineering certification jobs now download the exact SDK tarball produced by the successful parent gate before installing dependencies.","The six-platform matrix remains source-bound to one immutable CLI tag and one immutable SDK candidate artifact."],"0.5.3":["Candidate packaging accepts both npm 11 array-form and npm 12 package-keyed JSON, with explicit diagnostics for malformed output.","Hosted SDK packaging now parses a bounded JSON file instead of relying on a large shell variable or an obsolete npm output shape."],"0.5.2":["Hosted certification now caps SDK declaration generation at two concurrent entry points and cleans declaration output in isolated bounded-memory workers.","SDK build subprocess failures now report their terminating signal or exit status instead of producing a silent hosted-run failure."],"0.5.1":["Hosted certification now builds the exact SDK candidate in bounded declaration groups, preventing parallel TypeScript declaration generation from exhausting GitHub-hosted runner resources.","Post-freeze readiness now distinguishes exact candidate tags verified at the candidate commit from collisions in release, registry, feed, and service namespaces."],"0.5.0":["Agent Profiles now provide enforceable Assistant, SWE, Reviewer, Writer, Research, Product, CI, DevOps, and Legal Research identities with bounded tools, permissions, skills, hooks, memory, isolation, and external-action authority.","The XENO Artifact Protocol adds durable plans, patches, diffs, reviews, screenshots, recordings, reports, provenance, approvals, and evidence relationships shared across local, hosted, and Hub workflows.","Secure Execution Contracts and capability leases now make filesystem, network, secret, process, device, browser, and external-action authority explicit and auditable.","Skills v2 adds standards-compatible SKILL.md discovery, progressive loading, bundled resources, invocation policy, version identity, and compatibility with XENO, .agents, and Claude skill locations.","MCP now supports current Streamable HTTP sessions and OAuth discovery while retaining compatible stdio and legacy SSE connections.","Browser, computer-use, hosted-agent, semantic-index, production-review, spec-planning, secure-sharing, and provider-onboarding surfaces are integrated through the shared platform contracts.","The retained TUI now presents stable grouped tool activity, live task and subagent status, candidate-bound edit previews, context-pressure and compaction state, and clearer turn completion receipts.","Six-product candidate certification now binds the SDK, XENO Use, XENO Browser, Agents API, CLI, and Hub to exact source identities, versions, tags, evidence, and protected release gates."],"0.4.45":["This transitional release is engineering-tested but not GA-certified: native PTY artifacts are unsigned and remain disabled by default until the Azure signing identity is approved; ordinary CLI and pipe-mode commands remain available.","App Server v2 now provides durable threads and turns, typed clients, permission ownership and expiry, bounded replay and backpressure, authenticated HTTP access, and additive v1 compatibility.","The terminal renderer now uses committed retained frames, bounded coalescing, one normal write per frame, a responsive 50-agent footer, accessibility modes, and a native terminal compatibility matrix.","Release certification now fails closed on six native architectures, platform and manifest signatures, reproducible package payloads, SBOMs, provenance attestations, independent approvals, npm OIDC publication, and public clean-install verification.","Long chat prompts now soft-wrap into a growing six-row composer with Unicode-safe editing, visual Up/Down navigation, file-panel parity, and a temporary XENO_INPUT_SOFT_WRAP=0 rollback switch.","Long-running model-authored shell commands now use managed operations: Ctrl+B promotes the same process, finite background work waits without model polling, and durable continuations resume exactly once after terminal output arrives.","ReadImage now uses Xeno's dependency-free owned raster codec for bounded PNG, BMP, Netpbm, and core-SVG previews; /processes and doctor expose task control, process-tree containment, operation-schema, and codec status.","Dynamic workflows now expose first-class run limits and terminal reducer summaries in run records and inspect JSON.","Background agent sessions now deliver durable completion, failure, stop, and request-keyed needs-input notifications to interactive parent chats and bounded headless runs without clobbering prompt drafts.","Workflow orchestration includes grouped phase/child progress, parent-chat completion notifications, WorkflowWait, /workflows drill-down, watch JSONL snapshots, and ultracode workflow prompts.","Workflow starts now support plan preview and exact-definition approval memory, scheduler ticks are serialized, and workflow lifecycle metrics are available through the OTel usage export.","Tool activity now uses semantic Update and Search labels, contextual line-numbered edit previews, expandable read/search/shell output, and accurate failure rendering.","Interactive chat now blocks repeated inspections and unrequested mutations on short questions, gives explicit research a larger typo-tolerant evidence budget, and reserves a tool-free final-answer turn when work limits are reached."],"0.4.44":["Markdown source links now render as clickable terminal links in supported terminals, with visible URLs preserved when links are disabled."],"0.4.43":["New background agents now appear in the footer immediately after launch, and the footer can show up to eight agent sessions."],"0.4.42":["Background agent footer rows now fit the common three-agent fanout without hiding the first agent on compact terminals.","Completed background agent sessions now close after BackgroundAgentJoin returns their result to the main agent."],"0.4.41":["Completed background agent footer rows now keep a fixed runtime instead of continuing to count upward."],"0.4.40":["One-shot background agent sessions now mark done after returning their result, while user-follow-up sessions stay idle for continued chat."],"0.4.39":["Background agent session activity now uses concise status labels like Thinking instead of showing the full task prompt."],"0.4.38":["Opened background agent sessions now show their own session activity line while keeping main-agent tool progress isolated."],"0.4.37":["Opened background agent sessions no longer show the main agent's active tool progress line."],"0.4.36":["Opened background agent sessions now render the same main-chat transcript surface for user messages, assistant messages, tool calls, and tool results."],"0.4.35":["Background agent session chat now includes tool calls and tool results in its visible history."],"0.4.34":["Opening a footer background agent now switches the main chat surface into that agent session instead of showing a separate info panel.","Child-session input now queues messages to that agent while Esc returns to the main chat."],"0.4.33":["Background agent footer rows now repaint immediately during active turns.","Remembered background-agent approvals now apply to later background-agent launches."],"0.4.32":["Startup release-note hints now sit directly under the note text and render dimmed in the side panel."],"0.4.31":["Unread release notes now render beside the startup XENO AGENT header on wide terminals."],"0.4.30":["BackgroundAgentList now only reports current-chat footer sessions so old workspace agents do not hide missing new deployments."],"0.4.29":["Background agent footer markers now use filled and empty squares.","Opening a background agent from the footer now shows its session chat with transcript and message input."],"0.4.28":["First-run default model is now gpt-5.5 while saved user model choices are preserved.","Number keys in the model picker now type into search instead of selecting by index.","Model selections made with /model now persist as the user's saved default."],"0.4.27":["Background agent footer rows are now scoped to the current chat session."],"0.4.26":["Background agent rows now sit below the status line and inherit the live chat model."],"0.4.25":["Legacy BackgroundAgent calls now create footer-visible interactive background sessions."],"0.4.24":["Model picker support now has a `xeno models --json` command, share export proof, and GitHub review artifact contracts."],"0.4.23":["Model picker and /model listings now refresh Xeno API model availability before switching."],"0.4.22":["Hook review now shows command-hook hashes and supports trust, disable, and explain commands.","Expanded lifecycle hooks now cover permission decisions, stop failures, and delegated subagent start/stop events.","Set XENO_STATUS_LINE_COMMAND to replace the TUI status line with a cached command output.","Rewind now saves the abandoned conversation branch as a manual checkpoint before restoring.","Interactive chat now supports Ctrl+R history search, Ctrl+G prompt editing, /vim input mode, and /copy answer/block/diff clipboard copy.","/theme is now a discoverable alias for /color with user/project custom theme files, and /processes stop-all stops running background tasks."],"0.4.20":["Shell completions now include the current control-plane commands, flags, statuses, scopes, and usage groups.","The local app-server browser page now includes prompt and process controls on top of advanced JSON-RPC.","Published CLI and SDK packages now include GitHub repository metadata.","Docs now call out the temporary GitHub Actions startup_failure blocker while local gates remain authoritative."],"0.1.0":["Persistent shell sessions now preserve cwd and shell state across Bash calls.","Delegated planner, explorer, executor, and reviewer branches now support staged and parallel policies.","MCP now supports stdio and SSE transports, prompt discovery, resource reads, and live tool sync.","Notebook, ask-user, and memory tools are available in the shared agent runtime.","CLI operator workflows now include doctor, bug-report, config editing, cost summaries, and runtime inspection."]};function ene(e=he){return Sjt[e]??[]}function Cjt(e=he){let t=ht().lastReleaseNotesSeen;return ene(e).length>0&&t!==e}function yk(e=he){hi({lastReleaseNotesSeen:e})}function VU(e){let t=e??he,n=ene(t);return n.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...n.map(r=>`- ${r}`)].join(`
|
|
4198
4198
|
`)}function hQe(e=he){if(Cjt(e))return[`What's new in XENO AGENT v${e}`,...ene(e).map(t=>`- ${t}`),"Run `xeno release-notes` to view this again."].join(`
|
|
4199
4199
|
`)}Rt();ac();ao();dT();import{spawn as xjt}from"node:child_process";import{setTimeout as nne}from"node:timers/promises";iw();import{resolve as HU}from"node:path";var gQe="cancel",Pa={name:"WorkflowCancel",command:`workflows ${gQe}`,nativeVerb:gQe,description:"Request cancellation of a local workflow and stop its child work. Acceptance is not confirmed termination. Inspect or wait on the same workflow while cancellation is pending; do not start replacement work until cancellation is confirmed.",argument:{name:"run_id",type:"string",required:!0,description:"Explicit workflow run ID; never inferred from the selected UI row."},mode:"always",requiresDisplay:!1,reversibility:"irreversible",parity:"exposed",readingTools:["WorkflowInspect","WorkflowWait"],readingCommand:"workflows inspect <run-id> --json",replyFields:{accepted:"True only after the durable cancellation request was read back. False means no workflow target was found.",cancelled:"True only when readback confirms cancellation and no child termination remains pending. False means cancellation is not confirmed, not that work is still running.",pending:"True when the request was accepted but termination or readback remains incomplete. Re-read the same workflow; this is not a new request.",operationId:"Stable cancellation operation ID, or null when no request was accepted. Repeated cancellation requests retain this ID.",run:"Observed cancellation snapshot (workflowRunId, workflowName, status, updatedAt, cancellation), or null if absent/unconfirmed. The native CLI retains its existing full run record; use WorkflowInspect for child details.",warning:"Present when accepted cancellation could not be confirmed or processed. It never grants permission to restart work."},cancellationFields:{schemaVersion:"Cancellation metadata schema version, currently 1.",operationId:"The same durable cancellation operation ID as the top-level reply.",workflowRunId:"Exact workflow targeted by this request.",requestedAt:"UTC timestamp of the durably published request.",pendingChildCount:"Children whose termination remains unconfirmed; absent before the first reconciliation pass.",lastError:"Optional bounded diagnostic about an unconfirmed child; absence does not independently prove completion.",completedAt:"Present only after child termination is confirmed.",notificationEnqueuedAt:"Present after the workflow-cancelled notification was persisted; it does not mean the parent consumed it."}};function bk(e,t){let n=e.run?.workflowName??t;return e.accepted?e.cancelled?`Cancelled ${n}`:`Cancellation pending for ${n}; inspect operation ${e.operationId}`:`Workflow run not found: ${t}`}function AQe(e){let t=e.run;return{...e,run:t?{workflowRunId:t.workflowRunId,workflowName:t.workflowName,status:t.status,updatedAt:t.updatedAt,cancellation:t.cancellation}:null}}var wQe=()=>[Pa.description,`Mode: ${Pa.mode}; requiresDisplay: ${Pa.requiresDisplay}; reversibility: ${Pa.reversibility}. Read back with ${Pa.readingTools.join(" or ")}.`,"Returns JSON: "+Object.entries(Pa.replyFields).map(([e,t])=>`${e}: ${t}`).join(" "),"Cancellation progress: "+Object.entries(Pa.cancellationFields).map(([e,t])=>`${e}: ${t}`).join(" ")].join(" ");function Ks(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
4200
4200
|
`)}function Rjt(e,t){if(t){Ks(e);return}if(e.ok&&e.definition){process.stdout.write(`Workflow valid: ${e.definition.name}
|
|
@@ -5665,7 +5665,7 @@ ${U.dim("The original session is unchanged and still resumable.")}`)}catch(n){le
|
|
|
5665
5665
|
`);return}process.stdout.write(`${await CA(t,!!e.all,!0)}
|
|
5666
5666
|
`)})}import{resolve as IHe}from"node:path";import{randomUUID as HVe}from"node:crypto";import{performance as xie}from"node:perf_hooks";import{lookup as j3t}from"node:dns/promises";import{isIP as Oj}from"node:net";import{request as K3t}from"node:http";import{request as Z3t}from"node:https";import{isIP as MVe}from"node:net";import{once as e6t}from"node:events";import{createHash as o6t}from"node:crypto";import{isIP as NVe}from"node:net";import{createHash as fHe}from"node:crypto";import{chmod as pYt,mkdir as mHe,open as fYt,readFile as mYt,rename as hYt,unlink as gYt}from"node:fs/promises";import{dirname as AYt,join as jVe,resolve as wYt}from"node:path";import{mkdirSync as bYt,readFileSync as vYt,rmSync as hHe,writeFileSync as IYt}from"node:fs";import{hostname as gHe}from"node:os";import{dirname as kYt}from"node:path";var c8n=300*1e3;function _3t(e){return/^data:([^;,]+)[;,]/i.exec(e.trim())?.[1]}function $3t(e){let t=[];for(let n of e){if(n.type==="text"){t.push(n.text);continue}if(n.type==="image_url"){t.push(`[image ${_3t(n.image_url.url)??"unknown"}]`);continue}let r=n.text??n.data;if(r&&r.trim().length>0){t.push(r);continue}let i=n.uri??n.mimeType??"resource";t.push(`[resource ${i}]`)}return t.join(`
|
|
5667
5667
|
|
|
5668
|
-
`).trim()}function Nj(e){return typeof e=="string"?e:$3t(e)}var B3t=1,M3t=12,N3t=128,O3t=/^xeno\.[a-z0-9]+(?:[._][a-z0-9]+)*$/u,D3t=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u,L3t=/(?:[\\/]|@|https?:|bearer|token|secret|password|credential|api[_-]?key|[0-9a-f]{8}-[0-9a-f-]{27,})/iu,Q3t=new Set(["arch","cached","capability","category","component","contained","error_code","frame_kind","gate","method","mode","operation","outcome","platform","previous_state","protocol_version","provider","queue","reason","recovery","retry_kind","state","status","tool","transport","trigger"]),TVe=new Set,PVe=new Map;function F3t(e){let t=e.trim().toLowerCase();return!t||t.length>64||L3t.test(t)||!D3t.test(t)?null:t}function U3t(e,t){if(typeof t=="boolean")return t;if(typeof t=="number")return e!=="protocol_version"||!Number.isInteger(t)||t<0||t>100?null:t;if(typeof t!="string")return null;let n=F3t(t);if(!n)return null;let r=PVe.get(e);return r||(r=new Set,PVe.set(e,r)),!r.has(n)&&r.size>=N3t?"other":(r.add(n),n)}function q3t(e={}){let t={};for(let[n,r]of Object.entries(e)){if(Object.keys(t).length>=M3t)break;if(!Q3t.has(n))continue;let i=U3t(n,r);i!==null&&(t[n]=i)}return Object.freeze(t)}function WVe(e){if(TVe.size===0||!O3t.test(e.name)||e.name.length>128)return;let t=e.kind==="event"?1:e.value??1;if(!Number.isFinite(t)||t<0)return;let n=Object.freeze({schemaVersion:B3t,kind:e.kind,name:e.name,value:Math.min(t,Number.MAX_SAFE_INTEGER),timestamp:(e.timestamp??new Date).toISOString(),attributes:q3t(e.attributes)});for(let r of TVe)try{r(n)}catch{}}function Pj(e,t=1,n){WVe({kind:"counter",name:e,value:t,attributes:n})}function _Ve(e,t,n){WVe({kind:"histogram",name:e,value:t,attributes:n})}var V3t=["context length","context window","maximum context","too many tokens","request too large"];function H3t(e){let t=e.toLowerCase();return V3t.some(n=>t.includes(n))}var Cr=class extends Error{category;code;retryable;providerId;statusCode;retryAfterMs;requestId;constructor(e,t){super(e,t.cause!==void 0?{cause:t.cause}:void 0),this.name="ProviderError",this.category=t.category,this.code=t.code,this.retryable=t.retryable??!1,this.providerId=t.providerId,this.statusCode=t.statusCode,this.retryAfterMs=t.retryAfterMs,this.requestId=t.requestId}};function W3t(e,t=Date.now()){if(!e)return;let n=Number(e.trim());if(Number.isFinite(n)&&n>=0)return Math.ceil(n*1e3);let r=Date.parse(e);if(Number.isFinite(r))return Math.max(0,r-t)}function G3t(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e,n=t.error;if(typeof n=="string")return n;if(n&&typeof n=="object"){let r=n;if(typeof r.message=="string")return r.message;if(typeof r.type=="string")return r.type}return typeof t.message=="string"?t.message:""}function Rie(e,t){return t.some(n=>e.includes(n))}function J3t(e){let t=G3t(e.body).trim(),n=t.toLowerCase(),r=t?`: ${t.slice(0,1e3)}`:"",i={providerId:e.providerId,statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId};return e.statusCode===401?new Cr(`Provider authentication failed${r}`,{...i,category:"authentication",code:"PROVIDER_AUTHENTICATION_FAILED"}):e.statusCode===403?new Cr(`Provider authorization failed${r}`,{...i,category:"authorization",code:"PROVIDER_AUTHORIZATION_FAILED"}):Rie(n,["api key not valid","invalid api key","api key expired","api_key_invalid","invalid authentication credentials","missing api key"])?new Cr(`Provider authentication failed${r}`,{...i,category:"authentication",code:"PROVIDER_AUTHENTICATION_FAILED"}):e.statusCode===429?new Cr(`Provider rate limit reached${r}`,{...i,category:"rate_limit",code:"PROVIDER_RATE_LIMITED",retryable:!0}):H3t(n)?new Cr(`Provider context window exceeded${r}`,{...i,category:"context_overflow",code:"PROVIDER_CONTEXT_OVERFLOW"}):Rie(n,["safety","content policy","blocked_reason","responsible_ai_policy_violation"])?new Cr(`Provider safety policy refused the request${r}`,{...i,category:"safety_refusal",code:"PROVIDER_SAFETY_REFUSAL"}):e.statusCode===404||Rie(n,["model not found","model does not exist","unsupported model"])?new Cr(`Provider model is unavailable${r}`,{...i,category:"unsupported_model",code:"PROVIDER_MODEL_UNSUPPORTED"}):e.statusCode===408||e.statusCode===504?new Cr(`Provider request timed out${r}`,{...i,category:"timeout",code:"PROVIDER_TIMEOUT",retryable:!0}):e.statusCode>=500||e.statusCode===409||e.statusCode===425?new Cr(`Provider server error${r}`,{...i,category:"server",code:"PROVIDER_SERVER_ERROR",retryable:!0}):new Cr(`Provider rejected the request with HTTP ${e.statusCode}${r}`,{...i,category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"})}function Dn(e,t,n){return new Cr(`Malformed ${e} response: ${t}`,{providerId:e,category:"malformed_response",code:"PROVIDER_MALFORMED_RESPONSE",...n!==void 0?{cause:n}:{}})}function $ie(e,t){return Pj("xeno.provider.capability_mismatches",1,{component:"provider_contract",provider:e,capability:t,error_code:"provider_capability_unsupported"}),new Cr(`${e} does not advertise the required ${t} capability`,{providerId:e,category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"})}var GVe=new Set(["metadata.google.internal","metadata.azure.internal","instance-data.ec2.internal"]);function ta(e){return new Cr(`Provider endpoint rejected: ${e}`,{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"})}function X3t(e){let t=e.split(".");if(t.length!==4)return null;let n=t.map(r=>Number(r));return n.every(r=>Number.isInteger(r)&&r>=0&&r<=255)?n:null}function $Ve(e){let t=X3t(e);if(!t)return"public";let[n,r]=t;return n===0?"unspecified":n===127?"loopback":n===169&&r===254?"link-local":n===10||n===172&&r>=16&&r<=31||n===192&&r===168?"private":"public"}function Bie(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"").split("%")[0];Oj(t)===6&&(t=new URL(`http://[${t}]`).hostname.slice(1,-1));let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),i=Number.parseInt(n[2],16);return`${r>>8}.${r&255}.${i>>8}.${i&255}`}return t}function JVe(e){let t=Bie(e);return Oj(t)===4?$Ve(t):t==="::"||t==="::0"?"unspecified":t==="::1"?"loopback":t.startsWith("::ffff:")?$Ve(t.slice(7)):/^f[cd]/.test(t)?"private":/^fe[89ab]/.test(t)?"link-local":"public"}function BVe(e){return e==="example"||e.endsWith(".example")||e==="test"||e.endsWith(".test")||e==="invalid"||e.endsWith(".invalid")}function z3t(e){return e==="localhost"||e.endsWith(".localhost")}function Uie(e,t={}){let n;try{n=new URL(e)}catch{throw ta("the URL is invalid")}if(n.username||n.password)throw ta("embedded credentials are forbidden");if(n.hash||n.search)throw ta("base URLs cannot contain a query or fragment");if(!n.hostname||n.hostname.includes("%"))throw ta("the hostname is empty or ambiguous");if(GVe.has(n.hostname.toLowerCase()))throw ta("cloud metadata destinations are forbidden");if(n.protocol!=="https:"&&n.protocol!=="http:")throw ta(`scheme ${n.protocol} is unsupported`);let r=t.profile??"public-https";if(n.protocol==="http:"&&r!=="local-network")throw ta("plain HTTP requires the explicit local-network profile");let i=n.hostname.replace(/^\[|\]$/g,""),o=Oj(i)?JVe(i):null;if(o==="link-local"||o==="unspecified")throw ta(`${o} destinations are forbidden`);if(r==="public-https"&&(o==="private"||o==="loopback"||z3t(n.hostname)))throw ta("private and loopback destinations require the local-network profile");if(r==="local-network"&&n.protocol==="http:"&&o==="public"&&!t.allowedHosts?.includes(n.hostname))throw ta("local-network HTTP must resolve to loopback or a private address");return n}async function Y3t(e,t={}){await XVe(e,t)}async function XVe(e,t={}){let n=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(GVe.has(n))throw ta("cloud metadata destinations are forbidden");let r=new Set((t.allowedHosts??[]).map(s=>s.toLowerCase())),i=Oj(n)?[n]:BVe(n)?[]:t.resolveHostname?await t.resolveHostname(n):(await j3t(n,{all:!0,verbatim:!0})).map(s=>s.address);if(!i.length&&!BVe(n))throw ta("DNS resolution returned no addresses");let o=t.profile??"public-https";for(let s of i){let a=JVe(s);if(a==="link-local"||a==="unspecified")throw ta(`DNS resolved to a forbidden ${a} address`);if(o==="public-https"&&a!=="public"&&!r.has(n))throw ta(`DNS resolved public endpoint to ${a} address ${s}`);if(o==="local-network"&&e.protocol==="http:"&&a==="public"&&!r.has(n))throw ta(`local-network HTTP resolved to public address ${s}`)}return i}function t6t(e,t){return{dispatch(n,r){let i,o=!1,s=u=>{o||(o=!0,i?.destroy(),r.onError(u))},a=t[0];if(!a||!MVe(a)||new URL(n.origin).origin!==e.origin)return queueMicrotask(()=>s(new Error("Provider connection has no authorized pinned address"))),!0;let c=n.headers??{},l=(e.protocol==="https:"?Z3t:K3t)(new URL(n.path,e.origin),{method:n.method,headers:c,agent:!1,rejectUnauthorized:!0,lookup:(u,d,p)=>{let f={address:a,family:MVe(a)};typeof d=="object"&&d.all?p(null,[f]):p(null,a,f.family)}},u=>{i=u;let d=u.rawHeaders.map(f=>Buffer.from(f)),p=()=>u.resume();r.onHeaders(u.statusCode??500,d,p,u.statusMessage??"")===!1&&u.pause(),u.on("data",f=>{r.onData(f)||u.pause()}),u.on("end",()=>{o||(o=!0,r.onComplete(u.rawTrailers.map(f=>Buffer.from(f))))}),u.on("error",s),u.on("aborted",()=>s(new Error("Provider response was interrupted")))});return l.on("socket",u=>{u.once("connect",()=>{(!u.remoteAddress||Bie(u.remoteAddress)!==Bie(a))&&l.destroy(new Error("Provider socket did not connect to its authorized address"))})}),l.on("error",s),r.onConnect(u=>l.destroy(u??new Error("Provider request aborted"))),(async()=>{try{let u=n.body;if(typeof u=="string"||u instanceof Uint8Array)l.end(u);else{if(u)for await(let d of u){if(l.destroyed)return;l.write(d)||await e6t(l,"drain")}l.end()}}catch(u){l.destroy(u instanceof Error?u:new Error("Provider request body failed"))}})(),!0}}}var oE={connectTimeoutMs:15e3,totalTimeoutMs:12e4,idleTimeoutMs:3e4,maxResponseBytes:8*1024*1024,maxHeaderBytes:64*1024,maxEventBytes:1024*1024};function n6t(e={}){for(let[t,n]of Object.entries(e))if(n!==void 0&&(!Number.isSafeInteger(n)||n<1))throw Dn("provider-transport",`${t} must be a positive safe integer`);return{connectTimeoutMs:Math.max(100,e.connectTimeoutMs??oE.connectTimeoutMs),totalTimeoutMs:Math.max(100,e.totalTimeoutMs??oE.totalTimeoutMs),idleTimeoutMs:Math.max(100,e.idleTimeoutMs??oE.idleTimeoutMs),maxResponseBytes:Math.max(1024,e.maxResponseBytes??oE.maxResponseBytes),maxHeaderBytes:Math.max(1024,e.maxHeaderBytes??oE.maxHeaderBytes),maxEventBytes:Math.max(1024,e.maxEventBytes??oE.maxEventBytes)}}async function w_(e,t){let n,r=new Promise((i,o)=>{n=()=>o(new Error("Provider operation aborted")),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()});try{return await Promise.race([e,r])}finally{t.removeEventListener("abort",n)}}function Mj(e,t,n,r){try{return e.decode(t,{stream:n})}catch{throw Dn(r,"response is not valid UTF-8")}}function Tie(e,t,n){let r=new Cr(t==="cancelled"?"Provider request was cancelled":"Provider request timed out",{providerId:e,category:t,code:t==="cancelled"?"PROVIDER_CANCELLED":"PROVIDER_TIMEOUT",retryable:t==="timeout",...n!==void 0?{cause:n}:{}});return t==="cancelled"&&(r.name="AbortError"),r}function r6t(e){let t=0;return e.forEach((n,r)=>{t+=Buffer.byteLength(r)+Buffer.byteLength(n)+4}),t}async function zVe(e,t,n,r){if(!e.body)return"";let i=e.body.getReader(),o=new TextDecoder("utf-8",{fatal:!0}),s=0,a="",c,l=()=>{c&&clearTimeout(c),c=setTimeout(()=>r.abort("idle-timeout"),n.idleTimeoutMs)};l();try{for(;;){let{value:u,done:d}=await w_(i.read(),r.signal);if(d)break;if(l(),s+=u.byteLength,s>n.maxResponseBytes)throw Dn(t,`response exceeded ${n.maxResponseBytes} bytes`);a+=Mj(o,u,!0,t)}return a+=Mj(o,void 0,!1,t),a}finally{c&&clearTimeout(c),i.cancel().catch(()=>{}),i.releaseLock()}}async function YVe(e,t,n,r){let i=xie.now(),o=n6t(n.limits);Pj("xeno.provider.requests",1,{component:"provider_transport",provider:n.providerId,transport:"http"});let s=new AbortController,a=null,c=t.signal,l=()=>s.abort("caller");if(c?.aborted)throw Tie(n.providerId,"cancelled");c?.addEventListener("abort",l,{once:!0});let u=setTimeout(()=>{a="total",s.abort("total-timeout")},o.totalTimeoutMs),d=setTimeout(()=>{a="connect",s.abort("connect-timeout")},o.connectTimeoutMs),p;try{let f=await w_(XVe(e,n.endpointPolicy),s.signal);if(s.signal.aborted)throw new Error("Provider request aborted before dispatch");let m={...t,signal:s.signal,redirect:"manual",dispatcher:t6t(e,f)},h=fetch(e,m);h.then(w=>{s.signal.aborted&&w.body?.cancel().catch(()=>{})},()=>{});let g=await w_(h,s.signal);if(p=g,clearTimeout(d),r6t(g.headers)>o.maxHeaderBytes)throw Dn(n.providerId,`response headers exceeded ${o.maxHeaderBytes} bytes`);if(g.redirected||g.status>=300&&g.status<400)throw new Cr("Provider redirects are disabled",{providerId:n.providerId,category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED",statusCode:g.status});let A=g.headers.get("content-length");if(A&&/^\d+$/.test(A)&&Number(A)>o.maxResponseBytes)throw Dn(n.providerId,`response exceeded ${o.maxResponseBytes} bytes`);if(!g.ok){let w=await zVe(g,n.providerId,o,s),b=w;try{b=w?JSON.parse(w):{}}catch{}throw J3t({providerId:n.providerId,statusCode:g.status,body:b,retryAfterMs:W3t(g.headers.get("retry-after")),requestId:g.headers.get("request-id")??g.headers.get("x-request-id")??void 0})}let y=await w_(r(g,s,o),s.signal);return Pj("xeno.provider.request_results",1,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"success"}),_Ve("xeno.provider.request_duration_ms",xie.now()-i,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"success"}),y}catch(f){let m;throw f instanceof Cr?m=f:c?.aborted||s.signal.reason==="caller"?m=Tie(n.providerId,"cancelled",f):a||s.signal.reason==="idle-timeout"?m=Tie(n.providerId,"timeout",f):m=new Cr("Provider transport failed",{providerId:n.providerId,category:"transport",code:"PROVIDER_TRANSPORT_ERROR",retryable:!0,cause:f}),s.abort("request-failed"),p?.body&&!p.body.locked&&p.body.cancel().catch(()=>{}),Pj("xeno.provider.request_results",1,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"error",category:m.category,error_code:m.code}),_Ve("xeno.provider.request_duration_ms",xie.now()-i,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"error",category:m.category}),m}finally{clearTimeout(d),clearTimeout(u),c?.removeEventListener("abort",l)}}async function i6t(e,t,n){return YVe(e,t,n,async(r,i,o)=>{let s=await zVe(r,n.providerId,o,i),a;try{a=s?JSON.parse(s):{}}catch(c){throw Dn(n.providerId,"body is not valid JSON",c)}if(!a||typeof a!="object"||Array.isArray(a))throw Dn(n.providerId,"JSON body must be an object");return a})}async function Dj(e,t,n,r){return YVe(e,t,n,async(i,o,s)=>{if(!i.body)throw Dn(n.providerId,"stream response has no body");let a=i.body.getReader(),c=new TextDecoder("utf-8",{fatal:!0}),l="",u=0,d="message",p=[],f,m=()=>{f&&clearTimeout(f),f=setTimeout(()=>o.abort("idle-timeout"),s.idleTimeoutMs)},h=async()=>{if(p.length===0){d="message";return}let g=p.join(`
|
|
5668
|
+
`).trim()}function Nj(e){return typeof e=="string"?e:$3t(e)}var B3t=1,M3t=12,N3t=128,O3t=/^xeno\.[a-z0-9]+(?:[._][a-z0-9]+)*$/u,D3t=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u,L3t=/(?:[\\/]|@|https?:|bearer|token|secret|password|credential|api[_-]?key|[0-9a-f]{8}-[0-9a-f-]{27,})/iu,Q3t=new Set(["arch","cached","capability","category","component","contained","error_code","frame_kind","gate","method","mode","operation","outcome","platform","previous_state","protocol_version","provider","queue","reason","recovery","retry_kind","state","status","tool","transport","trigger"]),TVe=new Set,PVe=new Map;function F3t(e){let t=e.trim().toLowerCase();return!t||t.length>64||L3t.test(t)||!D3t.test(t)?null:t}function U3t(e,t){if(typeof t=="boolean")return t;if(typeof t=="number")return e!=="protocol_version"||!Number.isInteger(t)||t<0||t>100?null:t;if(typeof t!="string")return null;let n=F3t(t);if(!n)return null;let r=PVe.get(e);return r||(r=new Set,PVe.set(e,r)),!r.has(n)&&r.size>=N3t?"other":(r.add(n),n)}function q3t(e={}){let t={};for(let[n,r]of Object.entries(e)){if(Object.keys(t).length>=M3t)break;if(!Q3t.has(n))continue;let i=U3t(n,r);i!==null&&(t[n]=i)}return Object.freeze(t)}function WVe(e){if(TVe.size===0||!O3t.test(e.name)||e.name.length>128)return;let t=e.kind==="event"?1:e.value??1;if(!Number.isFinite(t)||t<0)return;let n=Object.freeze({schemaVersion:B3t,kind:e.kind,name:e.name,value:Math.min(t,Number.MAX_SAFE_INTEGER),timestamp:(e.timestamp??new Date).toISOString(),attributes:q3t(e.attributes)});for(let r of TVe)try{r(n)}catch{}}function Pj(e,t=1,n){WVe({kind:"counter",name:e,value:t,attributes:n})}function _Ve(e,t,n){WVe({kind:"histogram",name:e,value:t,attributes:n})}var V3t=["context length","context window","maximum context","too many tokens","request too large"];function H3t(e){let t=e.toLowerCase();return V3t.some(n=>t.includes(n))}var Cr=class extends Error{category;code;retryable;providerId;statusCode;retryAfterMs;requestId;constructor(e,t){super(e,t.cause!==void 0?{cause:t.cause}:void 0),this.name="ProviderError",this.category=t.category,this.code=t.code,this.retryable=t.retryable??!1,this.providerId=t.providerId,this.statusCode=t.statusCode,this.retryAfterMs=t.retryAfterMs,this.requestId=t.requestId}};function W3t(e,t=Date.now()){if(!e)return;let n=Number(e.trim());if(Number.isFinite(n)&&n>=0)return Math.ceil(n*1e3);let r=Date.parse(e);if(Number.isFinite(r))return Math.max(0,r-t)}function G3t(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e,n=t.error;if(typeof n=="string")return n;if(n&&typeof n=="object"){let r=n;if(typeof r.message=="string")return r.message;if(typeof r.type=="string")return r.type}return typeof t.message=="string"?t.message:""}function Rie(e,t){return t.some(n=>e.includes(n))}function J3t(e){let t=G3t(e.body).trim(),n=t.toLowerCase(),r=t?`: ${t.slice(0,1e3)}`:"",i={providerId:e.providerId,statusCode:e.statusCode,retryAfterMs:e.retryAfterMs,requestId:e.requestId};return e.statusCode===401?new Cr(`Provider authentication failed${r}`,{...i,category:"authentication",code:"PROVIDER_AUTHENTICATION_FAILED"}):e.statusCode===403?new Cr(`Provider authorization failed${r}`,{...i,category:"authorization",code:"PROVIDER_AUTHORIZATION_FAILED"}):Rie(n,["api key not valid","invalid api key","api key expired","api_key_invalid","invalid authentication credentials","missing api key"])?new Cr(`Provider authentication failed${r}`,{...i,category:"authentication",code:"PROVIDER_AUTHENTICATION_FAILED"}):e.statusCode===429?new Cr(`Provider rate limit reached${r}`,{...i,category:"rate_limit",code:"PROVIDER_RATE_LIMITED",retryable:!0}):H3t(n)?new Cr(`Provider context window exceeded${r}`,{...i,category:"context_overflow",code:"PROVIDER_CONTEXT_OVERFLOW"}):Rie(n,["safety","content policy","blocked_reason","responsible_ai_policy_violation"])?new Cr(`Provider safety policy refused the request${r}`,{...i,category:"safety_refusal",code:"PROVIDER_SAFETY_REFUSAL"}):e.statusCode===404||Rie(n,["model not found","model does not exist","unsupported model","unknown provider for model"])?new Cr(`Provider model is unavailable${r}`,{...i,category:"unsupported_model",code:"PROVIDER_MODEL_UNSUPPORTED"}):e.statusCode===408||e.statusCode===504?new Cr(`Provider request timed out${r}`,{...i,category:"timeout",code:"PROVIDER_TIMEOUT",retryable:!0}):e.statusCode>=500||e.statusCode===409||e.statusCode===425?new Cr(`Provider server error${r}`,{...i,category:"server",code:"PROVIDER_SERVER_ERROR",retryable:!0}):new Cr(`Provider rejected the request with HTTP ${e.statusCode}${r}`,{...i,category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"})}function Dn(e,t,n){return new Cr(`Malformed ${e} response: ${t}`,{providerId:e,category:"malformed_response",code:"PROVIDER_MALFORMED_RESPONSE",...n!==void 0?{cause:n}:{}})}function $ie(e,t){return Pj("xeno.provider.capability_mismatches",1,{component:"provider_contract",provider:e,capability:t,error_code:"provider_capability_unsupported"}),new Cr(`${e} does not advertise the required ${t} capability`,{providerId:e,category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"})}var GVe=new Set(["metadata.google.internal","metadata.azure.internal","instance-data.ec2.internal"]);function ta(e){return new Cr(`Provider endpoint rejected: ${e}`,{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"})}function X3t(e){let t=e.split(".");if(t.length!==4)return null;let n=t.map(r=>Number(r));return n.every(r=>Number.isInteger(r)&&r>=0&&r<=255)?n:null}function $Ve(e){let t=X3t(e);if(!t)return"public";let[n,r]=t;return n===0?"unspecified":n===127?"loopback":n===169&&r===254?"link-local":n===10||n===172&&r>=16&&r<=31||n===192&&r===168?"private":"public"}function Bie(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"").split("%")[0];Oj(t)===6&&(t=new URL(`http://[${t}]`).hostname.slice(1,-1));let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),i=Number.parseInt(n[2],16);return`${r>>8}.${r&255}.${i>>8}.${i&255}`}return t}function JVe(e){let t=Bie(e);return Oj(t)===4?$Ve(t):t==="::"||t==="::0"?"unspecified":t==="::1"?"loopback":t.startsWith("::ffff:")?$Ve(t.slice(7)):/^f[cd]/.test(t)?"private":/^fe[89ab]/.test(t)?"link-local":"public"}function BVe(e){return e==="example"||e.endsWith(".example")||e==="test"||e.endsWith(".test")||e==="invalid"||e.endsWith(".invalid")}function z3t(e){return e==="localhost"||e.endsWith(".localhost")}function Uie(e,t={}){let n;try{n=new URL(e)}catch{throw ta("the URL is invalid")}if(n.username||n.password)throw ta("embedded credentials are forbidden");if(n.hash||n.search)throw ta("base URLs cannot contain a query or fragment");if(!n.hostname||n.hostname.includes("%"))throw ta("the hostname is empty or ambiguous");if(GVe.has(n.hostname.toLowerCase()))throw ta("cloud metadata destinations are forbidden");if(n.protocol!=="https:"&&n.protocol!=="http:")throw ta(`scheme ${n.protocol} is unsupported`);let r=t.profile??"public-https";if(n.protocol==="http:"&&r!=="local-network")throw ta("plain HTTP requires the explicit local-network profile");let i=n.hostname.replace(/^\[|\]$/g,""),o=Oj(i)?JVe(i):null;if(o==="link-local"||o==="unspecified")throw ta(`${o} destinations are forbidden`);if(r==="public-https"&&(o==="private"||o==="loopback"||z3t(n.hostname)))throw ta("private and loopback destinations require the local-network profile");if(r==="local-network"&&n.protocol==="http:"&&o==="public"&&!t.allowedHosts?.includes(n.hostname))throw ta("local-network HTTP must resolve to loopback or a private address");return n}async function Y3t(e,t={}){await XVe(e,t)}async function XVe(e,t={}){let n=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(GVe.has(n))throw ta("cloud metadata destinations are forbidden");let r=new Set((t.allowedHosts??[]).map(s=>s.toLowerCase())),i=Oj(n)?[n]:BVe(n)?[]:t.resolveHostname?await t.resolveHostname(n):(await j3t(n,{all:!0,verbatim:!0})).map(s=>s.address);if(!i.length&&!BVe(n))throw ta("DNS resolution returned no addresses");let o=t.profile??"public-https";for(let s of i){let a=JVe(s);if(a==="link-local"||a==="unspecified")throw ta(`DNS resolved to a forbidden ${a} address`);if(o==="public-https"&&a!=="public"&&!r.has(n))throw ta(`DNS resolved public endpoint to ${a} address ${s}`);if(o==="local-network"&&e.protocol==="http:"&&a==="public"&&!r.has(n))throw ta(`local-network HTTP resolved to public address ${s}`)}return i}function t6t(e,t){return{dispatch(n,r){let i,o=!1,s=u=>{o||(o=!0,i?.destroy(),r.onError(u))},a=t[0];if(!a||!MVe(a)||new URL(n.origin).origin!==e.origin)return queueMicrotask(()=>s(new Error("Provider connection has no authorized pinned address"))),!0;let c=n.headers??{},l=(e.protocol==="https:"?Z3t:K3t)(new URL(n.path,e.origin),{method:n.method,headers:c,agent:!1,rejectUnauthorized:!0,lookup:(u,d,p)=>{let f={address:a,family:MVe(a)};typeof d=="object"&&d.all?p(null,[f]):p(null,a,f.family)}},u=>{i=u;let d=u.rawHeaders.map(f=>Buffer.from(f)),p=()=>u.resume();r.onHeaders(u.statusCode??500,d,p,u.statusMessage??"")===!1&&u.pause(),u.on("data",f=>{r.onData(f)||u.pause()}),u.on("end",()=>{o||(o=!0,r.onComplete(u.rawTrailers.map(f=>Buffer.from(f))))}),u.on("error",s),u.on("aborted",()=>s(new Error("Provider response was interrupted")))});return l.on("socket",u=>{u.once("connect",()=>{(!u.remoteAddress||Bie(u.remoteAddress)!==Bie(a))&&l.destroy(new Error("Provider socket did not connect to its authorized address"))})}),l.on("error",s),r.onConnect(u=>l.destroy(u??new Error("Provider request aborted"))),(async()=>{try{let u=n.body;if(typeof u=="string"||u instanceof Uint8Array)l.end(u);else{if(u)for await(let d of u){if(l.destroyed)return;l.write(d)||await e6t(l,"drain")}l.end()}}catch(u){l.destroy(u instanceof Error?u:new Error("Provider request body failed"))}})(),!0}}}var oE={connectTimeoutMs:15e3,totalTimeoutMs:12e4,idleTimeoutMs:3e4,maxResponseBytes:8*1024*1024,maxHeaderBytes:64*1024,maxEventBytes:1024*1024};function n6t(e={}){for(let[t,n]of Object.entries(e))if(n!==void 0&&(!Number.isSafeInteger(n)||n<1))throw Dn("provider-transport",`${t} must be a positive safe integer`);return{connectTimeoutMs:Math.max(100,e.connectTimeoutMs??oE.connectTimeoutMs),totalTimeoutMs:Math.max(100,e.totalTimeoutMs??oE.totalTimeoutMs),idleTimeoutMs:Math.max(100,e.idleTimeoutMs??oE.idleTimeoutMs),maxResponseBytes:Math.max(1024,e.maxResponseBytes??oE.maxResponseBytes),maxHeaderBytes:Math.max(1024,e.maxHeaderBytes??oE.maxHeaderBytes),maxEventBytes:Math.max(1024,e.maxEventBytes??oE.maxEventBytes)}}async function w_(e,t){let n,r=new Promise((i,o)=>{n=()=>o(new Error("Provider operation aborted")),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()});try{return await Promise.race([e,r])}finally{t.removeEventListener("abort",n)}}function Mj(e,t,n,r){try{return e.decode(t,{stream:n})}catch{throw Dn(r,"response is not valid UTF-8")}}function Tie(e,t,n){let r=new Cr(t==="cancelled"?"Provider request was cancelled":"Provider request timed out",{providerId:e,category:t,code:t==="cancelled"?"PROVIDER_CANCELLED":"PROVIDER_TIMEOUT",retryable:t==="timeout",...n!==void 0?{cause:n}:{}});return t==="cancelled"&&(r.name="AbortError"),r}function r6t(e){let t=0;return e.forEach((n,r)=>{t+=Buffer.byteLength(r)+Buffer.byteLength(n)+4}),t}async function zVe(e,t,n,r){if(!e.body)return"";let i=e.body.getReader(),o=new TextDecoder("utf-8",{fatal:!0}),s=0,a="",c,l=()=>{c&&clearTimeout(c),c=setTimeout(()=>r.abort("idle-timeout"),n.idleTimeoutMs)};l();try{for(;;){let{value:u,done:d}=await w_(i.read(),r.signal);if(d)break;if(l(),s+=u.byteLength,s>n.maxResponseBytes)throw Dn(t,`response exceeded ${n.maxResponseBytes} bytes`);a+=Mj(o,u,!0,t)}return a+=Mj(o,void 0,!1,t),a}finally{c&&clearTimeout(c),i.cancel().catch(()=>{}),i.releaseLock()}}async function YVe(e,t,n,r){let i=xie.now(),o=n6t(n.limits);Pj("xeno.provider.requests",1,{component:"provider_transport",provider:n.providerId,transport:"http"});let s=new AbortController,a=null,c=t.signal,l=()=>s.abort("caller");if(c?.aborted)throw Tie(n.providerId,"cancelled");c?.addEventListener("abort",l,{once:!0});let u=setTimeout(()=>{a="total",s.abort("total-timeout")},o.totalTimeoutMs),d=setTimeout(()=>{a="connect",s.abort("connect-timeout")},o.connectTimeoutMs),p;try{let f=await w_(XVe(e,n.endpointPolicy),s.signal);if(s.signal.aborted)throw new Error("Provider request aborted before dispatch");let m={...t,signal:s.signal,redirect:"manual",dispatcher:t6t(e,f)},h=fetch(e,m);h.then(w=>{s.signal.aborted&&w.body?.cancel().catch(()=>{})},()=>{});let g=await w_(h,s.signal);if(p=g,clearTimeout(d),r6t(g.headers)>o.maxHeaderBytes)throw Dn(n.providerId,`response headers exceeded ${o.maxHeaderBytes} bytes`);if(g.redirected||g.status>=300&&g.status<400)throw new Cr("Provider redirects are disabled",{providerId:n.providerId,category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED",statusCode:g.status});let A=g.headers.get("content-length");if(A&&/^\d+$/.test(A)&&Number(A)>o.maxResponseBytes)throw Dn(n.providerId,`response exceeded ${o.maxResponseBytes} bytes`);if(!g.ok){let w=await zVe(g,n.providerId,o,s),b=w;try{b=w?JSON.parse(w):{}}catch{}throw J3t({providerId:n.providerId,statusCode:g.status,body:b,retryAfterMs:W3t(g.headers.get("retry-after")),requestId:g.headers.get("request-id")??g.headers.get("x-request-id")??void 0})}let y=await w_(r(g,s,o),s.signal);return Pj("xeno.provider.request_results",1,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"success"}),_Ve("xeno.provider.request_duration_ms",xie.now()-i,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"success"}),y}catch(f){let m;throw f instanceof Cr?m=f:c?.aborted||s.signal.reason==="caller"?m=Tie(n.providerId,"cancelled",f):a||s.signal.reason==="idle-timeout"?m=Tie(n.providerId,"timeout",f):m=new Cr("Provider transport failed",{providerId:n.providerId,category:"transport",code:"PROVIDER_TRANSPORT_ERROR",retryable:!0,cause:f}),s.abort("request-failed"),p?.body&&!p.body.locked&&p.body.cancel().catch(()=>{}),Pj("xeno.provider.request_results",1,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"error",category:m.category,error_code:m.code}),_Ve("xeno.provider.request_duration_ms",xie.now()-i,{component:"provider_transport",provider:n.providerId,transport:"http",outcome:"error",category:m.category}),m}finally{clearTimeout(d),clearTimeout(u),c?.removeEventListener("abort",l)}}async function i6t(e,t,n){return YVe(e,t,n,async(r,i,o)=>{let s=await zVe(r,n.providerId,o,i),a;try{a=s?JSON.parse(s):{}}catch(c){throw Dn(n.providerId,"body is not valid JSON",c)}if(!a||typeof a!="object"||Array.isArray(a))throw Dn(n.providerId,"JSON body must be an object");return a})}async function Dj(e,t,n,r){return YVe(e,t,n,async(i,o,s)=>{if(!i.body)throw Dn(n.providerId,"stream response has no body");let a=i.body.getReader(),c=new TextDecoder("utf-8",{fatal:!0}),l="",u=0,d="message",p=[],f,m=()=>{f&&clearTimeout(f),f=setTimeout(()=>o.abort("idle-timeout"),s.idleTimeoutMs)},h=async()=>{if(p.length===0){d="message";return}let g=p.join(`
|
|
5669
5669
|
`);if(Buffer.byteLength(g)>s.maxEventBytes)throw Dn(n.providerId,`stream event exceeded ${s.maxEventBytes} bytes`);await r({event:d,data:g}),d="message",p=[]};m();try{for(;;){let{value:g,done:A}=await w_(a.read(),o.signal);if(A)break;if(m(),u+=g.byteLength,u>s.maxResponseBytes)throw Dn(n.providerId,`stream exceeded ${s.maxResponseBytes} bytes`);for(l+=Mj(c,g,!0,n.providerId);;){let y=l.indexOf(`
|
|
5670
5670
|
`);if(y<0)break;let w=l.slice(0,y).replace(/\r$/,"");if(l=l.slice(y+1),!w)await h();else if(!w.startsWith(":")){let b=w.indexOf(":"),I=b<0?w:w.slice(0,b),v=b<0?"":w.slice(b+1).replace(/^ /,"");I==="event"?d=v:I==="data"&&p.push(v)}}}if(l+=Mj(c,void 0,!1,n.providerId),l.trim())for(let g of l.split(/\r?\n/))g.startsWith("data:")?p.push(g.slice(5).replace(/^ /,"")):g.startsWith("event:")&&(d=g.slice(6).trim());await h()}finally{f&&clearTimeout(f),a.cancel().catch(()=>{}),a.releaseLock()}})}var KVe=class extends Error{issues;constructor(e){super(`Invalid JSON Schema: ${e.map(t=>`${t.path||"#"} ${t.message}`).join("; ")}`),this.name="JsonSchemaCompilationError",this.issues=e}},Mie="https://json-schema.org/draft/2020-12/schema",s6t=new Set(["string","number","integer","boolean","array","object","null"]),a6t=new Set(["$schema","$id","$anchor","$ref","$defs","$comment","title","description","default","examples","deprecated","readOnly","writeOnly","type","enum","const","multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","format","prefixItems","items","contains","minContains","maxContains","minItems","maxItems","uniqueItems","properties","patternProperties","additionalProperties","required","dependentRequired","minProperties","maxProperties","allOf","anyOf","oneOf","not"]),ZVe=new Map([["date",e=>nHe(e)],["date-time",e=>x6t(e)],["time",e=>rHe(e)],["duration",e=>/^P(?!$)(?:\d+(?:[.,]\d+)?Y)?(?:\d+(?:[.,]\d+)?M)?(?:\d+(?:[.,]\d+)?W)?(?:\d+(?:[.,]\d+)?D)?(?:T(?=\d)(?:\d+(?:[.,]\d+)?H)?(?:\d+(?:[.,]\d+)?M)?(?:\d+(?:[.,]\d+)?S)?)?$/u.test(e)],["email",e=>OVe(e)],["idn-email",e=>OVe(e)],["hostname",e=>Oie(e)],["idn-hostname",e=>Oie(e)],["ipv4",e=>NVe(e)===4],["ipv6",e=>NVe(e)===6],["uuid",e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e)],["uri",e=>DVe(e)],["iri",e=>DVe(e)],["uri-reference",e=>LVe(e)],["iri-reference",e=>LVe(e)],["uri-template",e=>R6t(e)],["json-pointer",e=>/^(?:\/(?:[^~/]|~[01])*)*$/u.test(e)],["relative-json-pointer",e=>/^(?:0|[1-9]\d*)(?:#|(?:\/(?:[^~/]|~[01])*)*)$/u.test(e)],["regex",(e,t)=>qie(e,t.maxPatternLength)!==void 0]]);function c6t(e={}){return{strictKeywords:e.strictKeywords??!0,assertFormats:e.assertFormats??!1,maxSchemaDepth:jh(e.maxSchemaDepth,64,1,256,"maxSchemaDepth"),maxSchemaNodes:jh(e.maxSchemaNodes,4096,1,1e5,"maxSchemaNodes"),maxReferences:jh(e.maxReferences,512,0,1e4,"maxReferences"),maxPatternLength:jh(e.maxPatternLength,256,1,4096,"maxPatternLength"),maxValidationDepth:jh(e.maxValidationDepth,128,1,1024,"maxValidationDepth"),maxValidationSteps:jh(e.maxValidationSteps,1e5,100,1e7,"maxValidationSteps"),maxValidationErrors:jh(e.maxValidationErrors,64,1,1024,"maxValidationErrors"),maxInputBytes:jh(e.maxInputBytes,16*1024*1024,1024,256*1024*1024,"maxInputBytes")}}function jh(e,t,n,r,i){let o=e??t;if(!Number.isInteger(o)||o<n||o>r)throw new TypeError(`${i} must be an integer from ${n} to ${r}.`);return o}function l6t(e,t={}){let n={root:e,options:c6t(t),issues:[],rawByPointer:new Map,anchors:new Map,compiledByPointer:new Map,schemaNodes:0,references:0,nextNodeId:1};_j(e,"",0,n);let r=ty(e,"",0,n);if(n.issues.length>0||!r)throw new KVe(n.issues);return Object.freeze({dialect:Mie,formatAssertion:n.options.assertFormats,validate(i){let o=[],s=Nie(i);if(s)return o.push({path:s.path,keyword:"type",schemaPath:"#",message:s.message}),{valid:!1,errors:o,steps:0,truncated:!1};let a=JSON.stringify(i),c=Buffer.byteLength(a??"null","utf8");if(c>n.options.maxInputBytes)return o.push({path:"",keyword:"maxInputBytes",schemaPath:"#",message:`input is ${c} bytes; limit is ${n.options.maxInputBytes}`}),{valid:!1,errors:o,steps:0,truncated:!1};let l={options:n.options,errors:o,budget:{steps:0,exhausted:!1},activePairs:new Set,objectIds:new WeakMap,nextObjectId:{value:1}};return gf(i,r,"",0,l),{valid:o.length===0,errors:o,steps:l.budget.steps,truncated:l.budget.exhausted||o.length>=n.options.maxValidationErrors}}})}function u6t(e,t={}){if(!vc(e)||e.type!=="object"||!vc(e.properties))throw new KVe([{path:"#",keyword:"type",message:"tool input schema root must declare type object and a properties object"}]);return l6t(e,t)}function _j(e,t,n,r){if(n>r.options.maxSchemaDepth){Ft(r,t,void 0,`schema depth exceeds ${r.options.maxSchemaDepth}`);return}if(typeof e!="boolean"&&!vc(e)){Ft(r,t,void 0,"schema must be an object or boolean");return}if(!r.rawByPointer.has(t)){if(r.schemaNodes+=1,r.schemaNodes>r.options.maxSchemaNodes){Ft(r,t,void 0,`schema node count exceeds ${r.options.maxSchemaNodes}`);return}if(r.rawByPointer.set(t,e),typeof e!="boolean"){e.$anchor!==void 0&&(typeof e.$anchor!="string"||!/^[A-Za-z][A-Za-z0-9._:-]*$/u.test(e.$anchor)?Ft(r,t,"$anchor","$anchor must be a valid plain-name anchor"):r.anchors.has(e.$anchor)?Ft(r,t,"$anchor",`duplicate anchor ${e.$anchor}`):r.anchors.set(e.$anchor,t));for(let i of["$defs","properties","patternProperties"]){let o=e[i];if(o!==void 0){if(!vc(o)){Ft(r,t,i,`${i} must be an object`);continue}for(let[s,a]of Object.entries(o))_j(a,Af(t,i,s),n+1,r)}}for(let i of["items","contains","additionalProperties","not"])e[i]!==void 0&&_j(e[i],Af(t,i),n+1,r);for(let i of["prefixItems","allOf","anyOf","oneOf"]){let o=e[i];if(o!==void 0){if(!Array.isArray(o)){Ft(r,t,i,`${i} must be an array of schemas`);continue}o.forEach((s,a)=>_j(s,Af(t,i,String(a)),n+1,r))}}}}}function ty(e,t,n,r){let i=r.compiledByPointer.get(t);if(i)return i;if(typeof e!="boolean"&&!vc(e))return;let o={id:r.nextNodeId++,schemaPath:oHe(t)};if(r.compiledByPointer.set(t,o),typeof e=="boolean")return o.boolean=e,o;if(d6t(e,t,r),p6t(e,t,r),e.$schema!==void 0&&(t!==""||e.$schema!==Mie&&e.$schema!==`${Mie}#`)&&Ft(r,t,"$schema",t===""?`unsupported dialect ${String(e.$schema)}`:"$schema is only supported at the root"),e.$id!==void 0&&typeof e.$id!="string"&&Ft(r,t,"$id","$id must be a string"),e.$ref!==void 0)if(typeof e.$ref!="string")Ft(r,t,"$ref","$ref must be a string");else{r.references+=1,r.references>r.options.maxReferences&&Ft(r,t,"$ref",`reference count exceeds ${r.options.maxReferences}`);let s=y6t(e.$ref,t,r);if(s!==void 0){let a=r.rawByPointer.get(s);a===void 0?Ft(r,t,"$ref",`unresolved local reference ${e.$ref}`):o.ref=ty(a,s,n+1,r)}}if(o.types=f6t(e.type,t,r),e.enum!==void 0){let s=e.enum;!Array.isArray(s)||s.length===0?Ft(r,t,"enum","enum must be a non-empty array"):s.some((a,c)=>s.some((l,u)=>u<c&&aE(a,l)))?Ft(r,t,"enum","enum values must be unique"):s.some(a=>Nie(a))?Ft(r,t,"enum","enum values must be JSON values"):o.enumValues=s}if(Object.prototype.hasOwnProperty.call(e,"const")&&(Nie(e.const)?Ft(r,t,"const","const must be a JSON value"):(o.hasConst=!0,o.constValue=e.const)),o.multipleOf=A6t(e.multipleOf,t,"multipleOf",r),o.maximum=A_(e.maximum,t,"maximum",r),o.exclusiveMaximum=A_(e.exclusiveMaximum,t,"exclusiveMaximum",r),o.minimum=A_(e.minimum,t,"minimum",r),o.exclusiveMinimum=A_(e.exclusiveMinimum,t,"exclusiveMinimum",r),o.maxLength=Vh(e.maxLength,t,"maxLength",r),o.minLength=Vh(e.minLength,t,"minLength",r),o.minItems=Vh(e.minItems,t,"minItems",r),o.maxItems=Vh(e.maxItems,t,"maxItems",r),o.minContains=Vh(e.minContains,t,"minContains",r),o.maxContains=Vh(e.maxContains,t,"maxContains",r),o.minProperties=Vh(e.minProperties,t,"minProperties",r),o.maxProperties=Vh(e.maxProperties,t,"maxProperties",r),w6t(o,t,r),e.pattern!==void 0)if(typeof e.pattern!="string")Ft(r,t,"pattern","pattern must be a string");else{let s=qie(e.pattern,r.options.maxPatternLength);s?o.pattern={source:e.pattern,regex:s}:Ft(r,t,"pattern","pattern is invalid or outside the safe regex subset")}if(e.format!==void 0&&(typeof e.format!="string"?Ft(r,t,"format","format must be a string"):r.options.assertFormats&&!ZVe.has(e.format)?Ft(r,t,"format",`unsupported asserted format ${e.format}`):o.format=e.format),o.prefixItems=xj(e.prefixItems,t,"prefixItems",n,r,!0),o.items=Cj(e.items,t,"items",n,r),o.contains=Cj(e.contains,t,"contains",n,r),(e.minContains!==void 0||e.maxContains!==void 0)&&e.contains===void 0&&Ft(r,t,"contains","minContains/maxContains require contains"),e.uniqueItems!==void 0&&(typeof e.uniqueItems!="boolean"?Ft(r,t,"uniqueItems","uniqueItems must be boolean"):o.uniqueItems=e.uniqueItems),o.properties=m6t(e.properties,t,"properties",n,r),o.patternProperties=h6t(e.patternProperties,t,n,r),o.additionalProperties=Cj(e.additionalProperties,t,"additionalProperties",n,r),o.required=eHe(e.required,t,"required",r,!0),o.dependentRequired=g6t(e.dependentRequired,t,r),o.allOf=xj(e.allOf,t,"allOf",n,r,!1),o.anyOf=xj(e.anyOf,t,"anyOf",n,r,!1),o.oneOf=xj(e.oneOf,t,"oneOf",n,r,!1),o.not=Cj(e.not,t,"not",n,r),vc(e.$defs))for(let[s,a]of Object.entries(e.$defs))ty(a,Af(t,"$defs",s),n+1,r);return o}function d6t(e,t,n){if(n.options.strictKeywords)for(let r of Object.keys(e))!a6t.has(r)&&!r.startsWith("x-")&&Ft(n,t,r,`unsupported keyword ${r}`)}function p6t(e,t,n){for(let r of["$comment","title","description"])e[r]!==void 0&&typeof e[r]!="string"&&Ft(n,t,r,`${r} must be a string`);for(let r of["deprecated","readOnly","writeOnly"])e[r]!==void 0&&typeof e[r]!="boolean"&&Ft(n,t,r,`${r} must be boolean`);e.examples!==void 0&&!Array.isArray(e.examples)&&Ft(n,t,"examples","examples must be an array")}function f6t(e,t,n){if(e===void 0)return;let r=Array.isArray(e)?e:[e];if(r.length===0||r.some(i=>typeof i!="string"||!s6t.has(i))){Ft(n,t,"type","type must be a recognized type or non-empty unique type array");return}return new Set(r).size!==r.length&&Ft(n,t,"type","type array must not contain duplicates"),r}function Cj(e,t,n,r,i){if(e!==void 0)return ty(e,Af(t,n),r+1,i)}function xj(e,t,n,r,i,o){if(e!==void 0){if(!Array.isArray(e)||!o&&e.length===0){Ft(i,t,n,`${n} must be ${o?"an array":"a non-empty array"} of schemas`);return}return e.map((s,a)=>ty(s,Af(t,n,String(a)),r+1,i)).filter(s=>!!s)}}function m6t(e,t,n,r,i){if(e===void 0)return;if(!vc(e)){Ft(i,t,n,`${n} must be an object of schemas`);return}let o=new Map;for(let[s,a]of Object.entries(e)){let c=ty(a,Af(t,n,s),r+1,i);c&&o.set(s,c)}return o}function h6t(e,t,n,r){if(e===void 0)return;if(!vc(e)){Ft(r,t,"patternProperties","patternProperties must be an object of schemas");return}let i=[];for(let[o,s]of Object.entries(e)){let a=qie(o,r.options.maxPatternLength);if(!a){Ft(r,t,"patternProperties",`pattern ${JSON.stringify(o)} is invalid or outside the safe regex subset`);continue}let c=ty(s,Af(t,"patternProperties",o),n+1,r);c&&i.push({pattern:{source:o,regex:a},schema:c})}return i}function g6t(e,t,n){if(e===void 0)return;if(!vc(e)){Ft(n,t,"dependentRequired","dependentRequired must be an object");return}let r=new Map;for(let[i,o]of Object.entries(e)){let s=eHe(o,Af(t,"dependentRequired",i),"dependentRequired",n,!0);s&&r.set(i,s)}return r}function eHe(e,t,n,r,i){if(e!==void 0){if(!Array.isArray(e)||e.some(o=>typeof o!="string")){Ft(r,t,n,`${n} must be an array of strings`);return}return i&&new Set(e).size!==e.length&&Ft(r,t,n,`${n} values must be unique`),e}}function A6t(e,t,n,r){let i=A_(e,t,n,r);return i!==void 0&&i<=0&&Ft(r,t,n,`${n} must be greater than zero`),i!==void 0&&i>0?i:void 0}function A_(e,t,n,r){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)){Ft(r,t,n,`${n} must be a finite number`);return}return e}}function Vh(e,t,n,r){if(e!==void 0){if(!Number.isSafeInteger(e)||e<0){Ft(r,t,n,`${n} must be a non-negative safe integer`);return}return e}}function w6t(e,t,n){for(let[r,i,o]of[[e.minLength,e.maxLength,"length"],[e.minItems,e.maxItems,"items"],[e.minContains,e.maxContains,"contains"],[e.minProperties,e.maxProperties,"properties"]])r!==void 0&&i!==void 0&&r>i&&Ft(n,t,o,`minimum ${o} exceeds maximum`)}function y6t(e,t,n){if(!e.startsWith("#")){Ft(n,t,"$ref","remote and file references are not supported");return}if(e==="#")return"";if(e.startsWith("#/")){let o=`/${e.slice(2).split("/").map(s=>s.replace(/~1/g,"/").replace(/~0/g,"~")).map(iHe).join("/")}`;return n.rawByPointer.has(o)||Ft(n,t,"$ref",`unresolved JSON Pointer ${e}`),o}let r=e.slice(1),i=n.anchors.get(r);return i===void 0&&Ft(n,t,"$ref",`unresolved anchor ${e}`),i}function gf(e,t,n,r,i){if(!tHe(i)||i.errors.length>=i.options.maxValidationErrors)return;if(r>i.options.maxValidationDepth){gr(i,n,"maxDepth",t,`validation depth exceeds ${i.options.maxValidationDepth}`);return}if(t.boolean!==void 0){t.boolean||gr(i,n,"falseSchema",t,"is rejected by the false schema");return}let o=S6t(t,e,i);if(!i.activePairs.has(o)){i.activePairs.add(o);try{if(t.ref&&gf(e,t.ref,n,r+1,i),t.enumValues&&!t.enumValues.some(s=>aE(s,e))&&gr(i,n,"enum",t,`expected one of ${t.enumValues.map(Die).join(", ")} but got ${Pie(e)}`),t.hasConst&&!aE(t.constValue,e)&&gr(i,n,"const",t,`expected ${Die(t.constValue)} but got ${Pie(e)}`),t.types&&!t.types.some(s=>C6t(e,s))){let s=t.types.length===1?t.types[0]:`one of [${t.types.join(", ")}]`;gr(i,n,"type",t,`expected type ${s} but got ${Pie(e)}`);return}b6t(e,t,n,r,i),typeof e=="number"&&v6t(e,t,n,i),typeof e=="string"&&I6t(e,t,n,i),Array.isArray(e)&&k6t(e,t,n,r,i),vc(e)&&E6t(e,t,n,r,i)}finally{i.activePairs.delete(o)}}}function b6t(e,t,n,r,i){for(let o of t.allOf??[])gf(e,o,n,r+1,i);if(t.anyOf&&t.anyOf.filter(o=>$j(e,o,n,r+1,i)).length===0&&gr(i,n,"anyOf",t,"must match at least one anyOf branch"),t.oneOf){let o=t.oneOf.filter(s=>$j(e,s,n,r+1,i)).length;o!==1&&gr(i,n,"oneOf",t,`must match exactly one oneOf branch; matched ${o}`)}t.not&&$j(e,t.not,n,r+1,i)&&gr(i,n,"not",t,"must not match the disallowed schema")}function v6t(e,t,n,r){t.multipleOf!==void 0&&!T6t(e,t.multipleOf)&&gr(r,n,"multipleOf",t,`must be a multiple of ${t.multipleOf}`),t.maximum!==void 0&&e>t.maximum&&gr(r,n,"maximum",t,`must be <= ${t.maximum}`),t.exclusiveMaximum!==void 0&&e>=t.exclusiveMaximum&&gr(r,n,"exclusiveMaximum",t,`must be < ${t.exclusiveMaximum}`),t.minimum!==void 0&&e<t.minimum&&gr(r,n,"minimum",t,`must be >= ${t.minimum}`),t.exclusiveMinimum!==void 0&&e<=t.exclusiveMinimum&&gr(r,n,"exclusiveMinimum",t,`must be > ${t.exclusiveMinimum}`)}function I6t(e,t,n,r){let i=[...e].length;if(t.minLength!==void 0&&i<t.minLength&&gr(r,n,"minLength",t,`must contain at least ${t.minLength} Unicode code points`),t.maxLength!==void 0&&i>t.maxLength&&gr(r,n,"maxLength",t,`must contain at most ${t.maxLength} Unicode code points`),t.pattern&&!t.pattern.regex.test(e)&&gr(r,n,"pattern",t,`must match pattern ${JSON.stringify(t.pattern.source)}`),t.format&&r.options.assertFormats){let o=ZVe.get(t.format);o&&!o(e,r.options)&&gr(r,n,"format",t,`must match format ${t.format}`)}}function k6t(e,t,n,r,i){if(t.minItems!==void 0&&e.length<t.minItems&&gr(i,n,"minItems",t,`must contain at least ${t.minItems} items`),t.maxItems!==void 0&&e.length>t.maxItems&&gr(i,n,"maxItems",t,`must contain at most ${t.maxItems} items`),t.uniqueItems)e:for(let s=0;s<e.length;s+=1)for(let a=0;a<s;a+=1){if(!tHe(i))break e;if(aE(e[s],e[a])){gr(i,_d(n,String(s)),"uniqueItems",t,`duplicates item ${a}`);break e}}let o=t.prefixItems?.length??0;if(t.prefixItems?.forEach((s,a)=>{a<e.length&&gf(e[a],s,_d(n,String(a)),r+1,i)}),t.items)for(let s=o;s<e.length;s+=1)gf(e[s],t.items,_d(n,String(s)),r+1,i);if(t.contains){let s=0;for(let c=0;c<e.length;c+=1)$j(e[c],t.contains,_d(n,String(c)),r+1,i)&&(s+=1);let a=t.minContains??1;s<a&&gr(i,n,"minContains",t,`contains matched ${s} items; minimum is ${a}`),t.maxContains!==void 0&&s>t.maxContains&&gr(i,n,"maxContains",t,`contains matched ${s} items; maximum is ${t.maxContains}`)}}function E6t(e,t,n,r,i){let o=Object.keys(e);t.minProperties!==void 0&&o.length<t.minProperties&&gr(i,n,"minProperties",t,`must contain at least ${t.minProperties} properties`),t.maxProperties!==void 0&&o.length>t.maxProperties&&gr(i,n,"maxProperties",t,`must contain at most ${t.maxProperties} properties`);for(let s of t.required??[])Object.prototype.hasOwnProperty.call(e,s)||gr(i,_d(n,s),"required",t,"is required");for(let[s,a]of t.dependentRequired??[])if(Object.prototype.hasOwnProperty.call(e,s))for(let c of a)Object.prototype.hasOwnProperty.call(e,c)||gr(i,_d(n,c),"dependentRequired",t,`is required when ${s} is present`);for(let s of o){let a=!1,c=t.properties?.get(s);c&&(a=!0,gf(e[s],c,_d(n,s),r+1,i));for(let l of t.patternProperties??[])l.pattern.regex.test(s)&&(a=!0,gf(e[s],l.schema,_d(n,s),r+1,i));!a&&t.additionalProperties&&gf(e[s],t.additionalProperties,_d(n,s),r+1,i)}}function $j(e,t,n,r,i){let o={...i,errors:[],activePairs:new Set(i.activePairs)};return gf(e,t,n,r,o),o.errors.length===0&&!o.budget.exhausted}function tHe(e){return e.budget.steps+=1,e.budget.steps<=e.options.maxValidationSteps?!0:(e.budget.exhausted||(e.budget.exhausted=!0,gr(e,"","maxValidationSteps",{schemaPath:"#"},`validation steps exceed ${e.options.maxValidationSteps}`)),!1)}function gr(e,t,n,r,i){e.errors.length>=e.options.maxValidationErrors||e.errors.push({path:t,keyword:n,schemaPath:r.schemaPath,message:i})}function S6t(e,t,n){if(t!==null&&typeof t=="object"){let r=n.objectIds.get(t);return r===void 0&&(r=n.nextObjectId.value++,n.objectIds.set(t,r)),`${e.id}:object:${r}`}return`${e.id}:${typeof t}:${Die(t)}`}function C6t(e,t){switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"integer":return typeof e=="number"&&Number.isSafeInteger(e);case"boolean":return typeof e=="boolean";case"array":return Array.isArray(e);case"object":return vc(e);case"null":return e===null}}function Nie(e){let t=new WeakSet,n=(r,i)=>{if(r===null||typeof r=="string"||typeof r=="boolean")return;if(typeof r=="number")return Number.isFinite(r)?void 0:{path:i,message:"must be a finite JSON number"};if(typeof r!="object")return{path:i,message:`must be a JSON value, not ${typeof r}`};if(t.has(r))return{path:i,message:"must not contain cyclic references"};t.add(r);let o=Array.isArray(r)?r.entries():Object.entries(r);for(let[s,a]of o){let c=n(a,_d(i,String(s)));if(c)return c}t.delete(r)};return n(e,"")}function qie(e,t){if(!([...e].length>t)&&!/\\(?:[1-9]|k<)/u.test(e)&&!/\(\?<(?:[=!]|[A-Za-z])/u.test(e)&&!/\((?:[^()\\]|\\.)*[+*{](?:[^()\\]|\\.)*\)[+*{?]/u.test(e))try{return new RegExp(e,"u")}catch{return}}function nHe(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/u.exec(e);if(!t)return!1;let n=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3])));return n.getUTCFullYear()===Number(t[1])&&n.getUTCMonth()===Number(t[2])-1&&n.getUTCDate()===Number(t[3])}function rHe(e){let t=/^(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u.exec(e);return t?Number(t[1])<=23&&Number(t[2])<=59&&Number(t[3])<=60:!1}function x6t(e){let t=/^([^Tt ]+)[Tt ](.+)$/u.exec(e);return!!(t&&nHe(t[1])&&rHe(t[2]))}function OVe(e){if([...e].length>254||/[\s<>(),;:\\"\[\]]/u.test(e))return!1;let t=e.lastIndexOf("@");return t>0&&t<e.length-1&&[...e.slice(0,t)].length<=64&&Oie(e.slice(t+1))}function Oie(e){if([...e].length>253)return!1;let t=e.endsWith(".")?e.slice(0,-1):e;return t.length>0&&t.split(".").every(n=>n.length>0&&n.length<=63&&!n.startsWith("-")&&!n.endsWith("-")&&/^[\p{L}\p{N}-]+$/u.test(n))}function DVe(e){try{return!!(new URL(e).protocol&&!/\s/u.test(e))}catch{return!1}}function LVe(e){try{return new URL(e,"https://xeno.invalid/"),!/\s/u.test(e)}catch{return!1}}function R6t(e){let t=0;for(let n of e)if(n==="{"&&(t+=1),n==="}"&&(t-=1),t<0||t>1)return!1;return t===0&&![...e].some(n=>{let r=n.codePointAt(0);return r<=31||r===127})}function T6t(e,t){let n=e/t;return Math.abs(n-Math.round(n))<=Number.EPSILON*Math.max(1,Math.abs(n))*8}function vc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aE(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>aE(n,t[r]));if(vc(e)&&vc(t)){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(i=>Object.prototype.hasOwnProperty.call(t,i)&&aE(e[i],t[i]))}return!1}function _d(e,t){let n=/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(t)?t:`[${JSON.stringify(t)}]`;return e.length===0?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function Af(e,...t){return`${e}/${t.map(iHe).join("/")}`}function iHe(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function oHe(e){return e.length===0?"#":`#${e}`}function Ft(e,t,n,r){e.issues.length>=64||e.issues.push({path:oHe(t),...n?{keyword:n}:{},message:r})}function Pie(e){return e===null?"null":Array.isArray(e)?"array":typeof e=="number"?Number.isSafeInteger(e)?"integer":"number":typeof e}function Die(e){try{let t=JSON.stringify(e);return t===void 0?String(e):t}catch{return String(e)}}var Oa=class extends Error{dialect;path;constructor(e,t,n){super(`Tool schema cannot be projected to ${e} at ${t}: ${n}`),this.name="ToolSchemaProjectionError",this.dialect=e,this.path=t}},QVe=new Set(["$schema","$id","$anchor","$defs","$comment","title","default","examples","deprecated","readOnly","writeOnly"]),P6t=new Set(["type","description","enum","format","properties","required","items","minItems","maxItems","minLength","maxLength","minimum","maximum","anyOf"]);function _6t(e,t){u6t(e);let n=Qie(e),r=n,i=FVe(n);if(t==="xeno")return{schema:n,dialect:t,canonicalSha256:i,projectedSha256:i,changes:[]};let o={dialect:t,root:r,pointers:new Map,anchors:new Map,changes:[],activeReferences:new Set};Bj(r,"",o);let s=Zw(r,"#",o);if(!cE(s))throw new Oa(t,"#","provider tool root must remain an object schema");return B6t(n,s,t),{schema:s,dialect:t,canonicalSha256:i,projectedSha256:FVe(s),changes:o.changes}}function $6t(e,t){return e.map(n=>{let r=_6t(n.input_schema,t);return{definition:{...n,input_schema:r.schema},projection:r}})}function Zw(e,t,n){if(typeof e=="boolean"){if(n.dialect!=="google")return e;if(e)return{};throw new Oa(n.dialect,t,"false schemas are not representable by this provider")}if(typeof e.$ref=="string"){let i=M6t(e.$ref,t,n);if(n.activeReferences.has(e.$ref))throw new Oa(n.dialect,t,`recursive reference ${e.$ref} cannot be serialized safely`);let o=Object.fromEntries(Object.entries(e).filter(([a])=>a!=="$ref"&&!QVe.has(a)));if(Object.keys(o).length>0){if(n.dialect==="google")throw new Oa(n.dialect,t,"$ref siblings require an unsupported intersection");n.activeReferences.add(e.$ref);let a=Zw(i,`${t}/$ref`,n);n.activeReferences.delete(e.$ref);let c=Zw(o,t,n);return n.changes.push({path:t,keyword:"$ref",action:"transformed",reason:"inlined local reference with sibling intersection"}),{allOf:[a,c]}}n.activeReferences.add(e.$ref);let s=Zw(i,`${t}/$ref`,n);return n.activeReferences.delete(e.$ref),n.changes.push({path:t,keyword:"$ref",action:"transformed",reason:"inlined local reference"}),s}let r={};for(let[i,o]of Object.entries(e))if(i!=="$ref"){if(QVe.has(i)||i.startsWith("x-")){i==="description"?r.description=o:n.changes.push({path:t,keyword:i,action:"omitted",reason:"provider wire metadata is not required for canonical validation"});continue}if(n.dialect==="google"&&!P6t.has(i)){if(i==="const"){r.enum=[Qie(o)],n.changes.push({path:t,keyword:i,action:"transformed",reason:"Google wire schema represents const as a single-value enum"});continue}if(i==="prefixItems")throw new Oa(n.dialect,t,"tuple prefixItems cannot preserve the provider structural contract");n.changes.push({path:t,keyword:i,action:"omitted",reason:"constraint remains enforced by canonical local validation"});continue}if(i==="type"&&n.dialect==="google"&&Array.isArray(o)){let s=o.filter(a=>a!=="null");if(s.length!==1||o.length!==2)throw new Oa(n.dialect,t,"type union cannot be represented without weakening structure");r.type=s[0],r.nullable=!0,n.changes.push({path:t,keyword:i,action:"transformed",reason:"nullable two-type union mapped to Google nullable"});continue}if(i==="properties"||i==="patternProperties"||i==="$defs"){if(!cE(o))throw new Oa(n.dialect,t,`${i} must be an object`);let s={};for(let[a,c]of Object.entries(o))s[a]=Zw(c,`${t}/${i}/${jie(a)}`,n);r[i]=s;continue}if(["items","contains","additionalProperties","not"].includes(i)){r[i]=Zw(o,`${t}/${i}`,n);continue}if(["prefixItems","allOf","anyOf","oneOf"].includes(i)){if(!Array.isArray(o))throw new Oa(n.dialect,t,`${i} must be an array`);r[i]=o.map((s,a)=>Zw(s,`${t}/${i}/${a}`,n));continue}r[i]=Qie(o)}if(n.dialect==="google"){let i=e.type!==void 0||e.properties!==void 0||e.items!==void 0,o=r.type!==void 0||r.properties!==void 0||r.items!==void 0;if(!i&&(e.oneOf!==void 0||e.allOf!==void 0||e.not!==void 0)||i&&!o)throw new Oa(n.dialect,t,"minimum structural contract cannot be represented")}return r}function B6t(e,t,n){if(t.type!=="object"||!cE(t.properties))throw new Oa(n,"#","root object/properties contract changed");let r=Object.keys(e.properties).sort(),i=Object.keys(t.properties).sort();if(JSON.stringify(r)!==JSON.stringify(i))throw new Oa(n,"#","root property identity changed");let o=[...e.required??[]].sort(),s=Array.isArray(t.required)?[...t.required].sort():[];if(JSON.stringify(o)!==JSON.stringify(s))throw new Oa(n,"#","root required-property contract changed")}function Bj(e,t,n){if(n.pointers.set(t,e),typeof e!="boolean"){typeof e.$anchor=="string"&&n.anchors.set(e.$anchor,e);for(let r of["$defs","properties","patternProperties"]){let i=e[r];if(cE(i))for(let[o,s]of Object.entries(i))Bj(s,`${t}/${r}/${jie(o)}`,n)}for(let r of["items","contains","additionalProperties","not"]){let i=e[r];(typeof i=="boolean"||cE(i))&&Bj(i,`${t}/${r}`,n)}for(let r of["prefixItems","allOf","anyOf","oneOf"]){let i=e[r];Array.isArray(i)&&i.forEach((o,s)=>Bj(o,`${t}/${r}/${s}`,n))}}}function M6t(e,t,n){if(!e.startsWith("#"))throw new Oa(n.dialect,t,"remote references are forbidden");if(e==="#")return n.root;if(e.startsWith("#/")){let r=e.slice(1).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~")).map(jie).join("/"),i=n.pointers.get(r);if(i!==void 0)return i}else{let r=n.anchors.get(e.slice(1));if(r!==void 0)return r}throw new Oa(n.dialect,t,`unresolved reference ${e}`)}function FVe(e){return o6t("sha256").update(Lie(e)).digest("hex")}function Lie(e){return Array.isArray(e)?`[${e.map(Lie).join(",")}]`:cE(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Lie(e[t])}`).join(",")}}`:JSON.stringify(e)}function Qie(e){return JSON.parse(JSON.stringify(e))}function jie(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function cE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var N6t={anthropic:{streaming:!1,textInput:!0,imageInput:!0,tools:!0,parallelToolCalls:!0,structuredOutput:!1,reasoningMetadata:!1,usageAccounting:!0,cancellation:!0,retryAfter:!0,promptCaching:!1},"openai-responses":{streaming:!1,textInput:!0,imageInput:!0,tools:!0,parallelToolCalls:!0,structuredOutput:!1,reasoningMetadata:!1,usageAccounting:!0,cancellation:!0,retryAfter:!0,promptCaching:!1},google:{streaming:!1,textInput:!0,imageInput:!0,tools:!0,parallelToolCalls:!0,structuredOutput:!1,reasoningMetadata:!1,usageAccounting:!0,cancellation:!0,retryAfter:!0,promptCaching:!1}};function O6t(e){let t=e.kind==="anthropic"?"https://api.anthropic.com":e.kind==="google"?"https://generativelanguage.googleapis.com":e.kind==="openai-responses"?"https://api.openai.com":null;if(!e.baseURL&&!t)throw new Cr("Generic OpenAI-compatible providers require baseURL",{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"});let n=Uie(e.baseURL??t,{profile:e.endpointProfile,allowedHosts:e.allowedHosts,resolveHostname:e.resolveHostname});return n.pathname=n.pathname.replace(/\/$/,""),n}function Rj(e,t){let n=new URL(e.toString());return n.pathname=`${n.pathname.replace(/\/$/,"")}/${t.replace(/^\//,"")}`,n}function D6t(e){let t=e.authentication??{type:"bearer"};if(t.type==="none"||!e.apiKey)return{};if(t.type==="bearer")return{authorization:`Bearer ${e.apiKey}`};let n=t.header.trim().toLowerCase(),r=new Set(["host","content-length","connection","transfer-encoding","cookie","set-cookie","proxy-authorization"]);if(!/^[a-z0-9-]{1,80}$/.test(n)||r.has(n))throw new Cr("Generic provider authentication header is invalid",{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"});let i=t.prefix??"";if(/[\r\n]/.test(i))throw new Cr("Generic provider authentication prefix is invalid",{category:"endpoint_policy",code:"PROVIDER_ENDPOINT_REJECTED"});return{[n]:`${i}${e.apiKey}`}}function L6t(e){let t;if(e.kind==="openai-compatible"){if(!e.capabilityProfile)throw new Cr("Generic OpenAI-compatible providers require an explicit capabilityProfile",{category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"});t={...e.capabilityProfile};for(let n of["structuredOutput","promptCaching"])if(t[n])throw $ie("direct-openai-compatible",n);if(!!e.streaming!=!!t.streaming)throw new Cr("Generic endpoint streaming config must match capabilityProfile.streaming",{category:"unsupported_capability",code:"PROVIDER_CAPABILITY_UNSUPPORTED"})}else t={...N6t[e.kind],streaming:!!e.streaming,reasoningMetadata:e.kind==="anthropic"&&!!e.streaming};return{...t,vision:t.imageInput}}function Lj(e,t){return{providerId:t,endpointPolicy:{profile:e.endpointProfile,allowedHosts:e.allowedHosts,resolveHostname:e.resolveHostname},limits:e.transportLimits}}function sHe(e){let t=/^data:([^;,]+);base64,([a-z0-9+/=\r\n]+)$/i.exec(e);return t?{mediaType:t[1],data:t[2].replace(/\s/g,"")}:null}function y_(e){let t=Array.isArray(e.assistant_content)?e.assistant_content:[],n=Array.isArray(e.assistant_only_content)?e.assistant_only_content:[];return[...t,...n].filter(r=>r?.type==="image_url")}function aHe(e){return e.filter(t=>t?.type==="image_url")}function Q6t(e){return e.some(t=>Array.isArray(t.content)&&t.content.some(n=>n.type==="image_url"||n.type==="tool_result"&&y_(n).length>0))}function UVe(e){let t=sHe(e.image_url.url);return t?{type:"image",source:{type:"base64",media_type:t.mediaType,data:t.data}}:{type:"image",source:{type:"url",url:e.image_url.url}}}function F6t(e){return e.map(t=>({role:t.role,content:typeof t.content=="string"?t.content:t.content.flatMap(n=>{if(n.type==="image_url")return[UVe(n)];if(n.type==="text")return[n];if(n.type==="tool_use")return[{type:"tool_use",id:n.id,name:n.name,input:n.input}];let r=y_(n),i=[{type:"text",text:Nj(n.content)}];return i.push(...r.map(UVe)),[{type:"tool_result",tool_use_id:n.tool_use_id,content:i,is_error:n.is_error}]})}))}function U6t(e){return{type:"input_image",image_url:e.image_url.url,detail:e.image_url.detail??"auto"}}function q6t(e){let t=[];for(let n of e){if(typeof n.content=="string"){t.push({role:n.role,content:n.content});continue}let r=n.content.filter(o=>o.type==="text").map(o=>o.text).join(`
|
|
5671
5671
|
`),i=[...aHe(n.content),...n.content.flatMap(o=>o.type==="tool_result"?y_(o):[])];(r||i.length)&&t.push({role:n.role,content:[...r?[{type:"input_text",text:r}]:[],...i.map(U6t)]});for(let o of n.content)o.type==="tool_use"?t.push({type:"function_call",call_id:o.id,name:o.name,arguments:JSON.stringify(o.input)}):o.type==="tool_result"&&t.push({type:"function_call_output",call_id:o.tool_use_id,output:Nj(o.content)})}return t}function qVe(e){let t=sHe(e.image_url.url);return t?{inlineData:{mimeType:t.mediaType,data:t.data}}:{fileData:{fileUri:e.image_url.url}}}function j6t(e){let t=new Map;for(let n of e)if(Array.isArray(n.content))for(let r of n.content)r.type==="tool_use"&&t.set(r.id,r.name);return e.map(n=>typeof n.content=="string"?{role:n.role==="assistant"?"model":"user",parts:[{text:n.content}]}:{role:n.role==="assistant"?"model":"user",parts:n.content.flatMap(r=>{if(r.type==="image_url")return[qVe(r)];if(r.type==="text")return[{text:r.text}];if(r.type==="tool_use")return[{functionCall:{id:r.id,name:r.name,args:r.input},...r.provider_metadata?.thoughtSignature?{thoughtSignature:r.provider_metadata.thoughtSignature}:{}}];let i=Nj(r.content);return[{functionResponse:{id:r.tool_use_id,name:t.get(r.tool_use_id)??"unknown_tool",response:r.is_error?{error:i}:{result:i}}},...y_(r).map(qVe)]})})}function V6t(e,t){let n=t?[{role:"system",content:t}]:[];for(let r of e){if(typeof r.content=="string"){n.push({role:r.role,content:r.content});continue}let i=r.content.filter(a=>a.type==="text").map(a=>a.text).join(`
|