@xenosystem/agent-sdk 0.10.37 → 0.10.39
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/artifacts/index.cjs +9 -9
- package/dist/artifacts/index.js +9 -9
- package/dist/artifacts/metafile-cjs.json +1 -1
- package/dist/artifacts/metafile-esm.json +1 -1
- package/dist/automation/index.cjs +8 -8
- package/dist/automation/index.d.cts +10 -0
- package/dist/automation/index.d.ts +10 -0
- package/dist/automation/index.js +9 -9
- package/dist/automation/metafile-cjs.json +1 -1
- package/dist/automation/metafile-esm.json +1 -1
- package/dist/control-plane/index.cjs +1 -1
- package/dist/control-plane/index.js +1 -1
- package/dist/electron/index.cjs +221 -200
- package/dist/electron/index.d.cts +91 -1
- package/dist/electron/index.d.ts +91 -1
- package/dist/electron/index.js +221 -200
- package/dist/electron/metafile-cjs.json +1 -1
- package/dist/electron/metafile-esm.json +1 -1
- package/dist/index.cjs +397 -372
- package/dist/index.d.cts +136 -4
- package/dist/index.d.ts +136 -4
- package/dist/index.js +397 -372
- package/dist/intelligence/index.cjs +9 -9
- package/dist/intelligence/index.js +9 -9
- package/dist/intelligence/metafile-cjs.json +1 -1
- package/dist/intelligence/metafile-esm.json +1 -1
- package/dist/mcp/index.d.cts +10 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/providers/index.cjs +9 -9
- package/dist/providers/index.js +9 -9
- package/dist/providers/metafile-cjs.json +1 -1
- package/dist/providers/metafile-esm.json +1 -1
- package/dist/recipes/index.cjs +2 -2
- package/dist/recipes/index.js +2 -2
- package/dist/recipes/metafile-cjs.json +1 -1
- package/dist/recipes/metafile-esm.json +1 -1
- package/dist/research/index.cjs +3 -3
- package/dist/research/index.js +3 -3
- package/dist/research/metafile-cjs.json +1 -1
- package/dist/research/metafile-esm.json +1 -1
- package/dist/session/index.cjs +25 -25
- package/dist/session/index.js +25 -25
- package/dist/session/metafile-cjs.json +1 -1
- package/dist/session/metafile-esm.json +1 -1
- package/dist/sharing/index.cjs +4 -4
- package/dist/sharing/index.js +4 -4
- package/dist/sharing/metafile-cjs.json +1 -1
- package/dist/sharing/metafile-esm.json +1 -1
- package/dist/utils/index.cjs +23 -23
- package/dist/utils/index.d.cts +15 -1
- package/dist/utils/index.d.ts +15 -1
- package/dist/utils/index.js +23 -23
- package/dist/utils/metafile-cjs.json +1 -1
- package/dist/utils/metafile-esm.json +1 -1
- package/package.json +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Hn=Object.create;var Ve=Object.defineProperty;var Gn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Wn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var Jn=(e,t)=>{for(var r in t)Ve(e,r,{get:t[r],enumerable:!0})},ur=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of zn(t))!qn.call(e,o)&&o!==r&&Ve(e,o,{get:()=>t[o],enumerable:!(n=Gn(t,o))||n.enumerable});return e};var pr=(e,t,r)=>(r=e!=null?Hn(Wn(e)):{},ur(t||!e||!e.__esModule?Ve(r,"default",{value:e,enumerable:!0}):r,e)),Kn=e=>ur(Ve({},"__esModule",{value:!0}),e);var Ma={};Jn(Ma,{CliGovernedAutomationRuntime:()=>lt,SqliteAutomationExecutionJournal:()=>rt,XENO_AUTOMATION_OPERATIONS:()=>se,XENO_AUTOMATION_PROTOCOL_VERSION:()=>te,XENO_BROWSER_CONTROL_PLANE_OPERATIONS:()=>bi,XenoAutomationError:()=>d,XenoBrowserControlPlaneAdapter:()=>Te,XenoGovernedAutomationExecutor:()=>$e,XenoHostGovernedAutomationRuntime:()=>lt,XenoLoopbackAutomationAdapter:()=>Fe,assertRequiredXenoAutomationEvidence:()=>Be,assertValidXenoAutomationAdapterManifest:()=>V,assertValidXenoAutomationRequest:()=>J,assertXenoAutomationAdapterConformant:()=>pi,assertXenoAutomationAdapterRequirements:()=>We,assertXenoAutomationAuthority:()=>qe,buildXenoAutomationCapabilityUse:()=>Ot,createCliAutomationAuditSink:()=>Ea,createCliGovernedAutomationRuntime:()=>ba,createXenoAutomationConformanceReport:()=>ln,createXenoGovernedAutomationTools:()=>rr,createXenoHostAutomationAuditSink:()=>Ea,createXenoHostGovernedAutomationRuntime:()=>ba,describeXenoAutomationOperation:()=>X,inspectCliAutomationStatus:()=>va,inspectXenoHostAutomationStatus:()=>va,isXenoAutomationOperation:()=>je,materializeXenoAutomationEvidence:()=>Ze,openSqliteAutomationExecutionJournal:()=>ui,pending:()=>Y,persistXenoAutomationEvidence:()=>Ee,readCliAutomationEnvironment:()=>cr,readXenoHostAutomationEnvironment:()=>cr,renderCliAutomationStatus:()=>La,renderXenoHostAutomationStatus:()=>La,resolveXenoAutomationEvidencePolicy:()=>_t,runDurableAutomation:()=>Ut});module.exports=Kn(Ma);var te=1;var ft=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"]),mt=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"]),gt=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),ht=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),se=[...ft,...mt,...gt,...ht];function X(e){if(ft.has(e))return{operation:e,surface:"browser",effect:"observe",evidence:{before:"disabled",after:e==="browser.wait"||e==="browser.tabs.list"?"optional":"required",recording:"optional"}};if(mt.has(e)){let t=e==="browser.record.start"||e==="browser.record.stop";return{operation:e,surface:"browser",effect:"act",evidence:{before:"required",after:"required",recording:e==="browser.record.stop"?"required":"optional"}}}if(gt.has(e))return{operation:e,surface:"computer",effect:"observe",evidence:{before:"disabled",after:e==="computer.wait"?"optional":"required",recording:"optional"}};if(ht.has(e))return{operation:e,surface:"computer",effect:"act",evidence:{before:"required",after:"required",recording:"optional"}};throw new TypeError(`Unsupported XENO automation operation: ${e}`)}function je(e){return ft.has(e)||mt.has(e)||gt.has(e)||ht.has(e)}var d=class extends Error{constructor(r,n,o,i){super(n,i);this.code=r;this.detail=o;this.name="XenoAutomationError"}code;detail};var kr=require("node:crypto"),Xr=require("node:os");var Re=require("node:fs"),M=require("node:path"),Yn=/^(?:con|prn|aux|nul|clock\$|com[1-9]|lpt[1-9])(?:\..*)?$/i;function Zn(e){return e.replace(/\//g,"\\")}function Qn(e){let t=[],r=Zn(e),n=r.toLowerCase();if(r.startsWith("\\\\?\\")||r.startsWith("\\\\.\\")||r.startsWith("\\??\\"))return t.push({code:"DEVICE_PATH",message:"Extended-length, NT, and Windows device paths are not accepted at security boundaries."}),t;if(r.startsWith("\\\\"))return t.push({code:"UNC_PATH",message:"UNC paths are not accepted at security boundaries."}),t;/^[a-z]:($|[^\\])/i.test(r)?t.push({code:"DRIVE_RELATIVE_PATH",message:"Drive-relative Windows paths are ambiguous and are not accepted."}):/^\\(?!\\)/.test(r)&&t.push({code:"ROOT_RELATIVE_PATH",message:"Root-relative Windows paths are ambiguous and are not accepted."});let o=/^[a-z]:/i.test(r)?2:0;r.slice(o).includes(":")&&t.push({code:"ALTERNATE_DATA_STREAM",message:"Windows alternate data stream paths are not accepted."});for(let i of r.split("\\"))!i||i==="."||i===".."||/^[a-z]:$/i.test(i)||((i.endsWith(".")||i.endsWith(" "))&&t.push({code:"NON_CANONICAL_SEGMENT",message:`Windows path segment has an ambiguous trailing character: ${i}`}),Yn.test(i)&&t.push({code:"RESERVED_DEVICE_NAME",message:`Windows reserved device name is not accepted: ${i}`}));return(n.includes("\\globalroot\\")||n.includes("\\device\\"))&&t.push({code:"DEVICE_PATH",message:"Windows object-manager device paths are not accepted."}),t}function eo(e,t=process.platform){return e.length===0?[{code:"EMPTY_PATH",message:"Empty paths are not accepted."}]:e.includes("\0")?[{code:"NUL_BYTE",message:"Paths containing NUL bytes are not accepted."}]:t==="win32"||/^[a-z]:/i.test(e)||e.startsWith("\\")?Qn(e):[]}function to(e){let r=(0,M.resolve)(e),n=[];for(;!(0,Re.existsSync)(r);){let i=(0,M.dirname)(r);if(i===r)break;n.unshift(r.slice(i.length).replace(/^[/\\]+/,"")),r=i}let o=(0,Re.existsSync)(r)?Re.realpathSync.native(r):r;return{canonicalPath:n.reduce((i,a)=>(0,M.join)(i,a),o),existingAncestor:o}}function ce(e,t){let r=t?.platform??process.platform,n=eo(e,r);if(n.length>0){let a=new Error(`${n[0].code}: ${n[0].message}`);throw a.name="SecurityPathError",a}let o=(0,M.isAbsolute)(e)?(0,M.resolve)(e):(0,M.resolve)(t?.baseDirectory??process.cwd(),e),i=to(o);return{input:e,absolutePath:o,...i}}function fr(e){let t=(0,M.resolve)(e);return process.platform==="win32"?t.toLowerCase():t}function mr(e,t){let r;try{r=fr(ce(e).canonicalPath)}catch{return!1}for(let n of t){let o;try{o=fr(ce(n).canonicalPath)}catch{continue}if(r===o||r.startsWith(o+M.sep))return!0}return!1}var de=require("node:fs");var At=require("node:path"),ja=String.raw`
|
|
2
2
|
using System;
|
|
3
3
|
using System.ComponentModel;
|
|
4
4
|
using System.Runtime.InteropServices;
|
|
@@ -907,7 +907,7 @@ namespace Xeno.Security
|
|
|
907
907
|
}
|
|
908
908
|
}
|
|
909
909
|
}
|
|
910
|
-
`,
|
|
910
|
+
`,Ha=String.raw`
|
|
911
911
|
public static class Program
|
|
912
912
|
{
|
|
913
913
|
private static string Decode(string name)
|
|
@@ -933,11 +933,11 @@ public static class Program
|
|
|
933
933
|
return Xeno.Security.RestrictedProcessLauncher.Run(command, cwd, lowIntegrity, restrictedToken, tokenProbe);
|
|
934
934
|
}
|
|
935
935
|
}
|
|
936
|
-
`;function mr(){let e=process.env.SystemRoot??process.env.WINDIR;if(e){let t=(0,At.join)(e,"Microsoft.NET","Framework64","v4.0.30319","csc.exe");if((0,de.existsSync)(t))return t;let r=(0,At.join)(e,"Microsoft.NET","Framework","v4.0.30319","csc.exe");if((0,de.existsSync)(r))return r}return null}var It=require("node:child_process"),j=require("node:fs"),re=require("node:path"),Ar="XENO_BWRAP_PROFILE_OK",gr=5e3,yt;function hr(e){try{return!(0,j.existsSync)(e)||!(0,j.statSync)(e).isFile()?null:((0,j.accessSync)(e,j.constants.X_OK),(0,j.realpathSync)(e))}catch{return null}}function Qn(){let e=process.env.XENO_BWRAP_PATH?.trim();if(e)return hr((0,re.isAbsolute)(e)?e:(0,re.resolve)(e));let t=["/usr/bin/bwrap","/bin/bwrap",...(process.env.PATH??"").split(re.delimiter).filter(Boolean).map(r=>(0,re.join)(r,"bwrap"))];for(let r of new Set(t)){let n=hr(r);if(n)return n}return null}function eo(){return["--die-with-parent","--new-session","--unshare-user","--unshare-pid","--unshare-uts","--unshare-ipc","--ro-bind","/","/","--proc","/proc","--dev","/dev","--chdir","/","--","/bin/sh","-c",`test -r /proc/self/status && printf ${Ar}`]}function yr(){let e=[process.platform,process.env.XENO_BWRAP_PATH??"",process.env.PATH??""].join("\0");if(yt?.key===e)return{...yt.capability};let t;if(process.platform!=="linux")t={available:!1,reason:"The bubblewrap process-hardening profile can only be probed on a Linux host."};else{let r=Qn();if(!r)t={available:!1,reason:"bubblewrap is not installed or is not executable."};else{let n=(0,It.spawnSync)(r,["--version"],{encoding:"utf8",timeout:gr}),o=(0,It.spawnSync)(r,eo(),{encoding:"utf8",timeout:gr,env:process.env}),i=n.status===0?n.stdout.trim():void 0;if(o.status===0&&o.stdout===Ar)t={available:!0,executable:r,...i?{version:i}:{},reason:`An active ${i??"bubblewrap"} namespace profile passed its mount, PID, user, IPC, UTS, /proc, and /dev probe.`};else{let a=[o.error?.message,o.stderr.trim(),o.signal?`signal ${o.signal}`:void 0,o.status!==null?`exit ${o.status}`:void 0].filter(Boolean).join("; ");t={available:!1,executable:r,...i?{version:i}:{},reason:`bubblewrap was found but its active namespace profile failed${a?`: ${a}`:"."}`}}}}return yt={key:e,capability:t},{...t}}var ye=require("node:crypto"),He=require("node:fs"),wr=require("node:path"),wt="xeno.containment-certification.v1",Ir=512*1024,to=744*60*60*1e3,br=Object.freeze(["allowedFilesystemRead","allowedFilesystemWrite","outsideFilesystemReadDenied","outsideFilesystemWriteDenied","unlistedFilesystemReadDenied","unlistedFilesystemWriteDenied","symlinkEscapeDenied","networkDefaultDeny","environmentSecretsExcluded","childProcessPolicyInherited","standardCommandLaunch","processTreeCleanup","timeoutEnforced","hostPolicyRecoveryClean","uiRestrictionsEnforced"]),b=class extends Error{constructor(t){super(`CONTAINMENT_CERTIFICATION_INVALID: ${t}`),this.name="ContainmentCertificationError"}};function ro(e){let t={...e};return delete t.signature,Buffer.from(JSON.stringify(Et(t)),"utf8")}function Er(e,t,r=new Date){if(!(0,wr.isAbsolute)(e.manifestPath))throw new b("manifestPath must be absolute");Oe(e.candidateSha256,"candidateSha256");let n=(0,He.statSync)(e.manifestPath);if(!n.isFile())throw new b("manifestPath must reference a regular file");if(n.size<=0||n.size>Ir)throw new b(`manifest size must be between 1 and ${Ir} bytes`);let o=(0,He.readFileSync)(e.manifestPath),i;try{i=JSON.parse(o.toString("utf8"))}catch{throw new b("manifest is not valid JSON")}let a=no(i);if(e.expectedCertificationId&&a.certificationId!==e.expectedCertificationId)throw new b("certificationId does not match the host binding");if(a.candidate.sha256.toLowerCase()!==e.candidateSha256.toLowerCase())throw new b("candidate digest does not match the running candidate binding");if(a.platform.os!==t.platform||a.platform.arch!==t.arch)throw new b("certification platform or architecture does not match this host");if(a.adapter.name!==t.name||a.adapter.version!==t.version||a.adapter.backend!==t.backend||a.adapter.isolationTier!==t.isolationTier||a.adapter.nativeBinarySha256.toLowerCase()!==t.nativeBinarySha256.toLowerCase())throw new b("certified adapter identity does not match the installed native adapter");let c=bt(a.issuedAt,"issuedAt"),s=bt(a.expiresAt,"expiresAt");if(s<=c)throw new b("expiresAt must be later than issuedAt");if(s-c>to)throw new b("certification lifetime exceeds 31 days");if(r.getTime()<c-5*6e4)throw new b("certification is not active yet");if(r.getTime()>=s)throw new b("certification has expired");for(let p of br)if(a.conformance.checks[p]!==!0)throw new b(`required conformance check did not pass: ${p}`);if(!a.approvals.some(p=>p.role==="security-reviewer"&&p.subject!==a.issuedBy))throw new b("an independent security-reviewer approval is required");let l=e.trustedPublicKeys[a.signature.keyId];if(!l)throw new b("signature key is not trusted by this host");let y;try{y=Buffer.from(a.signature.value,"base64")}catch{throw new b("signature is not valid base64")}if(y.length!==64)throw new b("Ed25519 signature must be 64 bytes");let A=!1;try{A=(0,ye.verify)(null,ro(a),(0,ye.createPublicKey)(l),y)}catch{throw new b("signature key or value is invalid")}if(!A)throw new b("signature verification failed");return{manifest:a,manifestSha256:(0,ye.createHash)("sha256").update(o).digest("hex")}}function no(e){let t=ne(e,"manifest");if(t.schemaVersion!==wt)throw new b(`schemaVersion must be ${wt}`);let r=T(t.certificationId,"certificationId"),n=ne(t.candidate,"candidate"),o=ne(t.adapter,"adapter"),i=ne(t.platform,"platform"),a=ne(t.conformance,"conformance"),c=ne(a.checks,"conformance.checks"),s=ne(t.signature,"signature"),l=t.approvals;if(!Array.isArray(l)||l.length===0)throw new b("approvals must contain at least one approval");let y=l.map((E,S)=>{let I=ne(E,`approvals[${S}]`),$=T(I.role,`approvals[${S}].role`);if($!=="security-reviewer"&&$!=="release-reviewer")throw new b(`approvals[${S}].role is invalid`);let ae=$;bt(T(I.approvedAt,`approvals[${S}].approvedAt`),`approvals[${S}].approvedAt`);let xe=T(I.approvalSha256,`approvals[${S}].approvalSha256`);return Oe(xe,`approvals[${S}].approvalSha256`),{subject:T(I.subject,`approvals[${S}].subject`),role:ae,approvedAt:I.approvedAt,approvalArtifactId:T(I.approvalArtifactId,`approvals[${S}].approvalArtifactId`),approvalSha256:xe}}),A=T(o.backend,"adapter.backend");if(A!=="processcontainer"&&A!=="bubblewrap"&&A!=="seatbelt")throw new b("adapter.backend is invalid");let p=T(i.os,"platform.os"),v=T(i.arch,"platform.arch");if(T(s.algorithm,"signature.algorithm")!=="ed25519")throw new b("signature.algorithm must be ed25519");let x={};for(let E of br){if(c[E]!==!0)throw new b(`conformance.checks.${E} must be true`);x[E]=!0}let C=T(o.nativeBinarySha256,"adapter.nativeBinarySha256"),R=T(n.sha256,"candidate.sha256"),k=T(a.reportSha256,"conformance.reportSha256");if(Oe(C,"adapter.nativeBinarySha256"),Oe(R,"candidate.sha256"),Oe(k,"conformance.reportSha256"),a.passed!==!0)throw new b("conformance.passed must be true");return{schemaVersion:wt,certificationId:r,candidate:{product:T(n.product,"candidate.product"),version:T(n.version,"candidate.version"),sha256:R},adapter:{name:o.name==="microsoft-mxc"?"microsoft-mxc":oo(),version:T(o.version,"adapter.version"),backend:A,isolationTier:T(o.isolationTier,"adapter.isolationTier"),nativeBinarySha256:C},platform:{os:p,arch:v},conformance:{reportArtifactId:T(a.reportArtifactId,"conformance.reportArtifactId"),reportSha256:k,passed:!0,checks:x},issuedAt:T(t.issuedAt,"issuedAt"),expiresAt:T(t.expiresAt,"expiresAt"),issuedBy:T(t.issuedBy,"issuedBy"),approvals:y,signature:{algorithm:"ed25519",keyId:T(s.keyId,"signature.keyId"),value:T(s.value,"signature.value")}}}function oo(){throw new b("adapter.name must be microsoft-mxc")}function ne(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new b(`${t} must be an object`);return e}function T(e,t){if(typeof e!="string"||e.trim().length===0)throw new b(`${t} must be a non-empty string`);return e}function Oe(e,t){if(!/^[a-f0-9]{64}$/i.test(e))throw new b(`${t} must be a SHA-256 hex digest`)}function bt(e,t){let r=Date.parse(e);if(!Number.isFinite(r))throw new b(`${t} must be an ISO timestamp`);return r}function Et(e){return Array.isArray(e)?e.map(Et):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Et(r)])):e}var le=require("node:crypto"),w=require("node:fs"),Tr=require("node:os"),_=require("node:path"),Tt=require("node:child_process"),Cr=require("node:url");var vr="microsoft-mxc",_e="0.7.0";var io="@microsoft/mxc-sdk",ao="sha512-EWhz2pKkcPluZHAOI1yneV+JK0NO/3hdh7nABBb0x4PjyUWMeSWPTBAjtIu+BhtMYOqlaijSPZMZ0Hs/J4ZL4A==",Ja=10*6e4,so=Object.freeze({"win32-x64-wxc-exec.exe":"db0a3422be9e1b396cc1b2547c70ff16b27412438a31c10a45abf370cac86ae2","win32-arm64-wxc-exec.exe":"e430d0e4f44f616e91db684f8d825a6dc93e06a1262b8d00bcaac7522a317aab","linux-x64-lxc-exec":"1efe3f817f5ae9ba9f9f2fd59142e79b2dde7a4dd024576b0ddb635fc87edeb5","linux-arm64-lxc-exec":"fdc00ccecf362ae3ddd8ccad93fd7c8b5b1f03c68897ab05ef1c9f1d327ea3fe","darwin-arm64-mxc-exec-mac":"77c07a86f483ed91dd5be290cd77878ac0c56fe113cdb8c764e7e5201c744ad2"}),Ka=Object.freeze({"win32-x64-wxc-host-prep.exe":"531fb3cdb4b0c964908fd71b71d40961417afb399cbab72f92a25e95309a6416","win32-arm64-wxc-host-prep.exe":"3ef702332286a39153fc259310b5021e3de3c191751d7522684f6475f73af5ef"});function co(e){return e.some(t=>t.includes("wxc-host-prep prepare-system-drive")||t.includes("wxc-host-prep prepare-null-device"))}function lo(e,t){if(e!=="win32"&&e!=="linux"&&e!=="darwin"||t!=="x64"&&t!=="arm64"||e==="darwin"&&t!=="arm64")return;let r=e==="win32"?"wxc-exec.exe":e==="darwin"?"mxc-exec-mac":"lxc-exec",n=so[`${e}-${t}-${r}`];return n?{platform:e,arch:t,binaryName:r,sha256:n}:void 0}var vt;function Pr(e={}){if(vt&&!e.refresh)return Sr(vt);let t=uo();return vt=t,Sr(t)}function uo(){let e=process.platform,t=process.arch,r=lo(e,t),n=!!r,o=po();if(!o)return n?D(`reviewed MXC ${_e} native assets are not installed`,!1,!0):D(St(e,t),!1,!1);let i=(0,_.dirname)(o);if(!n)return D(St(e,t),!0,!1,{packageRoot:i});let a="";try{let p=JSON.parse((0,w.readFileSync)(o,"utf8"));if(a=String(p.version??""),p.sourcePackage?.name!==io||p.sourcePackage.version!==_e||p.sourcePackage.integrity!==ao)return D("MXC native asset provenance metadata is invalid",!0,!0,{packageRoot:i})}catch{return D("MXC package metadata is unreadable",!0,!0,{packageRoot:i})}if(a!==_e)return D(`MXC version ${a||"unknown"} is installed; XENO requires exactly ${_e}`,!0,!0,{packageRoot:i});if(!r)return D(St(e,t),!0,!1,{packageRoot:i});let c=(0,_.join)(i,"bin",t,r.binaryName);if(!(0,w.existsSync)(c)||!(0,w.statSync)(c).isFile())return D(`MXC native binary is missing: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a});let s=c;try{s=fo(c,r)}catch(p){return D(`MXC packaged native binary could not be materialized: ${p instanceof Error?p.message:String(p)}`,!0,!0,{packageRoot:i,version:a})}if(e!=="win32")try{(0,w.accessSync)(s,w.constants.X_OK)}catch{return D(`MXC native binary is not executable: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a})}let l=(0,le.createHash)("sha256").update((0,w.readFileSync)(s)).digest("hex"),y=r.sha256;if(!y||l!==y)return D(`MXC native binary digest is not trusted for ${e}/${t}`,!0,!0,{packageRoot:i,version:a});if(e==="win32"){let p=(0,Tt.spawnSync)(s,["--probe"],{encoding:"utf8",timeout:5e3,windowsHide:!0});if(p.error||p.status!==0)return D(`MXC native probe failed: ${p.error?.message??(p.stderr.trim()||`exit ${p.status}`)}`,!0,!0,{packageRoot:i,version:a});let v;try{v=JSON.parse(p.stdout)}catch{return D("MXC native probe returned invalid JSON",!0,!0,{packageRoot:i,version:a})}let m=typeof v.tier=="string"?v.tier:"unknown",x=Array.isArray(v.warnings)?v.warnings.filter(k=>typeof k=="string"):[],C=v.probes&&typeof v.probes=="object"?v.probes:void 0,R=C?.uiCapabilities&&typeof C.uiCapabilities=="object"?Object.fromEntries(Object.entries(C.uiCapabilities).filter(k=>typeof k[1]=="boolean")):void 0;return{installed:!0,supported:!0,available:!0,name:vr,version:a,packageRoot:i,nativeBinaryPath:s,nativeBinarySha256:l,backend:"processcontainer",isolationTier:m,platform:e,arch:t,warnings:x,needsHostPreparation:co(x),reason:`MXC ${a} processcontainer is installed (${m}).`,...R?{uiCapabilities:R}:{}}}if(e==="linux"){let p=(0,Tt.spawnSync)("bwrap",["--version"],{encoding:"utf8",timeout:5e3});if(p.error||p.status!==0)return D("MXC requires bubblewrap on PATH for the stable Linux process adapter",!0,!0,{packageRoot:i,version:a})}let A=e==="darwin"?"seatbelt":"bubblewrap";return{installed:!0,supported:!0,available:!0,name:vr,version:a,packageRoot:i,nativeBinaryPath:s,nativeBinarySha256:l,backend:A,isolationTier:A,platform:e,arch:t,warnings:[],needsHostPreparation:!1,reason:`MXC ${a} ${A} adapter is installed.`}}function po(){let e=process.resourcesPath,t=process.env.XENO_MXC_ASSET_ROOT?.trim(),r=typeof __dirname=="string"?__dirname:(0,_.dirname)((0,Cr.fileURLToPath)(void 0)),n=[...e&&(0,_.isAbsolute)(e)?[(0,_.join)(e,"mxc","package.json")]:[],...t&&(0,_.isAbsolute)(t)?[(0,_.join)(t,"package.json")]:[],(0,_.join)(r,"..","native","mxc","package.json"),(0,_.join)(r,"..","..","native","mxc","package.json")];for(let o of n){if(!(0,w.existsSync)(o))continue;let i=(0,w.lstatSync)(o);if(!(!i.isFile()||i.isSymbolicLink()))return(0,w.realpathSync)(o)}}function fo(e,t){if(!!!process.pkg)return e;let n=(0,_.join)((0,Tr.tmpdir)(),"xeno-mxc",_e,t.sha256);(0,w.mkdirSync)(n,{recursive:!0,mode:448});let o=(0,_.join)(n,t.binaryName);if((0,w.existsSync)(o)){let s=(0,w.lstatSync)(o);if(!s.isFile()||s.isSymbolicLink())throw new Error("materialized MXC path is not a regular file");if((0,le.createHash)("sha256").update((0,w.readFileSync)(o)).digest("hex")!==t.sha256)throw new Error("materialized MXC binary digest is invalid");return process.platform!=="win32"&&(0,w.chmodSync)(o,448),o}let i=(0,w.readFileSync)(e);if((0,le.createHash)("sha256").update(i).digest("hex")!==t.sha256)throw new Error("embedded MXC binary digest is invalid");let c=`${o}.${process.pid}.${(0,le.randomUUID)()}.tmp`;(0,w.writeFileSync)(c,i,{flag:"wx",mode:448});try{(0,w.renameSync)(c,o)}catch(s){try{(0,w.unlinkSync)(c)}catch{}if(!(0,w.existsSync)(o))throw s;let l=(0,w.lstatSync)(o);if((l.isFile()&&!l.isSymbolicLink()?(0,le.createHash)("sha256").update((0,w.readFileSync)(o)).digest("hex"):"")!==t.sha256)throw s}return process.platform!=="win32"&&(0,w.chmodSync)(o,448),o}function St(e,t){return e!=="win32"&&e!=="linux"&&e!=="darwin"?`MXC has no stable process adapter for ${e}/${t}`:t!=="x64"&&t!=="arm64"?`MXC does not ship a ${e}/${t} native adapter`:"MXC Seatbelt currently ships for macOS ARM64 only"}function D(e,t=!1,r=!1,n={}){return{...n,installed:t,supported:r,available:!1,warnings:[],needsHostPreparation:!1,reason:e}}function Sr(e){return{...e,warnings:[...e.warnings],...e.uiCapabilities?{uiCapabilities:{...e.uiCapabilities}}:{}}}var ue=class extends Error{code;constructor(t,r){super(`${t}: ${r}`),this.name="ExecutionSecurityError",this.code=t}},mo=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),go=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!0,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!0,environmentSanitization:!0}),ho=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),Ao=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!0,networkIsolation:!0,inheritedHandleAllowlist:!0,environmentSanitization:!0}),Ct=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0});function yo(e){let t=e?.executionLevel;if(e?.requireOsContainment&&t&&t!=="contained")throw new ue("SECURITY_POLICY_INVALID","requireOsContainment is a strict contained-mode compatibility flag and conflicts with the requested executionLevel.");return t??(e?.requireOsContainment?"contained":"policy-only")}function Io(e){return e?.trustMode??"trusted-workspace"}function xr(e,t=process.platform,r){if(e==="policy-only")return{available:!0,requestedLevel:e,effectiveLevel:"policy-only",adapter:"policy-enforcer",isolation:"policy-only",certified:!0,capabilities:{...mo},limitations:["No restricted process identity.","No filesystem isolation.","No network isolation."],reason:"Policy and permission checks are active without operating-system process isolation."};if(e==="process-hardened"){if(t==="win32"&&mr())return{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"windows-restricted-token-job",isolation:"process-hardening",certified:!0,capabilities:{...go},limitations:["Filesystem reads are not isolated.","Network access is not isolated.","This mode is not suitable for untrusted code."],reason:"Windows restricted-token, low-integrity, explicit-handle, and kill-on-close Job Object process hardening is available."};if(t==="linux"){let o=yr();return o.available?{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"linux-bubblewrap",isolation:"process-hardening",certified:!0,capabilities:{...ho},limitations:["Filesystem reads are not isolated; the host root is mounted read-only.","Network access is not isolated.","Inherited file descriptors are limited by the host launcher rather than an adapter-owned allowlist.","This mode is not suitable for untrusted code."],reason:`linux-bubblewrap is available: ${o.reason}`}:{available:!1,requestedLevel:e,effectiveLevel:"unavailable",adapter:"unavailable",isolation:"none",certified:!1,capabilities:{...Ct},limitations:["No certified process-hardening adapter is available for this platform."],reason:`Linux bubblewrap process hardening is unavailable: ${o.reason}`}}return{available:!1,requestedLevel:e,effectiveLevel:"unavailable",adapter:"unavailable",isolation:"none",certified:!1,capabilities:{...Ct},limitations:["No certified process-hardening adapter is available for this platform."],reason:t==="win32"?"The Windows .NET Framework C# compiler is unavailable, so the restricted-token launcher cannot start.":`No certified process-hardened adapter is implemented for ${t}.`}}if(t!==process.platform)return Ge(t,`Native containment for ${t} cannot be certified from a ${process.platform} host.`);let n=Pr();if(!n.available||!n.name||!n.version||!n.backend||!n.isolationTier||!n.nativeBinarySha256||!n.platform||!n.arch)return Ge(t,n.reason,n);if(!r)return Ge(t,`${n.reason} A signed candidate-bound XENO containment certification was not supplied.`,n);try{let o={name:n.name,version:n.version,backend:n.backend,isolationTier:n.isolationTier,nativeBinarySha256:n.nativeBinarySha256,platform:n.platform,arch:n.arch},i=Er(r,o);return{available:!0,requestedLevel:e,effectiveLevel:"contained",adapter:"microsoft-mxc",isolation:"filesystem-network",certified:!0,capabilities:{...Ao},limitations:[...n.warnings],reason:`${n.reason} Signed XENO certification ${i.manifest.certificationId} is valid for this candidate.`,adapterVersion:n.version,backend:n.backend,isolationTier:n.isolationTier,nativeBinarySha256:n.nativeBinarySha256,certificationArtifactId:i.manifest.certificationId,certificationManifestSha256:i.manifestSha256,needsHostPreparation:n.needsHostPreparation}}catch(o){return Ge(t,o instanceof Error?o.message:"Containment certification validation failed.",n)}}function wo(e,t){if(Io(e)==="untrusted"&&t!=="contained")throw new ue("UNTRUSTED_EXECUTION_DISABLED","Untrusted execution requires certified contained mode; policy-only and process-hardened modes are trusted-workspace features.")}function bo(e){let t=e.requestedLevel==="contained"?"CONTAINMENT_UNAVAILABLE":"PROCESS_HARDENING_UNAVAILABLE";return new ue(t,e.reason)}function Rr(e,t=process.platform){let r=yo(e);wo(e,r);let n=xr(r,t,e.containmentCertification);if(!n.available)throw bo(n);if(r==="process-hardened"&&e.allowNetwork!==!0)throw new ue("NETWORK_ISOLATION_UNAVAILABLE","Process-hardened execution cannot enforce network denial. Set allowNetwork=true explicitly for a trusted workspace or request certified contained mode.");if(r!=="policy-only"){let o=ce(e.workingDirectory??process.cwd()).canonicalPath,i=[...e.allowedDirectories,...e.temporaryDirectories??[]];if(!fr(o,i))throw new ue("SECURITY_POLICY_INVALID",`Secured process working directory is outside the canonical allowed directories: ${o}`)}return n}function Ge(e,t,r){let n=r?.available===!0;return{available:!1,requestedLevel:"contained",effectiveLevel:"unavailable",adapter:n?"microsoft-mxc":"unavailable",isolation:n?"filesystem-network":"none",certified:!1,capabilities:{...Ct},limitations:["Contained mode remains fail-closed until a signed, candidate-bound XENO certification is valid.",...r?.warnings??[],...e==="win32"&&!n?["Windows restricted-token execution is process hardening only."]:[]],reason:t,...r?.version?{adapterVersion:r.version}:{},...r?.backend?{backend:r.backend}:{},...r?.isolationTier?{isolationTier:r.isolationTier}:{},...r?.nativeBinarySha256?{nativeBinarySha256:r.nativeBinarySha256}:{},...r?{needsHostPreparation:r.needsHostPreparation}:{}}}var Xr=1,P=class extends Error{constructor(r,n){super(n);this.code=r;this.name="XenoSecureExecutionContractError"}code};function Dr(e){let t=e.platform??process.platform,r=e.policy.executionLevel??(e.policy.requireOsContainment?"contained":"policy-only"),n=e.adapterStatus??Rr(e.policy,t);if(!n.available||n.effectiveLevel==="unavailable")throw new P("SECURITY_CONTRACT_UNAVAILABLE",n.reason);if(n.requestedLevel!==r||n.effectiveLevel!==r)throw new P("SECURITY_CONTRACT_INVALID","Execution adapter status does not match the requested security level");let i=(e.now??(()=>new Date().toISOString()))(),a=Ne([...e.policy.allowedDirectories,...e.policy.temporaryDirectories??[],e.policy.workingDirectory??process.cwd()],e.policy.workingDirectory,t),c=Ne(e.filesystem?.readRoots??a,e.policy.workingDirectory,t),s=e.profile.capabilities.permissionProfile==="read-only",l=s?[]:Ne(e.filesystem?.writeRoots??a,e.policy.workingDirectory,t),y=s?[]:Ne(e.filesystem?.executeRoots??a,e.policy.workingDirectory,t),A=Ne(e.filesystem?.deniedRoots??e.policy.deniedDirectories??[],e.policy.workingDirectory,t),p=n.capabilities.filesystemIsolation?"os":"policy",v=n.capabilities.networkIsolation?"os":r==="process-hardened"?"none":"policy",m=r==="contained"?"deny":e.network?.default??(e.policy.allowNetwork?"allow":"deny"),x=v==="none";if(x&&(!e.policy.allowNetwork||m!=="allow"))throw new P("SECURITY_CONTRACT_INVALID","An adapter without network isolation requires explicit unrestricted-network acknowledgement");if(s&&(e.browser?.mode==="act"||e.computer?.mode==="act"||(e.secrets?.length??0)>0))throw new P("SECURITY_CONTRACT_INVALID","Read-only Agent Profiles cannot receive browser action, computer action, or secret projection authority");let C=e.certificationArtifactId??n.certificationArtifactId;if(e.certificationArtifactId&&n.certificationArtifactId&&e.certificationArtifactId!==n.certificationArtifactId)throw new P("SECURITY_CONTRACT_INVALID","Requested certification artifact does not match the adapter certification");if(r==="contained"&&!C)throw new P("SECURITY_CONTRACT_INVALID","Contained execution requires a candidate-bound certification artifact");let R=Ie(e.environment?.deniedKeys??[]),k=new Set(R),E=ke(e.browser?.allowedDomains??[]),S=ke(e.browser?.readAllowedDomains??E),I=ke(e.browser?.actAllowedDomains??E),$=ke([...E,...S,...I]),ae={schemaVersion:Xr,contractId:e.contractId,createdAt:i,...e.expiresAt?{expiresAt:e.expiresAt}:{},identity:{...e.identity},requestedLevel:r,effectiveLevel:n.effectiveLevel,trustMode:e.policy.trustMode??"trusted-workspace",profile:{id:e.profile.profile.id,version:e.profile.profile.version,fingerprint:e.profile.fingerprint,permissionProfile:e.profile.capabilities.permissionProfile},filesystem:{enforcement:p,readRoots:c,writeRoots:l,executeRoots:y,deniedRoots:A},network:{enforcement:v,default:m,allowDestinations:Or(e.network?.allowDestinations??[]),denyDestinations:Or(e.network?.denyDestinations??[]),dns:e.network?.dns??((e.network?.allowDestinations?.length??0)>0||m==="allow"?"system":"disabled"),...e.network?.proxyUrl?{proxyUrl:e.network.proxyUrl}:{},downloads:e.network?.downloads??"deny",acknowledgedUnrestricted:x},process:{processTreeControl:n.capabilities.processTreeControl,cleanup:n.capabilities.processTreeControl?"kill-tree":"best-effort",inheritedHandleAllowlist:n.capabilities.inheritedHandleAllowlist,...Co(e.process)},environment:{inheritance:e.environment?.inheritance??"allowlist",allowedKeys:Ie(e.environment?.allowedKeys??e.policy.containedEnvironmentAllowlist??[]).filter($n=>!k.has($n)),deniedKeys:R},secrets:To(e.secrets??[]),externalActions:{default:e.profile.capabilities.externalActions.default,overrides:{...e.profile.capabilities.externalActions.overrides},requireCurrentTurnApproval:Ie(e.profile.capabilities.externalActions.requireCurrentTurnApproval),requireCapabilityLease:!0},browser:{mode:e.browser?.mode??"none",profile:e.browser?.profile??"ephemeral",allowedDomains:$,readAllowedDomains:S,actAllowedDomains:I,deniedDomains:ke(e.browser?.deniedDomains??[]),allowedSchemes:vo(e.browser?.allowedSchemes??["https"]),allowedPorts:So(e.browser?.allowedPorts??[443]),redirectPolicy:e.browser?.redirectPolicy??"policy",allowLoopbackDevelopment:e.browser?.allowLoopbackDevelopment??!1,downloads:e.browser?.downloads??"deny",uploads:e.browser?.uploads??"deny",recording:e.browser?.recording??"disabled"},computer:{mode:e.computer?.mode??"none",allowedApplications:Ie(e.computer?.allowedApplications??[]),sensitiveRegionRedaction:e.computer?.sensitiveRegionRedaction??!0,humanStopRequired:e.computer?.humanStopRequired??!0},capabilityLeaseIds:Ie(e.capabilityLeaseIds??[]),adapter:{id:n.adapter,version:e.adapterVersion??n.adapterVersion??"1",platform:t,architecture:e.architecture??(0,kr.arch)(),certified:n.certified,...C?{certificationArtifactId:C}:{},capabilities:{...n.capabilities},limitations:[...n.limitations]},...e.auditEventIds?{auditEventIds:Ie(e.auditEventIds)}:{}},xe={...ae,fingerprint:Lr(ae)};return xt(xe),xe}function Eo(e){let t=[];if(!e||typeof e!="object")return["Contract must be an object"];if(e.schemaVersion!==Xr&&t.push("Unsupported schemaVersion"),e.contractId?.trim()||t.push("contractId is required"),(!e.identity?.runId?.trim()||!e.identity?.agentId?.trim())&&t.push("runId and agentId are required"),_r(e.createdAt)||t.push("createdAt must be an ISO 8601 timestamp"),e.expiresAt&&(!_r(e.expiresAt)||Date.parse(e.expiresAt)<=Date.parse(e.createdAt))&&t.push("expiresAt must be later than createdAt"),e.requestedLevel!==e.effectiveLevel&&t.push("requestedLevel and effectiveLevel must match"),e.trustMode==="untrusted"&&e.effectiveLevel!=="contained"&&t.push("Untrusted execution requires contained mode"),e.effectiveLevel==="contained"&&(e.adapter.certified||t.push("Contained mode requires a certified adapter"),e.adapter.certificationArtifactId||t.push("Contained mode requires a certification artifact"),(!e.adapter.capabilities.filesystemIsolation||e.filesystem.enforcement!=="os")&&t.push("Contained mode requires OS filesystem isolation"),(!e.adapter.capabilities.networkIsolation||e.network.enforcement!=="os")&&t.push("Contained mode requires OS network isolation"),e.network.default!=="deny"&&t.push("Contained networking must default deny")),e.network.enforcement==="none"&&!e.network.acknowledgedUnrestricted&&t.push("Unrestricted networking must be explicitly acknowledged"),e.filesystem.writeRoots.length>0&&e.profile.permissionProfile==="read-only"&&t.push("Read-only profiles cannot receive write roots"),(!Array.isArray(e.browser.readAllowedDomains)||!Array.isArray(e.browser.actAllowedDomains))&&t.push("Browser read/action domain policies are required"),(!Array.isArray(e.browser.allowedSchemes)||e.browser.allowedSchemes.some(r=>r!=="http"&&r!=="https"))&&t.push("Browser allowed schemes are invalid"),(!Array.isArray(e.browser.allowedPorts)||e.browser.allowedPorts.some(r=>!Number.isInteger(r)||r<1||r>65535))&&t.push("Browser allowed ports are invalid"),e.secrets.some(r=>!r.secretId.trim())&&t.push("Secret projections require non-empty secret IDs"),new Set(e.secrets.map(r=>r.secretId)).size!==e.secrets.length&&t.push("Secret IDs must be unique"),new Set(e.capabilityLeaseIds).size!==e.capabilityLeaseIds.length&&t.push("Capability lease IDs must be unique"),/^[a-f0-9]{64}$/.test(e.profile.fingerprint)||t.push("Profile fingerprint is invalid"),!/^[a-f0-9]{64}$/.test(e.fingerprint))t.push("Contract fingerprint is invalid");else{let r={...e};delete r.fingerprint,Lr(r)!==e.fingerprint&&t.push("Contract fingerprint does not match content")}return t}function xt(e){let t=Eo(e);if(t.length>0){let r=t.includes("Contract fingerprint does not match content");throw new P(r?"SECURITY_CONTRACT_FINGERPRINT_MISMATCH":"SECURITY_CONTRACT_INVALID",t.join("; "))}}function Lr(e){return(0,Nr.createHash)("sha256").update(JSON.stringify(Pt(e))).digest("hex")}function Ie(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort().map(t=>t)}function Ne(e,t,r){return[...new Set(e.map(n=>ce(n,{baseDirectory:t,platform:r}).canonicalPath))].sort((n,o)=>n.localeCompare(o))}function Or(e){let t=new Map;for(let r of e){if(!r.host?.trim())throw new P("SECURITY_CONTRACT_INVALID","Network destinations require a host");if(r.host.includes("*"))throw new P("SECURITY_CONTRACT_INVALID","Network destinations cannot contain wildcards");if(r.port!==void 0&&(!Number.isInteger(r.port)||r.port<1||r.port>65535))throw new P("SECURITY_CONTRACT_INVALID","Network destination port is invalid");let n={...r,host:r.host.trim().toLowerCase().replace(/\.$/,"")};t.set(`${n.scheme??""}:${n.host}:${n.port??""}`,n)}return[...t.values()].sort((r,n)=>r.host.localeCompare(n.host)||(r.port??0)-(n.port??0))}function ke(e){let t=new Set;for(let r of e){let n=r.trim().toLowerCase().replace(/\.$/,"");if(!n)continue;if(n.includes("*")||n.includes("://")||n.includes("/")||n.includes(":"))throw new P("SECURITY_CONTRACT_INVALID",`Browser domain rule is invalid: ${r}`);let o=n.startsWith(".")?n.slice(1):n;if(!/^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/.test(o)&&o!=="localhost")throw new P("SECURITY_CONTRACT_INVALID",`Browser domain rule is invalid: ${r}`);t.add(n)}return[...t].sort((r,n)=>r.localeCompare(n))}function vo(e){for(let t of e)if(t!=="http"&&t!=="https")throw new P("SECURITY_CONTRACT_INVALID",`Browser scheme is invalid: ${t}`);return[...new Set(e)].sort()}function So(e){for(let t of e)if(!Number.isInteger(t)||t<1||t>65535)throw new P("SECURITY_CONTRACT_INVALID",`Browser port is invalid: ${t}`);return[...new Set(e)].sort((t,r)=>t-r)}function To(e){let t=new Map;for(let r of e){if(!r.secretId?.trim())throw new P("SECURITY_CONTRACT_INVALID","Secret projections require an ID");if(t.has(r.secretId))throw new P("SECURITY_CONTRACT_INVALID",`Secret ${r.secretId} is projected more than once`);t.set(r.secretId,{...r})}return[...t.values()].sort((r,n)=>r.secretId.localeCompare(n.secretId))}function Co(e){let t={};for(let[r,n]of Object.entries(e??{})){if(!Number.isSafeInteger(n)||Number(n)<1)throw new P("SECURITY_CONTRACT_INVALID",`${r} must be a positive safe integer`);Object.assign(t,{[r]:n})}return t}function Pt(e){return Array.isArray(e)?e.map(Pt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Pt(r)]))}function _r(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}var Po=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,Mr=1048576;function J(e){(!e||typeof e!="object")&&z("Automation request must be an object"),e.protocolVersion!==1&&z("Unsupported automation protocol version"),we(e.operationId,"operationId"),we(e.idempotencyKey,"idempotencyKey"),we(e.capabilityLeaseId,"capabilityLeaseId"),we(e.governingToolName,"governingToolName"),(!Number.isSafeInteger(e.expectedLeaseVersion)||e.expectedLeaseVersion<1)&&z("expectedLeaseVersion must be a positive safe integer"),Fr(e.requestedAt)||z("requestedAt must be an ISO 8601 timestamp"),je(e.operation)||z(`Unsupported automation operation: ${e.operation}`),(!e.parameters||typeof e.parameters!="object"||Array.isArray(e.parameters))&&z("parameters must be a JSON object");let t;try{t=Buffer.byteLength(JSON.stringify(e.parameters),"utf8")}catch(r){throw new d("AUTOMATION_REQUEST_INVALID","parameters must be serializable JSON",void 0,{cause:r})}if(t>Mr&&z(`parameters exceed ${Mr} bytes`),we(e.identity?.runId,"identity.runId"),we(e.identity?.agentId,"identity.agentId"),xt(e.executionContract),xo(e),!e.executionContract.capabilityLeaseIds.includes(e.capabilityLeaseId))throw new d("AUTOMATION_CONTRACT_INVALID",`Capability lease ${e.capabilityLeaseId} is not bound to the execution contract`);if(e.executionContract.expiresAt&&Date.parse(e.executionContract.expiresAt)<=Date.now())throw new d("AUTOMATION_CONTRACT_EXPIRED","Execution contract has expired")}function F(e){(!e||typeof e!="object")&&V("Adapter manifest must be an object"),e.protocolVersion!==1&&V("Adapter protocol version is unsupported"),We(e.adapterId,"adapterId"),We(e.adapterVersion,"adapterVersion"),We(e.platform,"platform"),We(e.architecture,"architecture"),e.targetBinding!=="atomic-preflight"&&V("Adapter must implement atomic preflight target binding"),(!Array.isArray(e.operations)||e.operations.length===0)&&V("Adapter must declare operations");let t=new Set;for(let r of e.operations)je(r)||V(`Adapter declares unknown operation ${r}`),t.has(r)&&V(`Adapter declares duplicate operation ${r}`),t.add(r);e.certified&&!e.certificationArtifactId&&V("A certified automation adapter requires a certification artifact"),Array.isArray(e.limitations)||V("Adapter limitations must be an array"),e.operations.some(r=>r.startsWith("browser."))&&(!e.policyEnforcement.domain||!e.policyEnforcement.scheme||!e.policyEnforcement.port)&&V("Browser adapters must enforce domain, scheme, and port policy"),e.operations.some(r=>r.startsWith("computer."))&&!e.supports.immediateStop&&V("Computer-use adapters must support immediate stop")}function qe(e,t){let r=X(e.operation);if(!t.operations.includes(e.operation))throw new d("AUTOMATION_OPERATION_UNSUPPORTED",`Adapter ${t.adapterId} does not support ${e.operation}`);if(r.surface==="browser"){let n=e.executionContract.browser.mode;if(n==="none"||r.effect==="act"&&n!=="act")throw new d("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(e.operation==="browser.download"&&e.executionContract.browser.downloads==="deny")throw new d("AUTOMATION_POLICY_DENIED","Execution contract denies browser downloads");if(e.operation==="browser.upload"&&e.executionContract.browser.uploads==="deny")throw new d("AUTOMATION_POLICY_DENIED","Execution contract denies browser uploads");if(e.operation.startsWith("browser.record.")&&e.executionContract.browser.recording!=="bounded")throw new d("AUTOMATION_POLICY_DENIED","Execution contract denies browser recording")}else{let n=e.executionContract.computer.mode;if(n==="none"||r.effect==="act"&&n!=="act")throw new d("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(e.executionContract.computer.sensitiveRegionRedaction&&t.supports.sensitiveRegionRedaction!==!0)throw new d("AUTOMATION_POLICY_DENIED","Owning adapter cannot satisfy required sensitive-region redaction; preflight capture refused.")}}function ze(e,t,r){qe(e,t);let n=X(e.operation);if(n.surface==="browser")Ro(e,r,n.effect==="act");else{let o=e.executionContract.computer.allowedApplications,i=e.operation==="computer.launch"?_o(e):r.applicationId??e.declaredTarget?.applicationId;if((e.operation==="computer.launch"||o.length>0)&&(!i||!o.includes(i)))throw new d("AUTOMATION_POLICY_DENIED",`Application ${i??"<unknown>"} is not allowed`)}}function Ot(e,t){let r=X(e.operation),n=r.surface==="browser"?r.effect==="act"?"browser-act":"browser-read":r.effect==="act"?"computer-act":"computer-observe";return{subject:{runId:e.identity.runId,agentId:e.identity.agentId,...e.identity.turnId?{turnId:e.identity.turnId}:{},toolName:e.governingToolName,operationId:e.operationId},kind:n,operation:e.operation,...Ur(e,t)?{resource:Ur(e,t)}:{},...$r(t)?{destination:$r(t)}:{}}}function Ur(e,t){return Oo(t)??e.declaredTarget?.resource}function _t(e){let t=X(e.operation).evidence,r=e.evidencePolicy??{},n=Rt(t.before,r.before),o=Rt(t.after,r.after),i=Rt(t.recording,r.recording),a=r.retainUntil;return a&&!Fr(a)&&z("evidencePolicy.retainUntil must be an ISO 8601 timestamp"),{before:n,after:o,recording:i,sensitivity:r.sensitivity??"confidential",...a?{retainUntil:a}:{},...r.legalHold!==void 0?{legalHold:r.legalHold}:{}}}function xo(e){let t=e.executionContract.identity,r=["runId","agentId","sessionId","turnId","taskId","workspaceId"];for(let n of r){let o=t[n],i=e.identity[n];if(o!==void 0&&o!==i)throw new d("AUTOMATION_IDENTITY_MISMATCH",`Automation identity ${n} does not match the execution contract`)}}function Ro(e,t,r){let n=t.url??t.origin??e.declaredTarget?.url??e.declaredTarget?.origin;if(!n){if(["browser.tabs.list","browser.wait"].includes(e.operation))return;throw new d("AUTOMATION_PREFLIGHT_INVALID","Browser preflight did not bind an effective URL")}let o;try{o=new URL(n)}catch{throw new d("AUTOMATION_POLICY_DENIED","Browser target URL is invalid")}if(o.username||o.password)throw new d("AUTOMATION_POLICY_DENIED","Browser target URLs cannot contain credentials");let i=o.protocol.replace(/:$/,"");i!=="http"&&i!=="https"&&pe(`Browser scheme ${o.protocol} is not supported`);let a=i,c=o.hostname.toLowerCase().replace(/\.$/,""),s=o.port?Number(o.port):a==="https"?443:80,l=e.executionContract.browser,y=No(c);if(Vr(c,l.deniedDomains)&&pe(`Browser domain ${c} is denied`),Br(o,e.executionContract.network.denyDestinations)&&pe(`Network policy explicitly denies ${a}://${c}:${s}`),y&&l.allowLoopbackDevelopment)return;l.allowedSchemes.includes(a)||pe(`Browser scheme ${o.protocol} is not allowed`),l.allowedPorts.includes(s)||pe(`Browser port ${s} is not allowed`);let A=r?l.actAllowedDomains:l.readAllowedDomains;Vr(c,A)||pe(`Browser domain ${c} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&(Br(o,e.executionContract.network.allowDestinations)||pe(`Network policy does not allow ${a}://${c}:${s}`))}function Br(e,t){let r=e.protocol.replace(/:$/,""),n=e.hostname.toLowerCase().replace(/\.$/,""),o=e.port?Number(e.port):r==="https"?443:80;return t.some(i=>{let a=i.scheme?.replace(/^custom:/,"");return i.host===n&&(i.port===void 0||i.port===o)&&(a===void 0||a===r)})}function Oo(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function $r(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function _o(e){let t=e.parameters.target,r=t&&typeof t=="object"&&!Array.isArray(t)?t.app_id:void 0,n=e.parameters.applicationId??r??e.declaredTarget?.applicationId;return typeof n=="string"&&n.length>0?n:void 0}function Vr(e,t){return t.some(r=>{let n=r.toLowerCase();if(n.startsWith(".")){let o=n.slice(1);return e===o||e.endsWith(`.${o}`)}return e===n})}function No(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Rt(e,t){let r={disabled:0,optional:1,required:2};return!t||r[t]<=r[e]?e:t}function we(e,t){(typeof e!="string"||!Po.test(e))&&z(`${t} is invalid`)}function We(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&V(`${t} is invalid`)}function Fr(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}function pe(e){throw new d("AUTOMATION_POLICY_DENIED",e)}function z(e){throw new d("AUTOMATION_REQUEST_INVALID",e)}function V(e){throw new d("AUTOMATION_OPERATION_UNSUPPORTED",e)}var en=require("node:crypto");var jr=["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","page"],Hr=["draft","pending_review","approved","rejected","superseded","archived"],Gr=["public","internal","confidential","restricted"],Wr=["agent","tool","user","system","integration"],qr=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],zr=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var Nt=require("node:buffer");var Jr=require("node:crypto");function fe(e){return{algorithm:"sha256",value:(0,Jr.createHash)("sha256").update(e).digest("hex")}}var ko=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Je="custom:";function Xe(e,t=Je){return e.startsWith(t)?ko.test(e.slice(t.length)):!1}var be=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,r){super(t),this.name="XenoArtifactValidationError",this.issues=r.map(n=>({...n}))}},kt=class extends Error{constructor(r,n){super(`Artifact state cannot transition from ${r} to ${n}`);this.fromState=r;this.toState=n;this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},Xo={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},Do="[\\u0000-\\u001f\\u007f]",Lo=new RegExp(Do),Kr=/^[a-f0-9]{64}$/,Mo=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Uo=new Set(Hr),Bo=new Set(Gr),$o=new Set(Wr),Vo=new Set(jr),Fo=new Set(qr),jo=new Set(zr);function u(e,t,r,n){e.push({path:t,code:r,message:n})}function g(e,t,r,n=1024){return typeof e!="string"||e.trim().length===0?(u(r,t,"required_string","Value must be a non-empty string"),!1):(e.length>n&&u(r,t,"string_too_long",`Value must not exceed ${n} characters`),Lo.test(e)&&u(r,t,"control_character","Value must not contain control characters"),!0)}function De(e,t,r){e!==void 0&&(!Number.isFinite(Date.parse(e))||!e.includes("T"))&&u(r,t,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function me(e,t,r,n){typeof e=="string"&&e.startsWith(t)&&(Xe(e,t)||u(n,r,"invalid_custom_name",`Custom name after ${t} is invalid`))}function Yr(e,t,r){if(!e||typeof e!="object"){u(r,t,"missing_actor","Actor is required");return}g(e.kind,`${t}.kind`,r,64),$o.has(e.kind)||u(r,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),g(e.id,`${t}.id`,r,512),e?.displayName!==void 0&&g(e.displayName,`${t}.displayName`,r,512),e?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.profileFingerprint)&&u(r,`${t}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function Xt(e,t,r){if(!e||typeof e!="object"){u(r,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":g(e.path,`${t}.path`,r,4096);break;case"source-line":g(e.path,`${t}.path`,r,4096),(!Number.isInteger(e.startLine)||e.startLine<1)&&u(r,`${t}.startLine`,"invalid_line","startLine must be a positive integer"),e.endLine!==void 0&&(!Number.isInteger(e.endLine)||e.endLine<e.startLine)&&u(r,`${t}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":g(e.path,`${t}.path`,r,4096),g(e.hunkId,`${t}.hunkId`,r,512);break;case"symbol":g(e.path,`${t}.path`,r,4096),g(e.symbol,`${t}.symbol`,r,1024);break;case"dom-node":g(e.pageId,`${t}.pageId`,r,512),!e.selector&&!e.accessibilityId&&!e.snapshotArtifactId&&u(r,t,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":g(e.recordingArtifactId,`${t}.recordingArtifactId`,r,512),(!Number.isFinite(e.startMs)||e.startMs<0)&&u(r,`${t}.startMs`,"invalid_time","startMs must be a non-negative finite number"),e.endMs!==void 0&&(!Number.isFinite(e.endMs)||e.endMs<e.startMs)&&u(r,`${t}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":g(e.mediaArtifactId,`${t}.mediaArtifactId`,r,512),[e.x,e.y,e.width,e.height].every(Number.isFinite)?(e.width<=0||e.height<=0)&&u(r,t,"invalid_region_size","Region width and height must be positive"):u(r,t,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":g(e.artifactId,`${t}.artifactId`,r,512);break;default:typeof e.kind!="string"||!e.kind.startsWith("custom:")?u(r,`${t}.kind`,"unknown_anchor","Anchor kind is not supported"):me(e.kind,"custom:",`${t}.kind`,r)}}function Le(e,t,r,n){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||u(r,t,"non_finite_number","JSON numbers must be finite");return}if(typeof e!="object"){u(r,t,"non_json_value","Value must be JSON-serializable");return}if(n.has(e)){u(r,t,"cyclic_value","Value must not contain cycles");return}if(n.add(e),Array.isArray(e))e.forEach((o,i)=>Le(o,`${t}[${i}]`,r,n));else for(let[o,i]of Object.entries(e))i===void 0?u(r,`${t}.${o}`,"undefined_value","Undefined is not valid JSON"):Le(i,`${t}.${o}`,r,n);n.delete(e)}}function Ho(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_artifact",message:"Artifact must be an object"}];if(e.schemaVersion!==1&&u(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),g(e.artifactId,"artifactId",t,512),(!Number.isInteger(e.revision)||e.revision<1)&&u(t,"revision","invalid_revision","revision must be a positive integer"),g(e.kind,"kind",t,160),typeof e.kind=="string"&&!Vo.has(e.kind)&&!e.kind.startsWith("custom:")&&u(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),me(e.kind,"custom:","kind",t),g(e.title,"title",t,1024),e.description!==void 0&&g(e.description,"description",t,32768),g(e.state,"state",t,64),Uo.has(e.state)||u(t,"state","unknown_state","Artifact state is not supported"),g(e.createdAt,"createdAt",t,128),De(e.createdAt,"createdAt",t),De(e.updatedAt,"updatedAt",t),e.updatedAt&&Number.isFinite(Date.parse(e.createdAt))&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&u(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt"),g(e.mediaType,"mediaType",t,255),g(e.sensitivity,"sensitivity",t,64),Bo.has(e.sensitivity)||u(t,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),e.identity)for(let[n,o]of Object.entries(e.identity))o!==void 0&&g(o,`identity.${n}`,t,512);if(!e.content||typeof e.content!="object")u(t,"content","missing_content","content descriptor is required");else{!e.content.hash||typeof e.content.hash!="object"?u(t,"content.hash","missing_hash","content hash is required"):(g(e.content.hash.algorithm,"content.hash.algorithm",t,128),me(e.content.hash.algorithm,"custom:","content.hash.algorithm",t),typeof e.content.hash.algorithm=="string"&&e.content.hash.algorithm!=="sha256"&&!e.content.hash.algorithm.startsWith("custom:")&&u(t,"content.hash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported"),g(e.content.hash.value,"content.hash.value",t,512),e.content.hash.algorithm==="sha256"&&!Kr.test(e.content.hash.value)&&u(t,"content.hash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters")),(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0)&&u(t,"content.sizeBytes","invalid_size","sizeBytes must be a non-negative safe integer");let n=e.content.storage;if(!n||typeof n!="object")u(t,"content.storage","missing_storage","storage reference is required");else if(n.type==="inline")if(n.text===void 0==(n.base64===void 0))u(t,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;n.text!==void 0?o=Nt.Buffer.from(n.text,"utf8"):n.base64!==void 0&&(Mo.test(n.base64)?o=Nt.Buffer.from(n.base64,"base64"):u(t,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),o&&e.content.sizeBytes!==o.byteLength&&u(t,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),o&&e.content.hash.algorithm==="sha256"&&fe(o).value!==e.content.hash.value&&u(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else n.type==="file"?g(n.path,"content.storage.path",t,4096):n.type==="blob"?g(n.uri,"content.storage.uri",t,8192):n.type==="git"?(g(n.commit,"content.storage.commit",t,512),g(n.path,"content.storage.path",t,4096)):n.type==="url"?(g(n.url,"content.storage.url",t,8192),De(n.expiresAt,"content.storage.expiresAt",t)):n.type==="external"?(g(n.provider,"content.storage.provider",t,255),g(n.locator,"content.storage.locator",t,8192)):u(t,"content.storage.type","unknown_storage","Storage type is not supported");e.content.encoding!==void 0&&(typeof e.content.encoding!="string"||e.content.encoding!=="utf8"&&e.content.encoding!=="base64"&&e.content.encoding!=="binary"&&!e.content.encoding.startsWith("custom:"))&&u(t,"content.encoding","unknown_encoding","Content encoding is not supported"),me(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?u(t,"provenance","missing_provenance","provenance is required"):(Yr(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((n,o)=>g(n,`provenance.capabilityLeaseIds[${o}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((n,o)=>g(n,`provenance.sourceArtifactIds[${o}]`,t,512)),e.provenance.attributes&&Le(e.provenance.attributes,"provenance.attributes",t,new Set));let r=new Set;return e.relationships?.forEach((n,o)=>{let i=`relationships[${o}]`;g(n.relation,`${i}.relation`,t,160),typeof n.relation=="string"&&!jo.has(n.relation)&&!n.relation.startsWith("custom:")&&u(t,`${i}.relation`,"unknown_relationship","Relationship type is not supported"),me(n.relation,"custom:",`${i}.relation`,t),g(n.target?.type,`${i}.target.type`,t,160),typeof n.target?.type=="string"&&!Fo.has(n.target.type)&&!n.target.type.startsWith("custom:")&&u(t,`${i}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),me(n.target?.type,"custom:",`${i}.target.type`,t),g(n.target?.id,`${i}.target.id`,t,512);let a=`${n.relation}:${n.target?.type}:${n.target?.id}:${n.target?.revision??""}`;r.has(a)&&u(t,i,"duplicate_relationship","Duplicate relationship"),r.add(a),n.attributes&&Le(n.attributes,`${i}.attributes`,t,new Set)}),e.anchors?.forEach((n,o)=>Xt(n,`anchors[${o}]`,t)),e.revision===1&&e.predecessorRevision!==void 0&&u(t,"predecessorRevision","unexpected_predecessor","First revision cannot have a predecessor"),e.revision>1&&(!Number.isInteger(e.predecessorRevision)||(e.predecessorRevision??0)>=e.revision)&&u(t,"predecessorRevision","invalid_predecessor","Later revisions require an earlier predecessor revision"),De(e.retention?.retainUntil,"retention.retainUntil",t),e.retention?.legalHold!==void 0&&typeof e.retention.legalHold!="boolean"&&u(t,"retention.legalHold","invalid_boolean","legalHold must be a boolean"),e.extensions&&Le(e.extensions,"extensions",t,new Set),t}function Ke(e){let t=Ho(e);if(t.length>0)throw new be("XENO artifact validation failed",t)}function Go(e,t){return Xo[e].includes(t)}function Ye(e,t){if(!Go(e,t))throw new kt(e,t)}function Dt(e,t){let r=[];return e.schemaVersion!==1&&u(r,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),g(e.eventId,"eventId",r,512),g(e.artifactId,"artifactId",r,512),(!Number.isInteger(e.artifactRevision)||e.artifactRevision<1)&&u(r,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(e.sequence)||e.sequence<1)&&u(r,"sequence","invalid_sequence","sequence must be a positive integer"),g(e.recordedAt,"recordedAt",r,128),De(e.recordedAt,"recordedAt",r),Yr(e.actor,"actor",r),!e.artifactHash||typeof e.artifactHash!="object"?u(r,"artifactHash","missing_hash","Artifact hash is required"):(g(e.artifactHash.algorithm,"artifactHash.algorithm",r,128),me(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",r),g(e.artifactHash.value,"artifactHash.value",r,512),e.artifactHash.algorithm==="sha256"&&!Kr.test(e.artifactHash.value)&&u(r,"artifactHash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters"),typeof e.artifactHash.algorithm=="string"&&e.artifactHash.algorithm!=="sha256"&&!e.artifactHash.algorithm.startsWith("custom:")&&u(r,"artifactHash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported")),["review-requested","comment-added","comment-resolved","comment-reopened","decision-recorded","review-withdrawn"].includes(e.type)||u(r,"type","unknown_review_event","Review event type is not supported"),e.type==="comment-added"?(g(e.commentId,"commentId",r,512),g(e.body,"body",r,65536),e.anchor&&Xt(e.anchor,"anchor",r)):e.type==="comment-resolved"||e.type==="comment-reopened"?g(e.commentId,"commentId",r,512):e.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(e.decision)||u(r,"decision","unknown_review_decision","Review decision is not supported"),e.scope&&Xt(e.scope,"scope",r)),t&&(e.artifactId!==t.artifactId&&u(r,"artifactId","artifact_mismatch","Review event targets a different artifact"),e.artifactRevision!==t.revision&&u(r,"artifactRevision","revision_mismatch","Review event targets a different revision"),e.artifactHash&&(e.artifactHash.algorithm!==t.content.hash.algorithm||e.artifactHash.value!==t.content.hash.value)&&u(r,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),r}function Lt(e){let t="not_requested",r,n,o,i=0,a=new Set,c=new Set;for(let s of[...e].sort((l,y)=>l.sequence-y.sequence))o=s.recordedAt,s.type==="review-requested"?t="pending":s.type==="review-withdrawn"?t="withdrawn":s.type==="comment-added"?(a.add(s.commentId),c.delete(s.commentId),t==="not_requested"&&(t="pending")):s.type==="comment-resolved"?c.add(s.commentId):s.type==="comment-reopened"?c.delete(s.commentId):s.type==="decision-recorded"&&(s.scope?i+=1:(r=s.decision,n=s.eventId,t=s.decision));return{status:t,totalComments:a.size,unresolvedComments:[...a].filter(s=>!c.has(s)).length,...r?{latestDecision:r}:{},...n?{latestDecisionEventId:n}:{},...i>0?{scopedDecisionCount:i}:{},...o?{lastReviewedAt:o}:{}}}var f=class extends Error{constructor(r,n,o,i){super(n,i);this.code=r;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},Ue=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(t={}){this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(r=>(this.idCounter+=1,`${r}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),t.initialState&&this.hydrate(t.initialState)}exportState(){let t=[...this.records.values()].flatMap(r=>[...r.values()]).sort(Zr).map(r=>({artifact:Me(r.artifact),recordVersion:r.recordVersion,lifecycleEvents:structuredClone(r.lifecycleEvents),reviewEvents:structuredClone(r.reviewEvents)}));return{schemaVersion:1,records:t}}async create(t){if(Ke(t),this.assertInitialState(t),t.revision!==1)throw new f("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:t.artifactId,revision:t.revision});if(this.records.has(t.artifactId))throw new f("ARTIFACT_ALREADY_EXISTS",`Artifact ${t.artifactId} already exists`,{artifactId:t.artifactId});let r=Me(t),n=this.createLifecycleEvent({artifact:r,sequence:1,actor:r.provenance.producer,fromState:null,toState:r.state,reason:"artifact-created"}),o={artifact:r,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(r.artifactId,new Map([[r.revision,o]])),this.currentRevisions.set(r.artifactId,r.revision),ge(o)}async createRevision(t,r={}){Ke(t),this.assertInitialState(t);let n=this.getMutable(t.artifactId);this.assertVersion(n,r.expectedRecordVersion);let o=n.artifact.revision+1;if(t.revision!==o||t.predecessorRevision!==n.artifact.revision)throw new f("ARTIFACT_REVISION_INVALID",`Revision ${t.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:t.artifactId,currentRevision:n.artifact.revision,requestedRevision:t.revision});if(qo(t,n.artifact))throw new f("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:t.artifactId,revision:t.revision});if(n.artifact.state==="archived")throw new f("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:t.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){Ye(n.artifact.state,"superseded");let s=this.now(),l=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:r.actor??t.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:r.reason??`superseded-by-revision-${t.revision}`,recordedAt:s});n.artifact.state="superseded",n.artifact.updatedAt=s,n.lifecycleEvents.push(l),n.recordVersion+=1}let i=Me(t),a=this.createLifecycleEvent({artifact:i,sequence:1,actor:r.actor??i.provenance.producer,fromState:null,toState:i.state,reason:r.reason??`revision-created-from-${n.artifact.revision}`}),c={artifact:i,recordVersion:1,lifecycleEvents:[a],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,c),this.currentRevisions.set(i.artifactId,i.revision),ge(c)}async get(t,r){let n=this.records.get(t);if(!n)return;let o=r??this.currentRevisions.get(t);if(o===void 0)return;let i=n.get(o);return i?ge(i):void 0}async require(t,r){let n=await this.get(t,r);if(!n)throw new f("ARTIFACT_NOT_FOUND",`Artifact ${t}${r===void 0?"":` revision ${r}`} was not found`,{artifactId:t,...r===void 0?{}:{revision:r}});return n}async list(t={}){let r=[];for(let[n,o]of this.records)if(!(t.artifactIds&&!t.artifactIds.includes(n)))if(t.includeSuperseded)r.push(...o.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let a=o.get(i);a&&r.push(a)}}return r.filter(n=>zo(n.artifact,t)).sort(Zr).map(ge)}async listRevisions(t){let r=this.records.get(t);return r?[...r.values()].sort((n,o)=>n.artifact.revision-o.artifact.revision).map(ge):[]}async transition(t){let r=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(r,t.expectedRecordVersion),Ye(r.artifact.state,t.toState),t.toState==="approved"||t.toState==="rejected"){let a=t.reviewEventId?r.reviewEvents.find(s=>s.eventId===t.reviewEventId&&s.type==="decision-recorded"):void 0,c=Lt(r.reviewEvents);if(!a||a.decision!==t.toState||c.latestDecisionEventId!==a.eventId)throw new f("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${t.toState} requires a matching decision event`,{artifactId:t.artifactId,revision:r.artifact.revision});if(t.toState==="approved"&&c.unresolvedComments>0)throw new f("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${c.unresolvedComments} unresolved review comment(s)`,{artifactId:t.artifactId,revision:r.artifact.revision,unresolvedComments:c.unresolvedComments})}let n=this.now(),o=r.artifact.state,i=this.createLifecycleEvent({artifact:r.artifact,sequence:r.lifecycleEvents.length+1,actor:t.actor,fromState:o,toState:t.toState,reason:t.reason,reviewEventId:t.reviewEventId,recordedAt:n});return r.artifact.state=t.toState,r.artifact.updatedAt=n,r.lifecycleEvents.push(i),r.recordVersion+=1,ge(r)}async appendReviewEvent(t){let r=t.event,n=this.getMutable(r.artifactId,r.artifactRevision);if(this.assertVersion(n,t.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new f("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:r.artifactId,revision:r.artifactRevision});if(this.assertReviewCommentState(n,r),(r.type==="review-requested"||r.type==="review-withdrawn"||r.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new f("ARTIFACT_REVIEW_INVALID",`${r.type} requires an artifact in pending_review state`,{artifactId:r.artifactId,revision:r.artifactRevision});let o={...structuredClone(r),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=Dt(o,n.artifact);if(i.length>0)throw new be("XENO artifact review event validation failed",i);return n.reviewEvents.push(o),n.recordVersion+=1,ge(n)}getMutable(t,r){let n=this.records.get(t),o=r??this.currentRevisions.get(t),i=o===void 0?void 0:n?.get(o);if(!i)throw new f("ARTIFACT_NOT_FOUND",`Artifact ${t}${r===void 0?"":` revision ${r}`} was not found`,{artifactId:t,...r===void 0?{}:{revision:r}});return i}assertVersion(t,r){if(r!==void 0&&r!==t.recordVersion)throw new f("ARTIFACT_CONFLICT",`Expected record version ${r}, found ${t.recordVersion}`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision,expectedRecordVersion:r,actualRecordVersion:t.recordVersion})}assertInitialState(t){if(t.state!=="draft"&&t.state!=="pending_review")throw new f("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:t.artifactId,revision:t.revision})}assertReviewCommentState(t,r){if(r.type==="comment-added"){if(t.reviewEvents.some(i=>i.type==="comment-added"&&i.commentId===r.commentId))throw new f("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} already exists`);if(r.parentCommentId&&!t.reviewEvents.some(i=>i.type==="comment-added"&&i.commentId===r.parentCommentId))throw new f("ARTIFACT_REVIEW_INVALID",`Parent comment ${r.parentCommentId} does not exist`);return}if(r.type!=="comment-resolved"&&r.type!=="comment-reopened")return;if(!t.reviewEvents.some(i=>i.type==="comment-added"&&i.commentId===r.commentId))throw new f("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} does not exist`);let o=Jo(t.reviewEvents,r.commentId);if(r.type==="comment-resolved"&&o.resolved)throw new f("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} is already resolved`);if(r.type==="comment-reopened"&&!o.resolved)throw new f("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} is not resolved`)}createLifecycleEvent(t){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:t.artifact.artifactId,revision:t.artifact.revision,sequence:t.sequence,recordedAt:t.recordedAt??this.now(),actor:{...t.actor},fromState:t.fromState,toState:t.toState,...t.reason?{reason:t.reason}:{},...t.reviewEventId?{reviewEventId:t.reviewEventId}:{}}}nextEventId(t){let r=this.idFactory(t);if(typeof r!="string"||r.trim().length===0||this.eventIds.has(r))throw new f("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${t} ID`);return this.eventIds.add(r),r}hydrate(t){if(t.schemaVersion!==1||!Array.isArray(t.records))throw new f("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let r=[...t.records].sort((n,o)=>n.artifact.artifactId.localeCompare(o.artifact.artifactId)||n.artifact.revision-o.artifact.revision);for(let n of r){let o=Wo(n,this.eventIds),i=this.records.get(o.artifact.artifactId);if(i||(i=new Map,this.records.set(o.artifact.artifactId,i)),i.has(o.artifact.revision))throw new f("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${o.artifact.artifactId}:${o.artifact.revision}`);i.set(o.artifact.revision,o),this.currentRevisions.set(o.artifact.artifactId,o.artifact.revision)}for(let[n,o]of this.records){let i=[...o.values()].sort((a,c)=>a.artifact.revision-c.artifact.revision);for(let a=0;a<i.length;a+=1){let c=i[a],s=a+1;if(c.artifact.revision!==s)throw new f("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${s}`);if(a===0&&c.artifact.predecessorRevision!==void 0)throw new f("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(a>0&&c.artifact.predecessorRevision!==s-1)throw new f("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${s} has an invalid predecessor`);if(a<i.length-1&&c.artifact.state!=="superseded")throw new f("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${s} must be superseded`)}}}};function Wo(e,t){if(Ke(e.artifact),!Number.isInteger(e.recordVersion)||e.recordVersion<1)throw new f("ARTIFACT_REVISION_INVALID","Persisted artifact recordVersion must be a positive integer",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(!Array.isArray(e.lifecycleEvents)||e.lifecycleEvents.length===0||!Array.isArray(e.reviewEvents))throw new f("ARTIFACT_REVISION_INVALID","Persisted artifact records require lifecycle and review event arrays",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let r=e.lifecycleEvents.length+e.reviewEvents.length;if(e.recordVersion!==r)throw new f("ARTIFACT_REVISION_INVALID",`Persisted record version ${e.recordVersion} does not match ${r} mutations`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let n=null;for(let i=0;i<e.lifecycleEvents.length;i+=1){let a=e.lifecycleEvents[i];if(a.schemaVersion!==1||a.artifactId!==e.artifact.artifactId||a.revision!==e.artifact.revision||a.sequence!==i+1||a.fromState!==n||typeof a.eventId!="string"||a.eventId.length===0||t.has(a.eventId)||!Number.isFinite(Date.parse(a.recordedAt)))throw new f("ARTIFACT_REVISION_INVALID",`Persisted lifecycle event ${i+1} is invalid`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(n===null){if(a.toState!=="draft"&&a.toState!=="pending_review")throw new f("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:e.artifact.artifactId,revision:e.artifact.revision})}else Ye(n,a.toState);t.add(a.eventId),n=a.toState}if(n!==e.artifact.state)throw new f("ARTIFACT_REVISION_INVALID","Persisted artifact state does not match its lifecycle tail",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let o=new Map;for(let i=0;i<e.reviewEvents.length;i+=1){let a=e.reviewEvents[i];if(a.sequence!==i+1||t.has(a.eventId))throw new f("ARTIFACT_REVIEW_INVALID",`Persisted review event ${i+1} has an invalid sequence or duplicate ID`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let c=Dt(a,e.artifact);if(c.length>0)throw new be("Persisted XENO artifact review event validation failed",c);if(a.type==="comment-added"){if(o.has(a.commentId)||a.parentCommentId!==void 0&&!o.has(a.parentCommentId))throw new f("ARTIFACT_REVIEW_INVALID",`Persisted comment ${a.commentId} has an invalid identity or parent`);o.set(a.commentId,!1)}else if(a.type==="comment-resolved"||a.type==="comment-reopened"){let s=o.get(a.commentId);if(s===void 0||a.type==="comment-resolved"&&s||a.type==="comment-reopened"&&!s)throw new f("ARTIFACT_REVIEW_INVALID",`Persisted comment transition for ${a.commentId} is invalid`);o.set(a.commentId,a.type==="comment-resolved")}t.add(a.eventId)}return{artifact:Me(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function qo(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function zo(e,t){return!(t.kinds&&!t.kinds.includes(e.kind)||t.states&&!t.states.includes(e.state)||t.runId&&e.identity?.runId!==t.runId||t.sessionId&&e.identity?.sessionId!==t.sessionId||t.turnId&&e.identity?.turnId!==t.turnId||t.taskId&&e.identity?.taskId!==t.taskId||t.workspaceId&&e.identity?.workspaceId!==t.workspaceId||t.repositoryId&&e.identity?.repositoryId!==t.repositoryId||t.producerId&&e.provenance.producer.id!==t.producerId||t.sensitivity&&!t.sensitivity.includes(e.sensitivity))}function Zr(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function Jo(e,t){let r=!1;for(let n of e)(n.type==="comment-resolved"||n.type==="comment-reopened")&&n.commentId===t&&(r=n.type==="comment-resolved");return{resolved:r}}function Me(e){return structuredClone(e)}function ge(e){return{artifact:Me(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:Lt(e.reviewEvents)}}var Mt=32*1024*1024,Ko=1024*1024*1024,Yo=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function Ze(e){let r=(e.now??(()=>new Date().toISOString()))(),n=new Set;return e.evidence.map((o,i)=>{if(Qo(o),n.has(o.evidenceId))throw new d("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${o.evidenceId}`);n.add(o.evidenceId);let a=Zo(o),c=(0,en.createHash)("sha256").update(`${e.request.operationId}\0${o.evidenceId}\0${a.hash.value}`).digest("hex").slice(0,32);return{schemaVersion:1,artifactId:`automation_${c}`,revision:1,kind:o.kind,title:o.title,...o.description?{description:o.description}:{},state:"draft",createdAt:r,mediaType:o.mediaType,sensitivity:o.sensitivity??e.policy.sensitivity,identity:{...e.request.identity},content:a,provenance:{producer:{kind:"tool",id:e.request.governingToolName,displayName:e.manifest.adapterId,profileFingerprint:e.request.executionContract.profile.fingerprint},operationId:e.request.operationId,executionContractFingerprint:e.request.executionContract.fingerprint,capabilityLeaseIds:[e.request.capabilityLeaseId],attributes:{automationProtocolVersion:e.request.protocolVersion,automationOperation:e.request.operation,automationEvidenceId:o.evidenceId,automationEvidencePhase:o.phase,adapterId:e.manifest.adapterId,adapterVersion:e.manifest.adapterVersion,evidenceIndex:i}},...o.anchors?{anchors:structuredClone(o.anchors)}:{},...e.policy.retainUntil||e.policy.legalHold!==void 0?{retention:{...e.policy.retainUntil?{retainUntil:e.policy.retainUntil}:{},...e.policy.legalHold!==void 0?{legalHold:e.policy.legalHold}:{}}}:{},extensions:{...o.extensions??{},xenoAutomation:{phase:o.phase,adapter:e.manifest.adapterId,certifiedAdapter:e.manifest.certified}}}})}async function Ee(e,t){if(!e)return t.map(n=>structuredClone(n));let r=[];for(let n of t)try{let o=await e.create(n);r.push(o.artifact)}catch(o){if(o instanceof f&&o.code==="ARTIFACT_ALREADY_EXISTS"){let i=await e.require(n.artifactId,n.revision);if(i.artifact.content.hash.value===n.content.hash.value){r.push(i.artifact);continue}}throw new d("AUTOMATION_EVIDENCE_PERSISTENCE_FAILED",`Failed to persist automation evidence ${n.artifactId}`,{artifactId:n.artifactId},{cause:o})}return r}function Be(e,t,r){if(t[r]==="required"&&!e.some(n=>n.phase===r))throw new d("AUTOMATION_EVIDENCE_REQUIRED",`Automation operation requires ${r} evidence before it can be trusted`)}function Zo(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return Qr(t),{hash:fe(e.content.text),sizeBytes:t,storage:{type:"inline",text:e.content.text},encoding:"utf8",...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}if(e.content.type==="base64"){let t=ei(e.content.base64);return Qr(t.byteLength),{hash:fe(t),sizeBytes:t.byteLength,storage:{type:"inline",base64:e.content.base64},encoding:"base64",...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}if(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0||e.content.sizeBytes>Ko)throw new d("AUTOMATION_EVIDENCE_INVALID","Referenced evidence size is invalid");if(!e.content.hash?.algorithm||!e.content.hash.value)throw new d("AUTOMATION_EVIDENCE_INVALID","Referenced evidence requires a content hash");if(e.content.hash.algorithm==="sha256"&&!/^[a-f0-9]{64}$/.test(e.content.hash.value))throw new d("AUTOMATION_EVIDENCE_INVALID","Referenced evidence SHA-256 is invalid");return{hash:{...e.content.hash},sizeBytes:e.content.sizeBytes,storage:structuredClone(e.content.storage),...e.content.encoding?{encoding:e.content.encoding}:{},...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}function Qo(e){(!e||typeof e!="object")&&K("Evidence must be an object"),Yo.test(e.evidenceId)||K("Evidence ID is invalid"),["before","action","after","recording","diagnostic"].includes(e.phase)||K("Evidence phase is invalid"),(!e.kind||!e.title?.trim()||e.title.length>512)&&K("Evidence kind and title are required"),/^[\w!#$&^_.+-]+\/[\w!#$&^_.+-]+(?:;.*)?$/.test(e.mediaType)||K("Evidence media type is invalid")}function ei(e){(e.length===0||e.length>Math.ceil(Mt/3)*4+4)&&K("Inline base64 evidence is empty or too large"),(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)&&K("Inline evidence is not canonical base64");let t=Buffer.from(e,"base64");return t.toString("base64")!==e&&K("Inline evidence is not canonical base64"),t}function Qr(e){e>Mt&&K(`Inline evidence exceeds ${Mt} bytes`)}function K(e){throw new d("AUTOMATION_EVIDENCE_INVALID",e)}var an=require("node:crypto");var et=require("node:crypto");var tn=16*1024*1024;async function Ut(e,t,r,n){await e.assertCurrent(t);let o={operationId:t.operationId,fingerprint:r,ownerToken:(0,et.randomUUID)()},i=await e.journal.begin(o);if(await e.assertCurrent(t),!i.claimed){if(i.record.outcome.kind!=="result")throw Y();let p=await e.artifactRepository.require(i.record.outcome.artifactId,1),v=p.artifact;if(v.content.storage.type!=="inline"||v.content.encoding!=="utf8"||v.provenance.operationId!==t.operationId||v.extensions?.automationRequestFingerprint!==r)throw Y();let m=v.content.storage.text;if(typeof m!="string"||Buffer.byteLength(m)>tn||Qe(m)!==i.record.outcome.sha256||v.content.hash.value!==i.record.outcome.sha256)throw Y();let x=JSON.parse(m);return rn(x,t),await e.assertCurrent(t),{...x,replayed:!0}}let a="automation-consume:"+Qe(t.operationId+"\0"+r),c=await n(a);rn(c,t);let s=JSON.stringify(c),l=Buffer.byteLength(s);if(l>tn)throw Y();let y=Qe(s),A={schemaVersion:1,artifactId:"automation_result_"+Qe(t.operationId+"\0"+r),revision:1,kind:"custom:automation-result",title:"Governed automation outcome",state:"draft",createdAt:c.completedAt,mediaType:"application/json",sensitivity:"restricted",identity:{...t.identity},content:{hash:{algorithm:"sha256",value:y},sizeBytes:l,encoding:"utf8",storage:{type:"inline",text:s}},provenance:{producer:{kind:"system",id:"xeno-governed-automation"},operationId:t.operationId,executionContractFingerprint:t.executionContract.fingerprint,capabilityLeaseIds:[t.capabilityLeaseId]},extensions:{automationRequestFingerprint:r}};return await e.assertCurrent(t),await Ee(e.artifactRepository,[A]),await e.journal.finish(o,{kind:"result",artifactId:A.artifactId,sha256:y}),await e.assertCurrent(t),{...c,replayed:!1}}function rn(e,t){if(!e||typeof e!="object")throw Y();let r=e;if(r.operationId!==t.operationId||!["ok","error","cancelled","denied","evidence-incomplete"].includes(r.status)||!r.target||!Array.isArray(r.artifacts)||!r.lease||!r.adapter)throw Y()}function Qe(e){return(0,et.createHash)("sha256").update(e).digest("hex")}function Y(){return new d("AUTOMATION_OUTCOME_PENDING","Automation outcome is pending or unknown; recover the same operation rather than dispatching it again")}var nn=3e4,on=1e3,$e=class{adapter;leaseAuthority;durable;artifactRepository;now;assertCurrent;executions=new Map;active=new Map;constructor(t){if(this.adapter=t.adapter,this.leaseAuthority=t.leaseAuthority,!!t.leaseAuthority==!!t.durable)throw new Error("Choose exactly one legacy or durable automation authority");this.durable=t.durable,this.artifactRepository=t.durable?.artifactRepository??t.artifactRepository,this.now=t.now??(()=>new Date().toISOString()),this.assertCurrent=t.assertCurrent||t.adapter.assertCurrent?async r=>{await t.assertCurrent?.(r),await t.adapter.assertCurrent?.(r)}:void 0,this.onPreflight=t.onPreflight,this.onGrant=t.onGrant}onPreflight;onGrant;execute(t,r){t=structuredClone(t);let n=ii(t),o=this.executions.get(t.operationId);if(o){if(o.fingerprint!==n)throw new d("AUTOMATION_OPERATION_CONFLICT",`Operation ${t.operationId} was already submitted with different authority or parameters`);if(this.durable){let l=this.durable;return l.assertCurrent(t).then(()=>this.assertCurrent?.(t)).then(()=>o.promise).then(async y=>(await l.assertCurrent(t),await this.assertCurrent?.(t),structuredClone(y)))}return this.assertCurrent?Promise.resolve(this.assertCurrent(t)).then(()=>o.promise).then(async l=>(await this.assertCurrent?.(t),structuredClone(l))):o.promise}if(this.active.size>=on)throw new d("AUTOMATION_OPERATION_CONFLICT","Automation active-operation capacity reached");let i=new AbortController,a=ai(r,i);this.active.set(t.operationId,i);let c=this.durable,s=(c?Ut({...c,assertCurrent:async l=>{await c.assertCurrent(l),await this.assertCurrent?.(l)}},t,n,l=>this.executeFresh(t,i.signal,l)):this.executeFresh(t,i.signal)).finally(()=>{a(),this.active.delete(t.operationId)});return this.executions.set(t.operationId,{fingerprint:n,promise:s}),this.durable&&s.then(()=>this.executions.delete(t.operationId),()=>this.executions.delete(t.operationId)),this.trimIdempotencyRecords(),s}async stop(t,r="human-stop"){let n=this.active.get(t);return n?(n.abort(new Error(r)),await this.adapter.stop?.(t,r),!0):!1}async executeFresh(t,r,n){J(t),await this.assertCurrent?.(t),H(r);let o=await this.adapter.manifest();F(o),qe(t,o);let i=X(t.operation),a=_t(t),c=this.now(),s=await this.adapter.preflight(t,r);ti(s,this.now()),ze(t,o,s.observedTarget),H(r),await this.onPreflight?.(structuredClone(t),structuredClone(s),r),H(r);let l=s.evidence??[];J(t),await this.assertCurrent?.(t),H(r),Be(l,a,"before");let y=await Ee(this.artifactRepository,Ze({request:t,manifest:o,policy:a,evidence:l,now:this.now}));if(H(r),Date.parse(s.expiresAt)<=Date.parse(this.now()))throw new d("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let A=Ot(t,s.observedTarget);await this.assertCurrent?.(t);let p;if(this.durable){await this.durable.assertCurrent(t);let I=await this.durable.consume(n,t.capabilityLeaseId,t.expectedLeaseVersion,A);if(I.executionDisposition!=="dispatch-once"||I.replayed)throw Y();p=I.lease,await this.durable.assertCurrent(t)}else p=await this.leaseAuthority.consume(t.capabilityLeaseId,t.expectedLeaseVersion,A);let v={contractFingerprint:t.executionContract.fingerprint,lease:p,capabilityUse:A};await this.onGrant?.(structuredClone(t),structuredClone(s),structuredClone(v),r),H(r);let m;try{H(r),J(t),await this.assertCurrent?.(t),H(r),m=await this.adapter.execute(t,s,v,r)}catch(I){return Bt({request:t,manifest:o,descriptorEffect:i.effect,target:s.observedTarget,lease:p,artifacts:y,startedAt:c,completedAt:this.now(),status:r.aborted?"cancelled":"error",code:r.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_ADAPTER_ERROR",message:r.aborted?"Automation operation was stopped":si(I)})}if(ri(m),H(r),J(t),await this.assertCurrent?.(t),m.operationId!==void 0&&m.operationId!==t.operationId)throw new d("AUTOMATION_RESPONSE_INVALID","Adapter returned another operation identity");let x=ni(s.observedTarget,m.observedTarget),C;try{ze(t,o,m.observedTarget)}catch(I){C=I instanceof Error?I:new Error(String(I))}if(x||C)return Bt({request:t,manifest:o,descriptorEffect:i.effect,target:s.observedTarget,lease:p,artifacts:y,startedAt:m.startedAt,completedAt:m.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:x??C.message});if(m.status!=="ok")return{operationId:t.operationId,status:m.status,effect:i.effect,startedAt:m.startedAt,completedAt:m.completedAt,adapter:$t(o),target:structuredClone(m.observedTarget),artifacts:y,lease:Vt(p),error:m.error?{...m.error}:{code:"AUTOMATION_ADAPTER_ERROR",message:"Owning adapter refused the operation."}};let R=m.evidence??[];oi(l,R);let k=[],E;try{Be(R,a,"after"),Be([...l,...R],a,"recording"),k=await Ee(this.artifactRepository,Ze({request:t,manifest:o,policy:a,evidence:R,now:this.now}))}catch(I){E=I instanceof Error?I:new Error(String(I))}let S=[...y,...k];return H(r),J(t),await this.assertCurrent?.(t),E?Bt({request:t,manifest:o,descriptorEffect:i.effect,target:m.observedTarget,lease:p,artifacts:S,startedAt:m.startedAt,completedAt:m.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:E.message}):{operationId:t.operationId,status:m.status,effect:i.effect,startedAt:m.startedAt,completedAt:m.completedAt,adapter:$t(o),target:structuredClone(m.observedTarget),...m.data!==void 0?{data:structuredClone(m.data)}:{},artifacts:S,lease:Vt(p),...m.error?{error:{...m.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>on;){let t=this.executions.keys().next().value;if(!t||this.active.has(t))break;this.executions.delete(t)}}};function ti(e,t){if(!e||typeof e!="object"||!e.token?.trim())throw new d("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an invalid preflight token");let r=Date.parse(e.preparedAt),n=Date.parse(e.expiresAt),o=Date.parse(t);if(!Number.isFinite(r)||!Number.isFinite(n)||n<=r||n<=o)throw new d("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an expired or invalid preflight window");if(n-r>nn)throw new d("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${nn} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new d("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function ri(e){if(!e||typeof e!="object")throw new d("AUTOMATION_REQUEST_INVALID","Adapter returned no result");if(!["ok","denied","cancelled","error"].includes(e.status))throw new d("AUTOMATION_REQUEST_INVALID","Adapter returned an invalid status");if(!Number.isFinite(Date.parse(e.startedAt))||!Number.isFinite(Date.parse(e.completedAt)))throw new d("AUTOMATION_REQUEST_INVALID","Adapter result timestamps are invalid");if(Date.parse(e.completedAt)<Date.parse(e.startedAt))throw new d("AUTOMATION_REQUEST_INVALID","Adapter completion precedes its start");if(!e.observedTarget||typeof e.observedTarget!="object")throw new d("AUTOMATION_REQUEST_INVALID","Adapter result has no observed target")}function ni(e,t){let r=["tabId","pageId","deviceId","applicationId","displayId"];for(let n of r)if(e[n]!==void 0&&e[n]!==t[n])return`Adapter changed bound ${n} between preflight and execution`}function oi(e,t){let r=new Set(e.map(n=>n.evidenceId));for(let n of t){if(r.has(n.evidenceId))throw new d("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${n.evidenceId}`);r.add(n.evidenceId)}}function Bt(e){return{operationId:e.request.operationId,status:e.status,effect:e.descriptorEffect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:$t(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:Vt(e.lease),error:{code:e.code,message:e.message}}}function $t(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function Vt(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function ii(e){return(0,an.createHash)("sha256").update(JSON.stringify(Ft(e))).digest("hex")}function Ft(e){return Array.isArray(e)?e.map(Ft):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Ft(r)]))}function ai(e,t){if(!e)return()=>{};let r=()=>t.abort(e.reason);return e.aborted?r():e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)}function H(e){if(e.aborted)throw new d("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function si(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}var cn=require("node:path");async function ci(e){if(!(0,cn.isAbsolute)(e))throw Error("Automation journal requires an absolute host-owned path");let{DatabaseSync:t}=await import("node:sqlite");return new rt(new t(e))}var rt=class{constructor(t){this.database=t;try{if(t.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);"),t.prepare("SELECT version FROM automation_execution_schema WHERE id=1").get()?.version!==1)throw Error("Unsupported automation execution journal");t.exec("CREATE TABLE IF NOT EXISTS automation_executions(id TEXT PRIMARY KEY,body TEXT NOT NULL)")}catch(r){throw t.close(),this.closed=!0,r}}database;closed=!1;async begin(t){return t=structuredClone(t),jt(t),ve(t,["operationId","fingerprint","ownerToken"]),this.transaction(()=>{let r=this.read(t.operationId);if(r){if(r.fingerprint!==t.fingerprint)throw tt();return{claimed:!1,record:r}}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 o={schemaVersion:1,...t,outcome:{kind:"pending"}};return this.database.prepare("INSERT INTO automation_executions(id,body) VALUES(?,?)").run(t.operationId,sn(o)),{claimed:!0,record:o}})}async get(t){if(typeof t!="string"||!t.trim()||t.length>1024)throw Error("Invalid automation journal identity");return this.transaction(()=>this.read(t))}async finish(t,r){t=structuredClone(t),r=structuredClone(r),jt(t),ve(t,["operationId","fingerprint","ownerToken"]);let n={schemaVersion:1,...t,outcome:r};return Ht(n),this.transaction(()=>{let o=this.read(t.operationId);if(!o||o.fingerprint!==t.fingerprint||o.ownerToken!==t.ownerToken)throw tt();if(o.outcome.kind!=="pending"){if(JSON.stringify(o.outcome)!==JSON.stringify(r))throw tt();return}this.database.prepare("UPDATE automation_executions SET body=? WHERE id=?").run(sn(n),t.operationId)})}close(){this.closed||(this.closed=!0,this.database.close())}read(t){let r=this.database.prepare("SELECT CASE WHEN length(body)<=16384 THEN body ELSE NULL END AS body FROM automation_executions WHERE id=?").get(t);if(!r)return;if(typeof r.body!="string")throw Error("Corrupt automation journal size");let n=JSON.parse(r.body);if(Ht(n),n.operationId!==t)throw tt();return n}async transaction(t){let r=Date.now()+1e3;for(;;){if(this.closed)throw Error("Automation journal closed");let n=!1;try{this.database.exec("BEGIN IMMEDIATE"),n=!0;let o=t();return this.database.exec("COMMIT"),o}catch(o){if(n)try{this.database.exec("ROLLBACK")}catch{}if(Date.now()>=r||!/SQLITE_BUSY|database is locked/.test(String(o)))throw o;await new Promise(i=>setTimeout(i,10))}}}};function jt(e){for(let t of[e.operationId,e.ownerToken])if(typeof t!="string"||!t.trim()||t.length>1024)throw Error("Invalid automation journal identity");if(!/^[a-f0-9]{64}$/.test(e.fingerprint))throw Error("Invalid automation journal fingerprint")}function Ht(e){if(!e||typeof e!="object")throw Error("Invalid automation journal record");let t=e;if(jt(t),ve(t,["schemaVersion","operationId","fingerprint","ownerToken","outcome"]),t.schemaVersion!==1||!t.outcome)throw Error("Invalid automation journal schema");let r=t.outcome;if(r.kind==="result"){if(ve(r,["kind","artifactId","sha256"]),typeof r.artifactId!="string"||!r.artifactId||r.artifactId.length>256||!/^[a-f0-9]{64}$/.test(r.sha256))throw Error("Invalid automation result reference")}else if(r.kind==="failed"){if(ve(r,["kind","code"]),typeof r.code!="string"||!/^AUTOMATION_[A-Z_]{1,100}$/.test(r.code))throw Error("Invalid automation failure code")}else if(r.kind==="pending")ve(r,["kind"]);else throw Error("Invalid automation journal outcome")}function ve(e,t){if(Array.isArray(e)||Object.keys(e).some(r=>!t.includes(r)))throw Error("Unexpected automation journal fields")}function sn(e){Ht(e);let t=JSON.stringify(e);if(t.length>16384)throw Error("Automation journal record too large");return t}function tt(){return new d("AUTOMATION_OPERATION_CONFLICT","Automation operation identity or owner conflicts with durable state")}function dn(e,t=()=>new Date().toISOString()){let r=[];li(r,"manifest.valid",()=>F(e));let n=new Set(e.operations);return Se(r,n,e.supports.consoleInspection,"browser.console.read","console inspection"),Se(r,n,e.supports.networkInspection,"browser.network.read","network inspection"),Se(r,n,e.supports.storageInspection,"browser.storage.read","storage inspection"),Se(r,n,e.supports.pageErrorInspection,"browser.page-errors.read","page-error inspection"),Se(r,n,e.supports.recordings,"browser.record.start","recording start"),Se(r,n,e.supports.recordings,"browser.record.stop","recording stop"),n.has("browser.upload")&&oe(r,"policy.upload",e.policyEnforcement.upload,"Upload policy is enforced"),n.has("browser.download")&&oe(r,"policy.download",e.policyEnforcement.download,"Download policy is enforced"),[...n].some(o=>o.startsWith("browser."))&&(oe(r,"policy.redirect",e.policyEnforcement.redirect,"Redirect policy is enforced"),oe(r,"control.handback",e.supports.deterministicHandback,"Deterministic hand-back is supported")),[...n].some(o=>o.startsWith("computer."))&&(oe(r,"control.stop",e.supports.immediateStop,"Immediate human stop is supported"),oe(r,"privacy.redaction",e.supports.sensitiveRegionRedaction,"Sensitive-region redaction is supported")),oe(r,"certification.binding",!e.certified||!!e.certificationArtifactId,e.certified?"Certification artifact is bound":"Adapter does not claim certification"),{protocolVersion:1,adapter:{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture},generatedAt:t(),passed:r.every(o=>o.status==="pass"),checks:r}}function di(e){let r=dn(e).checks.filter(n=>n.status==="fail");if(r.length>0)throw new d("AUTOMATION_OPERATION_UNSUPPORTED",r.map(n=>`${n.id}: ${n.message}`).join("; "))}function Se(e,t,r,n,o){let i=t.has(n);oe(e,`capability.${n}`,r===i,r===i?`${o} declaration matches the operation catalog`:`${o} declaration does not match ${n}`)}function li(e,t,r){try{r(),e.push({id:t,status:"pass",message:"Manifest satisfies the protocol contract"})}catch(n){e.push({id:t,status:"fail",message:n instanceof Error?n.message:String(n)})}}function oe(e,t,r,n){e.push({id:t,status:r?"pass":"fail",message:n})}var ui=6e4,pi=48*1024*1024,Ve=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;ownedView;constructor(t){if(this.endpoint=fi(t.baseUrl),this.token=mi(t.token),this.timeoutMs=ln(t.timeoutMs??ui,1e3,3e5,"timeoutMs"),this.maxResponseBytes=ln(t.maxResponseBytes??pi,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=t.fetch??globalThis.fetch,t.ownedView&&(!/^[a-f0-9]{64}$/.test(t.ownedView.ownerId)||!t.ownedView.sessionId?.trim()))throw new d("AUTOMATION_REQUEST_INVALID","Owned Browser frame binding is invalid.");if(this.ownedView=t.ownedView?Object.freeze({...t.ownedView}):void 0,typeof this.fetchImpl!="function")throw new d("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}async preflight(t,r){let n=await this.request("preflight","POST",t,r);if(this.ownedView&&t.operation==="browser.screenshot"){let o=t.declaredTarget?.tabId;if(!o||n.observedTarget.tabId!==o||t.identity.sessionId!==this.ownedView.sessionId)throw new d("AUTOMATION_IDENTITY_MISMATCH","Owned capture requires the exact host session and tab.");let i=await this.request(`target?tabId=${encodeURIComponent(o)}`,"GET",void 0,r);if(i.tabId!==o||!Number.isSafeInteger(i.documentEpoch)||i.documentEpoch<0)throw new d("AUTOMATION_TARGET_CHANGED","Owned capture target metadata changed.");return{...n,adapterState:{...n.adapterState,ownedViewDocumentEpoch:i.documentEpoch}}}return n}async execute(t,r,n,o){if(this.ownedView&&t.operation==="browser.screenshot"){let i=t.declaredTarget?.tabId,a=r.adapterState?.ownedViewDocumentEpoch;if(!i||r.observedTarget.tabId!==i||t.identity.sessionId!==this.ownedView.sessionId||!Number.isSafeInteger(a))throw new d("AUTOMATION_IDENTITY_MISMATCH","Owned frame does not bind this request.");let c=new Date().toISOString(),s=await this.request("view-frame","POST",{version:1,...this.ownedView,tabId:i,documentEpoch:a,request:t,preflight:r,grant:n},o);if(s.version!==1||s.ownerId!==this.ownedView.ownerId||s.sessionId!==this.ownedView.sessionId||s.tabId!==i||s.documentEpoch!==a||s.mediaType!=="image/png"||!Number.isFinite(Date.parse(s.capturedAt))||Date.parse(s.capturedAt)<Date.parse(c)||s.origin!==new URL(r.observedTarget.url??r.observedTarget.origin??"").origin||typeof s.base64!="string"||s.base64.length>5592408||!/^[A-Za-z0-9+/]+={0,2}$/.test(s.base64)||s.base64.length%4!==0)throw new d("AUTOMATION_RESPONSE_INVALID","Owned Browser returned a changed or oversized frame.");o.throwIfAborted(),J(t);let l=Buffer.from(s.base64,"base64");if(l.length<24||l.length>4*1024*1024||l.subarray(0,8).toString("hex")!=="89504e470d0a1a0a"||l.readUInt32BE(16)<1||l.readUInt32BE(20)<1||l.readUInt32BE(16)*l.readUInt32BE(20)>2073600)throw new d("AUTOMATION_RESPONSE_INVALID","Owned Browser returned invalid bounded PNG bytes.");return{operationId:t.operationId,status:"ok",startedAt:c,completedAt:s.capturedAt,observedTarget:r.observedTarget,evidence:[{evidenceId:`${t.operationId}.after`,phase:"after",kind:"screenshot",title:"Owned Browser frame",mediaType:"image/png",content:{type:"base64",base64:s.base64},sensitivity:"restricted"}]}}return this.request("execute","POST",{request:t,preflight:r,grant:n},o)}async stop(t,r){await this.request("stop","POST",{operationId:t,reason:r.slice(0,512)})}async request(t,r,n,o){let i=new AbortController,a=Ai(o,i),c=setTimeout(()=>i.abort(new Error("automation transport timeout")),this.timeoutMs);try{if(i.signal.aborted)throw new Error("Automation was cancelled before dispatch");let s=new URL(t,this.endpoint),l=this.fetchImpl(s,{method:r,redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.token}`,accept:"application/json",...r==="POST"?{"content-type":"application/json"}:{}},...r==="POST"?{body:JSON.stringify(n??{})}:{},signal:i.signal});l.then(p=>{i.signal.aborted&&p.body?.cancel().catch(()=>{})},()=>{});let y=await Gt(l,i.signal),A=await Gt(gi(y,this.maxResponseBytes,i.signal),i.signal);if(!y.ok){let p=hi(A);throw new d("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${t}: ${p.message}`,{status:y.status,route:t,adapterCode:p.code})}if(!Wt(A)||A.ok!==!0||!("result"in A))throw new d("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${t} envelope`);return A.result}catch(s){if(s instanceof d)throw s;let l=o?.aborted;throw new d(l?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",l?"Automation transport was stopped":`XENO Browser ${t} transport failed`,{route:t},{cause:s})}finally{clearTimeout(c),a()}}};function fi(e){let t;try{t=new URL(e)}catch(n){throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL is invalid",void 0,{cause:n})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires HTTP(S)");if(t.username||t.password||t.search||t.hash)throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL cannot contain credentials, query, or fragment");let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="::1")throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport must use a loopback host");if(!t.port)throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires an explicit port");return t.pathname="/v1/automation/",t}function mi(e){if(typeof e!="string"||e.length<32||e.length>512||/\s/.test(e))throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser session token is invalid");return e}async function gi(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw new d("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);if(e.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new d("AUTOMATION_RESPONSE_INVALID","XENO Browser response is not application/json");if(!e.body)throw new d("AUTOMATION_RESPONSE_INVALID","XENO Browser response body is missing");let i=e.body.getReader(),a=[],c=0;try{for(;;){let{done:y,value:A}=await Gt(i.read(),r);if(y)break;if(c+=A.byteLength,c>t)throw await i.cancel("response too large"),new d("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);a.push(A)}}finally{i.cancel().catch(()=>{}),i.releaseLock()}let s=new Uint8Array(c),l=0;for(let y of a)s.set(y,l),l+=y.byteLength;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch(y){throw new d("AUTOMATION_RESPONSE_INVALID","XENO Browser response contains invalid JSON",void 0,{cause:y})}}async function Gt(e,t){let r,n=new Promise((o,i)=>{r=()=>i(t.reason??new Error("Automation operation cancelled")),t.addEventListener("abort",r,{once:!0}),t.aborted&&r()});try{return await Promise.race([e,n])}finally{t.removeEventListener("abort",r)}}function hi(e){return Wt(e)&&Wt(e.error)?{code:typeof e.error.code=="string"?e.error.code.slice(0,128):"UNKNOWN",message:typeof e.error.message=="string"?e.error.message.slice(0,1024):"request failed"}:{code:"UNKNOWN",message:"request failed"}}function Ai(e,t){if(!e)return()=>{};let r=()=>t.abort(e.reason);return e.aborted?r():e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)}function ln(e,t,r,n){if(!Number.isSafeInteger(e)||e<t||e>r)throw new d("AUTOMATION_TRANSPORT_ERROR",`${n} must be an integer from ${t} to ${r}`);return e}function Wt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var yi=["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"],Te=class extends Ve{driver;constructor(t){super(t),this.driver=t.driver}async manifest(){let t=await super.manifest();if(F(t),!(this.driver==="browser"?["xeno-browser","xeno-browser-native"]:["xeno-extension-native","xeno-extension"]).includes(t.adapterId)||t.operations.some(n=>!n.startsWith("browser.")))throw new d("AUTOMATION_OPERATION_UNSUPPORTED","Configured Browser driver returned a different owning adapter contract.");return t}};var Pe=require("node:fs"),_n=require("node:crypto"),Nn=require("node:os"),ee=require("node:path");var Zt=require("node:crypto"),U=require("node:fs/promises"),W=require("node:path");var G=ur(require("node:fs/promises"),1);var Ii=new Set(["EACCES","EBUSY","EPERM"]),wi=[10,20,40,80,160,320,640];async function un(e,t){for(let r=0;;r+=1)try{await G.rename(e,t);return}catch(n){let o=n.code,i=wi[r];if(process.platform!=="win32"||!o||!Ii.has(o)||i===void 0)throw n;await new Promise(a=>setTimeout(a,i))}}var Z=require("node:fs"),qt=require("node:os"),fn=require("node:path");function bi(){return new Date().toISOString()}function Ei(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function mn(e){try{return JSON.parse((0,Z.readFileSync)(e,"utf8"))}catch{return null}}function vi(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Si(e){return e.hostname!==(0,qt.hostname)()?!0:vi(e.pid)}function pn(e,t){(0,Z.mkdirSync)((0,fn.dirname)(e),{recursive:!0}),(0,Z.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
937
|
-
`,{encoding:"utf8",flag:"wx"})}function
|
|
938
|
-
`;if(Buffer.byteLength(a,"utf8")>this.maxSnapshotBytes)throw new f("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await(0,U.mkdir)(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await
|
|
939
|
-
`),await
|
|
940
|
-
`),toolPolicy:{mode:"inherit"},skills:[],memoryScope:"user",evidence:["file-references"],currentTurnApproval:[...
|
|
936
|
+
`;function gr(){let e=process.env.SystemRoot??process.env.WINDIR;if(e){let t=(0,At.join)(e,"Microsoft.NET","Framework64","v4.0.30319","csc.exe");if((0,de.existsSync)(t))return t;let r=(0,At.join)(e,"Microsoft.NET","Framework","v4.0.30319","csc.exe");if((0,de.existsSync)(r))return r}return null}var wt=require("node:child_process"),j=require("node:fs"),re=require("node:path"),yr="XENO_BWRAP_PROFILE_OK",hr=5e3,yt;function Ar(e){try{return!(0,j.existsSync)(e)||!(0,j.statSync)(e).isFile()?null:((0,j.accessSync)(e,j.constants.X_OK),(0,j.realpathSync)(e))}catch{return null}}function ro(){let e=process.env.XENO_BWRAP_PATH?.trim();if(e)return Ar((0,re.isAbsolute)(e)?e:(0,re.resolve)(e));let t=["/usr/bin/bwrap","/bin/bwrap",...(process.env.PATH??"").split(re.delimiter).filter(Boolean).map(r=>(0,re.join)(r,"bwrap"))];for(let r of new Set(t)){let n=Ar(r);if(n)return n}return null}function no(){return["--die-with-parent","--new-session","--unshare-user","--unshare-pid","--unshare-uts","--unshare-ipc","--ro-bind","/","/","--proc","/proc","--dev","/dev","--chdir","/","--","/bin/sh","-c",`test -r /proc/self/status && printf ${yr}`]}function wr(){let e=[process.platform,process.env.XENO_BWRAP_PATH??"",process.env.PATH??""].join("\0");if(yt?.key===e)return{...yt.capability};let t;if(process.platform!=="linux")t={available:!1,reason:"The bubblewrap process-hardening profile can only be probed on a Linux host."};else{let r=ro();if(!r)t={available:!1,reason:"bubblewrap is not installed or is not executable."};else{let n=(0,wt.spawnSync)(r,["--version"],{encoding:"utf8",timeout:hr}),o=(0,wt.spawnSync)(r,no(),{encoding:"utf8",timeout:hr,env:process.env}),i=n.status===0?n.stdout.trim():void 0;if(o.status===0&&o.stdout===yr)t={available:!0,executable:r,...i?{version:i}:{},reason:`An active ${i??"bubblewrap"} namespace profile passed its mount, PID, user, IPC, UTS, /proc, and /dev probe.`};else{let a=[o.error?.message,o.stderr.trim(),o.signal?`signal ${o.signal}`:void 0,o.status!==null?`exit ${o.status}`:void 0].filter(Boolean).join("; ");t={available:!1,executable:r,...i?{version:i}:{},reason:`bubblewrap was found but its active namespace profile failed${a?`: ${a}`:"."}`}}}}return yt={key:e,capability:t},{...t}}var ye=require("node:crypto"),He=require("node:fs"),br=require("node:path"),It="xeno.containment-certification.v1",Ir=512*1024,oo=744*60*60*1e3,Er=Object.freeze(["allowedFilesystemRead","allowedFilesystemWrite","outsideFilesystemReadDenied","outsideFilesystemWriteDenied","unlistedFilesystemReadDenied","unlistedFilesystemWriteDenied","symlinkEscapeDenied","networkDefaultDeny","environmentSecretsExcluded","childProcessPolicyInherited","standardCommandLaunch","processTreeCleanup","timeoutEnforced","hostPolicyRecoveryClean","uiRestrictionsEnforced"]),b=class extends Error{constructor(t){super(`CONTAINMENT_CERTIFICATION_INVALID: ${t}`),this.name="ContainmentCertificationError"}};function io(e){let t={...e};return delete t.signature,Buffer.from(JSON.stringify(Et(t)),"utf8")}function vr(e,t,r=new Date){if(!(0,br.isAbsolute)(e.manifestPath))throw new b("manifestPath must be absolute");Oe(e.candidateSha256,"candidateSha256");let n=(0,He.statSync)(e.manifestPath);if(!n.isFile())throw new b("manifestPath must reference a regular file");if(n.size<=0||n.size>Ir)throw new b(`manifest size must be between 1 and ${Ir} bytes`);let o=(0,He.readFileSync)(e.manifestPath),i;try{i=JSON.parse(o.toString("utf8"))}catch{throw new b("manifest is not valid JSON")}let a=ao(i);if(e.expectedCertificationId&&a.certificationId!==e.expectedCertificationId)throw new b("certificationId does not match the host binding");if(a.candidate.sha256.toLowerCase()!==e.candidateSha256.toLowerCase())throw new b("candidate digest does not match the running candidate binding");if(a.platform.os!==t.platform||a.platform.arch!==t.arch)throw new b("certification platform or architecture does not match this host");if(a.adapter.name!==t.name||a.adapter.version!==t.version||a.adapter.backend!==t.backend||a.adapter.isolationTier!==t.isolationTier||a.adapter.nativeBinarySha256.toLowerCase()!==t.nativeBinarySha256.toLowerCase())throw new b("certified adapter identity does not match the installed native adapter");let c=bt(a.issuedAt,"issuedAt"),s=bt(a.expiresAt,"expiresAt");if(s<=c)throw new b("expiresAt must be later than issuedAt");if(s-c>oo)throw new b("certification lifetime exceeds 31 days");if(r.getTime()<c-5*6e4)throw new b("certification is not active yet");if(r.getTime()>=s)throw new b("certification has expired");for(let p of Er)if(a.conformance.checks[p]!==!0)throw new b(`required conformance check did not pass: ${p}`);if(!a.approvals.some(p=>p.role==="security-reviewer"&&p.subject!==a.issuedBy))throw new b("an independent security-reviewer approval is required");let l=e.trustedPublicKeys[a.signature.keyId];if(!l)throw new b("signature key is not trusted by this host");let y;try{y=Buffer.from(a.signature.value,"base64")}catch{throw new b("signature is not valid base64")}if(y.length!==64)throw new b("Ed25519 signature must be 64 bytes");let A=!1;try{A=(0,ye.verify)(null,io(a),(0,ye.createPublicKey)(l),y)}catch{throw new b("signature key or value is invalid")}if(!A)throw new b("signature verification failed");return{manifest:a,manifestSha256:(0,ye.createHash)("sha256").update(o).digest("hex")}}function ao(e){let t=ne(e,"manifest");if(t.schemaVersion!==It)throw new b(`schemaVersion must be ${It}`);let r=T(t.certificationId,"certificationId"),n=ne(t.candidate,"candidate"),o=ne(t.adapter,"adapter"),i=ne(t.platform,"platform"),a=ne(t.conformance,"conformance"),c=ne(a.checks,"conformance.checks"),s=ne(t.signature,"signature"),l=t.approvals;if(!Array.isArray(l)||l.length===0)throw new b("approvals must contain at least one approval");let y=l.map((E,S)=>{let w=ne(E,`approvals[${S}]`),$=T(w.role,`approvals[${S}].role`);if($!=="security-reviewer"&&$!=="release-reviewer")throw new b(`approvals[${S}].role is invalid`);let ae=$;bt(T(w.approvedAt,`approvals[${S}].approvedAt`),`approvals[${S}].approvedAt`);let Pe=T(w.approvalSha256,`approvals[${S}].approvalSha256`);return Oe(Pe,`approvals[${S}].approvalSha256`),{subject:T(w.subject,`approvals[${S}].subject`),role:ae,approvedAt:w.approvedAt,approvalArtifactId:T(w.approvalArtifactId,`approvals[${S}].approvalArtifactId`),approvalSha256:Pe}}),A=T(o.backend,"adapter.backend");if(A!=="processcontainer"&&A!=="bubblewrap"&&A!=="seatbelt")throw new b("adapter.backend is invalid");let p=T(i.os,"platform.os"),v=T(i.arch,"platform.arch");if(T(s.algorithm,"signature.algorithm")!=="ed25519")throw new b("signature.algorithm must be ed25519");let P={};for(let E of Er){if(c[E]!==!0)throw new b(`conformance.checks.${E} must be true`);P[E]=!0}let C=T(o.nativeBinarySha256,"adapter.nativeBinarySha256"),R=T(n.sha256,"candidate.sha256"),k=T(a.reportSha256,"conformance.reportSha256");if(Oe(C,"adapter.nativeBinarySha256"),Oe(R,"candidate.sha256"),Oe(k,"conformance.reportSha256"),a.passed!==!0)throw new b("conformance.passed must be true");return{schemaVersion:It,certificationId:r,candidate:{product:T(n.product,"candidate.product"),version:T(n.version,"candidate.version"),sha256:R},adapter:{name:o.name==="microsoft-mxc"?"microsoft-mxc":so(),version:T(o.version,"adapter.version"),backend:A,isolationTier:T(o.isolationTier,"adapter.isolationTier"),nativeBinarySha256:C},platform:{os:p,arch:v},conformance:{reportArtifactId:T(a.reportArtifactId,"conformance.reportArtifactId"),reportSha256:k,passed:!0,checks:P},issuedAt:T(t.issuedAt,"issuedAt"),expiresAt:T(t.expiresAt,"expiresAt"),issuedBy:T(t.issuedBy,"issuedBy"),approvals:y,signature:{algorithm:"ed25519",keyId:T(s.keyId,"signature.keyId"),value:T(s.value,"signature.value")}}}function so(){throw new b("adapter.name must be microsoft-mxc")}function ne(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new b(`${t} must be an object`);return e}function T(e,t){if(typeof e!="string"||e.trim().length===0)throw new b(`${t} must be a non-empty string`);return e}function Oe(e,t){if(!/^[a-f0-9]{64}$/i.test(e))throw new b(`${t} must be a SHA-256 hex digest`)}function bt(e,t){let r=Date.parse(e);if(!Number.isFinite(r))throw new b(`${t} must be an ISO timestamp`);return r}function Et(e){return Array.isArray(e)?e.map(Et):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Et(r)])):e}var le=require("node:crypto"),I=require("node:fs"),Cr=require("node:os"),_=require("node:path"),Tt=require("node:child_process"),xr=require("node:url");var Sr="microsoft-mxc",_e="0.7.0";var co="@microsoft/mxc-sdk",lo="sha512-EWhz2pKkcPluZHAOI1yneV+JK0NO/3hdh7nABBb0x4PjyUWMeSWPTBAjtIu+BhtMYOqlaijSPZMZ0Hs/J4ZL4A==",Za=10*6e4,uo=Object.freeze({"win32-x64-wxc-exec.exe":"db0a3422be9e1b396cc1b2547c70ff16b27412438a31c10a45abf370cac86ae2","win32-arm64-wxc-exec.exe":"e430d0e4f44f616e91db684f8d825a6dc93e06a1262b8d00bcaac7522a317aab","linux-x64-lxc-exec":"1efe3f817f5ae9ba9f9f2fd59142e79b2dde7a4dd024576b0ddb635fc87edeb5","linux-arm64-lxc-exec":"fdc00ccecf362ae3ddd8ccad93fd7c8b5b1f03c68897ab05ef1c9f1d327ea3fe","darwin-arm64-mxc-exec-mac":"77c07a86f483ed91dd5be290cd77878ac0c56fe113cdb8c764e7e5201c744ad2"}),Qa=Object.freeze({"win32-x64-wxc-host-prep.exe":"531fb3cdb4b0c964908fd71b71d40961417afb399cbab72f92a25e95309a6416","win32-arm64-wxc-host-prep.exe":"3ef702332286a39153fc259310b5021e3de3c191751d7522684f6475f73af5ef"});function po(e){return e.some(t=>t.includes("wxc-host-prep prepare-system-drive")||t.includes("wxc-host-prep prepare-null-device"))}function fo(e,t){if(e!=="win32"&&e!=="linux"&&e!=="darwin"||t!=="x64"&&t!=="arm64"||e==="darwin"&&t!=="arm64")return;let r=e==="win32"?"wxc-exec.exe":e==="darwin"?"mxc-exec-mac":"lxc-exec",n=uo[`${e}-${t}-${r}`];return n?{platform:e,arch:t,binaryName:r,sha256:n}:void 0}var vt;function Pr(e={}){if(vt&&!e.refresh)return Tr(vt);let t=mo();return vt=t,Tr(t)}function mo(){let e=process.platform,t=process.arch,r=fo(e,t),n=!!r,o=go();if(!o)return n?D(`reviewed MXC ${_e} native assets are not installed`,!1,!0):D(St(e,t),!1,!1);let i=(0,_.dirname)(o);if(!n)return D(St(e,t),!0,!1,{packageRoot:i});let a="";try{let p=JSON.parse((0,I.readFileSync)(o,"utf8"));if(a=String(p.version??""),p.sourcePackage?.name!==co||p.sourcePackage.version!==_e||p.sourcePackage.integrity!==lo)return D("MXC native asset provenance metadata is invalid",!0,!0,{packageRoot:i})}catch{return D("MXC package metadata is unreadable",!0,!0,{packageRoot:i})}if(a!==_e)return D(`MXC version ${a||"unknown"} is installed; XENO requires exactly ${_e}`,!0,!0,{packageRoot:i});if(!r)return D(St(e,t),!0,!1,{packageRoot:i});let c=(0,_.join)(i,"bin",t,r.binaryName);if(!(0,I.existsSync)(c)||!(0,I.statSync)(c).isFile())return D(`MXC native binary is missing: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a});let s=c;try{s=ho(c,r)}catch(p){return D(`MXC packaged native binary could not be materialized: ${p instanceof Error?p.message:String(p)}`,!0,!0,{packageRoot:i,version:a})}if(e!=="win32")try{(0,I.accessSync)(s,I.constants.X_OK)}catch{return D(`MXC native binary is not executable: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a})}let l=(0,le.createHash)("sha256").update((0,I.readFileSync)(s)).digest("hex"),y=r.sha256;if(!y||l!==y)return D(`MXC native binary digest is not trusted for ${e}/${t}`,!0,!0,{packageRoot:i,version:a});if(e==="win32"){let p=(0,Tt.spawnSync)(s,["--probe"],{encoding:"utf8",timeout:5e3,windowsHide:!0});if(p.error||p.status!==0)return D(`MXC native probe failed: ${p.error?.message??(p.stderr.trim()||`exit ${p.status}`)}`,!0,!0,{packageRoot:i,version:a});let v;try{v=JSON.parse(p.stdout)}catch{return D("MXC native probe returned invalid JSON",!0,!0,{packageRoot:i,version:a})}let m=typeof v.tier=="string"?v.tier:"unknown",P=Array.isArray(v.warnings)?v.warnings.filter(k=>typeof k=="string"):[],C=v.probes&&typeof v.probes=="object"?v.probes:void 0,R=C?.uiCapabilities&&typeof C.uiCapabilities=="object"?Object.fromEntries(Object.entries(C.uiCapabilities).filter(k=>typeof k[1]=="boolean")):void 0;return{installed:!0,supported:!0,available:!0,name:Sr,version:a,packageRoot:i,nativeBinaryPath:s,nativeBinarySha256:l,backend:"processcontainer",isolationTier:m,platform:e,arch:t,warnings:P,needsHostPreparation:po(P),reason:`MXC ${a} processcontainer is installed (${m}).`,...R?{uiCapabilities:R}:{}}}if(e==="linux"){let p=(0,Tt.spawnSync)("bwrap",["--version"],{encoding:"utf8",timeout:5e3});if(p.error||p.status!==0)return D("MXC requires bubblewrap on PATH for the stable Linux process adapter",!0,!0,{packageRoot:i,version:a})}let A=e==="darwin"?"seatbelt":"bubblewrap";return{installed:!0,supported:!0,available:!0,name:Sr,version:a,packageRoot:i,nativeBinaryPath:s,nativeBinarySha256:l,backend:A,isolationTier:A,platform:e,arch:t,warnings:[],needsHostPreparation:!1,reason:`MXC ${a} ${A} adapter is installed.`}}function go(){let e=process.resourcesPath,t=process.env.XENO_MXC_ASSET_ROOT?.trim(),r=typeof __dirname=="string"?__dirname:(0,_.dirname)((0,xr.fileURLToPath)(void 0)),n=[...e&&(0,_.isAbsolute)(e)?[(0,_.join)(e,"mxc","package.json")]:[],...t&&(0,_.isAbsolute)(t)?[(0,_.join)(t,"package.json")]:[],(0,_.join)(r,"..","native","mxc","package.json"),(0,_.join)(r,"..","..","native","mxc","package.json")];for(let o of n){if(!(0,I.existsSync)(o))continue;let i=(0,I.lstatSync)(o);if(!(!i.isFile()||i.isSymbolicLink()))return(0,I.realpathSync)(o)}}function ho(e,t){if(!!!process.pkg)return e;let n=(0,_.join)((0,Cr.tmpdir)(),"xeno-mxc",_e,t.sha256);(0,I.mkdirSync)(n,{recursive:!0,mode:448});let o=(0,_.join)(n,t.binaryName);if((0,I.existsSync)(o)){let s=(0,I.lstatSync)(o);if(!s.isFile()||s.isSymbolicLink())throw new Error("materialized MXC path is not a regular file");if((0,le.createHash)("sha256").update((0,I.readFileSync)(o)).digest("hex")!==t.sha256)throw new Error("materialized MXC binary digest is invalid");return process.platform!=="win32"&&(0,I.chmodSync)(o,448),o}let i=(0,I.readFileSync)(e);if((0,le.createHash)("sha256").update(i).digest("hex")!==t.sha256)throw new Error("embedded MXC binary digest is invalid");let c=`${o}.${process.pid}.${(0,le.randomUUID)()}.tmp`;(0,I.writeFileSync)(c,i,{flag:"wx",mode:448});try{(0,I.renameSync)(c,o)}catch(s){try{(0,I.unlinkSync)(c)}catch{}if(!(0,I.existsSync)(o))throw s;let l=(0,I.lstatSync)(o);if((l.isFile()&&!l.isSymbolicLink()?(0,le.createHash)("sha256").update((0,I.readFileSync)(o)).digest("hex"):"")!==t.sha256)throw s}return process.platform!=="win32"&&(0,I.chmodSync)(o,448),o}function St(e,t){return e!=="win32"&&e!=="linux"&&e!=="darwin"?`MXC has no stable process adapter for ${e}/${t}`:t!=="x64"&&t!=="arm64"?`MXC does not ship a ${e}/${t} native adapter`:"MXC Seatbelt currently ships for macOS ARM64 only"}function D(e,t=!1,r=!1,n={}){return{...n,installed:t,supported:r,available:!1,warnings:[],needsHostPreparation:!1,reason:e}}function Tr(e){return{...e,warnings:[...e.warnings],...e.uiCapabilities?{uiCapabilities:{...e.uiCapabilities}}:{}}}var ue=class extends Error{code;constructor(t,r){super(`${t}: ${r}`),this.name="ExecutionSecurityError",this.code=t}},Ao=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),yo=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!0,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!0,environmentSanitization:!0}),wo=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),Io=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!0,networkIsolation:!0,inheritedHandleAllowlist:!0,environmentSanitization:!0}),Ct=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0});function bo(e){let t=e?.executionLevel;if(e?.requireOsContainment&&t&&t!=="contained")throw new ue("SECURITY_POLICY_INVALID","requireOsContainment is a strict contained-mode compatibility flag and conflicts with the requested executionLevel.");return t??(e?.requireOsContainment?"contained":"policy-only")}function Eo(e){return e?.trustMode??"trusted-workspace"}function Rr(e,t=process.platform,r){if(e==="policy-only")return{available:!0,requestedLevel:e,effectiveLevel:"policy-only",adapter:"policy-enforcer",isolation:"policy-only",certified:!0,capabilities:{...Ao},limitations:["No restricted process identity.","No filesystem isolation.","No network isolation."],reason:"Policy and permission checks are active without operating-system process isolation."};if(e==="process-hardened"){if(t==="win32"&&gr())return{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"windows-restricted-token-job",isolation:"process-hardening",certified:!0,capabilities:{...yo},limitations:["Filesystem reads are not isolated.","Network access is not isolated.","This mode is not suitable for untrusted code."],reason:"Windows restricted-token, low-integrity, explicit-handle, and kill-on-close Job Object process hardening is available."};if(t==="linux"){let o=wr();return o.available?{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"linux-bubblewrap",isolation:"process-hardening",certified:!0,capabilities:{...wo},limitations:["Filesystem reads are not isolated; the host root is mounted read-only.","Network access is not isolated.","Inherited file descriptors are limited by the host launcher rather than an adapter-owned allowlist.","This mode is not suitable for untrusted code."],reason:`linux-bubblewrap is available: ${o.reason}`}:{available:!1,requestedLevel:e,effectiveLevel:"unavailable",adapter:"unavailable",isolation:"none",certified:!1,capabilities:{...Ct},limitations:["No certified process-hardening adapter is available for this platform."],reason:`Linux bubblewrap process hardening is unavailable: ${o.reason}`}}return{available:!1,requestedLevel:e,effectiveLevel:"unavailable",adapter:"unavailable",isolation:"none",certified:!1,capabilities:{...Ct},limitations:["No certified process-hardening adapter is available for this platform."],reason:t==="win32"?"The Windows .NET Framework C# compiler is unavailable, so the restricted-token launcher cannot start.":`No certified process-hardened adapter is implemented for ${t}.`}}if(t!==process.platform)return Ge(t,`Native containment for ${t} cannot be certified from a ${process.platform} host.`);let n=Pr();if(!n.available||!n.name||!n.version||!n.backend||!n.isolationTier||!n.nativeBinarySha256||!n.platform||!n.arch)return Ge(t,n.reason,n);if(!r)return Ge(t,`${n.reason} A signed candidate-bound XENO containment certification was not supplied.`,n);try{let o={name:n.name,version:n.version,backend:n.backend,isolationTier:n.isolationTier,nativeBinarySha256:n.nativeBinarySha256,platform:n.platform,arch:n.arch},i=vr(r,o);return{available:!0,requestedLevel:e,effectiveLevel:"contained",adapter:"microsoft-mxc",isolation:"filesystem-network",certified:!0,capabilities:{...Io},limitations:[...n.warnings],reason:`${n.reason} Signed XENO certification ${i.manifest.certificationId} is valid for this candidate.`,adapterVersion:n.version,backend:n.backend,isolationTier:n.isolationTier,nativeBinarySha256:n.nativeBinarySha256,certificationArtifactId:i.manifest.certificationId,certificationManifestSha256:i.manifestSha256,needsHostPreparation:n.needsHostPreparation}}catch(o){return Ge(t,o instanceof Error?o.message:"Containment certification validation failed.",n)}}function vo(e,t){if(Eo(e)==="untrusted"&&t!=="contained")throw new ue("UNTRUSTED_EXECUTION_DISABLED","Untrusted execution requires certified contained mode; policy-only and process-hardened modes are trusted-workspace features.")}function So(e){let t=e.requestedLevel==="contained"?"CONTAINMENT_UNAVAILABLE":"PROCESS_HARDENING_UNAVAILABLE";return new ue(t,e.reason)}function Or(e,t=process.platform){let r=bo(e);vo(e,r);let n=Rr(r,t,e.containmentCertification);if(!n.available)throw So(n);if(r==="process-hardened"&&e.allowNetwork!==!0)throw new ue("NETWORK_ISOLATION_UNAVAILABLE","Process-hardened execution cannot enforce network denial. Set allowNetwork=true explicitly for a trusted workspace or request certified contained mode.");if(r!=="policy-only"){let o=ce(e.workingDirectory??process.cwd()).canonicalPath,i=[...e.allowedDirectories,...e.temporaryDirectories??[]];if(!mr(o,i))throw new ue("SECURITY_POLICY_INVALID",`Secured process working directory is outside the canonical allowed directories: ${o}`)}return n}function Ge(e,t,r){let n=r?.available===!0;return{available:!1,requestedLevel:"contained",effectiveLevel:"unavailable",adapter:n?"microsoft-mxc":"unavailable",isolation:n?"filesystem-network":"none",certified:!1,capabilities:{...Ct},limitations:["Contained mode remains fail-closed until a signed, candidate-bound XENO certification is valid.",...r?.warnings??[],...e==="win32"&&!n?["Windows restricted-token execution is process hardening only."]:[]],reason:t,...r?.version?{adapterVersion:r.version}:{},...r?.backend?{backend:r.backend}:{},...r?.isolationTier?{isolationTier:r.isolationTier}:{},...r?.nativeBinarySha256?{nativeBinarySha256:r.nativeBinarySha256}:{},...r?{needsHostPreparation:r.needsHostPreparation}:{}}}var Dr=1,x=class extends Error{constructor(r,n){super(n);this.code=r;this.name="XenoSecureExecutionContractError"}code};function Lr(e){let t=e.platform??process.platform,r=e.policy.executionLevel??(e.policy.requireOsContainment?"contained":"policy-only"),n=e.adapterStatus??Or(e.policy,t);if(!n.available||n.effectiveLevel==="unavailable")throw new x("SECURITY_CONTRACT_UNAVAILABLE",n.reason);if(n.requestedLevel!==r||n.effectiveLevel!==r)throw new x("SECURITY_CONTRACT_INVALID","Execution adapter status does not match the requested security level");let i=(e.now??(()=>new Date().toISOString()))(),a=Ne([...e.policy.allowedDirectories,...e.policy.temporaryDirectories??[],e.policy.workingDirectory??process.cwd()],e.policy.workingDirectory,t),c=Ne(e.filesystem?.readRoots??a,e.policy.workingDirectory,t),s=e.profile.capabilities.permissionProfile==="read-only",l=s?[]:Ne(e.filesystem?.writeRoots??a,e.policy.workingDirectory,t),y=s?[]:Ne(e.filesystem?.executeRoots??a,e.policy.workingDirectory,t),A=Ne(e.filesystem?.deniedRoots??e.policy.deniedDirectories??[],e.policy.workingDirectory,t),p=n.capabilities.filesystemIsolation?"os":"policy",v=n.capabilities.networkIsolation?"os":r==="process-hardened"?"none":"policy",m=r==="contained"?"deny":e.network?.default??(e.policy.allowNetwork?"allow":"deny"),P=v==="none";if(P&&(!e.policy.allowNetwork||m!=="allow"))throw new x("SECURITY_CONTRACT_INVALID","An adapter without network isolation requires explicit unrestricted-network acknowledgement");if(s&&(e.browser?.mode==="act"||e.computer?.mode==="act"||(e.secrets?.length??0)>0))throw new x("SECURITY_CONTRACT_INVALID","Read-only Agent Profiles cannot receive browser action, computer action, or secret projection authority");let C=e.certificationArtifactId??n.certificationArtifactId;if(e.certificationArtifactId&&n.certificationArtifactId&&e.certificationArtifactId!==n.certificationArtifactId)throw new x("SECURITY_CONTRACT_INVALID","Requested certification artifact does not match the adapter certification");if(r==="contained"&&!C)throw new x("SECURITY_CONTRACT_INVALID","Contained execution requires a candidate-bound certification artifact");let R=we(e.environment?.deniedKeys??[]),k=new Set(R),E=ke(e.browser?.allowedDomains??[]),S=ke(e.browser?.readAllowedDomains??E),w=ke(e.browser?.actAllowedDomains??E),$=ke([...E,...S,...w]),ae={schemaVersion:Dr,contractId:e.contractId,createdAt:i,...e.expiresAt?{expiresAt:e.expiresAt}:{},identity:{...e.identity},requestedLevel:r,effectiveLevel:n.effectiveLevel,trustMode:e.policy.trustMode??"trusted-workspace",profile:{id:e.profile.profile.id,version:e.profile.profile.version,fingerprint:e.profile.fingerprint,permissionProfile:e.profile.capabilities.permissionProfile},filesystem:{enforcement:p,readRoots:c,writeRoots:l,executeRoots:y,deniedRoots:A},network:{enforcement:v,default:m,allowDestinations:_r(e.network?.allowDestinations??[]),denyDestinations:_r(e.network?.denyDestinations??[]),dns:e.network?.dns??((e.network?.allowDestinations?.length??0)>0||m==="allow"?"system":"disabled"),...e.network?.proxyUrl?{proxyUrl:e.network.proxyUrl}:{},downloads:e.network?.downloads??"deny",acknowledgedUnrestricted:P},process:{processTreeControl:n.capabilities.processTreeControl,cleanup:n.capabilities.processTreeControl?"kill-tree":"best-effort",inheritedHandleAllowlist:n.capabilities.inheritedHandleAllowlist,...Ro(e.process)},environment:{inheritance:e.environment?.inheritance??"allowlist",allowedKeys:we(e.environment?.allowedKeys??e.policy.containedEnvironmentAllowlist??[]).filter(jn=>!k.has(jn)),deniedKeys:R},secrets:Po(e.secrets??[]),externalActions:{default:e.profile.capabilities.externalActions.default,overrides:{...e.profile.capabilities.externalActions.overrides},requireCurrentTurnApproval:we(e.profile.capabilities.externalActions.requireCurrentTurnApproval),requireCapabilityLease:!0},browser:{mode:e.browser?.mode??"none",profile:e.browser?.profile??"ephemeral",allowedDomains:$,readAllowedDomains:S,actAllowedDomains:w,deniedDomains:ke(e.browser?.deniedDomains??[]),allowedSchemes:Co(e.browser?.allowedSchemes??["https"]),allowedPorts:xo(e.browser?.allowedPorts??[443]),redirectPolicy:e.browser?.redirectPolicy??"policy",allowLoopbackDevelopment:e.browser?.allowLoopbackDevelopment??!1,downloads:e.browser?.downloads??"deny",uploads:e.browser?.uploads??"deny",recording:e.browser?.recording??"disabled"},computer:{mode:e.computer?.mode??"none",allowedApplications:we(e.computer?.allowedApplications??[]),sensitiveRegionRedaction:e.computer?.sensitiveRegionRedaction??!0,humanStopRequired:e.computer?.humanStopRequired??!0},capabilityLeaseIds:we(e.capabilityLeaseIds??[]),adapter:{id:n.adapter,version:e.adapterVersion??n.adapterVersion??"1",platform:t,architecture:e.architecture??(0,Xr.arch)(),certified:n.certified,...C?{certificationArtifactId:C}:{},capabilities:{...n.capabilities},limitations:[...n.limitations]},...e.auditEventIds?{auditEventIds:we(e.auditEventIds)}:{}},Pe={...ae,fingerprint:Mr(ae)};return Pt(Pe),Pe}function To(e){let t=[];if(!e||typeof e!="object")return["Contract must be an object"];if(e.schemaVersion!==Dr&&t.push("Unsupported schemaVersion"),e.contractId?.trim()||t.push("contractId is required"),(!e.identity?.runId?.trim()||!e.identity?.agentId?.trim())&&t.push("runId and agentId are required"),Nr(e.createdAt)||t.push("createdAt must be an ISO 8601 timestamp"),e.expiresAt&&(!Nr(e.expiresAt)||Date.parse(e.expiresAt)<=Date.parse(e.createdAt))&&t.push("expiresAt must be later than createdAt"),e.requestedLevel!==e.effectiveLevel&&t.push("requestedLevel and effectiveLevel must match"),e.trustMode==="untrusted"&&e.effectiveLevel!=="contained"&&t.push("Untrusted execution requires contained mode"),e.effectiveLevel==="contained"&&(e.adapter.certified||t.push("Contained mode requires a certified adapter"),e.adapter.certificationArtifactId||t.push("Contained mode requires a certification artifact"),(!e.adapter.capabilities.filesystemIsolation||e.filesystem.enforcement!=="os")&&t.push("Contained mode requires OS filesystem isolation"),(!e.adapter.capabilities.networkIsolation||e.network.enforcement!=="os")&&t.push("Contained mode requires OS network isolation"),e.network.default!=="deny"&&t.push("Contained networking must default deny")),e.network.enforcement==="none"&&!e.network.acknowledgedUnrestricted&&t.push("Unrestricted networking must be explicitly acknowledged"),e.filesystem.writeRoots.length>0&&e.profile.permissionProfile==="read-only"&&t.push("Read-only profiles cannot receive write roots"),(!Array.isArray(e.browser.readAllowedDomains)||!Array.isArray(e.browser.actAllowedDomains))&&t.push("Browser read/action domain policies are required"),(!Array.isArray(e.browser.allowedSchemes)||e.browser.allowedSchemes.some(r=>r!=="http"&&r!=="https"))&&t.push("Browser allowed schemes are invalid"),(!Array.isArray(e.browser.allowedPorts)||e.browser.allowedPorts.some(r=>!Number.isInteger(r)||r<1||r>65535))&&t.push("Browser allowed ports are invalid"),e.secrets.some(r=>!r.secretId.trim())&&t.push("Secret projections require non-empty secret IDs"),new Set(e.secrets.map(r=>r.secretId)).size!==e.secrets.length&&t.push("Secret IDs must be unique"),new Set(e.capabilityLeaseIds).size!==e.capabilityLeaseIds.length&&t.push("Capability lease IDs must be unique"),/^[a-f0-9]{64}$/.test(e.profile.fingerprint)||t.push("Profile fingerprint is invalid"),!/^[a-f0-9]{64}$/.test(e.fingerprint))t.push("Contract fingerprint is invalid");else{let r={...e};delete r.fingerprint,Mr(r)!==e.fingerprint&&t.push("Contract fingerprint does not match content")}return t}function Pt(e){let t=To(e);if(t.length>0){let r=t.includes("Contract fingerprint does not match content");throw new x(r?"SECURITY_CONTRACT_FINGERPRINT_MISMATCH":"SECURITY_CONTRACT_INVALID",t.join("; "))}}function Mr(e){return(0,kr.createHash)("sha256").update(JSON.stringify(xt(e))).digest("hex")}function we(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort().map(t=>t)}function Ne(e,t,r){return[...new Set(e.map(n=>ce(n,{baseDirectory:t,platform:r}).canonicalPath))].sort((n,o)=>n.localeCompare(o))}function _r(e){let t=new Map;for(let r of e){if(!r.host?.trim())throw new x("SECURITY_CONTRACT_INVALID","Network destinations require a host");if(r.host.includes("*"))throw new x("SECURITY_CONTRACT_INVALID","Network destinations cannot contain wildcards");if(r.port!==void 0&&(!Number.isInteger(r.port)||r.port<1||r.port>65535))throw new x("SECURITY_CONTRACT_INVALID","Network destination port is invalid");let n={...r,host:r.host.trim().toLowerCase().replace(/\.$/,"")};t.set(`${n.scheme??""}:${n.host}:${n.port??""}`,n)}return[...t.values()].sort((r,n)=>r.host.localeCompare(n.host)||(r.port??0)-(n.port??0))}function ke(e){let t=new Set;for(let r of e){let n=r.trim().toLowerCase().replace(/\.$/,"");if(!n)continue;if(n.includes("*")||n.includes("://")||n.includes("/")||n.includes(":"))throw new x("SECURITY_CONTRACT_INVALID",`Browser domain rule is invalid: ${r}`);let o=n.startsWith(".")?n.slice(1):n;if(!/^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/.test(o)&&o!=="localhost")throw new x("SECURITY_CONTRACT_INVALID",`Browser domain rule is invalid: ${r}`);t.add(n)}return[...t].sort((r,n)=>r.localeCompare(n))}function Co(e){for(let t of e)if(t!=="http"&&t!=="https")throw new x("SECURITY_CONTRACT_INVALID",`Browser scheme is invalid: ${t}`);return[...new Set(e)].sort()}function xo(e){for(let t of e)if(!Number.isInteger(t)||t<1||t>65535)throw new x("SECURITY_CONTRACT_INVALID",`Browser port is invalid: ${t}`);return[...new Set(e)].sort((t,r)=>t-r)}function Po(e){let t=new Map;for(let r of e){if(!r.secretId?.trim())throw new x("SECURITY_CONTRACT_INVALID","Secret projections require an ID");if(t.has(r.secretId))throw new x("SECURITY_CONTRACT_INVALID",`Secret ${r.secretId} is projected more than once`);t.set(r.secretId,{...r})}return[...t.values()].sort((r,n)=>r.secretId.localeCompare(n.secretId))}function Ro(e){let t={};for(let[r,n]of Object.entries(e??{})){if(!Number.isSafeInteger(n)||Number(n)<1)throw new x("SECURITY_CONTRACT_INVALID",`${r} must be a positive safe integer`);Object.assign(t,{[r]:n})}return t}function xt(e){return Array.isArray(e)?e.map(xt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,xt(r)]))}function Nr(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}var Oo=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,Ur=1048576;function J(e){(!e||typeof e!="object")&&q("Automation request must be an object"),e.protocolVersion!==1&&q("Unsupported automation protocol version"),Ie(e.operationId,"operationId"),Ie(e.idempotencyKey,"idempotencyKey"),Ie(e.capabilityLeaseId,"capabilityLeaseId"),Ie(e.governingToolName,"governingToolName"),(!Number.isSafeInteger(e.expectedLeaseVersion)||e.expectedLeaseVersion<1)&&q("expectedLeaseVersion must be a positive safe integer"),jr(e.requestedAt)||q("requestedAt must be an ISO 8601 timestamp"),je(e.operation)||q(`Unsupported automation operation: ${e.operation}`),(!e.parameters||typeof e.parameters!="object"||Array.isArray(e.parameters))&&q("parameters must be a JSON object");let t;try{t=Buffer.byteLength(JSON.stringify(e.parameters),"utf8")}catch(r){throw new d("AUTOMATION_REQUEST_INVALID","parameters must be serializable JSON",void 0,{cause:r})}if(t>Ur&&q(`parameters exceed ${Ur} bytes`),Ie(e.identity?.runId,"identity.runId"),Ie(e.identity?.agentId,"identity.agentId"),Pt(e.executionContract),_o(e),!e.executionContract.capabilityLeaseIds.includes(e.capabilityLeaseId))throw new d("AUTOMATION_CONTRACT_INVALID",`Capability lease ${e.capabilityLeaseId} is not bound to the execution contract`);if(e.executionContract.expiresAt&&Date.parse(e.executionContract.expiresAt)<=Date.now())throw new d("AUTOMATION_CONTRACT_EXPIRED","Execution contract has expired")}function V(e){(!e||typeof e!="object")&&F("Adapter manifest must be an object"),e.protocolVersion!==1&&F("Adapter protocol version is unsupported"),ze(e.adapterId,"adapterId"),ze(e.adapterVersion,"adapterVersion"),ze(e.platform,"platform"),ze(e.architecture,"architecture"),e.targetBinding!=="atomic-preflight"&&F("Adapter must implement atomic preflight target binding"),(!Array.isArray(e.operations)||e.operations.length===0)&&F("Adapter must declare operations");let t=new Set;for(let r of e.operations)je(r)||F(`Adapter declares unknown operation ${r}`),t.has(r)&&F(`Adapter declares duplicate operation ${r}`),t.add(r);e.certified&&!e.certificationArtifactId&&F("A certified automation adapter requires a certification artifact"),Array.isArray(e.limitations)||F("Adapter limitations must be an array"),e.operations.some(r=>r.startsWith("browser."))&&(!e.policyEnforcement.domain||!e.policyEnforcement.scheme||!e.policyEnforcement.port)&&F("Browser adapters must enforce domain, scheme, and port policy"),e.operations.some(r=>r.startsWith("computer."))&&!e.supports.immediateStop&&F("Computer-use adapters must support immediate stop")}function We(e,t){let r=X(e.operation);if(!t.operations.includes(e.operation))throw new d("AUTOMATION_OPERATION_UNSUPPORTED",`Adapter ${t.adapterId} does not support ${e.operation}`);if(r.surface==="browser"){let n=e.executionContract.browser.mode;if(n==="none"||r.effect==="act"&&n!=="act")throw new d("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(e.operation==="browser.download"&&e.executionContract.browser.downloads==="deny")throw new d("AUTOMATION_POLICY_DENIED","Execution contract denies browser downloads");if(e.operation==="browser.upload"&&e.executionContract.browser.uploads==="deny")throw new d("AUTOMATION_POLICY_DENIED","Execution contract denies browser uploads");if(e.operation.startsWith("browser.record.")&&e.executionContract.browser.recording!=="bounded")throw new d("AUTOMATION_POLICY_DENIED","Execution contract denies browser recording")}else{let n=e.executionContract.computer.mode;if(n==="none"||r.effect==="act"&&n!=="act")throw new d("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(e.executionContract.computer.sensitiveRegionRedaction&&t.supports.sensitiveRegionRedaction!==!0)throw new d("AUTOMATION_POLICY_DENIED","Owning adapter cannot satisfy required sensitive-region redaction; preflight capture refused.")}}function qe(e,t,r){We(e,t);let n=X(e.operation);if(n.surface==="browser")No(e,r,n.effect==="act");else{let o=e.executionContract.computer.allowedApplications,i=e.operation==="computer.launch"?Xo(e):r.applicationId??e.declaredTarget?.applicationId;if((e.operation==="computer.launch"||o.length>0)&&(!i||!o.includes(i)))throw new d("AUTOMATION_POLICY_DENIED",`Application ${i??"<unknown>"} is not allowed`)}}function Ot(e,t){let r=X(e.operation),n=r.surface==="browser"?r.effect==="act"?"browser-act":"browser-read":r.effect==="act"?"computer-act":"computer-observe";return{subject:{runId:e.identity.runId,agentId:e.identity.agentId,...e.identity.turnId?{turnId:e.identity.turnId}:{},toolName:e.governingToolName,operationId:e.operationId},kind:n,operation:e.operation,...Br(e,t)?{resource:Br(e,t)}:{},...Fr(t)?{destination:Fr(t)}:{}}}function Br(e,t){return ko(t)??e.declaredTarget?.resource}function _t(e){let t=X(e.operation).evidence,r=e.evidencePolicy??{},n=Rt(t.before,r.before),o=Rt(t.after,r.after),i=Rt(t.recording,r.recording),a=r.retainUntil;return a&&!jr(a)&&q("evidencePolicy.retainUntil must be an ISO 8601 timestamp"),{before:n,after:o,recording:i,sensitivity:r.sensitivity??"confidential",...a?{retainUntil:a}:{},...r.legalHold!==void 0?{legalHold:r.legalHold}:{}}}function _o(e){let t=e.executionContract.identity,r=["runId","agentId","sessionId","turnId","taskId","workspaceId"];for(let n of r){let o=t[n],i=e.identity[n];if(o!==void 0&&o!==i)throw new d("AUTOMATION_IDENTITY_MISMATCH",`Automation identity ${n} does not match the execution contract`)}}function No(e,t,r){let n=t.url??t.origin??e.declaredTarget?.url??e.declaredTarget?.origin;if(!n){if(["browser.tabs.list","browser.wait"].includes(e.operation))return;throw new d("AUTOMATION_PREFLIGHT_INVALID","Browser preflight did not bind an effective URL")}let o;try{o=new URL(n)}catch{throw new d("AUTOMATION_POLICY_DENIED","Browser target URL is invalid")}if(o.username||o.password)throw new d("AUTOMATION_POLICY_DENIED","Browser target URLs cannot contain credentials");let i=o.protocol.replace(/:$/,"");i!=="http"&&i!=="https"&&pe(`Browser scheme ${o.protocol} is not supported`);let a=i,c=o.hostname.toLowerCase().replace(/\.$/,""),s=o.port?Number(o.port):a==="https"?443:80,l=e.executionContract.browser,y=Do(c);if(Vr(c,l.deniedDomains)&&pe(`Browser domain ${c} is denied`),$r(o,e.executionContract.network.denyDestinations)&&pe(`Network policy explicitly denies ${a}://${c}:${s}`),y&&l.allowLoopbackDevelopment)return;l.allowedSchemes.includes(a)||pe(`Browser scheme ${o.protocol} is not allowed`),l.allowedPorts.includes(s)||pe(`Browser port ${s} is not allowed`);let A=r?l.actAllowedDomains:l.readAllowedDomains;Vr(c,A)||pe(`Browser domain ${c} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&($r(o,e.executionContract.network.allowDestinations)||pe(`Network policy does not allow ${a}://${c}:${s}`))}function $r(e,t){let r=e.protocol.replace(/:$/,""),n=e.hostname.toLowerCase().replace(/\.$/,""),o=e.port?Number(e.port):r==="https"?443:80;return t.some(i=>{let a=i.scheme?.replace(/^custom:/,"");return i.host===n&&(i.port===void 0||i.port===o)&&(a===void 0||a===r)})}function ko(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function Fr(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function Xo(e){let t=e.parameters.target,r=t&&typeof t=="object"&&!Array.isArray(t)?t.app_id:void 0,n=e.parameters.applicationId??r??e.declaredTarget?.applicationId;return typeof n=="string"&&n.length>0?n:void 0}function Vr(e,t){return t.some(r=>{let n=r.toLowerCase();if(n.startsWith(".")){let o=n.slice(1);return e===o||e.endsWith(`.${o}`)}return e===n})}function Do(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Rt(e,t){let r={disabled:0,optional:1,required:2};return!t||r[t]<=r[e]?e:t}function Ie(e,t){(typeof e!="string"||!Oo.test(e))&&q(`${t} is invalid`)}function ze(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&F(`${t} is invalid`)}function jr(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}function pe(e){throw new d("AUTOMATION_POLICY_DENIED",e)}function q(e){throw new d("AUTOMATION_REQUEST_INVALID",e)}function F(e){throw new d("AUTOMATION_OPERATION_UNSUPPORTED",e)}var tn=require("node:crypto");var Hr=["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","page"],Gr=["draft","pending_review","approved","rejected","superseded","archived"],zr=["public","internal","confidential","restricted"],Wr=["agent","tool","user","system","integration"],qr=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],Jr=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var Nt=require("node:buffer");var Kr=require("node:crypto");function fe(e){return{algorithm:"sha256",value:(0,Kr.createHash)("sha256").update(e).digest("hex")}}var Lo=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Je="custom:";function Xe(e,t=Je){return e.startsWith(t)?Lo.test(e.slice(t.length)):!1}var be=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,r){super(t),this.name="XenoArtifactValidationError",this.issues=r.map(n=>({...n}))}},kt=class extends Error{constructor(r,n){super(`Artifact state cannot transition from ${r} to ${n}`);this.fromState=r;this.toState=n;this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},Mo={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},Uo="[\\u0000-\\u001f\\u007f]",Bo=new RegExp(Uo),Yr=/^[a-f0-9]{64}$/,$o=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Fo=new Set(Gr),Vo=new Set(zr),jo=new Set(Wr),Ho=new Set(Hr),Go=new Set(qr),zo=new Set(Jr);function u(e,t,r,n){e.push({path:t,code:r,message:n})}function g(e,t,r,n=1024){return typeof e!="string"||e.trim().length===0?(u(r,t,"required_string","Value must be a non-empty string"),!1):(e.length>n&&u(r,t,"string_too_long",`Value must not exceed ${n} characters`),Bo.test(e)&&u(r,t,"control_character","Value must not contain control characters"),!0)}function De(e,t,r){e!==void 0&&(!Number.isFinite(Date.parse(e))||!e.includes("T"))&&u(r,t,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function me(e,t,r,n){typeof e=="string"&&e.startsWith(t)&&(Xe(e,t)||u(n,r,"invalid_custom_name",`Custom name after ${t} is invalid`))}function Zr(e,t,r){if(!e||typeof e!="object"){u(r,t,"missing_actor","Actor is required");return}g(e.kind,`${t}.kind`,r,64),jo.has(e.kind)||u(r,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),g(e.id,`${t}.id`,r,512),e?.displayName!==void 0&&g(e.displayName,`${t}.displayName`,r,512),e?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.profileFingerprint)&&u(r,`${t}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function Xt(e,t,r){if(!e||typeof e!="object"){u(r,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":g(e.path,`${t}.path`,r,4096);break;case"source-line":g(e.path,`${t}.path`,r,4096),(!Number.isInteger(e.startLine)||e.startLine<1)&&u(r,`${t}.startLine`,"invalid_line","startLine must be a positive integer"),e.endLine!==void 0&&(!Number.isInteger(e.endLine)||e.endLine<e.startLine)&&u(r,`${t}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":g(e.path,`${t}.path`,r,4096),g(e.hunkId,`${t}.hunkId`,r,512);break;case"symbol":g(e.path,`${t}.path`,r,4096),g(e.symbol,`${t}.symbol`,r,1024);break;case"dom-node":g(e.pageId,`${t}.pageId`,r,512),!e.selector&&!e.accessibilityId&&!e.snapshotArtifactId&&u(r,t,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":g(e.recordingArtifactId,`${t}.recordingArtifactId`,r,512),(!Number.isFinite(e.startMs)||e.startMs<0)&&u(r,`${t}.startMs`,"invalid_time","startMs must be a non-negative finite number"),e.endMs!==void 0&&(!Number.isFinite(e.endMs)||e.endMs<e.startMs)&&u(r,`${t}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":g(e.mediaArtifactId,`${t}.mediaArtifactId`,r,512),[e.x,e.y,e.width,e.height].every(Number.isFinite)?(e.width<=0||e.height<=0)&&u(r,t,"invalid_region_size","Region width and height must be positive"):u(r,t,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":g(e.artifactId,`${t}.artifactId`,r,512);break;default:typeof e.kind!="string"||!e.kind.startsWith("custom:")?u(r,`${t}.kind`,"unknown_anchor","Anchor kind is not supported"):me(e.kind,"custom:",`${t}.kind`,r)}}function Le(e,t,r,n){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||u(r,t,"non_finite_number","JSON numbers must be finite");return}if(typeof e!="object"){u(r,t,"non_json_value","Value must be JSON-serializable");return}if(n.has(e)){u(r,t,"cyclic_value","Value must not contain cycles");return}if(n.add(e),Array.isArray(e))e.forEach((o,i)=>Le(o,`${t}[${i}]`,r,n));else for(let[o,i]of Object.entries(e))i===void 0?u(r,`${t}.${o}`,"undefined_value","Undefined is not valid JSON"):Le(i,`${t}.${o}`,r,n);n.delete(e)}}function Wo(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_artifact",message:"Artifact must be an object"}];if(e.schemaVersion!==1&&u(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),g(e.artifactId,"artifactId",t,512),(!Number.isInteger(e.revision)||e.revision<1)&&u(t,"revision","invalid_revision","revision must be a positive integer"),g(e.kind,"kind",t,160),typeof e.kind=="string"&&!Ho.has(e.kind)&&!e.kind.startsWith("custom:")&&u(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),me(e.kind,"custom:","kind",t),g(e.title,"title",t,1024),e.description!==void 0&&g(e.description,"description",t,32768),g(e.state,"state",t,64),Fo.has(e.state)||u(t,"state","unknown_state","Artifact state is not supported"),g(e.createdAt,"createdAt",t,128),De(e.createdAt,"createdAt",t),De(e.updatedAt,"updatedAt",t),e.updatedAt&&Number.isFinite(Date.parse(e.createdAt))&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&u(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt"),g(e.mediaType,"mediaType",t,255),g(e.sensitivity,"sensitivity",t,64),Vo.has(e.sensitivity)||u(t,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),e.identity)for(let[n,o]of Object.entries(e.identity))o!==void 0&&g(o,`identity.${n}`,t,512);if(!e.content||typeof e.content!="object")u(t,"content","missing_content","content descriptor is required");else{!e.content.hash||typeof e.content.hash!="object"?u(t,"content.hash","missing_hash","content hash is required"):(g(e.content.hash.algorithm,"content.hash.algorithm",t,128),me(e.content.hash.algorithm,"custom:","content.hash.algorithm",t),typeof e.content.hash.algorithm=="string"&&e.content.hash.algorithm!=="sha256"&&!e.content.hash.algorithm.startsWith("custom:")&&u(t,"content.hash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported"),g(e.content.hash.value,"content.hash.value",t,512),e.content.hash.algorithm==="sha256"&&!Yr.test(e.content.hash.value)&&u(t,"content.hash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters")),(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0)&&u(t,"content.sizeBytes","invalid_size","sizeBytes must be a non-negative safe integer");let n=e.content.storage;if(!n||typeof n!="object")u(t,"content.storage","missing_storage","storage reference is required");else if(n.type==="inline")if(n.text===void 0==(n.base64===void 0))u(t,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;n.text!==void 0?o=Nt.Buffer.from(n.text,"utf8"):n.base64!==void 0&&($o.test(n.base64)?o=Nt.Buffer.from(n.base64,"base64"):u(t,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),o&&e.content.sizeBytes!==o.byteLength&&u(t,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),o&&e.content.hash.algorithm==="sha256"&&fe(o).value!==e.content.hash.value&&u(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else n.type==="file"?g(n.path,"content.storage.path",t,4096):n.type==="blob"?g(n.uri,"content.storage.uri",t,8192):n.type==="git"?(g(n.commit,"content.storage.commit",t,512),g(n.path,"content.storage.path",t,4096)):n.type==="url"?(g(n.url,"content.storage.url",t,8192),De(n.expiresAt,"content.storage.expiresAt",t)):n.type==="external"?(g(n.provider,"content.storage.provider",t,255),g(n.locator,"content.storage.locator",t,8192)):u(t,"content.storage.type","unknown_storage","Storage type is not supported");e.content.encoding!==void 0&&(typeof e.content.encoding!="string"||e.content.encoding!=="utf8"&&e.content.encoding!=="base64"&&e.content.encoding!=="binary"&&!e.content.encoding.startsWith("custom:"))&&u(t,"content.encoding","unknown_encoding","Content encoding is not supported"),me(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?u(t,"provenance","missing_provenance","provenance is required"):(Zr(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((n,o)=>g(n,`provenance.capabilityLeaseIds[${o}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((n,o)=>g(n,`provenance.sourceArtifactIds[${o}]`,t,512)),e.provenance.attributes&&Le(e.provenance.attributes,"provenance.attributes",t,new Set));let r=new Set;return e.relationships?.forEach((n,o)=>{let i=`relationships[${o}]`;g(n.relation,`${i}.relation`,t,160),typeof n.relation=="string"&&!zo.has(n.relation)&&!n.relation.startsWith("custom:")&&u(t,`${i}.relation`,"unknown_relationship","Relationship type is not supported"),me(n.relation,"custom:",`${i}.relation`,t),g(n.target?.type,`${i}.target.type`,t,160),typeof n.target?.type=="string"&&!Go.has(n.target.type)&&!n.target.type.startsWith("custom:")&&u(t,`${i}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),me(n.target?.type,"custom:",`${i}.target.type`,t),g(n.target?.id,`${i}.target.id`,t,512);let a=`${n.relation}:${n.target?.type}:${n.target?.id}:${n.target?.revision??""}`;r.has(a)&&u(t,i,"duplicate_relationship","Duplicate relationship"),r.add(a),n.attributes&&Le(n.attributes,`${i}.attributes`,t,new Set)}),e.anchors?.forEach((n,o)=>Xt(n,`anchors[${o}]`,t)),e.revision===1&&e.predecessorRevision!==void 0&&u(t,"predecessorRevision","unexpected_predecessor","First revision cannot have a predecessor"),e.revision>1&&(!Number.isInteger(e.predecessorRevision)||(e.predecessorRevision??0)>=e.revision)&&u(t,"predecessorRevision","invalid_predecessor","Later revisions require an earlier predecessor revision"),De(e.retention?.retainUntil,"retention.retainUntil",t),e.retention?.legalHold!==void 0&&typeof e.retention.legalHold!="boolean"&&u(t,"retention.legalHold","invalid_boolean","legalHold must be a boolean"),e.extensions&&Le(e.extensions,"extensions",t,new Set),t}function Ke(e){let t=Wo(e);if(t.length>0)throw new be("XENO artifact validation failed",t)}function qo(e,t){return Mo[e].includes(t)}function Ye(e,t){if(!qo(e,t))throw new kt(e,t)}function Dt(e,t){let r=[];return e.schemaVersion!==1&&u(r,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),g(e.eventId,"eventId",r,512),g(e.artifactId,"artifactId",r,512),(!Number.isInteger(e.artifactRevision)||e.artifactRevision<1)&&u(r,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(e.sequence)||e.sequence<1)&&u(r,"sequence","invalid_sequence","sequence must be a positive integer"),g(e.recordedAt,"recordedAt",r,128),De(e.recordedAt,"recordedAt",r),Zr(e.actor,"actor",r),!e.artifactHash||typeof e.artifactHash!="object"?u(r,"artifactHash","missing_hash","Artifact hash is required"):(g(e.artifactHash.algorithm,"artifactHash.algorithm",r,128),me(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",r),g(e.artifactHash.value,"artifactHash.value",r,512),e.artifactHash.algorithm==="sha256"&&!Yr.test(e.artifactHash.value)&&u(r,"artifactHash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters"),typeof e.artifactHash.algorithm=="string"&&e.artifactHash.algorithm!=="sha256"&&!e.artifactHash.algorithm.startsWith("custom:")&&u(r,"artifactHash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported")),["review-requested","comment-added","comment-resolved","comment-reopened","decision-recorded","review-withdrawn"].includes(e.type)||u(r,"type","unknown_review_event","Review event type is not supported"),e.type==="comment-added"?(g(e.commentId,"commentId",r,512),g(e.body,"body",r,65536),e.anchor&&Xt(e.anchor,"anchor",r)):e.type==="comment-resolved"||e.type==="comment-reopened"?g(e.commentId,"commentId",r,512):e.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(e.decision)||u(r,"decision","unknown_review_decision","Review decision is not supported"),e.scope&&Xt(e.scope,"scope",r)),t&&(e.artifactId!==t.artifactId&&u(r,"artifactId","artifact_mismatch","Review event targets a different artifact"),e.artifactRevision!==t.revision&&u(r,"artifactRevision","revision_mismatch","Review event targets a different revision"),e.artifactHash&&(e.artifactHash.algorithm!==t.content.hash.algorithm||e.artifactHash.value!==t.content.hash.value)&&u(r,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),r}function Lt(e){let t="not_requested",r,n,o,i=0,a=new Set,c=new Set;for(let s of[...e].sort((l,y)=>l.sequence-y.sequence))o=s.recordedAt,s.type==="review-requested"?t="pending":s.type==="review-withdrawn"?t="withdrawn":s.type==="comment-added"?(a.add(s.commentId),c.delete(s.commentId),t==="not_requested"&&(t="pending")):s.type==="comment-resolved"?c.add(s.commentId):s.type==="comment-reopened"?c.delete(s.commentId):s.type==="decision-recorded"&&(s.scope?i+=1:(r=s.decision,n=s.eventId,t=s.decision));return{status:t,totalComments:a.size,unresolvedComments:[...a].filter(s=>!c.has(s)).length,...r?{latestDecision:r}:{},...n?{latestDecisionEventId:n}:{},...i>0?{scopedDecisionCount:i}:{},...o?{lastReviewedAt:o}:{}}}var f=class extends Error{constructor(r,n,o,i){super(n,i);this.code=r;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},Ue=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(t={}){this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(r=>(this.idCounter+=1,`${r}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),t.initialState&&this.hydrate(t.initialState)}exportState(){let t=[...this.records.values()].flatMap(r=>[...r.values()]).sort(Qr).map(r=>({artifact:Me(r.artifact),recordVersion:r.recordVersion,lifecycleEvents:structuredClone(r.lifecycleEvents),reviewEvents:structuredClone(r.reviewEvents)}));return{schemaVersion:1,records:t}}async create(t){if(Ke(t),this.assertInitialState(t),t.revision!==1)throw new f("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:t.artifactId,revision:t.revision});if(this.records.has(t.artifactId))throw new f("ARTIFACT_ALREADY_EXISTS",`Artifact ${t.artifactId} already exists`,{artifactId:t.artifactId});let r=Me(t),n=this.createLifecycleEvent({artifact:r,sequence:1,actor:r.provenance.producer,fromState:null,toState:r.state,reason:"artifact-created"}),o={artifact:r,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(r.artifactId,new Map([[r.revision,o]])),this.currentRevisions.set(r.artifactId,r.revision),ge(o)}async createRevision(t,r={}){Ke(t),this.assertInitialState(t);let n=this.getMutable(t.artifactId);this.assertVersion(n,r.expectedRecordVersion);let o=n.artifact.revision+1;if(t.revision!==o||t.predecessorRevision!==n.artifact.revision)throw new f("ARTIFACT_REVISION_INVALID",`Revision ${t.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:t.artifactId,currentRevision:n.artifact.revision,requestedRevision:t.revision});if(Ko(t,n.artifact))throw new f("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:t.artifactId,revision:t.revision});if(n.artifact.state==="archived")throw new f("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:t.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){Ye(n.artifact.state,"superseded");let s=this.now(),l=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:r.actor??t.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:r.reason??`superseded-by-revision-${t.revision}`,recordedAt:s});n.artifact.state="superseded",n.artifact.updatedAt=s,n.lifecycleEvents.push(l),n.recordVersion+=1}let i=Me(t),a=this.createLifecycleEvent({artifact:i,sequence:1,actor:r.actor??i.provenance.producer,fromState:null,toState:i.state,reason:r.reason??`revision-created-from-${n.artifact.revision}`}),c={artifact:i,recordVersion:1,lifecycleEvents:[a],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,c),this.currentRevisions.set(i.artifactId,i.revision),ge(c)}async get(t,r){let n=this.records.get(t);if(!n)return;let o=r??this.currentRevisions.get(t);if(o===void 0)return;let i=n.get(o);return i?ge(i):void 0}async require(t,r){let n=await this.get(t,r);if(!n)throw new f("ARTIFACT_NOT_FOUND",`Artifact ${t}${r===void 0?"":` revision ${r}`} was not found`,{artifactId:t,...r===void 0?{}:{revision:r}});return n}async list(t={}){let r=[];for(let[n,o]of this.records)if(!(t.artifactIds&&!t.artifactIds.includes(n)))if(t.includeSuperseded)r.push(...o.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let a=o.get(i);a&&r.push(a)}}return r.filter(n=>Yo(n.artifact,t)).sort(Qr).map(ge)}async listRevisions(t){let r=this.records.get(t);return r?[...r.values()].sort((n,o)=>n.artifact.revision-o.artifact.revision).map(ge):[]}async transition(t){let r=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(r,t.expectedRecordVersion),Ye(r.artifact.state,t.toState),t.toState==="approved"||t.toState==="rejected"){let a=t.reviewEventId?r.reviewEvents.find(s=>s.eventId===t.reviewEventId&&s.type==="decision-recorded"):void 0,c=Lt(r.reviewEvents);if(!a||a.decision!==t.toState||c.latestDecisionEventId!==a.eventId)throw new f("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${t.toState} requires a matching decision event`,{artifactId:t.artifactId,revision:r.artifact.revision});if(t.toState==="approved"&&c.unresolvedComments>0)throw new f("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${c.unresolvedComments} unresolved review comment(s)`,{artifactId:t.artifactId,revision:r.artifact.revision,unresolvedComments:c.unresolvedComments})}let n=this.now(),o=r.artifact.state,i=this.createLifecycleEvent({artifact:r.artifact,sequence:r.lifecycleEvents.length+1,actor:t.actor,fromState:o,toState:t.toState,reason:t.reason,reviewEventId:t.reviewEventId,recordedAt:n});return r.artifact.state=t.toState,r.artifact.updatedAt=n,r.lifecycleEvents.push(i),r.recordVersion+=1,ge(r)}async appendReviewEvent(t){let r=t.event,n=this.getMutable(r.artifactId,r.artifactRevision);if(this.assertVersion(n,t.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new f("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:r.artifactId,revision:r.artifactRevision});if(this.assertReviewCommentState(n,r),(r.type==="review-requested"||r.type==="review-withdrawn"||r.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new f("ARTIFACT_REVIEW_INVALID",`${r.type} requires an artifact in pending_review state`,{artifactId:r.artifactId,revision:r.artifactRevision});let o={...structuredClone(r),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=Dt(o,n.artifact);if(i.length>0)throw new be("XENO artifact review event validation failed",i);return n.reviewEvents.push(o),n.recordVersion+=1,ge(n)}getMutable(t,r){let n=this.records.get(t),o=r??this.currentRevisions.get(t),i=o===void 0?void 0:n?.get(o);if(!i)throw new f("ARTIFACT_NOT_FOUND",`Artifact ${t}${r===void 0?"":` revision ${r}`} was not found`,{artifactId:t,...r===void 0?{}:{revision:r}});return i}assertVersion(t,r){if(r!==void 0&&r!==t.recordVersion)throw new f("ARTIFACT_CONFLICT",`Expected record version ${r}, found ${t.recordVersion}`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision,expectedRecordVersion:r,actualRecordVersion:t.recordVersion})}assertInitialState(t){if(t.state!=="draft"&&t.state!=="pending_review")throw new f("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:t.artifactId,revision:t.revision})}assertReviewCommentState(t,r){if(r.type==="comment-added"){if(t.reviewEvents.some(i=>i.type==="comment-added"&&i.commentId===r.commentId))throw new f("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} already exists`);if(r.parentCommentId&&!t.reviewEvents.some(i=>i.type==="comment-added"&&i.commentId===r.parentCommentId))throw new f("ARTIFACT_REVIEW_INVALID",`Parent comment ${r.parentCommentId} does not exist`);return}if(r.type!=="comment-resolved"&&r.type!=="comment-reopened")return;if(!t.reviewEvents.some(i=>i.type==="comment-added"&&i.commentId===r.commentId))throw new f("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} does not exist`);let o=Zo(t.reviewEvents,r.commentId);if(r.type==="comment-resolved"&&o.resolved)throw new f("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} is already resolved`);if(r.type==="comment-reopened"&&!o.resolved)throw new f("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} is not resolved`)}createLifecycleEvent(t){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:t.artifact.artifactId,revision:t.artifact.revision,sequence:t.sequence,recordedAt:t.recordedAt??this.now(),actor:{...t.actor},fromState:t.fromState,toState:t.toState,...t.reason?{reason:t.reason}:{},...t.reviewEventId?{reviewEventId:t.reviewEventId}:{}}}nextEventId(t){let r=this.idFactory(t);if(typeof r!="string"||r.trim().length===0||this.eventIds.has(r))throw new f("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${t} ID`);return this.eventIds.add(r),r}hydrate(t){if(t.schemaVersion!==1||!Array.isArray(t.records))throw new f("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let r=[...t.records].sort((n,o)=>n.artifact.artifactId.localeCompare(o.artifact.artifactId)||n.artifact.revision-o.artifact.revision);for(let n of r){let o=Jo(n,this.eventIds),i=this.records.get(o.artifact.artifactId);if(i||(i=new Map,this.records.set(o.artifact.artifactId,i)),i.has(o.artifact.revision))throw new f("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${o.artifact.artifactId}:${o.artifact.revision}`);i.set(o.artifact.revision,o),this.currentRevisions.set(o.artifact.artifactId,o.artifact.revision)}for(let[n,o]of this.records){let i=[...o.values()].sort((a,c)=>a.artifact.revision-c.artifact.revision);for(let a=0;a<i.length;a+=1){let c=i[a],s=a+1;if(c.artifact.revision!==s)throw new f("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${s}`);if(a===0&&c.artifact.predecessorRevision!==void 0)throw new f("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(a>0&&c.artifact.predecessorRevision!==s-1)throw new f("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${s} has an invalid predecessor`);if(a<i.length-1&&c.artifact.state!=="superseded")throw new f("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${s} must be superseded`)}}}};function Jo(e,t){if(Ke(e.artifact),!Number.isInteger(e.recordVersion)||e.recordVersion<1)throw new f("ARTIFACT_REVISION_INVALID","Persisted artifact recordVersion must be a positive integer",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(!Array.isArray(e.lifecycleEvents)||e.lifecycleEvents.length===0||!Array.isArray(e.reviewEvents))throw new f("ARTIFACT_REVISION_INVALID","Persisted artifact records require lifecycle and review event arrays",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let r=e.lifecycleEvents.length+e.reviewEvents.length;if(e.recordVersion!==r)throw new f("ARTIFACT_REVISION_INVALID",`Persisted record version ${e.recordVersion} does not match ${r} mutations`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let n=null;for(let i=0;i<e.lifecycleEvents.length;i+=1){let a=e.lifecycleEvents[i];if(a.schemaVersion!==1||a.artifactId!==e.artifact.artifactId||a.revision!==e.artifact.revision||a.sequence!==i+1||a.fromState!==n||typeof a.eventId!="string"||a.eventId.length===0||t.has(a.eventId)||!Number.isFinite(Date.parse(a.recordedAt)))throw new f("ARTIFACT_REVISION_INVALID",`Persisted lifecycle event ${i+1} is invalid`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(n===null){if(a.toState!=="draft"&&a.toState!=="pending_review")throw new f("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:e.artifact.artifactId,revision:e.artifact.revision})}else Ye(n,a.toState);t.add(a.eventId),n=a.toState}if(n!==e.artifact.state)throw new f("ARTIFACT_REVISION_INVALID","Persisted artifact state does not match its lifecycle tail",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let o=new Map;for(let i=0;i<e.reviewEvents.length;i+=1){let a=e.reviewEvents[i];if(a.sequence!==i+1||t.has(a.eventId))throw new f("ARTIFACT_REVIEW_INVALID",`Persisted review event ${i+1} has an invalid sequence or duplicate ID`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let c=Dt(a,e.artifact);if(c.length>0)throw new be("Persisted XENO artifact review event validation failed",c);if(a.type==="comment-added"){if(o.has(a.commentId)||a.parentCommentId!==void 0&&!o.has(a.parentCommentId))throw new f("ARTIFACT_REVIEW_INVALID",`Persisted comment ${a.commentId} has an invalid identity or parent`);o.set(a.commentId,!1)}else if(a.type==="comment-resolved"||a.type==="comment-reopened"){let s=o.get(a.commentId);if(s===void 0||a.type==="comment-resolved"&&s||a.type==="comment-reopened"&&!s)throw new f("ARTIFACT_REVIEW_INVALID",`Persisted comment transition for ${a.commentId} is invalid`);o.set(a.commentId,a.type==="comment-resolved")}t.add(a.eventId)}return{artifact:Me(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function Ko(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function Yo(e,t){return!(t.kinds&&!t.kinds.includes(e.kind)||t.states&&!t.states.includes(e.state)||t.runId&&e.identity?.runId!==t.runId||t.sessionId&&e.identity?.sessionId!==t.sessionId||t.turnId&&e.identity?.turnId!==t.turnId||t.taskId&&e.identity?.taskId!==t.taskId||t.workspaceId&&e.identity?.workspaceId!==t.workspaceId||t.repositoryId&&e.identity?.repositoryId!==t.repositoryId||t.producerId&&e.provenance.producer.id!==t.producerId||t.sensitivity&&!t.sensitivity.includes(e.sensitivity))}function Qr(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function Zo(e,t){let r=!1;for(let n of e)(n.type==="comment-resolved"||n.type==="comment-reopened")&&n.commentId===t&&(r=n.type==="comment-resolved");return{resolved:r}}function Me(e){return structuredClone(e)}function ge(e){return{artifact:Me(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:Lt(e.reviewEvents)}}var Mt=32*1024*1024,Qo=1024*1024*1024,ei=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function Ze(e){let r=(e.now??(()=>new Date().toISOString()))(),n=new Set;return e.evidence.map((o,i)=>{if(ri(o),n.has(o.evidenceId))throw new d("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${o.evidenceId}`);n.add(o.evidenceId);let a=ti(o),c=(0,tn.createHash)("sha256").update(`${e.request.operationId}\0${o.evidenceId}\0${a.hash.value}`).digest("hex").slice(0,32);return{schemaVersion:1,artifactId:`automation_${c}`,revision:1,kind:o.kind,title:o.title,...o.description?{description:o.description}:{},state:"draft",createdAt:r,mediaType:o.mediaType,sensitivity:o.sensitivity??e.policy.sensitivity,identity:{...e.request.identity},content:a,provenance:{producer:{kind:"tool",id:e.request.governingToolName,displayName:e.manifest.adapterId,profileFingerprint:e.request.executionContract.profile.fingerprint},operationId:e.request.operationId,executionContractFingerprint:e.request.executionContract.fingerprint,capabilityLeaseIds:[e.request.capabilityLeaseId],attributes:{automationProtocolVersion:e.request.protocolVersion,automationOperation:e.request.operation,automationEvidenceId:o.evidenceId,automationEvidencePhase:o.phase,adapterId:e.manifest.adapterId,adapterVersion:e.manifest.adapterVersion,evidenceIndex:i}},...o.anchors?{anchors:structuredClone(o.anchors)}:{},...e.policy.retainUntil||e.policy.legalHold!==void 0?{retention:{...e.policy.retainUntil?{retainUntil:e.policy.retainUntil}:{},...e.policy.legalHold!==void 0?{legalHold:e.policy.legalHold}:{}}}:{},extensions:{...o.extensions??{},xenoAutomation:{phase:o.phase,adapter:e.manifest.adapterId,certifiedAdapter:e.manifest.certified}}}})}async function Ee(e,t){if(!e)return t.map(n=>structuredClone(n));let r=[];for(let n of t)try{let o=await e.create(n);r.push(o.artifact)}catch(o){if(o instanceof f&&o.code==="ARTIFACT_ALREADY_EXISTS"){let i=await e.require(n.artifactId,n.revision);if(i.artifact.content.hash.value===n.content.hash.value){r.push(i.artifact);continue}}throw new d("AUTOMATION_EVIDENCE_PERSISTENCE_FAILED",`Failed to persist automation evidence ${n.artifactId}`,{artifactId:n.artifactId},{cause:o})}return r}function Be(e,t,r){if(t[r]==="required"&&!e.some(n=>n.phase===r))throw new d("AUTOMATION_EVIDENCE_REQUIRED",`Automation operation requires ${r} evidence before it can be trusted`)}function ti(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return en(t),{hash:fe(e.content.text),sizeBytes:t,storage:{type:"inline",text:e.content.text},encoding:"utf8",...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}if(e.content.type==="base64"){let t=ni(e.content.base64);return en(t.byteLength),{hash:fe(t),sizeBytes:t.byteLength,storage:{type:"inline",base64:e.content.base64},encoding:"base64",...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}if(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0||e.content.sizeBytes>Qo)throw new d("AUTOMATION_EVIDENCE_INVALID","Referenced evidence size is invalid");if(!e.content.hash?.algorithm||!e.content.hash.value)throw new d("AUTOMATION_EVIDENCE_INVALID","Referenced evidence requires a content hash");if(e.content.hash.algorithm==="sha256"&&!/^[a-f0-9]{64}$/.test(e.content.hash.value))throw new d("AUTOMATION_EVIDENCE_INVALID","Referenced evidence SHA-256 is invalid");return{hash:{...e.content.hash},sizeBytes:e.content.sizeBytes,storage:structuredClone(e.content.storage),...e.content.encoding?{encoding:e.content.encoding}:{},...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}function ri(e){(!e||typeof e!="object")&&K("Evidence must be an object"),ei.test(e.evidenceId)||K("Evidence ID is invalid"),["before","action","after","recording","diagnostic"].includes(e.phase)||K("Evidence phase is invalid"),(!e.kind||!e.title?.trim()||e.title.length>512)&&K("Evidence kind and title are required"),/^[\w!#$&^_.+-]+\/[\w!#$&^_.+-]+(?:;.*)?$/.test(e.mediaType)||K("Evidence media type is invalid")}function ni(e){(e.length===0||e.length>Math.ceil(Mt/3)*4+4)&&K("Inline base64 evidence is empty or too large"),(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)&&K("Inline evidence is not canonical base64");let t=Buffer.from(e,"base64");return t.toString("base64")!==e&&K("Inline evidence is not canonical base64"),t}function en(e){e>Mt&&K(`Inline evidence exceeds ${Mt} bytes`)}function K(e){throw new d("AUTOMATION_EVIDENCE_INVALID",e)}var sn=require("node:crypto");var et=require("node:crypto");var rn=16*1024*1024;async function Ut(e,t,r,n){await e.assertCurrent(t);let o={operationId:t.operationId,fingerprint:r,ownerToken:(0,et.randomUUID)()},i=await e.journal.begin(o);if(await e.assertCurrent(t),!i.claimed){if(i.record.outcome.kind!=="result")throw Y();let p=await e.artifactRepository.require(i.record.outcome.artifactId,1),v=p.artifact;if(v.content.storage.type!=="inline"||v.content.encoding!=="utf8"||v.provenance.operationId!==t.operationId||v.extensions?.automationRequestFingerprint!==r)throw Y();let m=v.content.storage.text;if(typeof m!="string"||Buffer.byteLength(m)>rn||Qe(m)!==i.record.outcome.sha256||v.content.hash.value!==i.record.outcome.sha256)throw Y();let P=JSON.parse(m);return nn(P,t),await e.assertCurrent(t),{...P,replayed:!0}}let a="automation-consume:"+Qe(t.operationId+"\0"+r),c=await n(a);nn(c,t);let s=JSON.stringify(c),l=Buffer.byteLength(s);if(l>rn)throw Y();let y=Qe(s),A={schemaVersion:1,artifactId:"automation_result_"+Qe(t.operationId+"\0"+r),revision:1,kind:"custom:automation-result",title:"Governed automation outcome",state:"draft",createdAt:c.completedAt,mediaType:"application/json",sensitivity:"restricted",identity:{...t.identity},content:{hash:{algorithm:"sha256",value:y},sizeBytes:l,encoding:"utf8",storage:{type:"inline",text:s}},provenance:{producer:{kind:"system",id:"xeno-governed-automation"},operationId:t.operationId,executionContractFingerprint:t.executionContract.fingerprint,capabilityLeaseIds:[t.capabilityLeaseId]},extensions:{automationRequestFingerprint:r}};return await e.assertCurrent(t),await Ee(e.artifactRepository,[A]),await e.journal.finish(o,{kind:"result",artifactId:A.artifactId,sha256:y}),await e.assertCurrent(t),{...c,replayed:!1}}function nn(e,t){if(!e||typeof e!="object")throw Y();let r=e;if(r.operationId!==t.operationId||!["ok","error","cancelled","denied","evidence-incomplete"].includes(r.status)||!r.target||!Array.isArray(r.artifacts)||!r.lease||!r.adapter)throw Y()}function Qe(e){return(0,et.createHash)("sha256").update(e).digest("hex")}function Y(){return new d("AUTOMATION_OUTCOME_PENDING","Automation outcome is pending or unknown; recover the same operation rather than dispatching it again")}var on=3e4,an=1e3,$e=class{adapter;leaseAuthority;durable;artifactRepository;now;assertCurrent;executions=new Map;active=new Map;constructor(t){if(this.adapter=t.adapter,this.leaseAuthority=t.leaseAuthority,!!t.leaseAuthority==!!t.durable)throw new Error("Choose exactly one legacy or durable automation authority");this.durable=t.durable,this.artifactRepository=t.durable?.artifactRepository??t.artifactRepository,this.now=t.now??(()=>new Date().toISOString()),this.assertCurrent=t.assertCurrent||t.adapter.assertCurrent?async r=>{await t.assertCurrent?.(r),await t.adapter.assertCurrent?.(r)}:void 0,this.onPreflight=t.onPreflight,this.onGrant=t.onGrant}onPreflight;onGrant;execute(t,r){t=structuredClone(t);let n=ci(t),o=this.executions.get(t.operationId);if(o){if(o.fingerprint!==n)throw new d("AUTOMATION_OPERATION_CONFLICT",`Operation ${t.operationId} was already submitted with different authority or parameters`);if(this.durable){let l=this.durable;return l.assertCurrent(t).then(()=>this.assertCurrent?.(t)).then(()=>o.promise).then(async y=>(await l.assertCurrent(t),await this.assertCurrent?.(t),structuredClone(y)))}return this.assertCurrent?Promise.resolve(this.assertCurrent(t)).then(()=>o.promise).then(async l=>(await this.assertCurrent?.(t),structuredClone(l))):o.promise}if(this.active.size>=an)throw new d("AUTOMATION_OPERATION_CONFLICT","Automation active-operation capacity reached");let i=new AbortController,a=di(r,i);this.active.set(t.operationId,i);let c=this.durable,s=(c?Ut({...c,assertCurrent:async l=>{await c.assertCurrent(l),await this.assertCurrent?.(l)}},t,n,l=>this.executeFresh(t,i.signal,l)):this.executeFresh(t,i.signal)).finally(()=>{a(),this.active.delete(t.operationId)});return this.executions.set(t.operationId,{fingerprint:n,promise:s}),this.durable&&s.then(()=>this.executions.delete(t.operationId),()=>this.executions.delete(t.operationId)),this.trimIdempotencyRecords(),s}async stop(t,r="human-stop"){let n=this.active.get(t);return n?(n.abort(new Error(r)),await this.adapter.stop?.(t,r),!0):!1}async executeFresh(t,r,n){J(t),await this.assertCurrent?.(t),H(r);let o=await this.adapter.manifest();V(o),We(t,o);let i=X(t.operation),a=_t(t),c=this.now(),s=await this.adapter.preflight(t,r);oi(s,this.now()),qe(t,o,s.observedTarget),H(r),await this.onPreflight?.(structuredClone(t),structuredClone(s),r),H(r);let l=s.evidence??[];J(t),await this.assertCurrent?.(t),H(r),Be(l,a,"before");let y=await Ee(this.artifactRepository,Ze({request:t,manifest:o,policy:a,evidence:l,now:this.now}));if(H(r),Date.parse(s.expiresAt)<=Date.parse(this.now()))throw new d("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let A=Ot(t,s.observedTarget);await this.assertCurrent?.(t);let p;if(this.durable){await this.durable.assertCurrent(t);let w=await this.durable.consume(n,t.capabilityLeaseId,t.expectedLeaseVersion,A);if(w.executionDisposition!=="dispatch-once"||w.replayed)throw Y();p=w.lease,await this.durable.assertCurrent(t)}else p=await this.leaseAuthority.consume(t.capabilityLeaseId,t.expectedLeaseVersion,A);let v={contractFingerprint:t.executionContract.fingerprint,lease:p,capabilityUse:A};await this.onGrant?.(structuredClone(t),structuredClone(s),structuredClone(v),r),H(r);let m;try{H(r),J(t),await this.assertCurrent?.(t),H(r),m=await this.adapter.execute(t,s,v,r)}catch(w){return Bt({request:t,manifest:o,descriptorEffect:i.effect,target:s.observedTarget,lease:p,artifacts:y,startedAt:c,completedAt:this.now(),status:r.aborted?"cancelled":"error",code:r.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_ADAPTER_ERROR",message:r.aborted?"Automation operation was stopped":li(w)})}if(ii(m),H(r),J(t),await this.assertCurrent?.(t),m.operationId!==void 0&&m.operationId!==t.operationId)throw new d("AUTOMATION_RESPONSE_INVALID","Adapter returned another operation identity");let P=ai(s.observedTarget,m.observedTarget),C;try{qe(t,o,m.observedTarget)}catch(w){C=w instanceof Error?w:new Error(String(w))}if(P||C)return Bt({request:t,manifest:o,descriptorEffect:i.effect,target:s.observedTarget,lease:p,artifacts:y,startedAt:m.startedAt,completedAt:m.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:P??C.message});if(m.status!=="ok")return{operationId:t.operationId,status:m.status,effect:i.effect,startedAt:m.startedAt,completedAt:m.completedAt,adapter:$t(o),target:structuredClone(m.observedTarget),artifacts:y,lease:Ft(p),error:m.error?{...m.error}:{code:"AUTOMATION_ADAPTER_ERROR",message:"Owning adapter refused the operation."}};let R=m.evidence??[];si(l,R);let k=[],E;try{Be(R,a,"after"),Be([...l,...R],a,"recording"),k=await Ee(this.artifactRepository,Ze({request:t,manifest:o,policy:a,evidence:R,now:this.now}))}catch(w){E=w instanceof Error?w:new Error(String(w))}let S=[...y,...k];return H(r),J(t),await this.assertCurrent?.(t),E?Bt({request:t,manifest:o,descriptorEffect:i.effect,target:m.observedTarget,lease:p,artifacts:S,startedAt:m.startedAt,completedAt:m.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:E.message}):{operationId:t.operationId,status:m.status,effect:i.effect,startedAt:m.startedAt,completedAt:m.completedAt,adapter:$t(o),target:structuredClone(m.observedTarget),...m.data!==void 0?{data:structuredClone(m.data)}:{},artifacts:S,lease:Ft(p),...m.error?{error:{...m.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>an;){let t=this.executions.keys().next().value;if(!t||this.active.has(t))break;this.executions.delete(t)}}};function oi(e,t){if(!e||typeof e!="object"||!e.token?.trim())throw new d("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an invalid preflight token");let r=Date.parse(e.preparedAt),n=Date.parse(e.expiresAt),o=Date.parse(t);if(!Number.isFinite(r)||!Number.isFinite(n)||n<=r||n<=o)throw new d("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an expired or invalid preflight window");if(n-r>on)throw new d("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${on} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new d("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function ii(e){if(!e||typeof e!="object")throw new d("AUTOMATION_REQUEST_INVALID","Adapter returned no result");if(!["ok","denied","cancelled","error"].includes(e.status))throw new d("AUTOMATION_REQUEST_INVALID","Adapter returned an invalid status");if(!Number.isFinite(Date.parse(e.startedAt))||!Number.isFinite(Date.parse(e.completedAt)))throw new d("AUTOMATION_REQUEST_INVALID","Adapter result timestamps are invalid");if(Date.parse(e.completedAt)<Date.parse(e.startedAt))throw new d("AUTOMATION_REQUEST_INVALID","Adapter completion precedes its start");if(!e.observedTarget||typeof e.observedTarget!="object")throw new d("AUTOMATION_REQUEST_INVALID","Adapter result has no observed target")}function ai(e,t){let r=["tabId","pageId","deviceId","applicationId","displayId"];for(let n of r)if(e[n]!==void 0&&e[n]!==t[n])return`Adapter changed bound ${n} between preflight and execution`}function si(e,t){let r=new Set(e.map(n=>n.evidenceId));for(let n of t){if(r.has(n.evidenceId))throw new d("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${n.evidenceId}`);r.add(n.evidenceId)}}function Bt(e){return{operationId:e.request.operationId,status:e.status,effect:e.descriptorEffect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:$t(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:Ft(e.lease),error:{code:e.code,message:e.message}}}function $t(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function Ft(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function ci(e){return(0,sn.createHash)("sha256").update(JSON.stringify(Vt(e))).digest("hex")}function Vt(e){return Array.isArray(e)?e.map(Vt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Vt(r)]))}function di(e,t){if(!e)return()=>{};let r=()=>t.abort(e.reason);return e.aborted?r():e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)}function H(e){if(e.aborted)throw new d("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function li(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}var dn=require("node:path");async function ui(e){if(!(0,dn.isAbsolute)(e))throw Error("Automation journal requires an absolute host-owned path");let{DatabaseSync:t}=await import("node:sqlite");return new rt(new t(e))}var rt=class{constructor(t){this.database=t;try{if(t.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);"),t.prepare("SELECT version FROM automation_execution_schema WHERE id=1").get()?.version!==1)throw Error("Unsupported automation execution journal");t.exec("CREATE TABLE IF NOT EXISTS automation_executions(id TEXT PRIMARY KEY,body TEXT NOT NULL)")}catch(r){throw t.close(),this.closed=!0,r}}database;closed=!1;async begin(t){return t=structuredClone(t),jt(t),ve(t,["operationId","fingerprint","ownerToken"]),this.transaction(()=>{let r=this.read(t.operationId);if(r){if(r.fingerprint!==t.fingerprint)throw tt();return{claimed:!1,record:r}}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 o={schemaVersion:1,...t,outcome:{kind:"pending"}};return this.database.prepare("INSERT INTO automation_executions(id,body) VALUES(?,?)").run(t.operationId,cn(o)),{claimed:!0,record:o}})}async get(t){if(typeof t!="string"||!t.trim()||t.length>1024)throw Error("Invalid automation journal identity");return this.transaction(()=>this.read(t))}async finish(t,r){t=structuredClone(t),r=structuredClone(r),jt(t),ve(t,["operationId","fingerprint","ownerToken"]);let n={schemaVersion:1,...t,outcome:r};return Ht(n),this.transaction(()=>{let o=this.read(t.operationId);if(!o||o.fingerprint!==t.fingerprint||o.ownerToken!==t.ownerToken)throw tt();if(o.outcome.kind!=="pending"){if(JSON.stringify(o.outcome)!==JSON.stringify(r))throw tt();return}this.database.prepare("UPDATE automation_executions SET body=? WHERE id=?").run(cn(n),t.operationId)})}close(){this.closed||(this.closed=!0,this.database.close())}read(t){let r=this.database.prepare("SELECT CASE WHEN length(body)<=16384 THEN body ELSE NULL END AS body FROM automation_executions WHERE id=?").get(t);if(!r)return;if(typeof r.body!="string")throw Error("Corrupt automation journal size");let n=JSON.parse(r.body);if(Ht(n),n.operationId!==t)throw tt();return n}async transaction(t){let r=Date.now()+1e3;for(;;){if(this.closed)throw Error("Automation journal closed");let n=!1;try{this.database.exec("BEGIN IMMEDIATE"),n=!0;let o=t();return this.database.exec("COMMIT"),o}catch(o){if(n)try{this.database.exec("ROLLBACK")}catch{}if(Date.now()>=r||!/SQLITE_BUSY|database is locked/.test(String(o)))throw o;await new Promise(i=>setTimeout(i,10))}}}};function jt(e){for(let t of[e.operationId,e.ownerToken])if(typeof t!="string"||!t.trim()||t.length>1024)throw Error("Invalid automation journal identity");if(!/^[a-f0-9]{64}$/.test(e.fingerprint))throw Error("Invalid automation journal fingerprint")}function Ht(e){if(!e||typeof e!="object")throw Error("Invalid automation journal record");let t=e;if(jt(t),ve(t,["schemaVersion","operationId","fingerprint","ownerToken","outcome"]),t.schemaVersion!==1||!t.outcome)throw Error("Invalid automation journal schema");let r=t.outcome;if(r.kind==="result"){if(ve(r,["kind","artifactId","sha256"]),typeof r.artifactId!="string"||!r.artifactId||r.artifactId.length>256||!/^[a-f0-9]{64}$/.test(r.sha256))throw Error("Invalid automation result reference")}else if(r.kind==="failed"){if(ve(r,["kind","code"]),typeof r.code!="string"||!/^AUTOMATION_[A-Z_]{1,100}$/.test(r.code))throw Error("Invalid automation failure code")}else if(r.kind==="pending")ve(r,["kind"]);else throw Error("Invalid automation journal outcome")}function ve(e,t){if(Array.isArray(e)||Object.keys(e).some(r=>!t.includes(r)))throw Error("Unexpected automation journal fields")}function cn(e){Ht(e);let t=JSON.stringify(e);if(t.length>16384)throw Error("Automation journal record too large");return t}function tt(){return new d("AUTOMATION_OPERATION_CONFLICT","Automation operation identity or owner conflicts with durable state")}function ln(e,t=()=>new Date().toISOString()){let r=[];fi(r,"manifest.valid",()=>V(e));let n=new Set(e.operations);return Se(r,n,e.supports.consoleInspection,"browser.console.read","console inspection"),Se(r,n,e.supports.networkInspection,"browser.network.read","network inspection"),Se(r,n,e.supports.storageInspection,"browser.storage.read","storage inspection"),Se(r,n,e.supports.pageErrorInspection,"browser.page-errors.read","page-error inspection"),Se(r,n,e.supports.recordings,"browser.record.start","recording start"),Se(r,n,e.supports.recordings,"browser.record.stop","recording stop"),n.has("browser.upload")&&oe(r,"policy.upload",e.policyEnforcement.upload,"Upload policy is enforced"),n.has("browser.download")&&oe(r,"policy.download",e.policyEnforcement.download,"Download policy is enforced"),[...n].some(o=>o.startsWith("browser."))&&(oe(r,"policy.redirect",e.policyEnforcement.redirect,"Redirect policy is enforced"),oe(r,"control.handback",e.supports.deterministicHandback,"Deterministic hand-back is supported")),[...n].some(o=>o.startsWith("computer."))&&(oe(r,"control.stop",e.supports.immediateStop,"Immediate human stop is supported"),oe(r,"privacy.redaction",e.supports.sensitiveRegionRedaction,"Sensitive-region redaction is supported")),oe(r,"certification.binding",!e.certified||!!e.certificationArtifactId,e.certified?"Certification artifact is bound":"Adapter does not claim certification"),{protocolVersion:1,adapter:{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture},generatedAt:t(),passed:r.every(o=>o.status==="pass"),checks:r}}function pi(e){let r=ln(e).checks.filter(n=>n.status==="fail");if(r.length>0)throw new d("AUTOMATION_OPERATION_UNSUPPORTED",r.map(n=>`${n.id}: ${n.message}`).join("; "))}function Se(e,t,r,n,o){let i=t.has(n);oe(e,`capability.${n}`,r===i,r===i?`${o} declaration matches the operation catalog`:`${o} declaration does not match ${n}`)}function fi(e,t,r){try{r(),e.push({id:t,status:"pass",message:"Manifest satisfies the protocol contract"})}catch(n){e.push({id:t,status:"fail",message:n instanceof Error?n.message:String(n)})}}function oe(e,t,r,n){e.push({id:t,status:r?"pass":"fail",message:n})}var mi=6e4,gi=48*1024*1024,Fe=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;ownedView;constructor(t){if(this.endpoint=hi(t.baseUrl),this.token=Ai(t.token),this.timeoutMs=un(t.timeoutMs??mi,1e3,3e5,"timeoutMs"),this.maxResponseBytes=un(t.maxResponseBytes??gi,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=t.fetch??globalThis.fetch,t.ownedView&&(!/^[a-f0-9]{64}$/.test(t.ownedView.ownerId)||!t.ownedView.sessionId?.trim()))throw new d("AUTOMATION_REQUEST_INVALID","Owned Browser frame binding is invalid.");if(this.ownedView=t.ownedView?Object.freeze({...t.ownedView}):void 0,typeof this.fetchImpl!="function")throw new d("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}async preflight(t,r){let n=await this.request("preflight","POST",t,r);if(this.ownedView&&t.operation==="browser.screenshot"){let o=t.declaredTarget?.tabId;if(!o||n.observedTarget.tabId!==o||t.identity.sessionId!==this.ownedView.sessionId)throw new d("AUTOMATION_IDENTITY_MISMATCH","Owned capture requires the exact host session and tab.");let i=await this.request(`target?tabId=${encodeURIComponent(o)}`,"GET",void 0,r);if(i.tabId!==o||!Number.isSafeInteger(i.documentEpoch)||i.documentEpoch<0)throw new d("AUTOMATION_TARGET_CHANGED","Owned capture target metadata changed.");return{...n,adapterState:{...n.adapterState,ownedViewDocumentEpoch:i.documentEpoch}}}return n}async execute(t,r,n,o){if(this.ownedView&&t.operation==="browser.screenshot"){let i=t.declaredTarget?.tabId,a=r.adapterState?.ownedViewDocumentEpoch;if(!i||r.observedTarget.tabId!==i||t.identity.sessionId!==this.ownedView.sessionId||!Number.isSafeInteger(a))throw new d("AUTOMATION_IDENTITY_MISMATCH","Owned frame does not bind this request.");let c=new Date().toISOString(),s=await this.request("view-frame","POST",{version:1,...this.ownedView,tabId:i,documentEpoch:a,request:t,preflight:r,grant:n},o);if(s.version!==1||s.ownerId!==this.ownedView.ownerId||s.sessionId!==this.ownedView.sessionId||s.tabId!==i||s.documentEpoch!==a||s.mediaType!=="image/png"||!Number.isFinite(Date.parse(s.capturedAt))||Date.parse(s.capturedAt)<Date.parse(c)||s.origin!==new URL(r.observedTarget.url??r.observedTarget.origin??"").origin||typeof s.base64!="string"||s.base64.length>5592408||!/^[A-Za-z0-9+/]+={0,2}$/.test(s.base64)||s.base64.length%4!==0)throw new d("AUTOMATION_RESPONSE_INVALID","Owned Browser returned a changed or oversized frame.");o.throwIfAborted(),J(t);let l=Buffer.from(s.base64,"base64");if(l.length<24||l.length>4*1024*1024||l.subarray(0,8).toString("hex")!=="89504e470d0a1a0a"||l.readUInt32BE(16)<1||l.readUInt32BE(20)<1||l.readUInt32BE(16)*l.readUInt32BE(20)>2073600)throw new d("AUTOMATION_RESPONSE_INVALID","Owned Browser returned invalid bounded PNG bytes.");return{operationId:t.operationId,status:"ok",startedAt:c,completedAt:s.capturedAt,observedTarget:r.observedTarget,evidence:[{evidenceId:`${t.operationId}.after`,phase:"after",kind:"screenshot",title:"Owned Browser frame",mediaType:"image/png",content:{type:"base64",base64:s.base64},sensitivity:"restricted"}]}}return this.request("execute","POST",{request:t,preflight:r,grant:n},o)}async stop(t,r){await this.request("stop","POST",{operationId:t,reason:r.slice(0,512)})}async request(t,r,n,o){let i=new AbortController,a=Ii(o,i),c=setTimeout(()=>i.abort(new Error("automation transport timeout")),this.timeoutMs);try{if(i.signal.aborted)throw new Error("Automation was cancelled before dispatch");let s=new URL(t,this.endpoint),l=this.fetchImpl(s,{method:r,redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.token}`,accept:"application/json",...r==="POST"?{"content-type":"application/json"}:{}},...r==="POST"?{body:JSON.stringify(n??{})}:{},signal:i.signal});l.then(p=>{i.signal.aborted&&p.body?.cancel().catch(()=>{})},()=>{});let y=await Gt(l,i.signal),A=await Gt(yi(y,this.maxResponseBytes,i.signal),i.signal);if(!y.ok){let p=wi(A);throw new d("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${t}: ${p.message}`,{status:y.status,route:t,adapterCode:p.code})}if(!zt(A)||A.ok!==!0||!("result"in A))throw new d("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${t} envelope`);return A.result}catch(s){if(s instanceof d)throw s;let l=o?.aborted;throw new d(l?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",l?"Automation transport was stopped":`XENO Browser ${t} transport failed`,{route:t},{cause:s})}finally{clearTimeout(c),a()}}};function hi(e){let t;try{t=new URL(e)}catch(n){throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL is invalid",void 0,{cause:n})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires HTTP(S)");if(t.username||t.password||t.search||t.hash)throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL cannot contain credentials, query, or fragment");let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="::1")throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport must use a loopback host");if(!t.port)throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires an explicit port");return t.pathname="/v1/automation/",t}function Ai(e){if(typeof e!="string"||e.length<32||e.length>512||/\s/.test(e))throw new d("AUTOMATION_TRANSPORT_ERROR","XENO Browser session token is invalid");return e}async function yi(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw new d("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);if(e.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new d("AUTOMATION_RESPONSE_INVALID","XENO Browser response is not application/json");if(!e.body)throw new d("AUTOMATION_RESPONSE_INVALID","XENO Browser response body is missing");let i=e.body.getReader(),a=[],c=0;try{for(;;){let{done:y,value:A}=await Gt(i.read(),r);if(y)break;if(c+=A.byteLength,c>t)throw await i.cancel("response too large"),new d("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);a.push(A)}}finally{i.cancel().catch(()=>{}),i.releaseLock()}let s=new Uint8Array(c),l=0;for(let y of a)s.set(y,l),l+=y.byteLength;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch(y){throw new d("AUTOMATION_RESPONSE_INVALID","XENO Browser response contains invalid JSON",void 0,{cause:y})}}async function Gt(e,t){let r,n=new Promise((o,i)=>{r=()=>i(t.reason??new Error("Automation operation cancelled")),t.addEventListener("abort",r,{once:!0}),t.aborted&&r()});try{return await Promise.race([e,n])}finally{t.removeEventListener("abort",r)}}function wi(e){return zt(e)&&zt(e.error)?{code:typeof e.error.code=="string"?e.error.code.slice(0,128):"UNKNOWN",message:typeof e.error.message=="string"?e.error.message.slice(0,1024):"request failed"}:{code:"UNKNOWN",message:"request failed"}}function Ii(e,t){if(!e)return()=>{};let r=()=>t.abort(e.reason);return e.aborted?r():e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)}function un(e,t,r,n){if(!Number.isSafeInteger(e)||e<t||e>r)throw new d("AUTOMATION_TRANSPORT_ERROR",`${n} must be an integer from ${t} to ${r}`);return e}function zt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var bi=["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"],Te=class extends Fe{driver;constructor(t){super(t),this.driver=t.driver}async manifest(){let t=await super.manifest();if(V(t),!(this.driver==="browser"?["xeno-browser","xeno-browser-native"]:["xeno-extension-native","xeno-extension"]).includes(t.adapterId)||t.operations.some(n=>!n.startsWith("browser.")))throw new d("AUTOMATION_OPERATION_UNSUPPORTED","Configured Browser driver returned a different owning adapter contract.");return t}};var xe=require("node:fs"),Xn=require("node:crypto"),Dn=require("node:os"),ee=require("node:path");var Qt=require("node:crypto"),U=require("node:fs/promises"),z=require("node:path");var G=pr(require("node:fs/promises"),1);var pn=Symbol.for("@xenosystem/agent-sdk/file-cache"),fn=globalThis,Wt=fn[pn]??{entries:new Map,counters:{reads:0,hits:0}};fn[pn]=Wt;var rc=Wt.entries,nc=Wt.counters;var Ei=new Set(["EACCES","EBUSY","EPERM"]),vi=[10,20,40,80,160,320,640];async function mn(e,t){for(let r=0;;r+=1)try{await G.rename(e,t);return}catch(n){let o=n.code,i=vi[r];if(process.platform!=="win32"||!o||!Ei.has(o)||i===void 0)throw n;await new Promise(a=>setTimeout(a,i))}}var Z=require("node:fs"),qt=require("node:os"),hn=require("node:path");function Si(){return new Date().toISOString()}function Ti(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function An(e){try{return JSON.parse((0,Z.readFileSync)(e,"utf8"))}catch{return null}}function Ci(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function xi(e){return e.hostname!==(0,qt.hostname)()?!0:Ci(e.pid)}function gn(e,t){(0,Z.mkdirSync)((0,hn.dirname)(e),{recursive:!0}),(0,Z.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
937
|
+
`,{encoding:"utf8",flag:"wx"})}function Pi(e,t){let r=An(e);r?.pid!==t.pid||r.hostname!==t.hostname||(0,Z.rmSync)(e,{force:!0})}function yn(e,t,r){let n=Si(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,qt.hostname)(),processStartedAt:Ti(),version:r,acquiredAt:n,updatedAt:n};try{gn(e,o)}catch(i){if(i.code!=="EEXIST")throw i;let c=An(e);if(c&&xi(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);(0,Z.rmSync)(e,{force:!0}),gn(e,o)}return{record:o,release:()=>{Pi(e,o)}}}var wn="0.10.39";var bn=1,Ri="repository.v1.json",Oi=5e3,_i=20,Ni=64*1024*1024,nt=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(t){if(!t||typeof t.directory!="string"||t.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let r=t.snapshotFileName??Ri;if((0,z.basename)(r)!==r||!/^[A-Za-z0-9_.-]+$/.test(r))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,z.resolve)(t.directory),this.snapshotPath=(0,z.join)(this.directory,r),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Jt(t.lockTimeoutMs,Oi,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Jt(t.lockRetryMs,_i,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Jt(t.maxSnapshotBytes,Ni,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(r=>r.create(t))}async createRevision(t,r){return this.mutate(n=>n.createRevision(t,r))}async get(t,r){return(await this.load()).repository.get(t,r)}async require(t,r){return(await this.load()).repository.require(t,r)}async list(t){return(await this.load()).repository.list(t)}async listRevisions(t){return(await this.load()).repository.listRevisions(t)}async transition(t){return this.mutate(r=>r.transition(t))}async appendReviewEvent(t){return this.mutate(r=>r.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let r=await this.acquireLock();try{let n=await this.load(),o=await t(n.repository);return await this.persist(n),o}finally{r.release()}})}async enqueueMutation(t){let r=this.mutationTail.then(t,t);return this.mutationTail=r.then(()=>{},()=>{}),r}async acquireLock(){let t=Date.now(),r;for(;Date.now()-t<=this.lockTimeoutMs;)try{return yn(this.lockPath,`artifact-repository:${(0,z.basename)(this.snapshotPath)}`,wn)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;r=n,await Mi(this.lockRetryMs)}throw new f("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:r})}async load(){let t,r,n=!1;try{r=await this.readSnapshot(this.snapshotPath,!1)}catch(i){t=ot(i)}if(!r&&(t||await Li(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:t?.message??"primary snapshot missing"}),r=i,n=!0)}catch(i){throw t?new f("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,ot(i)])}):i}if(!r&&t)throw t;let o=r?.state??{schemaVersion:1,records:[]};return{repository:new Ue({now:this.now,idFactory:i=>`${i}_${(0,Qt.randomUUID)()}`,initialState:o}),generation:r?.generation??0,createdAt:r?.createdAt??this.now(),hasSnapshot:r!==void 0,recoveredFromBackup:n,...r?{sourceSnapshot:r}:{}}}async persist(t){let r=this.now(),o={...{schemaVersion:bn,generation:t.generation,createdAt:t.createdAt,updatedAt:r,state:t.repository.exportState()},generation:t.generation+1},i=Xi(o),a=`${JSON.stringify(i,null,2)}
|
|
938
|
+
`;if(Buffer.byteLength(a,"utf8")>this.maxSnapshotBytes)throw new f("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await(0,U.mkdir)(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await In(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
|
|
939
|
+
`),await In(this.snapshotPath,a)}async readSnapshot(t,r){let n;try{n=await(0,U.stat)(t)}catch(o){if(!r&&Yt(o,"ENOENT")||r&&Yt(o,"ENOENT"))return;throw Zt("Unable to inspect artifact repository snapshot",t,o)}if(!n.isFile()||n.size>this.maxSnapshotBytes)throw new f("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:t,sizeBytes:n.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await(0,U.readFile)(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return ki(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof f?o:Zt("Unable to parse artifact repository snapshot",t,o,!0)}}};function ki(e,t){if(!Kt(e)||e.schemaVersion!==bn||!Number.isInteger(e.generation)||e.generation<0||typeof e.createdAt!="string"||!Number.isFinite(Date.parse(e.createdAt))||typeof e.updatedAt!="string"||!Number.isFinite(Date.parse(e.updatedAt))||!Kt(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!Kt(e.checksum)||e.checksum.algorithm!=="sha256"||typeof e.checksum.value!="string")throw new f("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:t});let r=e,n=Di(r),o=En(n);if(r.checksum.value!==o)throw new f("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new Ue({initialState:r.state}),structuredClone(r)}function Xi(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:En(e)}}}function Di(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function En(e){return fe(JSON.stringify(e)).value}async function In(e,t){await(0,U.mkdir)((0,z.dirname)(e),{recursive:!0,mode:448});let r=`${e}.tmp.${process.pid}.${(0,Qt.randomUUID)()}`,n;try{n=await(0,U.open)(r,"wx",384),await n.writeFile(t,{encoding:"utf8"}),await n.sync(),await n.close(),n=void 0,await mn(r,e);try{let o=await(0,U.open)((0,z.dirname)(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{n&&await n.close().catch(()=>{}),await(0,U.unlink)(r).catch(()=>{})}}function Jt(e,t,r,n,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<r||e>n)throw new TypeError(`${o} must be an integer between ${r} and ${n}`);return e}function Kt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Yt(e,t){return e instanceof Error&&e.code===t}async function Li(e){try{return(await(0,U.stat)(e)).isFile()}catch(t){if(Yt(t,"ENOENT"))return!1;throw Zt("Unable to inspect artifact repository backup",e,t)}}function ot(e){return e instanceof Error?e:new Error(String(e))}function Zt(e,t,r,n=!1){return new f(n?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${ot(r).message}`,{snapshotPath:t},{cause:ot(r)})}function Mi(e){return new Promise(t=>setTimeout(t,e))}var Ce=require("node:os");var bc=(0,Ce.platform)();var Ec=(0,Ce.release)(),vc=(0,Ce.homedir)();var Rc=10080*60*1e3;var Ui=2,er=["publish","deploy","push","send","purchase","sign","file-legal","change-infrastructure"];function Bi(e){return Array.from(new Set((e??[]).map(t=>t.trim()).filter(Boolean)))}function Q(e){return{schemaVersion:Ui,id:e.id,version:"1.0.0",displayName:e.displayName,description:e.description,kind:e.kind??"primary",prompt:e.prompt,capabilities:{tools:e.toolPolicy??{mode:"inherit"},skills:{preload:e.skills??[],...e.skillAllow?{allow:e.skillAllow}:{},deny:[]},hooks:[],permissionProfile:e.permissionProfile??"default",externalActions:{default:e.externalDefault??"ask",...e.externalOverrides?{overrides:e.externalOverrides}:{},requireCurrentTurnApproval:e.currentTurnApproval??[]}},memory:{scope:e.memoryScope??"project",role:e.id,soul:e.soul??"read"},execution:{defaultMode:e.defaultMode??"chat",allowedModes:e.allowedModes??["chat","plan","execute","review"],isolation:e.isolation??"none",allowBackground:e.allowBackground??!0,planForComplexTasks:e.planForComplexTasks??!0,defaultDryRun:e.defaultDryRun??!1},completion:{evidence:e.evidence??[],requirePrimarySources:e.primarySources??!1,requireCurrentInformation:e.currentInformation??!1,requireHumanReview:e.humanReview??!1,stopConditions:e.stopConditions??["The requested outcome is complete and required evidence has been reported.","A real authorization, information, or external-state blocker prevents safe progress."]},presentation:{label:e.displayName,color:e.color,glyph:e.glyph},tags:Bi(e.tags)}}var Xc=[Q({id:"assistant",displayName:"Assistant",description:"General-purpose XENO collaborator for mixed research, planning, and implementation work.",prompt:["Work as a thoughtful generalist. Establish the user's actual outcome, inspect relevant context, and take scoped action.","Escalate into a narrower specialist profile when domain risk or task depth warrants it."].join(`
|
|
940
|
+
`),toolPolicy:{mode:"inherit"},skills:[],memoryScope:"user",evidence:["file-references"],currentTurnApproval:[...er],color:"cyan",glyph:"\u25A0",tags:["general","primary"]}),Q({id:"swe",displayName:"Software Engineer",description:"Repository-aware software engineer for careful implementation, debugging, refactoring, and verification.",prompt:["Inspect the repository before editing. Follow project instructions and preserve unrelated work.","Trace the smallest root cause, implement the narrowest coherent change, and verify from focused checks outward.","Do not claim completion without concrete test, typecheck, build, or runtime evidence appropriate to the risk."].join(`
|
|
941
941
|
`),toolPolicy:{mode:"default"},skills:["debug","run","verify"],permissionProfile:"trusted-dev",soul:"learn",evidence:["file-references","tests","typecheck","build","diff"],currentTurnApproval:["publish","deploy","push","change-infrastructure"],color:"green",glyph:"\u25C6",tags:["engineering","implementation"]}),Q({id:"reviewer",displayName:"Code Reviewer",description:"Read-only reviewer focused on correctness, regressions, safety, tests, and maintainability.",prompt:["Lead with concrete findings ordered by severity. Cite exact file locations and explain impact.","Do not edit code. Distinguish confirmed defects from risks and questions. State when no material finding is present."].join(`
|
|
942
942
|
`),kind:"subagent",toolPolicy:{mode:"readOnly"},skills:["code-review","verify"],permissionProfile:"read-only",memoryScope:"session",soul:"read",allowedModes:["chat","review"],defaultMode:"review",evidence:["file-references","diff"],externalDefault:"deny",color:"yellow",glyph:"\u25C7",tags:["engineering","review","read-only"]}),Q({id:"writer",displayName:"Writer",description:"Audience-aware writer and editor for clear, accurate, structurally coherent content.",prompt:["Determine audience, purpose, voice, format, and source constraints before drafting.","Preserve factual meaning, avoid invented claims, and revise for clarity, rhythm, consistency, and usefulness."].join(`
|
|
943
943
|
`),toolPolicy:{mode:"default",allow:["Read","Glob","Grep","LS","Write","Edit","WebSearch","WebFetch","Think","AskUser","Skill"]},skills:["verify"],evidence:["sources","file-references","diff"],currentTurnApproval:["send","publish"],color:"magenta",glyph:"\u2726",tags:["writing","editing"]}),Q({id:"research",displayName:"Researcher",description:"Evidence-first researcher for questions, comparisons, synthesis, and source-backed analysis.",prompt:["Break the question into verifiable claims. Prefer primary and authoritative sources, compare dates, and cite near each claim.","Separate sourced fact, inference, uncertainty, and recommendation. Do not make changes unless the user explicitly expands scope."].join(`
|
|
@@ -945,5 +945,5 @@ public static class Program
|
|
|
945
945
|
`),toolPolicy:{mode:"default",allow:["Read","Glob","Grep","LS","Write","Edit","WebSearch","WebFetch","Think","AskUser","Skill"]},skills:["verify"],evidence:["sources","file-references","diff"],currentTurnApproval:["send","publish","change-infrastructure"],color:"cyan",glyph:"\u25A3",tags:["product","planning"]}),Q({id:"ci",displayName:"CI Engineer",description:"Continuous-integration specialist for reproducing, repairing, and hardening automated gates.",prompt:["Identify the exact failing job and command. Reproduce it locally or in an equivalent immutable environment before patching.","Fix only the underlying failure, retain logs as evidence, and rerun the matching gate before broader validation."].join(`
|
|
946
946
|
`),toolPolicy:{mode:"default"},skills:["ci-repair","debug","run","verify"],permissionProfile:"trusted-dev",soul:"learn",evidence:["tests","typecheck","build","diff"],currentTurnApproval:["push","deploy","change-infrastructure"],color:"green",glyph:"\u25A4",tags:["engineering","ci","automation"]}),Q({id:"devops",displayName:"DevOps and Release",description:"Dry-run-first infrastructure and release specialist with explicit external-action gates.",prompt:["Inspect the release or infrastructure contract first. Build an immutable candidate and produce reproducible evidence.","Default to plan, preview, dry-run, and local verification. Never publish, deploy, push, sign, purchase, or mutate infrastructure unless the current user turn explicitly authorizes that exact action and target.","For releases, preserve SDK-before-CLI dependency order and verify the public artifact after publication."].join(`
|
|
947
947
|
`),toolPolicy:{mode:"default"},skills:["release","run","verify"],permissionProfile:"default",memoryScope:"project",soul:"learn",isolation:"worktree",defaultMode:"plan",defaultDryRun:!0,evidence:["tests","build","diff","deployment-proof","human-review"],humanReview:!0,currentTurnApproval:["publish","deploy","push","purchase","sign","change-infrastructure"],color:"yellow",glyph:"\u2B22",tags:["devops","release","infrastructure"]}),Q({id:"legal-research",displayName:"Legal Research",description:"Restricted legal-information researcher that produces sourced analysis for qualified human review.",prompt:["Identify jurisdiction, effective date, parties, and the precise legal question before analyzing it.","Use current primary legal sources wherever possible. Cite each material proposition and distinguish law, interpretation, uncertainty, and practical next steps.","Provide legal information, not professional representation. Never sign, file, submit, contact a party, accept terms, or make a payment."].join(`
|
|
948
|
-
`),toolPolicy:{mode:"readOnly"},skills:["verify"],permissionProfile:"default",memoryScope:"session",soul:"disabled",allowedModes:["chat","plan","review"],defaultMode:"review",evidence:["sources","human-review"],primarySources:!0,currentInformation:!0,humanReview:!0,externalDefault:"deny",color:"red",glyph:"\xA7",tags:["legal","research","restricted","read-only"],stopConditions:["The jurisdiction or effective date is unknown and materially changes the answer.","The task requires legal representation, filing, signature, payment, or contact with a third party.","The sourced analysis is complete and clearly marked for qualified human review."]})];var bn=1,O=class extends Error{constructor(r,n,o){super(n);this.code=r;this.detail=o;this.name="XenoCapabilityLeaseError"}code;detail},Mi=new Set(["filesystem-write","process-execute","network-connect","secret-use","external-action","browser-act","computer-act"]),Ui=new Set(Qt),Bi=new Set(["filesystem-read","filesystem-write","process-execute","network-connect","secret-use","external-action","browser-read","browser-act","computer-observe","computer-act","tool-invoke"]),$i=new Set(["cli","hub","ide","api","hosted"]),Vi=/^[a-f0-9]{64}$/;function Fi(e,t){En(e);let r=e.scope,n=r.governingToolName??e.subject.toolName;if(r.kind!=="external-action"){if(!n)return{eligible:!1,approvalRequirement:"principal",reason:"Non-external capability requests must identify the governing tool."};let o=Hi(t,n,r.effect);if(!o.eligible)return o}if(t.capabilities.permissionProfile==="read-only"&&r.effect!=="read")return{eligible:!1,approvalRequirement:"principal",reason:"The active read-only permission profile cannot request mutating, executable, or external authority."};if(r.kind==="external-action"){let o=r.externalAction;if(!o)return{eligible:!1,approvalRequirement:"current-turn",reason:"External-action capability requests require an exact action."};let i=t.capabilities.externalActions,a=i.overrides?.[o]??i.default;if(a==="deny")return{eligible:!1,approvalRequirement:"current-turn",profileDecision:a,reason:`Agent Profile ${t.profile.id} denies external action ${o}.`};let c=a==="ask"||i.requireCurrentTurnApproval.includes(o);return c&&!e.subject.turnId?{eligible:!1,approvalRequirement:"current-turn",profileDecision:a,reason:`External action ${o} requires a subject turn ID for current-turn approval.`}:{eligible:!0,approvalRequirement:c?"current-turn":"principal",profileDecision:a,reason:c?`External action ${o} requires approval in the active turn.`:`External action ${o} is requestable but still requires a bounded lease approval.`}}return{eligible:!0,approvalRequirement:"principal",reason:`Capability ${r.kind} is requestable within Agent Profile ${t.profile.id}.`}}function En(e){if(!e||typeof e!="object")throw h("Capability lease request must be an object");if(B(e.subject?.runId,"subject.runId"),B(e.subject?.agentId,"subject.agentId"),e.subject?.turnId!==void 0&&B(e.subject.turnId,"subject.turnId"),B(e.reason,"reason",8192),Ae(e.requestedBy,"requestedBy"),Gi(e.scope),e.policyFingerprints?.forEach(t=>at(t,"policyFingerprints")),e.maxUses!==void 0&&(!Number.isInteger(e.maxUses)||e.maxUses<1))throw h("maxUses must be a positive integer");if(e.durationMs!==void 0&&(!Number.isSafeInteger(e.durationMs)||e.durationMs<1))throw h("durationMs must be a positive safe integer");if(e.requestTtlMs!==void 0&&(!Number.isSafeInteger(e.requestTtlMs)||e.requestTtlMs<1))throw h("requestTtlMs must be a positive safe integer")}var it=class e{leases=new Map;now;idFactory;maximumDurationMs;maximumRequestTtlMs;maximumUses;idCounter=0;constructor(t={}){this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(()=>`lease_${Date.now().toString(36)}_${(++this.idCounter).toString(36)}`),this.maximumDurationMs=t.maximumDurationMs??15*6e4,this.maximumRequestTtlMs=t.maximumRequestTtlMs??5*6e4,this.maximumUses=t.maximumUses??100}static fromPersistedLease(t,r={}){ji(t);let n=new e(r);return n.leases.set(t.leaseId,ie(t)),n}request(t,r){let n=Fi(t,r);if(!n.eligible)throw new O("LEASE_NOT_REQUESTABLE",n.reason);let o=t.leaseId??this.idFactory();if(B(o,"leaseId"),this.leases.has(o))throw new O("LEASE_CONFLICT",`Capability lease ${o} already exists`);let i=this.now(),a=Math.min(t.durationMs??6e4,this.maximumDurationMs),c=Math.min(t.requestTtlMs??5*6e4,this.maximumRequestTtlMs),s=Math.min(t.maxUses??1,this.maximumUses),l={schemaVersion:bn,leaseId:o,version:1,state:"requested",subject:qi(t.subject),scope:zi(t.scope),reason:t.reason,requestedAt:i,requestExpiresAt:wn(i,c),durationMs:a,maxUses:s,useCount:0,childInheritance:t.childInheritance??"none",approvalRequirement:n.approvalRequirement,requestedBy:{...t.requestedBy},profileFingerprint:r.fingerprint,policyFingerprints:he(t.policyFingerprints??[]),...t.auditEventIds?{auditEventIds:he(t.auditEventIds)}:{},...t.evidenceArtifactIds?{evidenceArtifactIds:he(t.evidenceArtifactIds)}:{}};return this.leases.set(o,l),ie(l)}approve(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="requested")throw new O("LEASE_CONFLICT",`Capability lease ${r.leaseId} is ${r.state}`);if(Ae(t.approvedBy,"approvedBy"),vn(t.approvalContext),r.approvalRequirement==="current-turn"&&(!r.subject.turnId||t.approvalContext.turnId!==r.subject.turnId))throw new O("LEASE_APPROVAL_REQUIRED","Capability lease requires approval bound to the requesting turn");let n=this.now();return r.state="active",r.version+=1,r.activatedAt=n,r.expiresAt=wn(n,r.durationMs),r.approvedBy={...t.approvedBy},r.approvalContext={...t.approvalContext},ie(r)}deny(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="requested")throw new O("LEASE_CONFLICT",`Capability lease ${r.leaseId} is ${r.state}`);return Ae(t.deniedBy,"deniedBy"),r.state="denied",r.version+=1,r.deniedAt=this.now(),r.deniedBy={...t.deniedBy},ie(r)}revoke(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="active")throw new O("LEASE_CONFLICT",`Only active leases can be revoked; ${r.leaseId} is ${r.state}`);return Ae(t.revokedBy,"revokedBy"),r.state="revoked",r.version+=1,r.revokedAt=this.now(),r.revokedBy={...t.revokedBy},ie(r)}consume(t,r,n){let o=this.requireMutable(t);if(this.assertVersion(o,r),this.refreshState(o),o.state==="requested")throw new O("LEASE_APPROVAL_REQUIRED",`Capability lease ${t} is not approved`);if(o.state==="expired")throw new O("LEASE_EXPIRED",`Capability lease ${t} expired`);if(o.state==="revoked")throw new O("LEASE_REVOKED",`Capability lease ${t} was revoked`);if(o.state==="exhausted")throw new O("LEASE_EXHAUSTED",`Capability lease ${t} is exhausted`);if(o.state!=="active")throw new O("LEASE_SCOPE_MISMATCH",`Capability lease ${t} is ${o.state}`);return Wi(o,n),o.useCount+=1,o.version+=1,o.useCount>=o.maxUses&&(o.state="exhausted",o.exhaustedAt=this.now()),ie(o)}get(t){let r=this.leases.get(t);if(r)return this.refreshState(r),ie(r)}list(t){let r=[];for(let n of this.leases.values())this.refreshState(n),!(t?.runId&&n.subject.runId!==t.runId)&&(t?.agentId&&n.subject.agentId!==t.agentId||t?.turnId&&n.subject.turnId!==t.turnId||r.push(ie(n)));return r.sort((n,o)=>n.requestedAt.localeCompare(o.requestedAt)||n.leaseId.localeCompare(o.leaseId))}requireMutable(t){let r=this.leases.get(t);if(!r)throw new O("LEASE_NOT_FOUND",`Capability lease ${t} was not found`);return r}assertVersion(t,r){if(t.version!==r)throw new O("LEASE_CONFLICT",`Expected capability lease version ${r}, found ${t.version}`,{leaseId:t.leaseId,expectedVersion:r,actualVersion:t.version})}refreshState(t){let r=Date.parse(this.now()),n=t.state==="requested"?Date.parse(t.requestExpiresAt):Date.parse(t.expiresAt??"");(t.state==="requested"||t.state==="active")&&Number.isFinite(n)&&r>=n&&(t.state="expired",t.version+=1,t.expiredAt=this.now())}};function ji(e){if(!e||typeof e!="object"||Array.isArray(e)||JSON.stringify(e).length>65536)throw h("Invalid persisted lease row");let t=e;if(t.schemaVersion!==bn)throw h("Unsupported persisted lease schema");if(En(t),B(t.leaseId,"leaseId"),at(t.profileFingerprint,"profileFingerprint"),!Array.isArray(t.policyFingerprints))throw h("policyFingerprints must be an array");if(t.policyFingerprints.forEach(r=>at(r,"policyFingerprint")),!Number.isSafeInteger(t.durationMs)||t.durationMs<1||!Number.isSafeInteger(t.maxUses)||t.maxUses<1)throw h("Invalid persisted lease limits");if(!Number.isSafeInteger(t.version)||t.version<1||!Number.isSafeInteger(t.useCount)||t.useCount<0||t.useCount>t.maxUses)throw h("Invalid persisted lease counters");if(!["requested","active","denied","revoked","expired","exhausted"].includes(t.state))throw h("Invalid persisted lease state");if(!["principal","current-turn"].includes(t.approvalRequirement)||!["none","explicit"].includes(t.childInheritance))throw h("Invalid persisted lease authority");for(let r of["requestedAt","requestExpiresAt","activatedAt","expiresAt","expiredAt","deniedAt","revokedAt","exhaustedAt"])if((r==="requestedAt"||r==="requestExpiresAt"||t[r]!==void 0)&&(typeof t[r]!="string"||!Number.isFinite(Date.parse(t[r]))))throw h(`Invalid persisted ${r}`);if(Date.parse(t.requestExpiresAt)<=Date.parse(t.requestedAt))throw h("Invalid persisted request expiry");if(["active","revoked","exhausted"].includes(t.state)||t.useCount>0){if(!t.activatedAt||!t.expiresAt||!t.approvedBy||!t.approvalContext||t.version<2)throw h("Persisted approval is incomplete");if(Ae(t.approvedBy,"approvedBy"),vn(t.approvalContext),Date.parse(t.expiresAt)!==Date.parse(t.activatedAt)+t.durationMs)throw h("Persisted expiry does not match approved duration");if(t.approvalRequirement==="current-turn"&&(!t.subject.turnId||t.approvalContext.turnId!==t.subject.turnId))throw h("Persisted turn approval does not match")}if(t.state==="requested"&&(t.version!==1||t.useCount!==0||t.approvedBy))throw h("Invalid requested lease");if(t.state==="active"&&t.useCount>=t.maxUses)throw h("Active lease is exhausted");if(t.state==="exhausted"&&t.useCount!==t.maxUses)throw h("Invalid exhausted lease");if(t.state==="revoked"){if(!t.revokedAt||!t.revokedBy)throw h("Missing revocation");Ae(t.revokedBy,"revokedBy")}if(t.state==="denied"){if(!t.deniedAt||!t.deniedBy)throw h("Missing denial");Ae(t.deniedBy,"deniedBy")}if(t.state==="expired"&&!t.expiredAt)throw h("Missing expiry transition")}function Hi(e,t,r){let n=e.capabilities.tools,o=t.trim().toLowerCase(),i=a=>a?.some(c=>c==="*"||c.trim().toLowerCase()===o)??!1;return n.mode==="none"||i(n.deny)?{eligible:!1,approvalRequirement:"principal",reason:`Agent Profile ${e.profile.id} denies tool ${t}.`}:n.allow&&!i(n.allow)?{eligible:!1,approvalRequirement:"principal",reason:`Tool ${t} is outside the Agent Profile allowlist.`}:n.mode==="readOnly"&&r!=="read"?{eligible:!1,approvalRequirement:"principal",reason:`Tool ${t} cannot request ${r} authority in read-only mode.`}:{eligible:!0,approvalRequirement:"principal",reason:`Tool ${t} is requestable.`}}function Gi(e){if(!e||typeof e!="object")throw h("scope is required");if(B(e.kind,"scope.kind"),!Bi.has(e.kind)&&!e.kind.startsWith("custom:"))throw h("scope.kind is not supported");if(e.kind.startsWith(Je)&&!Xe(e.kind))throw h("Custom capability kind is invalid");if(!["read","write","execute","external"].includes(e.effect))throw h("scope.effect is invalid");let t={"filesystem-read":"read","filesystem-write":"write","process-execute":"execute","network-connect":"external","secret-use":"external","external-action":"external","browser-read":"read","browser-act":"external","computer-observe":"read","computer-act":"external"};if(t[e.kind]&&t[e.kind]!==e.effect)throw h(`${e.kind} capability scopes must use ${t[e.kind]} effect`);if(!Array.isArray(e.operations)||e.operations.length===0)throw h("scope.operations must contain at least one operation");if(e.operations.forEach(r=>B(r,"scope.operations")),e.resources?.forEach(r=>B(r,"scope.resources",8192)),e.destinations?.forEach(r=>B(r,"scope.destinations",8192)),e.secretIds?.forEach(r=>B(r,"scope.secretIds",512)),e.kind==="external-action"){if(!e.externalAction||!Ui.has(e.externalAction))throw h("External-action scopes require a supported exact action");if(e.effect!=="external")throw h("External-action scopes must use external effect")}if(e.kind==="network-connect"&&(!e.destinations||e.destinations.length===0))throw h("Network capability scopes require at least one destination");if(e.kind==="secret-use"&&(!e.secretIds||e.secretIds.length===0))throw h("Secret capability scopes require at least one secret ID");if(Mi.has(e.kind)&&[...e.resources??[],...e.destinations??[],...e.secretIds??[]].some(n=>n.includes("*")))throw h("High-impact capability scopes cannot use wildcard resources")}function Wi(e,t){let r=e.subject;if(r.runId!==t.subject.runId||r.agentId!==t.subject.agentId)throw L(e,"run or agent subject");if(r.turnId&&r.turnId!==t.subject.turnId)throw L(e,"turn subject");if(r.toolName&&r.toolName!==t.subject.toolName)throw L(e,"tool subject");if(r.operationId&&r.operationId!==t.subject.operationId)throw L(e,"operation subject");if(e.scope.kind!==t.kind)throw L(e,"capability kind");if(!e.scope.operations.includes(t.operation))throw L(e,"operation");if(e.scope.resources?.length&&!t.resource)throw L(e,"resource");if(e.scope.destinations?.length&&!t.destination)throw L(e,"destination");if(e.scope.secretIds?.length&&!t.secretId)throw L(e,"secret");if(e.scope.externalAction&&!t.externalAction)throw L(e,"external action");if(t.resource&&!e.scope.resources?.includes(t.resource))throw L(e,"resource");if(t.destination&&!e.scope.destinations?.includes(t.destination))throw L(e,"destination");if(t.secretId&&!e.scope.secretIds?.includes(t.secretId))throw L(e,"secret");if(t.externalAction&&e.scope.externalAction!==t.externalAction)throw L(e,"external action")}function vn(e){if(!e||typeof e!="object")throw h("approvalContext is required");if(B(e.surface,"approvalContext.surface"),!$i.has(e.surface)&&!e.surface.startsWith("custom:"))throw h("approvalContext.surface is not supported");if(e.surface.startsWith(Je)&&!Xe(e.surface))throw h("Custom approval surface is invalid");e.promptHash!==void 0&&at(e.promptHash,"approvalContext.promptHash")}function Ae(e,t){if(!e||typeof e!="object")throw h(`${t} is required`);if(!["agent","tool","user","system","integration"].includes(e.kind))throw h(`${t}.kind is invalid`);B(e.id,`${t}.id`)}function at(e,t){if(!Vi.test(e))throw h(`${t} must be a 64-character lowercase hexadecimal fingerprint`)}function B(e,t,r=1024){if(typeof e!="string"||e.trim().length===0||e.length>r)throw h(`${t} must be a non-empty string no longer than ${r} characters`)}function h(e){return new O("LEASE_INVALID",e)}function L(e,t){return new O("LEASE_SCOPE_MISMATCH",`Capability use is outside lease ${e.leaseId} ${t} scope`)}function wn(e,t){return new Date(Date.parse(e)+t).toISOString()}function he(e){return[...new Set(e)]}function qi(e){return{...e}}function zi(e){return{...e,operations:he(e.operations),...e.resources?{resources:he(e.resources)}:{},...e.destinations?{destinations:he(e.destinations)}:{},...e.secretIds?{secretIds:he(e.secretIds)}:{}}}function ie(e){return structuredClone(e)}var st=require("node:crypto");var Ji=8*1024*1024,Ki=4;function tr(e){return da(e.operations??se).map(r=>Yi(r,e.runtime))}function Yi(e,t){return{definition:{name:e,description:ra(e),input_schema:Zi(e)},projectPolicyInput(r){let n=ia(e,r),o=oa(e,r);return{observabilityInput:n,permissionInput:o,permissionPreview:aa(e,r),approvalKey:`xeno-automation:${e}:${la(r)}`,riskLevel:na(e)}},async execute(r,n){if(e==="browser.screenshot"&&(typeof r.tabId!="string"||!r.tabId.trim()))return{success:!1,output:"",error:"Screen capture requires an explicit authorized tabId.",errorCode:"AUTOMATION_CAPTURE_TARGET_REQUIRED",retryable:!1};let o=n?.authorization;if(!o||o.toolName!==e)return{success:!1,output:"",error:"Governed automation requires a host-issued authorization receipt",errorCode:"AUTOMATION_AUTHORIZATION_RECEIPT_REQUIRED",retryable:!1};let i=n.operationId??`automation_${(0,st.randomUUID)()}`,a=rr(e,r);n.reportProgress?.({activity:"state",message:`Authorizing ${e}`});try{let c=await t.execute({operation:e,governingToolName:e,operationId:i,idempotencyKey:i,parameters:structuredClone(r),...a?{declaredTarget:a}:{},authorization:o,...n.signal?{signal:n.signal}:{},...n.reportProgress?{reportProgress:n.reportProgress}:{}}),s=c.status==="ok";return{success:s,output:JSON.stringify(sa(c)),...s?{}:{error:c.error?.message??`Governed automation ended with ${c.status}`,errorCode:c.error?.code??`AUTOMATION_${c.status.toUpperCase().replaceAll("-","_")}`},assistantContent:ca(c),evidence:c.artifacts.map(l=>({id:l.artifactId,kind:"artifact",status:c.status==="evidence-incomplete"?"failed":"verified",observedAt:l.updatedAt??l.createdAt,operationId:i,detail:{artifact_kind:l.kind,revision:l.revision,sensitivity:l.sensitivity}})),retryable:c.error?.retryable??!1}}catch(c){let s=n.signal?.aborted===!0;return{success:!1,output:"",error:s?"Governed automation was stopped":ua(c),errorCode:s?"AUTOMATION_CANCELLED":pa(c),retryable:!1}}}}}function Zi(e){let t=Qi(e),r=ea(e);return{type:"object",properties:t,...r.length>0?{required:r}:{},...e==="browser.locate"?{oneOf:[{required:["selector"]},{required:["text"]}]}:{},additionalProperties:!1}}function Qi(e){let t=(a,c=8192)=>({type:"string",minLength:1,maxLength:c,description:a}),r={type:"number"},n={type:"boolean"},o={type:"object",properties:{x:r,y:r},required:["x","y"],additionalProperties:!1},i={deviceId:t("Target xeno-use device ID.",256),applicationId:t("Expected or launch-target application ID.",512),displayId:t("Target display ID.",256)};switch(e){case"browser.navigate":return{url:t("Destination URL."),waitUntil:{enum:["load","none"]},tabId:t("Expected active tab ID. Hosts with multiple visible tabs should require this.",256)};case"browser.wait":return{until:{enum:["load","ms"]},value:{type:"integer",minimum:0,maximum:6e4}};case"browser.snapshot":return{mode:{enum:["text","html","markdown","a11y"]},tabId:t("Expected active tab ID.",256)};case"browser.screenshot":return{tabId:t("Expected active tab ID.",256)};case"browser.locate":return{selector:t("CSS selector."),text:t("Visible text to locate.")};case"browser.click":return{selector:t("CSS selector returned by browser.snapshot or browser.locate."),tabId:t("Expected active tab ID.",256)};case"browser.type":return{selector:t("CSS selector."),text:{type:"string",maxLength:65536},clear:n,submit:n,tabId:t("Expected active tab ID.",256)};case"browser.key":return{combo:t("Key combo such as Control+a or Enter.",256),tabId:t("Expected active tab ID.",256)};case"browser.select":return{selector:t("CSS selector."),value:t("Option value."),tabId:t("Expected active tab ID.",256)};case"browser.scroll":return{selector:t("Optional CSS selector."),dx:r,dy:r,tabId:t("Expected active tab ID.",256)};case"browser.tabs.open":return{url:t("URL to open in an isolated browser tab.")};case"browser.tabs.close":return{tabId:t("Tab ID to close.",256)};case"browser.console.read":case"browser.network.read":case"browser.page-errors.read":return{limit:{type:"integer",minimum:1,maximum:1e3},clear:n,tabId:t("Expected active tab ID.",256)};case"browser.storage.read":return{tabId:t("Expected active tab ID.",256)};case"browser.upload":return{selector:t("File input or drop-target selector."),backendNodeId:{type:"integer",minimum:1},hostPaths:{type:"array",items:t("Host file path.",32768),minItems:1,maxItems:64},drop:n,tabId:t("Expected active tab ID.",256)};case"browser.download":return{toPath:t("Approved destination path.",32768),trigger:{type:"object",properties:{url:t("Download URL."),selector:t("Download trigger selector.")},oneOf:[{required:["url"]},{required:["selector"]}],additionalProperties:!1},tabId:t("Expected active tab ID.",256)};case"browser.record.start":return{maxDurationMs:{type:"integer",minimum:1e3,maximum:6e4},intervalMs:{type:"integer",minimum:100,maximum:5e3},tabId:t("Expected active tab ID.",256)};case"browser.record.stop":return{tabId:t("Expected active tab ID.",256)};case"computer.observe":case"computer.screenshot":case"computer.window-state":return i;case"computer.point":return{...i,point:o,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.click":return{...i,point:o,button:{enum:["left","right","middle"]},modifiers:ta()};case"computer.double-click":case"computer.right-click":return{...i,point:o};case"computer.drag":return{...i,from:o,to:o,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.type":return{...i,text:{type:"string",maxLength:65536}};case"computer.key":return{...i,combo:t("Key combo such as Control+a or Enter.",256)};case"computer.scroll":return{...i,at:o,delta:o};case"computer.wait":return{...i,milliseconds:{type:"integer",minimum:0,maximum:3e5}};case"computer.launch":return{...i,applicationId:t("Explicitly allowlisted application ID.",512)};case"browser.back":case"browser.forward":case"browser.reload":return{tabId:t("Expected active tab ID.",256)};case"browser.tabs.list":return{}}}function ea(e){switch(e){case"browser.navigate":case"browser.tabs.open":return["url"];case"browser.click":return["selector"];case"browser.type":return["selector","text"];case"browser.key":return["combo"];case"browser.select":return["selector","value"];case"browser.upload":return["hostPaths"];case"browser.download":return["toPath","trigger"];case"browser.screenshot":return["tabId"];case"computer.point":case"computer.click":case"computer.double-click":case"computer.right-click":return["point"];case"computer.drag":return["from","to"];case"computer.type":return["text"];case"computer.key":return["combo"];case"computer.scroll":return["at","delta"];case"computer.launch":return["applicationId"];default:return[]}}function ta(){return{type:"object",properties:{shift:{type:"boolean"},ctrl:{type:"boolean"},alt:{type:"boolean"},meta:{type:"boolean"}},additionalProperties:!1}}function ra(e){let t=X(e),r=e.split(".").slice(1).join(" ");return`${t.effect==="act"?"Act on":"Inspect"} the ${t.surface} using governed ${r} automation. The host requires policy approval, an exact capability lease, target-bound preflight, and durable evidence.`}function na(e){return X(e).effect==="observe"?e==="browser.navigate"||e==="browser.tabs.open"?"medium":"low":["browser.type","browser.upload","browser.download","computer.type","computer.key","computer.launch"].includes(e)?"high":"medium"}function oa(e,t){let r=rr(e,t),n={operation:e};r&&(n.target=r);for(let o of["selector","clear","submit","combo","value","dx","dy","point","from","to","at","delta","milliseconds"])t[o]!==void 0&&(n[o]=structuredClone(t[o]));return typeof t.text=="string"&&(n.text=`[redacted ${t.text.length} characters]`),Array.isArray(t.hostPaths)&&(n.hostPaths=t.hostPaths.map(()=>"[redacted host path]")),typeof t.toPath=="string"&&(n.toPath="[redacted destination path]"),n}function ia(e,t){let r=structuredClone(t);return typeof r.text=="string"&&(r.text=`[redacted ${r.text.length} characters]`),Array.isArray(r.hostPaths)&&(r.hostPaths=r.hostPaths.map(()=>"[redacted host path]")),typeof r.toPath=="string"&&(r.toPath="[redacted destination path]"),Tn(r.trigger)&&typeof r.trigger.url=="string"&&(r.trigger={...r.trigger,url:Sn(r.trigger.url)}),typeof r.url=="string"&&(r.url=Sn(r.url)),{operation:e,...r}}function aa(e,t){let r=rr(e,t),n=r?.url??r?.applicationId??r?.deviceId??r?.tabId??r?.resource??"current target";return`${e} on ${n}`}function rr(e,t){let r={};return typeof t.url=="string"&&(r.url=t.url),typeof t.tabId=="string"&&(r.tabId=t.tabId),typeof t.deviceId=="string"&&(r.deviceId=t.deviceId),typeof t.applicationId=="string"&&(r.applicationId=t.applicationId),typeof t.displayId=="string"&&(r.displayId=t.displayId),(e==="browser.navigate"||e==="browser.tabs.list"||e==="browser.tabs.open")&&(r.resource="browser-tabs"),Object.keys(r).length>0?r:void 0}function sa(e){return{operationId:e.operationId,status:e.status,effect:e.effect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:e.adapter,target:e.target,...e.data!==void 0?{data:e.data}:{},artifacts:e.artifacts.map(t=>({artifactId:t.artifactId,revision:t.revision,kind:t.kind,title:t.title,state:t.state,mediaType:t.mediaType,sensitivity:t.sensitivity,hash:t.content.hash,sizeBytes:t.content.sizeBytes})),lease:e.lease,...e.error?{error:e.error}:{}}}function ca(e){let t=[];for(let r of e.artifacts){if(t.length>=Ki||!r.mediaType.startsWith("image/"))continue;let n=r.content.storage;if(n.type!=="inline"||typeof n.base64!="string")continue;let o=Math.floor(n.base64.length*.75);o<=0||o>Ji||t.push({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${n.base64}`,detail:"high"}})}return t}function da(e){let t=new Set(se),r=new Set;for(let n of e){if(!t.has(n))throw new TypeError(`Unsupported XENO automation operation: ${String(n)}`);r.add(n)}return Array.from(r)}function la(e){return(0,st.createHash)("sha256").update(er(e)).digest("hex")}function er(e){return Array.isArray(e)?`[${e.map(er).join(",")}]`:Tn(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${er(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function Sn(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid URL]"}}function ua(e){return e instanceof Error?e.message:String(e)}function pa(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:"AUTOMATION_EXECUTION_FAILED"}function Tn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var Pn=require("node:crypto"),fa=Symbol.for("@xenosystem/agent-sdk/tool-authorization/v1"),ma=globalThis,ga=ma[fa]??=new WeakMap;function xn(e,t,r){let n=ga.get(e);if(!n?.active||n.toolName!==t||e.toolName!==t||e.permission?.allowed!==!0||e.policy?.allowed!==!0||n.fingerprint!==Cn(r)||n.receiptFingerprint!==Cn(e))throw Object.assign(new Error("Governed execution requires the current exact orchestrator authorization"),{code:"AUTOMATION_AUTHORIZATION_RECEIPT_REQUIRED",retryable:!1})}function Cn(e){return(0,Pn.createHash)("sha256").update(JSON.stringify(nr(structuredClone(e),0))).digest("hex")}function nr(e,t){if(t>128)throw Error("Tool authorization input depth exceeded");if(Array.isArray(e))return e.map(r=>nr(r,t+1));if(e!==null&&typeof e=="object")return Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>[r,nr(n,t+1)]));if(typeof e=="number"&&!Number.isFinite(e))throw Error("Tool authorization input must be finite");if(!["string","number","boolean"].includes(typeof e)&&e!==null)throw Error("Tool authorization input is not JSON data");return e}var ha=se.filter(e=>e.startsWith("browser.")),Aa=se.filter(e=>e.startsWith("computer.")),or=6e4,lt=class{constructor(t){this.options=t;this.environment=t.environment??sr()}options;leases=new it({maximumDurationMs:or,maximumUses:1});activeExecutors=new Map;environment;browserAdapter;computerAdapter;verifiedOperations=[];registered=new Map;register(t){if(this.options.safeMode)return 0;let r=this.verifiedOperations;if(r.length===0)return 0;let n=tr({runtime:this,operations:r});for(let o of n)if(t.has(o.definition.name)&&!this.registered.get(t)?.some(i=>i.definition.name===o.definition.name&&t.get(i.definition.name)===i))throw new Error("Automation capability registration conflicts with another tool owner.");return t.registerAll(n),this.registered.set(t,n),r.length}async registerVerified(t){for(let[n,o]of this.registered)for(let i of o)n.get(i.definition.name)===i&&n.unregister(i.definition.name);if(this.registered.clear(),this.verifiedOperations=[],this.options.safeMode)return 0;let r=[];for(let n of["browser","computer"])if(!(n==="computer"&&!this.options.computerHostAuthority)&&!(n==="browser"?!ar(this.environment.browser):!ut(this.environment.computer,!!this.options.computerAdapter)))try{let o=await this.adapterFor(n),i=await o.manifest();if(F(i),n==="computer"&&dt("observe",this.environment).sensitiveRegionRedaction&&i.supports.sensitiveRegionRedaction!==!0)continue;let a=n==="browser"?ha:Aa;r.push(...i.operations.filter(c=>a.includes(c)))}catch{}return this.verifiedOperations=[...new Set(r)],this.register(t)}async execute(t){if(this.options.safeMode)throw new Error("Governed automation is disabled in safe mode");if(ir(t),t.operation==="browser.screenshot"&&!t.declaredTarget?.tabId?.trim())throw new Error("Screen capture requires an explicit authorized tabId.");let r=X(t.operation),n=r.surface==="computer"?this.options.computerHostAuthority:void 0;if(r.surface==="computer"&&!n)throw new Error("Computer automation requires independent host operation authority.");let o=await this.adapterFor(r.surface),i=await o.manifest();if(F(i),r.surface==="computer"&&dt(r.effect,this.environment).sensitiveRegionRedaction&&i.supports.sensitiveRegionRedaction!==!0)throw new Error("Owning computer adapter cannot satisfy this host's required sensitive-region redaction.");if(!i.operations.includes(t.operation))throw new Error("Owning adapter no longer supports this operation; refresh capability discovery.");let a=this.options.profile(),c={runId:this.options.runId,agentId:this.options.agentId??"agent-main",...this.options.sessionId?{sessionId:this.options.sessionId}:{},turnId:t.authorization.turnId,...this.options.workspaceId?{workspaceId:this.options.workspaceId}:{}},s=Ra(t.operation,t.declaredTarget,this.environment),l=r.surface==="browser"?r.effect==="act"?"browser-act":"browser-read":r.effect==="act"?"computer-act":"computer-observe",y=r.effect==="act"?"external":"read",A=`lease-${(0,_n.randomUUID)()}`,p=(E,S,I)=>{if(t.signal?.throwIfAborted(),E!==A||S!==2||this.options.profile().fingerprint!==a.fingerprint)throw new Error("Automation lease authority changed during preflight; obtain fresh authorization.");let $=this.leases.request({leaseId:A,subject:{runId:c.runId,agentId:c.agentId,turnId:c.turnId,toolName:t.governingToolName,operationId:t.operationId},scope:{kind:l,effect:y,operations:[t.operation],...I.resource?{resources:[I.resource]}:{},...I.destination?{destinations:[I.destination]}:{},governingToolName:t.governingToolName},reason:`${t.operation} authorized by the CLI policy and permission layers`,requestedBy:{kind:"agent",id:c.agentId,profileFingerprint:a.fingerprint},durationMs:or,requestTtlMs:3e4,maxUses:1,childInheritance:"none",policyFingerprints:[a.fingerprint]},a),ae=this.leases.approve({leaseId:$.leaseId,expectedVersion:$.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:t.authorization.turnId,messageId:t.authorization.toolCallId}});return this.leases.consume(ae.leaseId,ae.version,I)},v=Dr({contractId:`contract-${t.operationId}`,identity:c,policy:this.securityPolicy(),profile:a,...this.options.securityStatus?{adapterStatus:this.options.securityStatus}:{},filesystem:{readRoots:[(0,ee.resolve)(this.options.cwd())],writeRoots:[(0,ee.resolve)(this.options.cwd())],executeRoots:[(0,ee.resolve)(this.options.cwd())]},network:xa(s,this.environment),browser:r.surface==="browser"?Pa(r.effect,s,this.environment):{mode:"none"},computer:r.surface==="computer"?dt(r.effect,this.environment):{mode:"none"},capabilityLeaseIds:[A],expiresAt:new Date(Date.now()+or).toISOString()}),m={protocolVersion:1,operationId:t.operationId,idempotencyKey:t.idempotencyKey,requestedAt:new Date().toISOString(),identity:c,governingToolName:t.governingToolName,operation:t.operation,parameters:Oa(t.parameters),...s?{declaredTarget:s}:{},executionContract:v,capabilityLeaseId:A,expectedLeaseVersion:2},x=new AbortController,C=x.signal,R=()=>x.abort(t.signal?.reason);t.signal?.aborted?R():t.signal?.addEventListener("abort",R,{once:!0});let k=new $e({adapter:o,assertCurrent:async E=>{if(C.throwIfAborted(),ir(t),this.options.profile().fingerprint!==a.fingerprint)throw new Error("Automation authority changed during execution; evidence release refused.");await n?.assertCurrent(structuredClone(E))},...n?{onPreflight:(E,S,I)=>n.recordPreflight(E,S,I),onGrant:(E,S,I,$)=>n.recordGrant(E,S,I,$)}:{},leaseAuthority:{consume:async(E,S,I)=>{let $=p(E,S,I);return await this.audit({eventType:"automation_lease_approved",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:A,contractFingerprint:v.fingerprint,permissionReason:t.authorization.permission.reason}),$}},artifactRepository:new nt({directory:(0,ee.resolve)(this.options.cwd(),".xeno","artifacts")})});if(this.activeExecutors.has(t.operationId)||this.activeExecutors.size>=64)throw t.signal?.removeEventListener("abort",R),Object.assign(new Error("Host automation operation identity is already active or capacity is reached."),{code:"AUTOMATION_OPERATION_CONFLICT",retryable:!1});this.activeExecutors.set(t.operationId,{executor:k,controller:x});try{t.reportProgress?.({activity:"state",message:`Executing governed ${t.operation}`}),await n?.begin(structuredClone(m),{authorization:t.authorization,profileFingerprint:a.fingerprint,assertCurrent:()=>{if(C.throwIfAborted(),ir(t),this.options.profile().fingerprint!==a.fingerprint)throw new Error("Computer host profile authority changed.")}},C);let E=await k.execute(m,C);return await this.audit({eventType:E.status==="ok"?"automation_completed":"automation_failed",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:A,contractFingerprint:v.fingerprint,status:E.status,artifactIds:E.artifacts.map(S=>S.artifactId)}),E}catch(E){throw await this.audit({eventType:"automation_failed",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:A,contractFingerprint:v.fingerprint,status:E instanceof Error?E.name:"error"}),E}finally{t.signal?.removeEventListener("abort",R);try{await n?.finish(structuredClone(m))}finally{this.activeExecutors.delete(t.operationId)}}}async stop(t,r="human-stop"){let n=this.activeExecutors.get(t);return n?(n.controller.abort(new Error(r)),await n.executor.stop(t,r),!0):!1}securityPolicy(){let t=this.options.securityPolicy?.();if(t)return t;let r=(0,ee.resolve)(this.options.cwd());return{allowedDirectories:[r],workingDirectory:r,capabilities:{terminal:!0,fileRead:!0,fileWrite:!0,appLaunch:!0},executionLevel:"policy-only",trustMode:"trusted-workspace",allowNetwork:!1}}adapterFor(t){if(t==="browser"){let n=this.environment.browser;if(!ar(n))throw new Error(Xn(n));return this.browserAdapter??=new Te({baseUrl:n.baseUrl,token:n.token,driver:n.driver,...n.ownedView?{ownedView:n.ownedView}:{}}),this.browserAdapter}let r=this.environment.computer;if(!ut(r,!!this.options.computerAdapter))throw new Error(cr(r,!!this.options.computerAdapter));return this.computerAdapter??=this.options.computerAdapter?Promise.resolve(this.options.computerAdapter):kn(r,this.options.computerOwnerAdmission),this.computerAdapter}async audit(t){try{await this.options.onAudit?.(t)}catch{}}};function ya(e){return new lt(e)}function Ia(e){if(e)return async t=>{let r=X(t.operation).effect;await e.append({trace_id:t.traceId,event_type:t.eventType,actor:"system",risk_level:r==="act"?"high":"low",...t.eventType==="automation_lease_approved"?{decision:"allow"}:{},status:t.eventType==="automation_failed"?"error":"ok",...t.eventType==="automation_failed"&&t.status?{reason:t.status}:{},metadata:{operation:t.operation,operation_id:t.operationId,lease_id:t.leaseId,contract_fingerprint:t.contractFingerprint,result_status:t.status,artifact_ids:t.artifactIds,permission_reason:t.permissionReason}})}}async function wa(e=sr()){let t=await Promise.all([Rn("browser",e),Rn("computer",e)]);return{schemaVersion:1,protocolVersion:1,enabled:t.some(r=>r.configured),surfaces:t,docs:"docs/GOVERNED_AUTOMATION.md"}}function sr(e=process.env){let t=e.XENO_BROWSER_DRIVER==="extension"?"extension":"browser",r=Ea(e,t),n=q(e.XENO_BROWSER_AUTOMATION_URL)??r?.baseUrl,o=q(e.XENO_BROWSER_AUTOMATION_TOKEN)??r?.token,i=q(e.XENO_USE_BASE_URL),a=q(e.XENO_USE_TOKEN)??ba(e.XENO_USE_TOKEN_FILE),c=q(e.XENO_USE_DEVICE_ID);return{browser:{driver:t,...n?{baseUrl:n}:{},...o?{token:o}:{},readDomains:ct(e.XENO_BROWSER_READ_DOMAINS),actDomains:ct(e.XENO_BROWSER_ACT_DOMAINS),deniedDomains:ct(e.XENO_BROWSER_DENIED_DOMAINS),ports:_a(e.XENO_BROWSER_ALLOWED_PORTS,[443]),allowLoopbackDevelopment:e.XENO_BROWSER_ALLOW_LOOPBACK_DEVELOPMENT==="1",uploads:On(e.XENO_BROWSER_UPLOADS,"prompt"),downloads:On(e.XENO_BROWSER_DOWNLOADS,"prompt"),recording:e.XENO_BROWSER_RECORDING==="bounded"?"bounded":"disabled"},computer:{...i?{baseUrl:i}:{},...a?{token:a}:{},...c?{deviceId:c}:{},allowedApplications:ct(e.XENO_USE_ALLOWED_APPLICATIONS)}}}function ba(e){let t=q(e);if(!(!t||!(0,Pe.existsSync)(t)))try{return q((0,Pe.readFileSync)(t,"utf8"))}catch{return}}function Ea(e,t){let n=q(e.XENO_BROWSER_SESSION_FILE)??(t==="extension"?q(e.XENO_EXTENSION_SESSION_FILE)??(0,ee.join)((0,Nn.homedir)(),".xeno","use-drivers","xeno-extension.json"):q(e.XENO_SESSION_FILE)??(e.APPDATA?(0,ee.join)(e.APPDATA,"xeno-browser","session.json"):void 0));if(!(!n||!(0,Pe.existsSync)(n)))try{let o=JSON.parse((0,Pe.readFileSync)(n,"utf8")),i=Number(o.port),a=typeof o.token=="string"?o.token:"",c=typeof o.driver=="string"?o.driver:void 0;return!Number.isSafeInteger(i)||i<=0||i>65535||!va(a)||c&&c!==(t==="extension"?"xeno-extension-native":"xeno-browser-loopback")?void 0:{baseUrl:`http://127.0.0.1:${i}`,token:a}}catch{return}}function va(e){return e.length>=32&&e.length<=512&&!/\s/.test(e)}async function Rn(e,t){let r=e==="browser"?t.browser:t.computer,n=e==="browser"?ar(t.browser):ut(t.computer),o=!!r&&Object.values(r).some(i=>typeof i=="string"&&i.length>0);if(!n)return{surface:e,configured:!1,available:!1,certified:!1,operations:[],limitations:["Adapter credentials are not completely configured."],...o?{error:e==="browser"?Xn(t.browser):cr(t.computer)}:{}};try{let a=await(e==="browser"?new Te({baseUrl:t.browser.baseUrl,token:t.browser.token,driver:t.browser.driver,...t.browser.ownedView?{ownedView:t.browser.ownedView}:{}}):await kn(t.computer)).manifest();if(F(a),e==="computer"&&dt("observe",t).sensitiveRegionRedaction&&a.supports.sensitiveRegionRedaction!==!0)throw new Error("Owning computer adapter cannot satisfy this host's required sensitive-region redaction.");return Ca(e,a)}catch(i){return{surface:e,configured:!0,available:!1,certified:!1,operations:[],limitations:["Configured adapter is unavailable."],error:dr(i)}}}async function kn(e,t){if(e={...e},!ut(e))throw new Error(cr(e));let r=await Ta(),n=new r.Use({baseUrl:e.baseUrl,...e.authorize?{authorize:Sa(e.authorize)}:{token:e.token}});return new r.XenoUseComputerAutomationAdapter({use:n,...e.deviceId?{defaultDeviceId:e.deviceId}:{},...t?{executingPrincipalId:t.executingPrincipalId,authorizeOwner:t.authorize}:{}})}function Sa(e){return async(t,r)=>{try{let n=await e(t,r);if(n?.tokenType==="DPoP")return n}catch{}throw Object.assign(new Error("Canonical computer request authorization is unavailable."),{code:"AUTOMATION_AUTHORIZATION_UNAVAILABLE",retryable:!1})}}async function Ta(){try{let e="@xeno-use/sdk",t="@xeno-use/agent-sdk-pack",[r,n]=await Promise.all([import(e),import(t)]);if(typeof r.Use!="function"||typeof n.XenoUseComputerAutomationAdapter!="function")throw new Error("installed xeno-use packages do not expose the governed adapter contract");return{Use:r.Use,XenoUseComputerAutomationAdapter:n.XenoUseComputerAutomationAdapter}}catch(e){throw new Error(`Computer automation requires @xeno-use/sdk and @xeno-use/agent-sdk-pack: ${dr(e)}`)}}function Ca(e,t){return{surface:e,configured:!0,available:!0,certified:t.certified,adapterId:t.adapterId,adapterVersion:t.adapterVersion,operations:[...t.operations],limitations:[...t.limitations]}}function Pa(e,t,r){let n=r.browser,o=Ln(t),i=o&&!Un(o.hostname)?o.hostname:void 0,a=pt([...n.readDomains,...i?[i]:[]]),c=pt([...n.actDomains,...e==="act"&&i?[i]:[]]),s=Bn([...n.ports,...o?[Mn(o)]:[]]);return{mode:e==="act"?"act":"read",profile:"ephemeral",readAllowedDomains:a,actAllowedDomains:c,deniedDomains:n.deniedDomains,allowedSchemes:n.allowLoopbackDevelopment?["https","http"]:["https"],allowedPorts:s,redirectPolicy:"policy",allowLoopbackDevelopment:n.allowLoopbackDevelopment,uploads:n.uploads,downloads:n.downloads,recording:n.recording}}function dt(e,t){return{mode:e==="act"?"act":"observe",allowedApplications:t.computer?.allowedApplications??[],sensitiveRegionRedaction:!0,humanStopRequired:!0}}function xa(e,t){let r=[],n=Ln(e);n&&r.push({scheme:n.protocol.replace(/:$/,""),host:n.hostname.toLowerCase(),port:Mn(n)});for(let o of pt([...t.browser?.readDomains??[],...t.browser?.actDomains??[]]))if(!(o.startsWith(".")||o.includes("*")))for(let i of t.browser?.ports??[443])r.push({scheme:i===80?"http":"https",host:o,port:i});return{default:"deny",allowDestinations:Na(r)}}function Ra(e,t,r){if(!e.startsWith("computer."))return t;let n=t?.deviceId??r.computer?.deviceId,o=t?.applicationId;if(!(!n&&!o&&!t))return{...t??{},...n?{deviceId:n}:{}}}function ir(e){let t=e.authorization;if(!t||t.toolName!==e.governingToolName||!t.permission.allowed||!t.policy.allowed)throw new Error("Automation authorization receipt does not match the governing tool");xn(t,e.governingToolName,e.parameters)}function Oa(e){try{return JSON.parse(JSON.stringify(e))}catch(t){throw new Error(`Automation parameters are not JSON serializable: ${dr(t)}`)}}function ar(e){return!!e?.baseUrl&&!!e.token}function ut(e,t=!1){return Dn(e,t)===void 0}function Xn(e){return`Browser automation configuration is incomplete; missing ${[e?.baseUrl?"":"XENO_BROWSER_AUTOMATION_URL",e?.token?"":"XENO_BROWSER_AUTOMATION_TOKEN"].filter(Boolean).join(", ")}`}function cr(e,t=!1){return Dn(e,t)??"Computer automation configuration is unavailable."}function Dn(e,t){let r=e?.token!==void 0,n=e?.authorize!==void 0;if(r&&n)return"Computer automation requires exactly one bootstrap token or canonical request authorizer.";if(n&&typeof e?.authorize!="function")return"Computer automation requires a callable canonical request authorizer.";if(r&&(typeof e?.token!="string"||!e.token.trim()))return"Computer automation bootstrap token is invalid.";if(e?.baseUrl!==void 0)try{let i=new URL(e.baseUrl);if(i.username||i.password||i.search||i.hash||i.pathname!=="/"||i.protocol!=="https:"&&!(i.protocol==="http:"&&Un(i.hostname)&&!n))return"Computer automation requires an HTTPS origin; explicit bootstrap compatibility may use loopback HTTP only."}catch{return"Computer automation endpoint must be a valid origin."}let o=[!t&&!e?.baseUrl?"XENO_USE_BASE_URL":"",!t&&!r&&!n?"XENO_USE_TOKEN or canonical request authorizer":"",e?.deviceId?.trim()?"":"XENO_USE_DEVICE_ID"].filter(Boolean);return o.length?`Computer automation configuration is incomplete; missing ${o.join(", ")}`:void 0}function Ln(e){let t=e?.url??e?.origin;if(t)try{return new URL(t)}catch{return}}function Mn(e){return e.port?Number(e.port):e.protocol==="http:"?80:443}function Un(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"}function ct(e){return pt((e??"").split(",").map(t=>t.trim().toLowerCase()).filter(Boolean))}function _a(e,t){let r=(e??"").split(",").map(n=>Number(n.trim())).filter(n=>Number.isSafeInteger(n)&&n>0&&n<=65535);return r.length>0?Bn(r):t}function On(e,t){return e==="deny"||e==="prompt"||e==="allow"?e:t}function q(e){let t=e?.trim();return t||void 0}function pt(e){return[...new Set(e)]}function Bn(e){return[...new Set(e)].sort((t,r)=>t-r)}function Na(e){let t=new Set;return e.filter(r=>{let n=`${r.scheme??""}:${r.host}:${r.port??""}`;return t.has(n)?!1:(t.add(n),!0)})}function dr(e){return e instanceof Error?e.message:String(e)}function ka(e){let t=["XENO governed automation",""];for(let r of e.surfaces){let n=r.configured?r.available?"available":"unavailable":"not configured",o=r.certified?"certified":"not release-certified";t.push(`${r.surface}: ${n}; ${o}`),r.adapterId&&t.push(` adapter: ${r.adapterId}@${r.adapterVersion??"unknown"}`),r.operations.length>0&&t.push(` operations: ${r.operations.length}`);for(let i of r.limitations)t.push(` limitation: ${i}`);r.error&&t.push(` error: ${r.error}`)}return t.push("",`Docs: ${e.docs}`),t.join(`
|
|
948
|
+
`),toolPolicy:{mode:"readOnly"},skills:["verify"],permissionProfile:"default",memoryScope:"session",soul:"disabled",allowedModes:["chat","plan","review"],defaultMode:"review",evidence:["sources","human-review"],primarySources:!0,currentInformation:!0,humanReview:!0,externalDefault:"deny",color:"red",glyph:"\xA7",tags:["legal","research","restricted","read-only"],stopConditions:["The jurisdiction or effective date is unknown and materially changes the answer.","The task requires legal representation, filing, signature, payment, or contact with a third party.","The sourced analysis is complete and clearly marked for qualified human review."]})];var Sn=1,O=class extends Error{constructor(r,n,o){super(n);this.code=r;this.detail=o;this.name="XenoCapabilityLeaseError"}code;detail},$i=new Set(["filesystem-write","process-execute","network-connect","secret-use","external-action","browser-act","computer-act"]),Fi=new Set(er),Vi=new Set(["filesystem-read","filesystem-write","process-execute","network-connect","secret-use","external-action","browser-read","browser-act","computer-observe","computer-act","tool-invoke"]),ji=new Set(["cli","hub","ide","api","hosted"]),Hi=/^[a-f0-9]{64}$/;function Gi(e,t){Tn(e);let r=e.scope,n=r.governingToolName??e.subject.toolName;if(r.kind!=="external-action"){if(!n)return{eligible:!1,approvalRequirement:"principal",reason:"Non-external capability requests must identify the governing tool."};let o=Wi(t,n,r.effect);if(!o.eligible)return o}if(t.capabilities.permissionProfile==="read-only"&&r.effect!=="read")return{eligible:!1,approvalRequirement:"principal",reason:"The active read-only permission profile cannot request mutating, executable, or external authority."};if(r.kind==="external-action"){let o=r.externalAction;if(!o)return{eligible:!1,approvalRequirement:"current-turn",reason:"External-action capability requests require an exact action."};let i=t.capabilities.externalActions,a=i.overrides?.[o]??i.default;if(a==="deny")return{eligible:!1,approvalRequirement:"current-turn",profileDecision:a,reason:`Agent Profile ${t.profile.id} denies external action ${o}.`};let c=a==="ask"||i.requireCurrentTurnApproval.includes(o);return c&&!e.subject.turnId?{eligible:!1,approvalRequirement:"current-turn",profileDecision:a,reason:`External action ${o} requires a subject turn ID for current-turn approval.`}:{eligible:!0,approvalRequirement:c?"current-turn":"principal",profileDecision:a,reason:c?`External action ${o} requires approval in the active turn.`:`External action ${o} is requestable but still requires a bounded lease approval.`}}return{eligible:!0,approvalRequirement:"principal",reason:`Capability ${r.kind} is requestable within Agent Profile ${t.profile.id}.`}}function Tn(e){if(!e||typeof e!="object")throw h("Capability lease request must be an object");if(B(e.subject?.runId,"subject.runId"),B(e.subject?.agentId,"subject.agentId"),e.subject?.turnId!==void 0&&B(e.subject.turnId,"subject.turnId"),B(e.reason,"reason",8192),Ae(e.requestedBy,"requestedBy"),qi(e.scope),e.policyFingerprints?.forEach(t=>at(t,"policyFingerprints")),e.maxUses!==void 0&&(!Number.isInteger(e.maxUses)||e.maxUses<1))throw h("maxUses must be a positive integer");if(e.durationMs!==void 0&&(!Number.isSafeInteger(e.durationMs)||e.durationMs<1))throw h("durationMs must be a positive safe integer");if(e.requestTtlMs!==void 0&&(!Number.isSafeInteger(e.requestTtlMs)||e.requestTtlMs<1))throw h("requestTtlMs must be a positive safe integer")}var it=class e{leases=new Map;now;idFactory;maximumDurationMs;maximumRequestTtlMs;maximumUses;idCounter=0;constructor(t={}){this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(()=>`lease_${Date.now().toString(36)}_${(++this.idCounter).toString(36)}`),this.maximumDurationMs=t.maximumDurationMs??15*6e4,this.maximumRequestTtlMs=t.maximumRequestTtlMs??5*6e4,this.maximumUses=t.maximumUses??100}static fromPersistedLease(t,r={}){zi(t);let n=new e(r);return n.leases.set(t.leaseId,ie(t)),n}request(t,r){let n=Gi(t,r);if(!n.eligible)throw new O("LEASE_NOT_REQUESTABLE",n.reason);let o=t.leaseId??this.idFactory();if(B(o,"leaseId"),this.leases.has(o))throw new O("LEASE_CONFLICT",`Capability lease ${o} already exists`);let i=this.now(),a=Math.min(t.durationMs??6e4,this.maximumDurationMs),c=Math.min(t.requestTtlMs??5*6e4,this.maximumRequestTtlMs),s=Math.min(t.maxUses??1,this.maximumUses),l={schemaVersion:Sn,leaseId:o,version:1,state:"requested",subject:Ki(t.subject),scope:Yi(t.scope),reason:t.reason,requestedAt:i,requestExpiresAt:vn(i,c),durationMs:a,maxUses:s,useCount:0,childInheritance:t.childInheritance??"none",approvalRequirement:n.approvalRequirement,requestedBy:{...t.requestedBy},profileFingerprint:r.fingerprint,policyFingerprints:he(t.policyFingerprints??[]),...t.auditEventIds?{auditEventIds:he(t.auditEventIds)}:{},...t.evidenceArtifactIds?{evidenceArtifactIds:he(t.evidenceArtifactIds)}:{}};return this.leases.set(o,l),ie(l)}approve(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="requested")throw new O("LEASE_CONFLICT",`Capability lease ${r.leaseId} is ${r.state}`);if(Ae(t.approvedBy,"approvedBy"),Cn(t.approvalContext),r.approvalRequirement==="current-turn"&&(!r.subject.turnId||t.approvalContext.turnId!==r.subject.turnId))throw new O("LEASE_APPROVAL_REQUIRED","Capability lease requires approval bound to the requesting turn");let n=this.now();return r.state="active",r.version+=1,r.activatedAt=n,r.expiresAt=vn(n,r.durationMs),r.approvedBy={...t.approvedBy},r.approvalContext={...t.approvalContext},ie(r)}deny(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="requested")throw new O("LEASE_CONFLICT",`Capability lease ${r.leaseId} is ${r.state}`);return Ae(t.deniedBy,"deniedBy"),r.state="denied",r.version+=1,r.deniedAt=this.now(),r.deniedBy={...t.deniedBy},ie(r)}revoke(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="active")throw new O("LEASE_CONFLICT",`Only active leases can be revoked; ${r.leaseId} is ${r.state}`);return Ae(t.revokedBy,"revokedBy"),r.state="revoked",r.version+=1,r.revokedAt=this.now(),r.revokedBy={...t.revokedBy},ie(r)}consume(t,r,n){let o=this.requireMutable(t);if(this.assertVersion(o,r),this.refreshState(o),o.state==="requested")throw new O("LEASE_APPROVAL_REQUIRED",`Capability lease ${t} is not approved`);if(o.state==="expired")throw new O("LEASE_EXPIRED",`Capability lease ${t} expired`);if(o.state==="revoked")throw new O("LEASE_REVOKED",`Capability lease ${t} was revoked`);if(o.state==="exhausted")throw new O("LEASE_EXHAUSTED",`Capability lease ${t} is exhausted`);if(o.state!=="active")throw new O("LEASE_SCOPE_MISMATCH",`Capability lease ${t} is ${o.state}`);return Ji(o,n),o.useCount+=1,o.version+=1,o.useCount>=o.maxUses&&(o.state="exhausted",o.exhaustedAt=this.now()),ie(o)}get(t){let r=this.leases.get(t);if(r)return this.refreshState(r),ie(r)}list(t){let r=[];for(let n of this.leases.values())this.refreshState(n),!(t?.runId&&n.subject.runId!==t.runId)&&(t?.agentId&&n.subject.agentId!==t.agentId||t?.turnId&&n.subject.turnId!==t.turnId||r.push(ie(n)));return r.sort((n,o)=>n.requestedAt.localeCompare(o.requestedAt)||n.leaseId.localeCompare(o.leaseId))}requireMutable(t){let r=this.leases.get(t);if(!r)throw new O("LEASE_NOT_FOUND",`Capability lease ${t} was not found`);return r}assertVersion(t,r){if(t.version!==r)throw new O("LEASE_CONFLICT",`Expected capability lease version ${r}, found ${t.version}`,{leaseId:t.leaseId,expectedVersion:r,actualVersion:t.version})}refreshState(t){let r=Date.parse(this.now()),n=t.state==="requested"?Date.parse(t.requestExpiresAt):Date.parse(t.expiresAt??"");(t.state==="requested"||t.state==="active")&&Number.isFinite(n)&&r>=n&&(t.state="expired",t.version+=1,t.expiredAt=this.now())}};function zi(e){if(!e||typeof e!="object"||Array.isArray(e)||JSON.stringify(e).length>65536)throw h("Invalid persisted lease row");let t=e;if(t.schemaVersion!==Sn)throw h("Unsupported persisted lease schema");if(Tn(t),B(t.leaseId,"leaseId"),at(t.profileFingerprint,"profileFingerprint"),!Array.isArray(t.policyFingerprints))throw h("policyFingerprints must be an array");if(t.policyFingerprints.forEach(r=>at(r,"policyFingerprint")),!Number.isSafeInteger(t.durationMs)||t.durationMs<1||!Number.isSafeInteger(t.maxUses)||t.maxUses<1)throw h("Invalid persisted lease limits");if(!Number.isSafeInteger(t.version)||t.version<1||!Number.isSafeInteger(t.useCount)||t.useCount<0||t.useCount>t.maxUses)throw h("Invalid persisted lease counters");if(!["requested","active","denied","revoked","expired","exhausted"].includes(t.state))throw h("Invalid persisted lease state");if(!["principal","current-turn"].includes(t.approvalRequirement)||!["none","explicit"].includes(t.childInheritance))throw h("Invalid persisted lease authority");for(let r of["requestedAt","requestExpiresAt","activatedAt","expiresAt","expiredAt","deniedAt","revokedAt","exhaustedAt"])if((r==="requestedAt"||r==="requestExpiresAt"||t[r]!==void 0)&&(typeof t[r]!="string"||!Number.isFinite(Date.parse(t[r]))))throw h(`Invalid persisted ${r}`);if(Date.parse(t.requestExpiresAt)<=Date.parse(t.requestedAt))throw h("Invalid persisted request expiry");if(["active","revoked","exhausted"].includes(t.state)||t.useCount>0){if(!t.activatedAt||!t.expiresAt||!t.approvedBy||!t.approvalContext||t.version<2)throw h("Persisted approval is incomplete");if(Ae(t.approvedBy,"approvedBy"),Cn(t.approvalContext),Date.parse(t.expiresAt)!==Date.parse(t.activatedAt)+t.durationMs)throw h("Persisted expiry does not match approved duration");if(t.approvalRequirement==="current-turn"&&(!t.subject.turnId||t.approvalContext.turnId!==t.subject.turnId))throw h("Persisted turn approval does not match")}if(t.state==="requested"&&(t.version!==1||t.useCount!==0||t.approvedBy))throw h("Invalid requested lease");if(t.state==="active"&&t.useCount>=t.maxUses)throw h("Active lease is exhausted");if(t.state==="exhausted"&&t.useCount!==t.maxUses)throw h("Invalid exhausted lease");if(t.state==="revoked"){if(!t.revokedAt||!t.revokedBy)throw h("Missing revocation");Ae(t.revokedBy,"revokedBy")}if(t.state==="denied"){if(!t.deniedAt||!t.deniedBy)throw h("Missing denial");Ae(t.deniedBy,"deniedBy")}if(t.state==="expired"&&!t.expiredAt)throw h("Missing expiry transition")}function Wi(e,t,r){let n=e.capabilities.tools,o=t.trim().toLowerCase(),i=a=>a?.some(c=>c==="*"||c.trim().toLowerCase()===o)??!1;return n.mode==="none"||i(n.deny)?{eligible:!1,approvalRequirement:"principal",reason:`Agent Profile ${e.profile.id} denies tool ${t}.`}:n.allow&&!i(n.allow)?{eligible:!1,approvalRequirement:"principal",reason:`Tool ${t} is outside the Agent Profile allowlist.`}:n.mode==="readOnly"&&r!=="read"?{eligible:!1,approvalRequirement:"principal",reason:`Tool ${t} cannot request ${r} authority in read-only mode.`}:{eligible:!0,approvalRequirement:"principal",reason:`Tool ${t} is requestable.`}}function qi(e){if(!e||typeof e!="object")throw h("scope is required");if(B(e.kind,"scope.kind"),!Vi.has(e.kind)&&!e.kind.startsWith("custom:"))throw h("scope.kind is not supported");if(e.kind.startsWith(Je)&&!Xe(e.kind))throw h("Custom capability kind is invalid");if(!["read","write","execute","external"].includes(e.effect))throw h("scope.effect is invalid");let t={"filesystem-read":"read","filesystem-write":"write","process-execute":"execute","network-connect":"external","secret-use":"external","external-action":"external","browser-read":"read","browser-act":"external","computer-observe":"read","computer-act":"external"};if(t[e.kind]&&t[e.kind]!==e.effect)throw h(`${e.kind} capability scopes must use ${t[e.kind]} effect`);if(!Array.isArray(e.operations)||e.operations.length===0)throw h("scope.operations must contain at least one operation");if(e.operations.forEach(r=>B(r,"scope.operations")),e.resources?.forEach(r=>B(r,"scope.resources",8192)),e.destinations?.forEach(r=>B(r,"scope.destinations",8192)),e.secretIds?.forEach(r=>B(r,"scope.secretIds",512)),e.kind==="external-action"){if(!e.externalAction||!Fi.has(e.externalAction))throw h("External-action scopes require a supported exact action");if(e.effect!=="external")throw h("External-action scopes must use external effect")}if(e.kind==="network-connect"&&(!e.destinations||e.destinations.length===0))throw h("Network capability scopes require at least one destination");if(e.kind==="secret-use"&&(!e.secretIds||e.secretIds.length===0))throw h("Secret capability scopes require at least one secret ID");if($i.has(e.kind)&&[...e.resources??[],...e.destinations??[],...e.secretIds??[]].some(n=>n.includes("*")))throw h("High-impact capability scopes cannot use wildcard resources")}function Ji(e,t){let r=e.subject;if(r.runId!==t.subject.runId||r.agentId!==t.subject.agentId)throw L(e,"run or agent subject");if(r.turnId&&r.turnId!==t.subject.turnId)throw L(e,"turn subject");if(r.toolName&&r.toolName!==t.subject.toolName)throw L(e,"tool subject");if(r.operationId&&r.operationId!==t.subject.operationId)throw L(e,"operation subject");if(e.scope.kind!==t.kind)throw L(e,"capability kind");if(!e.scope.operations.includes(t.operation))throw L(e,"operation");if(e.scope.resources?.length&&!t.resource)throw L(e,"resource");if(e.scope.destinations?.length&&!t.destination)throw L(e,"destination");if(e.scope.secretIds?.length&&!t.secretId)throw L(e,"secret");if(e.scope.externalAction&&!t.externalAction)throw L(e,"external action");if(t.resource&&!e.scope.resources?.includes(t.resource))throw L(e,"resource");if(t.destination&&!e.scope.destinations?.includes(t.destination))throw L(e,"destination");if(t.secretId&&!e.scope.secretIds?.includes(t.secretId))throw L(e,"secret");if(t.externalAction&&e.scope.externalAction!==t.externalAction)throw L(e,"external action")}function Cn(e){if(!e||typeof e!="object")throw h("approvalContext is required");if(B(e.surface,"approvalContext.surface"),!ji.has(e.surface)&&!e.surface.startsWith("custom:"))throw h("approvalContext.surface is not supported");if(e.surface.startsWith(Je)&&!Xe(e.surface))throw h("Custom approval surface is invalid");e.promptHash!==void 0&&at(e.promptHash,"approvalContext.promptHash")}function Ae(e,t){if(!e||typeof e!="object")throw h(`${t} is required`);if(!["agent","tool","user","system","integration"].includes(e.kind))throw h(`${t}.kind is invalid`);B(e.id,`${t}.id`)}function at(e,t){if(!Hi.test(e))throw h(`${t} must be a 64-character lowercase hexadecimal fingerprint`)}function B(e,t,r=1024){if(typeof e!="string"||e.trim().length===0||e.length>r)throw h(`${t} must be a non-empty string no longer than ${r} characters`)}function h(e){return new O("LEASE_INVALID",e)}function L(e,t){return new O("LEASE_SCOPE_MISMATCH",`Capability use is outside lease ${e.leaseId} ${t} scope`)}function vn(e,t){return new Date(Date.parse(e)+t).toISOString()}function he(e){return[...new Set(e)]}function Ki(e){return{...e}}function Yi(e){return{...e,operations:he(e.operations),...e.resources?{resources:he(e.resources)}:{},...e.destinations?{destinations:he(e.destinations)}:{},...e.secretIds?{secretIds:he(e.secretIds)}:{}}}function ie(e){return structuredClone(e)}var st=require("node:crypto");var Zi=8*1024*1024,Qi=4;function rr(e){return pa(e.operations??se).map(r=>ea(r,e.runtime))}function ea(e,t){return{definition:{name:e,description:ia(e),input_schema:ta(e)},projectPolicyInput(r){let n=ca(e,r),o=sa(e,r);return{observabilityInput:n,permissionInput:o,permissionPreview:da(e,r),approvalKey:`xeno-automation:${e}:${fa(r)}`,riskLevel:aa(e)}},async execute(r,n){if(e==="browser.screenshot"&&(typeof r.tabId!="string"||!r.tabId.trim()))return{success:!1,output:"",error:"Screen capture requires an explicit authorized tabId.",errorCode:"AUTOMATION_CAPTURE_TARGET_REQUIRED",retryable:!1};let o=n?.authorization;if(!o||o.toolName!==e)return{success:!1,output:"",error:"Governed automation requires a host-issued authorization receipt",errorCode:"AUTOMATION_AUTHORIZATION_RECEIPT_REQUIRED",retryable:!1};let i=n.operationId??`automation_${(0,st.randomUUID)()}`,a=nr(e,r);n.reportProgress?.({activity:"state",message:`Authorizing ${e}`});try{let c=await t.execute({operation:e,governingToolName:e,operationId:i,idempotencyKey:i,parameters:structuredClone(r),...a?{declaredTarget:a}:{},authorization:o,...n.signal?{signal:n.signal}:{},...n.reportProgress?{reportProgress:n.reportProgress}:{}}),s=c.status==="ok";return{success:s,output:JSON.stringify(la(c)),...s?{}:{error:c.error?.message??`Governed automation ended with ${c.status}`,errorCode:c.error?.code??`AUTOMATION_${c.status.toUpperCase().replaceAll("-","_")}`},assistantContent:ua(c),evidence:c.artifacts.map(l=>({id:l.artifactId,kind:"artifact",status:c.status==="evidence-incomplete"?"failed":"verified",observedAt:l.updatedAt??l.createdAt,operationId:i,detail:{artifact_kind:l.kind,revision:l.revision,sensitivity:l.sensitivity}})),retryable:c.error?.retryable??!1}}catch(c){let s=n.signal?.aborted===!0;return{success:!1,output:"",error:s?"Governed automation was stopped":ma(c),errorCode:s?"AUTOMATION_CANCELLED":ga(c),retryable:!1}}}}}function ta(e){let t=ra(e),r=na(e);return{type:"object",properties:t,...r.length>0?{required:r}:{},...e==="browser.locate"?{oneOf:[{required:["selector"]},{required:["text"]}]}:{},additionalProperties:!1}}function ra(e){let t=(a,c=8192)=>({type:"string",minLength:1,maxLength:c,description:a}),r={type:"number"},n={type:"boolean"},o={type:"object",properties:{x:r,y:r},required:["x","y"],additionalProperties:!1},i={deviceId:t("Target xeno-use device ID.",256),applicationId:t("Expected or launch-target application ID.",512),displayId:t("Target display ID.",256)};switch(e){case"browser.navigate":return{url:t("Destination URL."),waitUntil:{enum:["load","none"]},tabId:t("Expected active tab ID. Hosts with multiple visible tabs should require this.",256)};case"browser.wait":return{until:{enum:["load","ms"]},value:{type:"integer",minimum:0,maximum:6e4}};case"browser.snapshot":return{mode:{enum:["text","html","markdown","a11y"]},tabId:t("Expected active tab ID.",256)};case"browser.screenshot":return{tabId:t("Expected active tab ID.",256)};case"browser.locate":return{selector:t("CSS selector."),text:t("Visible text to locate.")};case"browser.click":return{selector:t("CSS selector returned by browser.snapshot or browser.locate."),tabId:t("Expected active tab ID.",256)};case"browser.type":return{selector:t("CSS selector."),text:{type:"string",maxLength:65536},clear:n,submit:n,tabId:t("Expected active tab ID.",256)};case"browser.key":return{combo:t("Key combo such as Control+a or Enter.",256),tabId:t("Expected active tab ID.",256)};case"browser.select":return{selector:t("CSS selector."),value:t("Option value."),tabId:t("Expected active tab ID.",256)};case"browser.scroll":return{selector:t("Optional CSS selector."),dx:r,dy:r,tabId:t("Expected active tab ID.",256)};case"browser.tabs.open":return{url:t("URL to open in an isolated browser tab.")};case"browser.tabs.close":return{tabId:t("Tab ID to close.",256)};case"browser.console.read":case"browser.network.read":case"browser.page-errors.read":return{limit:{type:"integer",minimum:1,maximum:1e3},clear:n,tabId:t("Expected active tab ID.",256)};case"browser.storage.read":return{tabId:t("Expected active tab ID.",256)};case"browser.upload":return{selector:t("File input or drop-target selector."),backendNodeId:{type:"integer",minimum:1},hostPaths:{type:"array",items:t("Host file path.",32768),minItems:1,maxItems:64},drop:n,tabId:t("Expected active tab ID.",256)};case"browser.download":return{toPath:t("Approved destination path.",32768),trigger:{type:"object",properties:{url:t("Download URL."),selector:t("Download trigger selector.")},oneOf:[{required:["url"]},{required:["selector"]}],additionalProperties:!1},tabId:t("Expected active tab ID.",256)};case"browser.record.start":return{maxDurationMs:{type:"integer",minimum:1e3,maximum:6e4},intervalMs:{type:"integer",minimum:100,maximum:5e3},tabId:t("Expected active tab ID.",256)};case"browser.record.stop":return{tabId:t("Expected active tab ID.",256)};case"computer.observe":case"computer.screenshot":case"computer.window-state":return i;case"computer.point":return{...i,point:o,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.click":return{...i,point:o,button:{enum:["left","right","middle"]},modifiers:oa()};case"computer.double-click":case"computer.right-click":return{...i,point:o};case"computer.drag":return{...i,from:o,to:o,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.type":return{...i,text:{type:"string",maxLength:65536}};case"computer.key":return{...i,combo:t("Key combo such as Control+a or Enter.",256)};case"computer.scroll":return{...i,at:o,delta:o};case"computer.wait":return{...i,milliseconds:{type:"integer",minimum:0,maximum:3e5}};case"computer.launch":return{...i,applicationId:t("Explicitly allowlisted application ID.",512)};case"browser.back":case"browser.forward":case"browser.reload":return{tabId:t("Expected active tab ID.",256)};case"browser.tabs.list":return{}}}function na(e){switch(e){case"browser.navigate":case"browser.tabs.open":return["url"];case"browser.click":return["selector"];case"browser.type":return["selector","text"];case"browser.key":return["combo"];case"browser.select":return["selector","value"];case"browser.upload":return["hostPaths"];case"browser.download":return["toPath","trigger"];case"browser.screenshot":return["tabId"];case"computer.point":case"computer.click":case"computer.double-click":case"computer.right-click":return["point"];case"computer.drag":return["from","to"];case"computer.type":return["text"];case"computer.key":return["combo"];case"computer.scroll":return["at","delta"];case"computer.launch":return["applicationId"];default:return[]}}function oa(){return{type:"object",properties:{shift:{type:"boolean"},ctrl:{type:"boolean"},alt:{type:"boolean"},meta:{type:"boolean"}},additionalProperties:!1}}function ia(e){let t=X(e),r=e.split(".").slice(1).join(" ");return`${t.effect==="act"?"Act on":"Inspect"} the ${t.surface} using governed ${r} automation. The host requires policy approval, an exact capability lease, target-bound preflight, and durable evidence.`}function aa(e){return X(e).effect==="observe"?e==="browser.navigate"||e==="browser.tabs.open"?"medium":"low":["browser.type","browser.upload","browser.download","computer.type","computer.key","computer.launch"].includes(e)?"high":"medium"}function sa(e,t){let r=nr(e,t),n={operation:e};r&&(n.target=r);for(let o of["selector","clear","submit","combo","value","dx","dy","point","from","to","at","delta","milliseconds"])t[o]!==void 0&&(n[o]=structuredClone(t[o]));return typeof t.text=="string"&&(n.text=`[redacted ${t.text.length} characters]`),Array.isArray(t.hostPaths)&&(n.hostPaths=t.hostPaths.map(()=>"[redacted host path]")),typeof t.toPath=="string"&&(n.toPath="[redacted destination path]"),n}function ca(e,t){let r=structuredClone(t);return typeof r.text=="string"&&(r.text=`[redacted ${r.text.length} characters]`),Array.isArray(r.hostPaths)&&(r.hostPaths=r.hostPaths.map(()=>"[redacted host path]")),typeof r.toPath=="string"&&(r.toPath="[redacted destination path]"),Pn(r.trigger)&&typeof r.trigger.url=="string"&&(r.trigger={...r.trigger,url:xn(r.trigger.url)}),typeof r.url=="string"&&(r.url=xn(r.url)),{operation:e,...r}}function da(e,t){let r=nr(e,t),n=r?.url??r?.applicationId??r?.deviceId??r?.tabId??r?.resource??"current target";return`${e} on ${n}`}function nr(e,t){let r={};return typeof t.url=="string"&&(r.url=t.url),typeof t.tabId=="string"&&(r.tabId=t.tabId),typeof t.deviceId=="string"&&(r.deviceId=t.deviceId),typeof t.applicationId=="string"&&(r.applicationId=t.applicationId),typeof t.displayId=="string"&&(r.displayId=t.displayId),(e==="browser.navigate"||e==="browser.tabs.list"||e==="browser.tabs.open")&&(r.resource="browser-tabs"),Object.keys(r).length>0?r:void 0}function la(e){return{operationId:e.operationId,status:e.status,effect:e.effect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:e.adapter,target:e.target,...e.data!==void 0?{data:e.data}:{},artifacts:e.artifacts.map(t=>({artifactId:t.artifactId,revision:t.revision,kind:t.kind,title:t.title,state:t.state,mediaType:t.mediaType,sensitivity:t.sensitivity,hash:t.content.hash,sizeBytes:t.content.sizeBytes})),lease:e.lease,...e.error?{error:e.error}:{}}}function ua(e){let t=[];for(let r of e.artifacts){if(t.length>=Qi||!r.mediaType.startsWith("image/"))continue;let n=r.content.storage;if(n.type!=="inline"||typeof n.base64!="string")continue;let o=Math.floor(n.base64.length*.75);o<=0||o>Zi||t.push({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${n.base64}`,detail:"high"}})}return t}function pa(e){let t=new Set(se),r=new Set;for(let n of e){if(!t.has(n))throw new TypeError(`Unsupported XENO automation operation: ${String(n)}`);r.add(n)}return Array.from(r)}function fa(e){return(0,st.createHash)("sha256").update(tr(e)).digest("hex")}function tr(e){return Array.isArray(e)?`[${e.map(tr).join(",")}]`:Pn(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${tr(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function xn(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid URL]"}}function ma(e){return e instanceof Error?e.message:String(e)}function ga(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:"AUTOMATION_EXECUTION_FAILED"}function Pn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var On=require("node:crypto"),ha=Symbol.for("@xenosystem/agent-sdk/tool-authorization/v1"),Aa=globalThis,ya=Aa[ha]??=new WeakMap;function _n(e,t,r){let n=ya.get(e);if(!n?.active||n.toolName!==t||e.toolName!==t||e.permission?.allowed!==!0||e.policy?.allowed!==!0||n.fingerprint!==Rn(r)||n.receiptFingerprint!==Rn(e))throw Object.assign(new Error("Governed execution requires the current exact orchestrator authorization"),{code:"AUTOMATION_AUTHORIZATION_RECEIPT_REQUIRED",retryable:!1})}function Rn(e){return(0,On.createHash)("sha256").update(JSON.stringify(or(structuredClone(e),0))).digest("hex")}function or(e,t){if(t>128)throw Error("Tool authorization input depth exceeded");if(Array.isArray(e))return e.map(r=>or(r,t+1));if(e!==null&&typeof e=="object")return Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>[r,or(n,t+1)]));if(typeof e=="number"&&!Number.isFinite(e))throw Error("Tool authorization input must be finite");if(!["string","number","boolean"].includes(typeof e)&&e!==null)throw Error("Tool authorization input is not JSON data");return e}var wa=se.filter(e=>e.startsWith("browser.")),Ia=se.filter(e=>e.startsWith("computer.")),ir=6e4,lt=class{constructor(t){this.options=t;this.environment=t.environment??cr()}options;leases=new it({maximumDurationMs:ir,maximumUses:1});activeExecutors=new Map;environment;browserAdapter;computerAdapter;verifiedOperations=[];registered=new Map;register(t){if(this.options.safeMode)return 0;let r=this.verifiedOperations;if(r.length===0)return 0;let n=rr({runtime:this,operations:r});for(let o of n)if(t.has(o.definition.name)&&!this.registered.get(t)?.some(i=>i.definition.name===o.definition.name&&t.get(i.definition.name)===i))throw new Error("Automation capability registration conflicts with another tool owner.");return t.registerAll(n),this.registered.set(t,n),r.length}async registerVerified(t){for(let[n,o]of this.registered)for(let i of o)n.get(i.definition.name)===i&&n.unregister(i.definition.name);if(this.registered.clear(),this.verifiedOperations=[],this.options.safeMode)return 0;let r=[];for(let n of["browser","computer"])if(!(n==="computer"&&!this.options.computerHostAuthority)&&!(n==="browser"?!sr(this.environment.browser):!ut(this.environment.computer,!!this.options.computerAdapter)))try{let o=await this.adapterFor(n),i=await o.manifest();if(V(i),n==="computer"&&dt("observe",this.environment).sensitiveRegionRedaction&&i.supports.sensitiveRegionRedaction!==!0)continue;let a=n==="browser"?wa:Ia;r.push(...i.operations.filter(c=>a.includes(c)))}catch{}return this.verifiedOperations=[...new Set(r)],this.register(t)}async execute(t){if(this.options.safeMode)throw new Error("Governed automation is disabled in safe mode");if(ar(t),t.operation==="browser.screenshot"&&!t.declaredTarget?.tabId?.trim())throw new Error("Screen capture requires an explicit authorized tabId.");let r=X(t.operation),n=r.surface==="computer"?this.options.computerHostAuthority:void 0;if(r.surface==="computer"&&!n)throw new Error("Computer automation requires independent host operation authority.");let o=await this.adapterFor(r.surface),i=await o.manifest();if(V(i),r.surface==="computer"&&dt(r.effect,this.environment).sensitiveRegionRedaction&&i.supports.sensitiveRegionRedaction!==!0)throw new Error("Owning computer adapter cannot satisfy this host's required sensitive-region redaction.");if(!i.operations.includes(t.operation))throw new Error("Owning adapter no longer supports this operation; refresh capability discovery.");let a=this.options.profile(),c={runId:this.options.runId,agentId:this.options.agentId??"agent-main",...this.options.sessionId?{sessionId:this.options.sessionId}:{},turnId:t.authorization.turnId,...this.options.workspaceId?{workspaceId:this.options.workspaceId}:{}},s=Na(t.operation,t.declaredTarget,this.environment),l=r.surface==="browser"?r.effect==="act"?"browser-act":"browser-read":r.effect==="act"?"computer-act":"computer-observe",y=r.effect==="act"?"external":"read",A=`lease-${(0,Xn.randomUUID)()}`,p=(E,S,w)=>{if(t.signal?.throwIfAborted(),E!==A||S!==2||this.options.profile().fingerprint!==a.fingerprint)throw new Error("Automation lease authority changed during preflight; obtain fresh authorization.");let $=this.leases.request({leaseId:A,subject:{runId:c.runId,agentId:c.agentId,turnId:c.turnId,toolName:t.governingToolName,operationId:t.operationId},scope:{kind:l,effect:y,operations:[t.operation],...w.resource?{resources:[w.resource]}:{},...w.destination?{destinations:[w.destination]}:{},governingToolName:t.governingToolName},reason:`${t.operation} authorized by the CLI policy and permission layers`,requestedBy:{kind:"agent",id:c.agentId,profileFingerprint:a.fingerprint},durationMs:ir,requestTtlMs:3e4,maxUses:1,childInheritance:"none",policyFingerprints:[a.fingerprint]},a),ae=this.leases.approve({leaseId:$.leaseId,expectedVersion:$.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:t.authorization.turnId,messageId:t.authorization.toolCallId}});return this.leases.consume(ae.leaseId,ae.version,w)},v=Lr({contractId:`contract-${t.operationId}`,identity:c,policy:this.securityPolicy(),profile:a,...this.options.securityStatus?{adapterStatus:this.options.securityStatus}:{},filesystem:{readRoots:[(0,ee.resolve)(this.options.cwd())],writeRoots:[(0,ee.resolve)(this.options.cwd())],executeRoots:[(0,ee.resolve)(this.options.cwd())]},network:_a(s,this.environment),browser:r.surface==="browser"?Oa(r.effect,s,this.environment):{mode:"none"},computer:r.surface==="computer"?dt(r.effect,this.environment):{mode:"none"},capabilityLeaseIds:[A],expiresAt:new Date(Date.now()+ir).toISOString()}),m={protocolVersion:1,operationId:t.operationId,idempotencyKey:t.idempotencyKey,requestedAt:new Date().toISOString(),identity:c,governingToolName:t.governingToolName,operation:t.operation,parameters:ka(t.parameters),...s?{declaredTarget:s}:{},executionContract:v,capabilityLeaseId:A,expectedLeaseVersion:2},P=new AbortController,C=P.signal,R=()=>P.abort(t.signal?.reason);t.signal?.aborted?R():t.signal?.addEventListener("abort",R,{once:!0});let k=new $e({adapter:o,assertCurrent:async E=>{if(C.throwIfAborted(),ar(t),this.options.profile().fingerprint!==a.fingerprint)throw new Error("Automation authority changed during execution; evidence release refused.");await n?.assertCurrent(structuredClone(E))},...n?{onPreflight:(E,S,w)=>n.recordPreflight(E,S,w),onGrant:(E,S,w,$)=>n.recordGrant(E,S,w,$)}:{},leaseAuthority:{consume:async(E,S,w)=>{let $=p(E,S,w);return await this.audit({eventType:"automation_lease_approved",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:A,contractFingerprint:v.fingerprint,permissionReason:t.authorization.permission.reason}),$}},artifactRepository:new nt({directory:(0,ee.resolve)(this.options.cwd(),".xeno","artifacts")})});if(this.activeExecutors.has(t.operationId)||this.activeExecutors.size>=64)throw t.signal?.removeEventListener("abort",R),Object.assign(new Error("Host automation operation identity is already active or capacity is reached."),{code:"AUTOMATION_OPERATION_CONFLICT",retryable:!1});this.activeExecutors.set(t.operationId,{executor:k,controller:P});try{t.reportProgress?.({activity:"state",message:`Executing governed ${t.operation}`}),await n?.begin(structuredClone(m),{authorization:t.authorization,profileFingerprint:a.fingerprint,assertCurrent:()=>{if(C.throwIfAborted(),ar(t),this.options.profile().fingerprint!==a.fingerprint)throw new Error("Computer host profile authority changed.")}},C);let E=await k.execute(m,C);return await this.audit({eventType:E.status==="ok"?"automation_completed":"automation_failed",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:A,contractFingerprint:v.fingerprint,status:E.status,artifactIds:E.artifacts.map(S=>S.artifactId)}),E}catch(E){throw await this.audit({eventType:"automation_failed",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:A,contractFingerprint:v.fingerprint,status:E instanceof Error?E.name:"error"}),E}finally{t.signal?.removeEventListener("abort",R);try{await n?.finish(structuredClone(m))}finally{this.activeExecutors.delete(t.operationId)}}}async stop(t,r="human-stop"){let n=this.activeExecutors.get(t);return n?(n.controller.abort(new Error(r)),await n.executor.stop(t,r),!0):!1}securityPolicy(){let t=this.options.securityPolicy?.();if(t)return t;let r=(0,ee.resolve)(this.options.cwd());return{allowedDirectories:[r],workingDirectory:r,capabilities:{terminal:!0,fileRead:!0,fileWrite:!0,appLaunch:!0},executionLevel:"policy-only",trustMode:"trusted-workspace",allowNetwork:!1}}adapterFor(t){if(t==="browser"){let n=this.environment.browser;if(!sr(n))throw new Error(Mn(n));return this.browserAdapter??=new Te({baseUrl:n.baseUrl,token:n.token,driver:n.driver,...n.ownedView?{ownedView:n.ownedView}:{}}),this.browserAdapter}let r=this.environment.computer;if(!ut(r,!!this.options.computerAdapter))throw new Error(dr(r,!!this.options.computerAdapter));return this.computerAdapter??=this.options.computerAdapter?Promise.resolve(this.options.computerAdapter):Ln(r,this.options.computerOwnerAdmission),this.computerAdapter}async audit(t){try{await this.options.onAudit?.(t)}catch{}}};function ba(e){return new lt(e)}function Ea(e){if(e)return async t=>{let r=X(t.operation).effect;await e.append({trace_id:t.traceId,event_type:t.eventType,actor:"system",risk_level:r==="act"?"high":"low",...t.eventType==="automation_lease_approved"?{decision:"allow"}:{},status:t.eventType==="automation_failed"?"error":"ok",...t.eventType==="automation_failed"&&t.status?{reason:t.status}:{},metadata:{operation:t.operation,operation_id:t.operationId,lease_id:t.leaseId,contract_fingerprint:t.contractFingerprint,result_status:t.status,artifact_ids:t.artifactIds,permission_reason:t.permissionReason}})}}async function va(e=cr()){let t=await Promise.all([Nn("browser",e),Nn("computer",e)]);return{schemaVersion:1,protocolVersion:1,enabled:t.some(r=>r.configured),surfaces:t,docs:"docs/GOVERNED_AUTOMATION.md"}}function cr(e=process.env){let t=e.XENO_BROWSER_DRIVER==="extension"?"extension":"browser",r=Ta(e,t),n=W(e.XENO_BROWSER_AUTOMATION_URL)??r?.baseUrl,o=W(e.XENO_BROWSER_AUTOMATION_TOKEN)??r?.token,i=W(e.XENO_USE_BASE_URL),a=W(e.XENO_USE_TOKEN)??Sa(e.XENO_USE_TOKEN_FILE),c=W(e.XENO_USE_DEVICE_ID);return{browser:{driver:t,...n?{baseUrl:n}:{},...o?{token:o}:{},readDomains:ct(e.XENO_BROWSER_READ_DOMAINS),actDomains:ct(e.XENO_BROWSER_ACT_DOMAINS),deniedDomains:ct(e.XENO_BROWSER_DENIED_DOMAINS),ports:Xa(e.XENO_BROWSER_ALLOWED_PORTS,[443]),allowLoopbackDevelopment:e.XENO_BROWSER_ALLOW_LOOPBACK_DEVELOPMENT==="1",uploads:kn(e.XENO_BROWSER_UPLOADS,"prompt"),downloads:kn(e.XENO_BROWSER_DOWNLOADS,"prompt"),recording:e.XENO_BROWSER_RECORDING==="bounded"?"bounded":"disabled"},computer:{...i?{baseUrl:i}:{},...a?{token:a}:{},...c?{deviceId:c}:{},allowedApplications:ct(e.XENO_USE_ALLOWED_APPLICATIONS)}}}function Sa(e){let t=W(e);if(!(!t||!(0,xe.existsSync)(t)))try{return W((0,xe.readFileSync)(t,"utf8"))}catch{return}}function Ta(e,t){let n=W(e.XENO_BROWSER_SESSION_FILE)??(t==="extension"?W(e.XENO_EXTENSION_SESSION_FILE)??(0,ee.join)((0,Dn.homedir)(),".xeno","use-drivers","xeno-extension.json"):W(e.XENO_SESSION_FILE)??(e.APPDATA?(0,ee.join)(e.APPDATA,"xeno-browser","session.json"):void 0));if(!(!n||!(0,xe.existsSync)(n)))try{let o=JSON.parse((0,xe.readFileSync)(n,"utf8")),i=Number(o.port),a=typeof o.token=="string"?o.token:"",c=typeof o.driver=="string"?o.driver:void 0;return!Number.isSafeInteger(i)||i<=0||i>65535||!Ca(a)||c&&c!==(t==="extension"?"xeno-extension-native":"xeno-browser-loopback")?void 0:{baseUrl:`http://127.0.0.1:${i}`,token:a}}catch{return}}function Ca(e){return e.length>=32&&e.length<=512&&!/\s/.test(e)}async function Nn(e,t){let r=e==="browser"?t.browser:t.computer,n=e==="browser"?sr(t.browser):ut(t.computer),o=!!r&&Object.values(r).some(i=>typeof i=="string"&&i.length>0);if(!n)return{surface:e,configured:!1,available:!1,certified:!1,operations:[],limitations:["Adapter credentials are not completely configured."],...o?{error:e==="browser"?Mn(t.browser):dr(t.computer)}:{}};try{let a=await(e==="browser"?new Te({baseUrl:t.browser.baseUrl,token:t.browser.token,driver:t.browser.driver,...t.browser.ownedView?{ownedView:t.browser.ownedView}:{}}):await Ln(t.computer)).manifest();if(V(a),e==="computer"&&dt("observe",t).sensitiveRegionRedaction&&a.supports.sensitiveRegionRedaction!==!0)throw new Error("Owning computer adapter cannot satisfy this host's required sensitive-region redaction.");return Ra(e,a)}catch(i){return{surface:e,configured:!0,available:!1,certified:!1,operations:[],limitations:["Configured adapter is unavailable."],error:lr(i)}}}async function Ln(e,t){if(e={...e},!ut(e))throw new Error(dr(e));let r=await Pa(),n=new r.Use({baseUrl:e.baseUrl,...e.authorize?{authorize:xa(e.authorize)}:{token:e.token}});return new r.XenoUseComputerAutomationAdapter({use:n,...e.deviceId?{defaultDeviceId:e.deviceId}:{},...t?{executingPrincipalId:t.executingPrincipalId,authorizeOwner:t.authorize}:{}})}function xa(e){return async(t,r)=>{try{let n=await e(t,r);if(n?.tokenType==="DPoP")return n}catch{}throw Object.assign(new Error("Canonical computer request authorization is unavailable."),{code:"AUTOMATION_AUTHORIZATION_UNAVAILABLE",retryable:!1})}}async function Pa(){try{let e="@xeno-use/sdk",t="@xeno-use/agent-sdk-pack",[r,n]=await Promise.all([import(e),import(t)]);if(typeof r.Use!="function"||typeof n.XenoUseComputerAutomationAdapter!="function")throw new Error("installed xeno-use packages do not expose the governed adapter contract");return{Use:r.Use,XenoUseComputerAutomationAdapter:n.XenoUseComputerAutomationAdapter}}catch(e){throw new Error(`Computer automation requires @xeno-use/sdk and @xeno-use/agent-sdk-pack: ${lr(e)}`)}}function Ra(e,t){return{surface:e,configured:!0,available:!0,certified:t.certified,adapterId:t.adapterId,adapterVersion:t.adapterVersion,operations:[...t.operations],limitations:[...t.limitations]}}function Oa(e,t,r){let n=r.browser,o=Bn(t),i=o&&!Fn(o.hostname)?o.hostname:void 0,a=pt([...n.readDomains,...i?[i]:[]]),c=pt([...n.actDomains,...e==="act"&&i?[i]:[]]),s=Vn([...n.ports,...o?[$n(o)]:[]]);return{mode:e==="act"?"act":"read",profile:"ephemeral",readAllowedDomains:a,actAllowedDomains:c,deniedDomains:n.deniedDomains,allowedSchemes:n.allowLoopbackDevelopment?["https","http"]:["https"],allowedPorts:s,redirectPolicy:"policy",allowLoopbackDevelopment:n.allowLoopbackDevelopment,uploads:n.uploads,downloads:n.downloads,recording:n.recording}}function dt(e,t){return{mode:e==="act"?"act":"observe",allowedApplications:t.computer?.allowedApplications??[],sensitiveRegionRedaction:!0,humanStopRequired:!0}}function _a(e,t){let r=[],n=Bn(e);n&&r.push({scheme:n.protocol.replace(/:$/,""),host:n.hostname.toLowerCase(),port:$n(n)});for(let o of pt([...t.browser?.readDomains??[],...t.browser?.actDomains??[]]))if(!(o.startsWith(".")||o.includes("*")))for(let i of t.browser?.ports??[443])r.push({scheme:i===80?"http":"https",host:o,port:i});return{default:"deny",allowDestinations:Da(r)}}function Na(e,t,r){if(!e.startsWith("computer."))return t;let n=t?.deviceId??r.computer?.deviceId,o=t?.applicationId;if(!(!n&&!o&&!t))return{...t??{},...n?{deviceId:n}:{}}}function ar(e){let t=e.authorization;if(!t||t.toolName!==e.governingToolName||!t.permission.allowed||!t.policy.allowed)throw new Error("Automation authorization receipt does not match the governing tool");_n(t,e.governingToolName,e.parameters)}function ka(e){try{return JSON.parse(JSON.stringify(e))}catch(t){throw new Error(`Automation parameters are not JSON serializable: ${lr(t)}`)}}function sr(e){return!!e?.baseUrl&&!!e.token}function ut(e,t=!1){return Un(e,t)===void 0}function Mn(e){return`Browser automation configuration is incomplete; missing ${[e?.baseUrl?"":"XENO_BROWSER_AUTOMATION_URL",e?.token?"":"XENO_BROWSER_AUTOMATION_TOKEN"].filter(Boolean).join(", ")}`}function dr(e,t=!1){return Un(e,t)??"Computer automation configuration is unavailable."}function Un(e,t){let r=e?.token!==void 0,n=e?.authorize!==void 0;if(r&&n)return"Computer automation requires exactly one bootstrap token or canonical request authorizer.";if(n&&typeof e?.authorize!="function")return"Computer automation requires a callable canonical request authorizer.";if(r&&(typeof e?.token!="string"||!e.token.trim()))return"Computer automation bootstrap token is invalid.";if(e?.baseUrl!==void 0)try{let i=new URL(e.baseUrl);if(i.username||i.password||i.search||i.hash||i.pathname!=="/"||i.protocol!=="https:"&&!(i.protocol==="http:"&&Fn(i.hostname)&&!n))return"Computer automation requires an HTTPS origin; explicit bootstrap compatibility may use loopback HTTP only."}catch{return"Computer automation endpoint must be a valid origin."}let o=[!t&&!e?.baseUrl?"XENO_USE_BASE_URL":"",!t&&!r&&!n?"XENO_USE_TOKEN or canonical request authorizer":"",e?.deviceId?.trim()?"":"XENO_USE_DEVICE_ID"].filter(Boolean);return o.length?`Computer automation configuration is incomplete; missing ${o.join(", ")}`:void 0}function Bn(e){let t=e?.url??e?.origin;if(t)try{return new URL(t)}catch{return}}function $n(e){return e.port?Number(e.port):e.protocol==="http:"?80:443}function Fn(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"}function ct(e){return pt((e??"").split(",").map(t=>t.trim().toLowerCase()).filter(Boolean))}function Xa(e,t){let r=(e??"").split(",").map(n=>Number(n.trim())).filter(n=>Number.isSafeInteger(n)&&n>0&&n<=65535);return r.length>0?Vn(r):t}function kn(e,t){return e==="deny"||e==="prompt"||e==="allow"?e:t}function W(e){let t=e?.trim();return t||void 0}function pt(e){return[...new Set(e)]}function Vn(e){return[...new Set(e)].sort((t,r)=>t-r)}function Da(e){let t=new Set;return e.filter(r=>{let n=`${r.scheme??""}:${r.host}:${r.port??""}`;return t.has(n)?!1:(t.add(n),!0)})}function lr(e){return e instanceof Error?e.message:String(e)}function La(e){let t=["XENO governed automation",""];for(let r of e.surfaces){let n=r.configured?r.available?"available":"unavailable":"not configured",o=r.certified?"certified":"not release-certified";t.push(`${r.surface}: ${n}; ${o}`),r.adapterId&&t.push(` adapter: ${r.adapterId}@${r.adapterVersion??"unknown"}`),r.operations.length>0&&t.push(` operations: ${r.operations.length}`);for(let i of r.limitations)t.push(` limitation: ${i}`);r.error&&t.push(` error: ${r.error}`)}return t.push("",`Docs: ${e.docs}`),t.join(`
|
|
949
949
|
`)}0&&(module.exports={CliGovernedAutomationRuntime,SqliteAutomationExecutionJournal,XENO_AUTOMATION_OPERATIONS,XENO_AUTOMATION_PROTOCOL_VERSION,XENO_BROWSER_CONTROL_PLANE_OPERATIONS,XenoAutomationError,XenoBrowserControlPlaneAdapter,XenoGovernedAutomationExecutor,XenoHostGovernedAutomationRuntime,XenoLoopbackAutomationAdapter,assertRequiredXenoAutomationEvidence,assertValidXenoAutomationAdapterManifest,assertValidXenoAutomationRequest,assertXenoAutomationAdapterConformant,assertXenoAutomationAdapterRequirements,assertXenoAutomationAuthority,buildXenoAutomationCapabilityUse,createCliAutomationAuditSink,createCliGovernedAutomationRuntime,createXenoAutomationConformanceReport,createXenoGovernedAutomationTools,createXenoHostAutomationAuditSink,createXenoHostGovernedAutomationRuntime,describeXenoAutomationOperation,inspectCliAutomationStatus,inspectXenoHostAutomationStatus,isXenoAutomationOperation,materializeXenoAutomationEvidence,openSqliteAutomationExecutionJournal,pending,persistXenoAutomationEvidence,readCliAutomationEnvironment,readXenoHostAutomationEnvironment,renderCliAutomationStatus,renderXenoHostAutomationStatus,resolveXenoAutomationEvidencePolicy,runDurableAutomation});
|