@xenosystem/agent-sdk 0.10.43 → 0.10.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/agents/index.cjs +11 -8
  2. package/dist/agents/index.js +11 -8
  3. package/dist/agents/metafile-cjs.json +1 -1
  4. package/dist/agents/metafile-esm.json +1 -1
  5. package/dist/artifacts/index.cjs +1 -1
  6. package/dist/artifacts/index.js +1 -1
  7. package/dist/automation/index.cjs +1 -1
  8. package/dist/automation/index.d.cts +4 -0
  9. package/dist/automation/index.d.ts +4 -0
  10. package/dist/automation/index.js +1 -1
  11. package/dist/automation/metafile-cjs.json +1 -1
  12. package/dist/automation/metafile-esm.json +1 -1
  13. package/dist/control-plane/index.cjs +1 -1
  14. package/dist/control-plane/index.js +1 -1
  15. package/dist/electron/index.cjs +214 -206
  16. package/dist/electron/index.d.cts +5 -0
  17. package/dist/electron/index.d.ts +5 -0
  18. package/dist/electron/index.js +214 -206
  19. package/dist/electron/metafile-cjs.json +1 -1
  20. package/dist/electron/metafile-esm.json +1 -1
  21. package/dist/governance/index.cjs +1 -1
  22. package/dist/governance/index.js +1 -1
  23. package/dist/governance/metafile-cjs.json +1 -1
  24. package/dist/governance/metafile-esm.json +1 -1
  25. package/dist/index.cjs +386 -373
  26. package/dist/index.d.cts +64 -1
  27. package/dist/index.d.ts +64 -1
  28. package/dist/index.js +387 -374
  29. package/dist/mcp/index.d.cts +4 -0
  30. package/dist/mcp/index.d.ts +4 -0
  31. package/dist/metafile-cjs.json +1 -1
  32. package/dist/metafile-esm.json +1 -1
  33. package/dist/session/index.cjs +1 -1
  34. package/dist/session/index.js +1 -1
  35. package/dist/skills/index.cjs +8 -5
  36. package/dist/skills/index.js +8 -5
  37. package/dist/skills/metafile-cjs.json +1 -1
  38. package/dist/skills/metafile-esm.json +1 -1
  39. package/dist/utils/index.cjs +19 -16
  40. package/dist/utils/index.js +19 -16
  41. package/dist/utils/metafile-cjs.json +1 -1
  42. package/dist/utils/metafile-esm.json +1 -1
  43. package/package.json +1 -1
@@ -934,7 +934,7 @@ public static class Program
934
934
  }
935
935
  }
936
936
  `;function Wt(){let e=process.env.SystemRoot??process.env.WINDIR;if(e){let t=zt(e,"Microsoft.NET","Framework64","v4.0.30319","csc.exe");if(Gt(t))return t;let r=zt(e,"Microsoft.NET","Framework","v4.0.30319","csc.exe");if(Gt(r))return r}return null}import{spawnSync as qt}from"node:child_process";import{accessSync as $n,constants as Fn,existsSync as Vn,realpathSync as jn,statSync as Hn}from"node:fs";import{delimiter as Gn,isAbsolute as zn,join as Wn,resolve as qn}from"node:path";var Yt="XENO_BWRAP_PROFILE_OK",Jt=5e3,Qe;function Kt(e){try{return!Vn(e)||!Hn(e).isFile()?null:($n(e,Fn.X_OK),jn(e))}catch{return null}}function Jn(){let e=process.env.XENO_BWRAP_PATH?.trim();if(e)return Kt(zn(e)?e:qn(e));let t=["/usr/bin/bwrap","/bin/bwrap",...(process.env.PATH??"").split(Gn).filter(Boolean).map(r=>Wn(r,"bwrap"))];for(let r of new Set(t)){let n=Kt(r);if(n)return n}return null}function Kn(){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 ${Yt}`]}function Zt(){let e=[process.platform,process.env.XENO_BWRAP_PATH??"",process.env.PATH??""].join("\0");if(Qe?.key===e)return{...Qe.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=Jn();if(!r)t={available:!1,reason:"bubblewrap is not installed or is not executable."};else{let n=qt(r,["--version"],{encoding:"utf8",timeout:Jt}),o=qt(r,Kn(),{encoding:"utf8",timeout:Jt,env:process.env}),i=n.status===0?n.stdout.trim():void 0;if(o.status===0&&o.stdout===Yt)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 Qe={key:e,capability:t},{...t}}import{createHash as Yn,createPublicKey as Zn,verify as Qn}from"node:crypto";import{readFileSync as eo,statSync as to}from"node:fs";import{isAbsolute as ro}from"node:path";var et="xeno.containment-certification.v1",Qt=512*1024,no=744*60*60*1e3,er=Object.freeze(["allowedFilesystemRead","allowedFilesystemWrite","outsideFilesystemReadDenied","outsideFilesystemWriteDenied","unlistedFilesystemReadDenied","unlistedFilesystemWriteDenied","symlinkEscapeDenied","networkDefaultDeny","environmentSecretsExcluded","childProcessPolicyInherited","standardCommandLaunch","processTreeCleanup","timeoutEnforced","hostPolicyRecoveryClean","uiRestrictionsEnforced"]),I=class extends Error{constructor(t){super(`CONTAINMENT_CERTIFICATION_INVALID: ${t}`),this.name="ContainmentCertificationError"}};function oo(e){let t={...e};return delete t.signature,Buffer.from(JSON.stringify(rt(t)),"utf8")}function tr(e,t,r=new Date){if(!ro(e.manifestPath))throw new I("manifestPath must be absolute");me(e.candidateSha256,"candidateSha256");let n=to(e.manifestPath);if(!n.isFile())throw new I("manifestPath must reference a regular file");if(n.size<=0||n.size>Qt)throw new I(`manifest size must be between 1 and ${Qt} bytes`);let o=eo(e.manifestPath),i;try{i=JSON.parse(o.toString("utf8"))}catch{throw new I("manifest is not valid JSON")}let a=io(i);if(e.expectedCertificationId&&a.certificationId!==e.expectedCertificationId)throw new I("certificationId does not match the host binding");if(a.candidate.sha256.toLowerCase()!==e.candidateSha256.toLowerCase())throw new I("candidate digest does not match the running candidate binding");if(a.platform.os!==t.platform||a.platform.arch!==t.arch)throw new I("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 I("certified adapter identity does not match the installed native adapter");let c=tt(a.issuedAt,"issuedAt"),s=tt(a.expiresAt,"expiresAt");if(s<=c)throw new I("expiresAt must be later than issuedAt");if(s-c>no)throw new I("certification lifetime exceeds 31 days");if(r.getTime()<c-5*6e4)throw new I("certification is not active yet");if(r.getTime()>=s)throw new I("certification has expired");for(let p of er)if(a.conformance.checks[p]!==!0)throw new I(`required conformance check did not pass: ${p}`);if(!a.approvals.some(p=>p.role==="security-reviewer"&&p.subject!==a.issuedBy))throw new I("an independent security-reviewer approval is required");let l=e.trustedPublicKeys[a.signature.keyId];if(!l)throw new I("signature key is not trusted by this host");let y;try{y=Buffer.from(a.signature.value,"base64")}catch{throw new I("signature is not valid base64")}if(y.length!==64)throw new I("Ed25519 signature must be 64 bytes");let A=!1;try{A=Qn(null,oo(a),Zn(l),y)}catch{throw new I("signature key or value is invalid")}if(!A)throw new I("signature verification failed");return{manifest:a,manifestSha256:Yn("sha256").update(o).digest("hex")}}function io(e){let t=z(e,"manifest");if(t.schemaVersion!==et)throw new I(`schemaVersion must be ${et}`);let r=S(t.certificationId,"certificationId"),n=z(t.candidate,"candidate"),o=z(t.adapter,"adapter"),i=z(t.platform,"platform"),a=z(t.conformance,"conformance"),c=z(a.checks,"conformance.checks"),s=z(t.signature,"signature"),l=t.approvals;if(!Array.isArray(l)||l.length===0)throw new I("approvals must contain at least one approval");let y=l.map((b,v)=>{let w=z(b,`approvals[${v}]`),L=S(w.role,`approvals[${v}].role`);if(L!=="security-reviewer"&&L!=="release-reviewer")throw new I(`approvals[${v}].role is invalid`);let Y=L;tt(S(w.approvedAt,`approvals[${v}].approvedAt`),`approvals[${v}].approvedAt`);let fe=S(w.approvalSha256,`approvals[${v}].approvalSha256`);return me(fe,`approvals[${v}].approvalSha256`),{subject:S(w.subject,`approvals[${v}].subject`),role:Y,approvedAt:w.approvedAt,approvalArtifactId:S(w.approvalArtifactId,`approvals[${v}].approvalArtifactId`),approvalSha256:fe}}),A=S(o.backend,"adapter.backend");if(A!=="processcontainer"&&A!=="bubblewrap"&&A!=="seatbelt")throw new I("adapter.backend is invalid");let p=S(i.os,"platform.os"),E=S(i.arch,"platform.arch");if(S(s.algorithm,"signature.algorithm")!=="ed25519")throw new I("signature.algorithm must be ed25519");let x={};for(let b of er){if(c[b]!==!0)throw new I(`conformance.checks.${b} must be true`);x[b]=!0}let T=S(o.nativeBinarySha256,"adapter.nativeBinarySha256"),P=S(n.sha256,"candidate.sha256"),_=S(a.reportSha256,"conformance.reportSha256");if(me(T,"adapter.nativeBinarySha256"),me(P,"candidate.sha256"),me(_,"conformance.reportSha256"),a.passed!==!0)throw new I("conformance.passed must be true");return{schemaVersion:et,certificationId:r,candidate:{product:S(n.product,"candidate.product"),version:S(n.version,"candidate.version"),sha256:P},adapter:{name:o.name==="microsoft-mxc"?"microsoft-mxc":ao(),version:S(o.version,"adapter.version"),backend:A,isolationTier:S(o.isolationTier,"adapter.isolationTier"),nativeBinarySha256:T},platform:{os:p,arch:E},conformance:{reportArtifactId:S(a.reportArtifactId,"conformance.reportArtifactId"),reportSha256:_,passed:!0,checks:x},issuedAt:S(t.issuedAt,"issuedAt"),expiresAt:S(t.expiresAt,"expiresAt"),issuedBy:S(t.issuedBy,"issuedBy"),approvals:y,signature:{algorithm:"ed25519",keyId:S(s.keyId,"signature.keyId"),value:S(s.value,"signature.value")}}}function ao(){throw new I("adapter.name must be microsoft-mxc")}function z(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new I(`${t} must be an object`);return e}function S(e,t){if(typeof e!="string"||e.trim().length===0)throw new I(`${t} must be a non-empty string`);return e}function me(e,t){if(!/^[a-f0-9]{64}$/i.test(e))throw new I(`${t} must be a SHA-256 hex digest`)}function tt(e,t){let r=Date.parse(e);if(!Number.isFinite(r))throw new I(`${t} must be an ISO timestamp`);return r}function rt(e){return Array.isArray(e)?e.map(rt):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,rt(r)])):e}import{createHash as Pe,randomUUID as so}from"node:crypto";import{accessSync as co,chmodSync as rr,constants as lo,existsSync as Re,lstatSync as it,mkdirSync as uo,readFileSync as he,realpathSync as po,renameSync as fo,statSync as mo,unlinkSync as go,writeFileSync as ho}from"node:fs";import{tmpdir as Ao}from"node:os";import{dirname as sr,isAbsolute as nr,join as Q,parse as $s}from"node:path";import{spawnSync as or}from"node:child_process";import{fileURLToPath as yo}from"node:url";var ir="microsoft-mxc",ge="0.7.0";var wo="@microsoft/mxc-sdk",Io="sha512-EWhz2pKkcPluZHAOI1yneV+JK0NO/3hdh7nABBb0x4PjyUWMeSWPTBAjtIu+BhtMYOqlaijSPZMZ0Hs/J4ZL4A==",Gs=10*6e4,bo=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"}),zs=Object.freeze({"win32-x64-wxc-host-prep.exe":"531fb3cdb4b0c964908fd71b71d40961417afb399cbab72f92a25e95309a6416","win32-arm64-wxc-host-prep.exe":"3ef702332286a39153fc259310b5021e3de3c191751d7522684f6475f73af5ef"});function Eo(e){return e.some(t=>t.includes("wxc-host-prep prepare-system-drive")||t.includes("wxc-host-prep prepare-null-device"))}function vo(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=bo[`${e}-${t}-${r}`];return n?{platform:e,arch:t,binaryName:r,sha256:n}:void 0}var nt;function cr(e={}){if(nt&&!e.refresh)return ar(nt);let t=So();return nt=t,ar(t)}function So(){let e=process.platform,t=process.arch,r=vo(e,t),n=!!r,o=To();if(!o)return n?N(`reviewed MXC ${ge} native assets are not installed`,!1,!0):N(ot(e,t),!1,!1);let i=sr(o);if(!n)return N(ot(e,t),!0,!1,{packageRoot:i});let a="";try{let p=JSON.parse(he(o,"utf8"));if(a=String(p.version??""),p.sourcePackage?.name!==wo||p.sourcePackage.version!==ge||p.sourcePackage.integrity!==Io)return N("MXC native asset provenance metadata is invalid",!0,!0,{packageRoot:i})}catch{return N("MXC package metadata is unreadable",!0,!0,{packageRoot:i})}if(a!==ge)return N(`MXC version ${a||"unknown"} is installed; XENO requires exactly ${ge}`,!0,!0,{packageRoot:i});if(!r)return N(ot(e,t),!0,!1,{packageRoot:i});let c=Q(i,"bin",t,r.binaryName);if(!Re(c)||!mo(c).isFile())return N(`MXC native binary is missing: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a});let s=c;try{s=Co(c,r)}catch(p){return N(`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{co(s,lo.X_OK)}catch{return N(`MXC native binary is not executable: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a})}let l=Pe("sha256").update(he(s)).digest("hex"),y=r.sha256;if(!y||l!==y)return N(`MXC native binary digest is not trusted for ${e}/${t}`,!0,!0,{packageRoot:i,version:a});if(e==="win32"){let p=or(s,["--probe"],{encoding:"utf8",timeout:5e3,windowsHide:!0});if(p.error||p.status!==0)return N(`MXC native probe failed: ${p.error?.message??(p.stderr.trim()||`exit ${p.status}`)}`,!0,!0,{packageRoot:i,version:a});let E;try{E=JSON.parse(p.stdout)}catch{return N("MXC native probe returned invalid JSON",!0,!0,{packageRoot:i,version:a})}let m=typeof E.tier=="string"?E.tier:"unknown",x=Array.isArray(E.warnings)?E.warnings.filter(_=>typeof _=="string"):[],T=E.probes&&typeof E.probes=="object"?E.probes:void 0,P=T?.uiCapabilities&&typeof T.uiCapabilities=="object"?Object.fromEntries(Object.entries(T.uiCapabilities).filter(_=>typeof _[1]=="boolean")):void 0;return{installed:!0,supported:!0,available:!0,name:ir,version:a,packageRoot:i,nativeBinaryPath:s,nativeBinarySha256:l,backend:"processcontainer",isolationTier:m,platform:e,arch:t,warnings:x,needsHostPreparation:Eo(x),reason:`MXC ${a} processcontainer is installed (${m}).`,...P?{uiCapabilities:P}:{}}}if(e==="linux"){let p=or("bwrap",["--version"],{encoding:"utf8",timeout:5e3});if(p.error||p.status!==0)return N("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:ir,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 To(){let e=process.resourcesPath,t=process.env.XENO_MXC_ASSET_ROOT?.trim(),r=typeof __dirname=="string"?__dirname:sr(yo(import.meta.url)),n=[...e&&nr(e)?[Q(e,"mxc","package.json")]:[],...t&&nr(t)?[Q(t,"package.json")]:[],Q(r,"..","native","mxc","package.json"),Q(r,"..","..","native","mxc","package.json")];for(let o of n){if(!Re(o))continue;let i=it(o);if(!(!i.isFile()||i.isSymbolicLink()))return po(o)}}function Co(e,t){if(!!!process.pkg)return e;let n=Q(Ao(),"xeno-mxc",ge,t.sha256);uo(n,{recursive:!0,mode:448});let o=Q(n,t.binaryName);if(Re(o)){let s=it(o);if(!s.isFile()||s.isSymbolicLink())throw new Error("materialized MXC path is not a regular file");if(Pe("sha256").update(he(o)).digest("hex")!==t.sha256)throw new Error("materialized MXC binary digest is invalid");return process.platform!=="win32"&&rr(o,448),o}let i=he(e);if(Pe("sha256").update(i).digest("hex")!==t.sha256)throw new Error("embedded MXC binary digest is invalid");let c=`${o}.${process.pid}.${so()}.tmp`;ho(c,i,{flag:"wx",mode:448});try{fo(c,o)}catch(s){try{go(c)}catch{}if(!Re(o))throw s;let l=it(o);if((l.isFile()&&!l.isSymbolicLink()?Pe("sha256").update(he(o)).digest("hex"):"")!==t.sha256)throw s}return process.platform!=="win32"&&rr(o,448),o}function ot(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 N(e,t=!1,r=!1,n={}){return{...n,installed:t,supported:r,available:!1,warnings:[],needsHostPreparation:!1,reason:e}}function ar(e){return{...e,warnings:[...e.warnings],...e.uiCapabilities?{uiCapabilities:{...e.uiCapabilities}}:{}}}var ee=class extends Error{code;constructor(t,r){super(`${t}: ${r}`),this.name="ExecutionSecurityError",this.code=t}},xo=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),Po=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!0,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!0,environmentSanitization:!0}),Ro=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),Oo=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!0,networkIsolation:!0,inheritedHandleAllowlist:!0,environmentSanitization:!0}),at=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0});function _o(e){let t=e?.executionLevel;if(e?.requireOsContainment&&t&&t!=="contained")throw new ee("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 No(e){return e?.trustMode??"trusted-workspace"}function dr(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:{...xo},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"&&Wt())return{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"windows-restricted-token-job",isolation:"process-hardening",certified:!0,capabilities:{...Po},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=Zt();return o.available?{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"linux-bubblewrap",isolation:"process-hardening",certified:!0,capabilities:{...Ro},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:{...at},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:{...at},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 Oe(t,`Native containment for ${t} cannot be certified from a ${process.platform} host.`);let n=cr();if(!n.available||!n.name||!n.version||!n.backend||!n.isolationTier||!n.nativeBinarySha256||!n.platform||!n.arch)return Oe(t,n.reason,n);if(!r)return Oe(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=tr(r,o);return{available:!0,requestedLevel:e,effectiveLevel:"contained",adapter:"microsoft-mxc",isolation:"filesystem-network",certified:!0,capabilities:{...Oo},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 Oe(t,o instanceof Error?o.message:"Containment certification validation failed.",n)}}function ko(e,t){if(No(e)==="untrusted"&&t!=="contained")throw new ee("UNTRUSTED_EXECUTION_DISABLED","Untrusted execution requires certified contained mode; policy-only and process-hardened modes are trusted-workspace features.")}function Xo(e){let t=e.requestedLevel==="contained"?"CONTAINMENT_UNAVAILABLE":"PROCESS_HARDENING_UNAVAILABLE";return new ee(t,e.reason)}function lr(e,t=process.platform){let r=_o(e);ko(e,r);let n=dr(r,t,e.containmentCertification);if(!n.available)throw Xo(n);if(r==="process-hardened"&&e.allowNetwork!==!0)throw new ee("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=Z(e.workingDirectory??process.cwd()).canonicalPath,i=[...e.allowedDirectories,...e.temporaryDirectories??[]];if(!Ht(o,i))throw new ee("SECURITY_POLICY_INVALID",`Secured process working directory is outside the canonical allowed directories: ${o}`)}return n}function Oe(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:{...at},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 fr=1,C=class extends Error{constructor(r,n){super(n);this.code=r;this.name="XenoSecureExecutionContractError"}code};function mr(e){let t=e.platform??process.platform,r=e.policy.executionLevel??(e.policy.requireOsContainment?"contained":"policy-only"),n=e.adapterStatus??lr(e.policy,t);if(!n.available||n.effectiveLevel==="unavailable")throw new C("SECURITY_CONTRACT_UNAVAILABLE",n.reason);if(n.requestedLevel!==r||n.effectiveLevel!==r)throw new C("SECURITY_CONTRACT_INVALID","Execution adapter status does not match the requested security level");let i=(e.now??(()=>new Date().toISOString()))(),a=Ae([...e.policy.allowedDirectories,...e.policy.temporaryDirectories??[],e.policy.workingDirectory??process.cwd()],e.policy.workingDirectory,t),c=Ae(e.filesystem?.readRoots??a,e.policy.workingDirectory,t),s=e.profile.capabilities.permissionProfile==="read-only",l=s?[]:Ae(e.filesystem?.writeRoots??a,e.policy.workingDirectory,t),y=s?[]:Ae(e.filesystem?.executeRoots??a,e.policy.workingDirectory,t),A=Ae(e.filesystem?.deniedRoots??e.policy.deniedDirectories??[],e.policy.workingDirectory,t),p=n.capabilities.filesystemIsolation?"os":"policy",E=n.capabilities.networkIsolation?"os":r==="process-hardened"?"none":"policy",m=r==="contained"?"deny":e.network?.default??(e.policy.allowNetwork?"allow":"deny"),x=E==="none";if(x&&(!e.policy.allowNetwork||m!=="allow"))throw new C("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 C("SECURITY_CONTRACT_INVALID","Read-only Agent Profiles cannot receive browser action, computer action, or secret projection authority");let T=e.certificationArtifactId??n.certificationArtifactId;if(e.certificationArtifactId&&n.certificationArtifactId&&e.certificationArtifactId!==n.certificationArtifactId)throw new C("SECURITY_CONTRACT_INVALID","Requested certification artifact does not match the adapter certification");if(r==="contained"&&!T)throw new C("SECURITY_CONTRACT_INVALID","Contained execution requires a candidate-bound certification artifact");let P=ce(e.environment?.deniedKeys??[]),_=new Set(P),b=ye(e.browser?.allowedDomains??[]),v=ye(e.browser?.readAllowedDomains??b),w=ye(e.browser?.actAllowedDomains??b),L=ye([...b,...v,...w]),Y={schemaVersion:fr,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:E,default:m,allowDestinations:ur(e.network?.allowDestinations??[]),denyDestinations:ur(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,...Fo(e.process)},environment:{inheritance:e.environment?.inheritance??"allowlist",allowedKeys:ce(e.environment?.allowedKeys??e.policy.containedEnvironmentAllowlist??[]).filter(Rn=>!_.has(Rn)),deniedKeys:P},secrets:$o(e.secrets??[]),externalActions:{default:e.profile.capabilities.externalActions.default,overrides:{...e.profile.capabilities.externalActions.overrides},requireCurrentTurnApproval:ce(e.profile.capabilities.externalActions.requireCurrentTurnApproval),requireCapabilityLease:!0},browser:{mode:e.browser?.mode??"none",profile:e.browser?.profile??"ephemeral",allowedDomains:L,readAllowedDomains:v,actAllowedDomains:w,deniedDomains:ye(e.browser?.deniedDomains??[]),allowedSchemes:Uo(e.browser?.allowedSchemes??["https"]),allowedPorts:Bo(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:ce(e.computer?.allowedApplications??[]),sensitiveRegionRedaction:e.computer?.sensitiveRegionRedaction??!0,humanStopRequired:e.computer?.humanStopRequired??!0},capabilityLeaseIds:ce(e.capabilityLeaseIds??[]),adapter:{id:n.adapter,version:e.adapterVersion??n.adapterVersion??"1",platform:t,architecture:e.architecture??Lo(),certified:n.certified,...T?{certificationArtifactId:T}:{},capabilities:{...n.capabilities},limitations:[...n.limitations]},...e.auditEventIds?{auditEventIds:ce(e.auditEventIds)}:{}},fe={...Y,fingerprint:gr(Y)};return ct(fe),fe}function Mo(e){let t=[];if(!e||typeof e!="object")return["Contract must be an object"];if(e.schemaVersion!==fr&&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"),pr(e.createdAt)||t.push("createdAt must be an ISO 8601 timestamp"),e.expiresAt&&(!pr(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,gr(r)!==e.fingerprint&&t.push("Contract fingerprint does not match content")}return t}function ct(e){let t=Mo(e);if(t.length>0){let r=t.includes("Contract fingerprint does not match content");throw new C(r?"SECURITY_CONTRACT_FINGERPRINT_MISMATCH":"SECURITY_CONTRACT_INVALID",t.join("; "))}}function gr(e){return Do("sha256").update(JSON.stringify(st(e))).digest("hex")}function ce(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort().map(t=>t)}function Ae(e,t,r){return[...new Set(e.map(n=>Z(n,{baseDirectory:t,platform:r}).canonicalPath))].sort((n,o)=>n.localeCompare(o))}function ur(e){let t=new Map;for(let r of e){if(!r.host?.trim())throw new C("SECURITY_CONTRACT_INVALID","Network destinations require a host");if(r.host.includes("*"))throw new C("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 C("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 ye(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 C("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 C("SECURITY_CONTRACT_INVALID",`Browser domain rule is invalid: ${r}`);t.add(n)}return[...t].sort((r,n)=>r.localeCompare(n))}function Uo(e){for(let t of e)if(t!=="http"&&t!=="https")throw new C("SECURITY_CONTRACT_INVALID",`Browser scheme is invalid: ${t}`);return[...new Set(e)].sort()}function Bo(e){for(let t of e)if(!Number.isInteger(t)||t<1||t>65535)throw new C("SECURITY_CONTRACT_INVALID",`Browser port is invalid: ${t}`);return[...new Set(e)].sort((t,r)=>t-r)}function $o(e){let t=new Map;for(let r of e){if(!r.secretId?.trim())throw new C("SECURITY_CONTRACT_INVALID","Secret projections require an ID");if(t.has(r.secretId))throw new C("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 Fo(e){let t={};for(let[r,n]of Object.entries(e??{})){if(!Number.isSafeInteger(n)||Number(n)<1)throw new C("SECURITY_CONTRACT_INVALID",`${r} must be a positive safe integer`);Object.assign(t,{[r]:n})}return t}function st(e){return Array.isArray(e)?e.map(st):!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,st(r)]))}function pr(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}var Vo=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,hr=1048576;function W(e){(!e||typeof e!="object")&&V("Automation request must be an object"),e.protocolVersion!==1&&V("Unsupported automation protocol version"),de(e.operationId,"operationId"),de(e.idempotencyKey,"idempotencyKey"),de(e.capabilityLeaseId,"capabilityLeaseId"),de(e.governingToolName,"governingToolName"),(!Number.isSafeInteger(e.expectedLeaseVersion)||e.expectedLeaseVersion<1)&&V("expectedLeaseVersion must be a positive safe integer"),vr(e.requestedAt)||V("requestedAt must be an ISO 8601 timestamp"),Ze(e.operation)||V(`Unsupported automation operation: ${e.operation}`),(!e.parameters||typeof e.parameters!="object"||Array.isArray(e.parameters))&&V("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>hr&&V(`parameters exceed ${hr} bytes`),de(e.identity?.runId,"identity.runId"),de(e.identity?.agentId,"identity.agentId"),ct(e.executionContract),jo(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 U(e){(!e||typeof e!="object")&&M("Adapter manifest must be an object"),e.protocolVersion!==1&&M("Adapter protocol version is unsupported"),_e(e.adapterId,"adapterId"),_e(e.adapterVersion,"adapterVersion"),_e(e.platform,"platform"),_e(e.architecture,"architecture"),e.targetBinding!=="atomic-preflight"&&M("Adapter must implement atomic preflight target binding"),(!Array.isArray(e.operations)||e.operations.length===0)&&M("Adapter must declare operations");let t=new Set;for(let r of e.operations)Ze(r)||M(`Adapter declares unknown operation ${r}`),t.has(r)&&M(`Adapter declares duplicate operation ${r}`),t.add(r);e.certified&&!e.certificationArtifactId&&M("A certified automation adapter requires a certification artifact"),Array.isArray(e.limitations)||M("Adapter limitations must be an array"),e.operations.some(r=>r.startsWith("browser."))&&(!e.policyEnforcement.domain||!e.policyEnforcement.scheme||!e.policyEnforcement.port)&&M("Browser adapters must enforce domain, scheme, and port policy"),e.operations.some(r=>r.startsWith("computer."))&&!e.supports.immediateStop&&M("Computer-use adapters must support immediate stop")}function lt(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 ut(e,t,r){lt(e,t);let n=X(e.operation);if(n.surface==="browser")Ho(e,r,n.effect==="act");else{let o=e.executionContract.computer.allowedApplications,i=e.operation==="computer.launch"?zo(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 br(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,...Ar(e,t)?{resource:Ar(e,t)}:{},...wr(t)?{destination:wr(t)}:{}}}function Ar(e,t){return Go(t)??e.declaredTarget?.resource}function Er(e){let t=X(e.operation).evidence,r=e.evidencePolicy??{},n=dt(t.before,r.before),o=dt(t.after,r.after),i=dt(t.recording,r.recording),a=r.retainUntil;return a&&!vr(a)&&V("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 jo(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 Ho(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"&&te(`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=Wo(c);if(Ir(c,l.deniedDomains)&&te(`Browser domain ${c} is denied`),yr(o,e.executionContract.network.denyDestinations)&&te(`Network policy explicitly denies ${a}://${c}:${s}`),y&&l.allowLoopbackDevelopment)return;l.allowedSchemes.includes(a)||te(`Browser scheme ${o.protocol} is not allowed`),l.allowedPorts.includes(s)||te(`Browser port ${s} is not allowed`);let A=r?l.actAllowedDomains:l.readAllowedDomains;Ir(c,A)||te(`Browser domain ${c} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&(yr(o,e.executionContract.network.allowDestinations)||te(`Network policy does not allow ${a}://${c}:${s}`))}function yr(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 Go(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function wr(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function zo(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 Ir(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 Wo(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function dt(e,t){let r={disabled:0,optional:1,required:2};return!t||r[t]<=r[e]?e:t}function de(e,t){(typeof e!="string"||!Vo.test(e))&&V(`${t} is invalid`)}function _e(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&M(`${t} is invalid`)}function vr(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}function te(e){throw new d("AUTOMATION_POLICY_DENIED",e)}function V(e){throw new d("AUTOMATION_REQUEST_INVALID",e)}function M(e){throw new d("AUTOMATION_OPERATION_UNSUPPORTED",e)}import{createHash as pi}from"node:crypto";var Sr=["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"],Tr=["draft","pending_review","approved","rejected","superseded","archived"],Cr=["public","internal","confidential","restricted"],xr=["agent","tool","user","system","integration"],Pr=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],Rr=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];import{Buffer as Or}from"node:buffer";import{createHash as qo}from"node:crypto";function re(e){return{algorithm:"sha256",value:qo("sha256").update(e).digest("hex")}}var Jo=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Ne="custom:";function we(e,t=Ne){return e.startsWith(t)?Jo.test(e.slice(t.length)):!1}var le=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,r){super(t),this.name="XenoArtifactValidationError",this.issues=r.map(n=>({...n}))}},pt=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"},Ko={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},Yo="[\\u0000-\\u001f\\u007f]",Zo=new RegExp(Yo),_r=/^[a-f0-9]{64}$/,Qo=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ei=new Set(Tr),ti=new Set(Cr),ri=new Set(xr),ni=new Set(Sr),oi=new Set(Pr),ii=new Set(Rr);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`),Zo.test(e)&&u(r,t,"control_character","Value must not contain control characters"),!0)}function Ie(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 ne(e,t,r,n){typeof e=="string"&&e.startsWith(t)&&(we(e,t)||u(n,r,"invalid_custom_name",`Custom name after ${t} is invalid`))}function Nr(e,t,r){if(!e||typeof e!="object"){u(r,t,"missing_actor","Actor is required");return}g(e.kind,`${t}.kind`,r,64),ri.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 ft(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"):ne(e.kind,"custom:",`${t}.kind`,r)}}function be(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)=>be(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"):be(i,`${t}.${o}`,r,n);n.delete(e)}}function ai(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"&&!ni.has(e.kind)&&!e.kind.startsWith("custom:")&&u(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),ne(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),ei.has(e.state)||u(t,"state","unknown_state","Artifact state is not supported"),g(e.createdAt,"createdAt",t,128),Ie(e.createdAt,"createdAt",t),Ie(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),ti.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),ne(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"&&!_r.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=Or.from(n.text,"utf8"):n.base64!==void 0&&(Qo.test(n.base64)?o=Or.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"&&re(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),Ie(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"),ne(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?u(t,"provenance","missing_provenance","provenance is required"):(Nr(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&&be(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"&&!ii.has(n.relation)&&!n.relation.startsWith("custom:")&&u(t,`${i}.relation`,"unknown_relationship","Relationship type is not supported"),ne(n.relation,"custom:",`${i}.relation`,t),g(n.target?.type,`${i}.target.type`,t,160),typeof n.target?.type=="string"&&!oi.has(n.target.type)&&!n.target.type.startsWith("custom:")&&u(t,`${i}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),ne(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&&be(n.attributes,`${i}.attributes`,t,new Set)}),e.anchors?.forEach((n,o)=>ft(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"),Ie(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&&be(e.extensions,"extensions",t,new Set),t}function ke(e){let t=ai(e);if(t.length>0)throw new le("XENO artifact validation failed",t)}function si(e,t){return Ko[e].includes(t)}function Xe(e,t){if(!si(e,t))throw new pt(e,t)}function mt(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),Ie(e.recordedAt,"recordedAt",r),Nr(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),ne(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",r),g(e.artifactHash.value,"artifactHash.value",r,512),e.artifactHash.algorithm==="sha256"&&!_r.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&&ft(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&&ft(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 gt(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},ve=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(kr).map(r=>({artifact:Ee(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=Ee(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),oe(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(di(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"){Xe(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=Ee(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),oe(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?oe(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=>li(n.artifact,t)).sort(kr).map(oe)}async listRevisions(t){let r=this.records.get(t);return r?[...r.values()].sort((n,o)=>n.artifact.revision-o.artifact.revision).map(oe):[]}async transition(t){let r=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(r,t.expectedRecordVersion),Xe(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=gt(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,oe(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=mt(o,n.artifact);if(i.length>0)throw new le("XENO artifact review event validation failed",i);return n.reviewEvents.push(o),n.recordVersion+=1,oe(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=ui(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=ci(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 ci(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 Xe(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=mt(a,e.artifact);if(c.length>0)throw new le("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:Ee(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function di(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function li(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 kr(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function ui(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 Ee(e){return structuredClone(e)}function oe(e){return{artifact:Ee(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:gt(e.reviewEvents)}}var ht=32*1024*1024,fi=1024*1024*1024,mi=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function At(e){let r=(e.now??(()=>new Date().toISOString()))(),n=new Set;return e.evidence.map((o,i)=>{if(hi(o),n.has(o.evidenceId))throw new d("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${o.evidenceId}`);n.add(o.evidenceId);let a=gi(o),c=pi("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 Se(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 De(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 gi(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return Xr(t),{hash:re(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=Ai(e.content.base64);return Xr(t.byteLength),{hash:re(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>fi)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 hi(e){(!e||typeof e!="object")&&j("Evidence must be an object"),mi.test(e.evidenceId)||j("Evidence ID is invalid"),["before","action","after","recording","diagnostic"].includes(e.phase)||j("Evidence phase is invalid"),(!e.kind||!e.title?.trim()||e.title.length>512)&&j("Evidence kind and title are required"),/^[\w!#$&^_.+-]+\/[\w!#$&^_.+-]+(?:;.*)?$/.test(e.mediaType)||j("Evidence media type is invalid")}function Ai(e){(e.length===0||e.length>Math.ceil(ht/3)*4+4)&&j("Inline base64 evidence is empty or too large"),(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)&&j("Inline evidence is not canonical base64");let t=Buffer.from(e,"base64");return t.toString("base64")!==e&&j("Inline evidence is not canonical base64"),t}function Xr(e){e>ht&&j(`Inline evidence exceeds ${ht} bytes`)}function j(e){throw new d("AUTOMATION_EVIDENCE_INVALID",e)}import{createHash as Ii}from"node:crypto";import{createHash as yi,randomUUID as wi}from"node:crypto";var Dr=16*1024*1024;async function Mr(e,t,r,n){await e.assertCurrent(t);let o={operationId:t.operationId,fingerprint:r,ownerToken:wi()},i=await e.journal.begin(o);if(await e.assertCurrent(t),!i.claimed){if(i.record.outcome.kind!=="result")throw q();let p=await e.artifactRepository.require(i.record.outcome.artifactId,1),E=p.artifact;if(E.content.storage.type!=="inline"||E.content.encoding!=="utf8"||E.provenance.operationId!==t.operationId||E.extensions?.automationRequestFingerprint!==r)throw q();let m=E.content.storage.text;if(typeof m!="string"||Buffer.byteLength(m)>Dr||Le(m)!==i.record.outcome.sha256||E.content.hash.value!==i.record.outcome.sha256)throw q();let x=JSON.parse(m);return Lr(x,t),await e.assertCurrent(t),{...x,replayed:!0}}let a="automation-consume:"+Le(t.operationId+"\0"+r),c=await n(a);Lr(c,t);let s=JSON.stringify(c),l=Buffer.byteLength(s);if(l>Dr)throw q();let y=Le(s),A={schemaVersion:1,artifactId:"automation_result_"+Le(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 Se(e.artifactRepository,[A]),await e.journal.finish(o,{kind:"result",artifactId:A.artifactId,sha256:y}),await e.assertCurrent(t),{...c,replayed:!1}}function Lr(e,t){if(!e||typeof e!="object")throw q();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 q()}function Le(e){return yi("sha256").update(e).digest("hex")}function q(){return new d("AUTOMATION_OUTCOME_PENDING","Automation outcome is pending or unknown; recover the same operation rather than dispatching it again")}var Ur=3e4,Br=1e3,Me=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=Ti(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>=Br)throw new d("AUTOMATION_OPERATION_CONFLICT","Automation active-operation capacity reached");let i=new AbortController,a=Ci(r,i);this.active.set(t.operationId,i);let c=this.durable,s=(c?Mr({...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){W(t),await this.assertCurrent?.(t),B(r);let o=await this.adapter.manifest();U(o),lt(t,o);let i=X(t.operation),a=Er(t),c=this.now(),s=await this.adapter.preflight(t,r);bi(s,this.now()),ut(t,o,s.observedTarget),B(r),await this.onPreflight?.(structuredClone(t),structuredClone(s),r),B(r);let l=s.evidence??[];W(t),await this.assertCurrent?.(t),B(r),De(l,a,"before");let y=await Se(this.artifactRepository,At({request:t,manifest:o,policy:a,evidence:l,now:this.now}));if(B(r),Date.parse(s.expiresAt)<=Date.parse(this.now()))throw new d("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let A=br(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 q();p=w.lease,await this.durable.assertCurrent(t)}else p=await this.leaseAuthority.consume(t.capabilityLeaseId,t.expectedLeaseVersion,A);let E={contractFingerprint:t.executionContract.fingerprint,lease:p,capabilityUse:A};await this.onGrant?.(structuredClone(t),structuredClone(s),structuredClone(E),r),B(r);let m;try{B(r),W(t),await this.assertCurrent?.(t),B(r),m=await this.adapter.execute(t,s,E,r)}catch(w){return yt({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":xi(w)})}if(Ei(m),B(r),W(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=vi(s.observedTarget,m.observedTarget),T;try{ut(t,o,m.observedTarget)}catch(w){T=w instanceof Error?w:new Error(String(w))}if(x||T)return yt({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??T.message});if(m.status!=="ok")return{operationId:t.operationId,status:m.status,effect:i.effect,startedAt:m.startedAt,completedAt:m.completedAt,adapter:wt(o),target:structuredClone(m.observedTarget),artifacts:y,lease:It(p),error:m.error?{...m.error}:{code:"AUTOMATION_ADAPTER_ERROR",message:"Owning adapter refused the operation."}};let P=m.evidence??[];Si(l,P);let _=[],b;try{De(P,a,"after"),De([...l,...P],a,"recording"),_=await Se(this.artifactRepository,At({request:t,manifest:o,policy:a,evidence:P,now:this.now}))}catch(w){b=w instanceof Error?w:new Error(String(w))}let v=[...y,..._];return B(r),W(t),await this.assertCurrent?.(t),b?yt({request:t,manifest:o,descriptorEffect:i.effect,target:m.observedTarget,lease:p,artifacts:v,startedAt:m.startedAt,completedAt:m.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:b.message}):{operationId:t.operationId,status:m.status,effect:i.effect,startedAt:m.startedAt,completedAt:m.completedAt,adapter:wt(o),target:structuredClone(m.observedTarget),...m.data!==void 0?{data:structuredClone(m.data)}:{},artifacts:v,lease:It(p),...m.error?{error:{...m.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>Br;){let t=this.executions.keys().next().value;if(!t||this.active.has(t))break;this.executions.delete(t)}}};function bi(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>Ur)throw new d("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${Ur} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new d("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function Ei(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 vi(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 yt(e){return{operationId:e.request.operationId,status:e.status,effect:e.descriptorEffect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:wt(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:It(e.lease),error:{code:e.code,message:e.message}}}function wt(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function It(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function Ti(e){return Ii("sha256").update(JSON.stringify(bt(e))).digest("hex")}function bt(e){return Array.isArray(e)?e.map(bt):!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,bt(r)]))}function Ci(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 B(e){if(e.aborted)throw new d("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function xi(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}import{isAbsolute as Pi}from"node:path";async function Gc(e){if(!Pi(e))throw Error("Automation journal requires an absolute host-owned path");let{DatabaseSync:t}=await import("node:sqlite");return new Et(new t(e))}var Et=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),vt(t),ue(t,["operationId","fingerprint","ownerToken"]),this.transaction(()=>{let r=this.read(t.operationId);if(r){if(r.fingerprint!==t.fingerprint)throw Ue();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,$r(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),vt(t),ue(t,["operationId","fingerprint","ownerToken"]);let n={schemaVersion:1,...t,outcome:r};return St(n),this.transaction(()=>{let o=this.read(t.operationId);if(!o||o.fingerprint!==t.fingerprint||o.ownerToken!==t.ownerToken)throw Ue();if(o.outcome.kind!=="pending"){if(JSON.stringify(o.outcome)!==JSON.stringify(r))throw Ue();return}this.database.prepare("UPDATE automation_executions SET body=? WHERE id=?").run($r(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(St(n),n.operationId!==t)throw Ue();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 vt(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 St(e){if(!e||typeof e!="object")throw Error("Invalid automation journal record");let t=e;if(vt(t),ue(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(ue(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(ue(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")ue(r,["kind"]);else throw Error("Invalid automation journal outcome")}function ue(e,t){if(Array.isArray(e)||Object.keys(e).some(r=>!t.includes(r)))throw Error("Unexpected automation journal fields")}function $r(e){St(e);let t=JSON.stringify(e);if(t.length>16384)throw Error("Automation journal record too large");return t}function Ue(){return new d("AUTOMATION_OPERATION_CONFLICT","Automation operation identity or owner conflicts with durable state")}function Ri(e,t=()=>new Date().toISOString()){let r=[];Oi(r,"manifest.valid",()=>U(e));let n=new Set(e.operations);return pe(r,n,e.supports.consoleInspection,"browser.console.read","console inspection"),pe(r,n,e.supports.networkInspection,"browser.network.read","network inspection"),pe(r,n,e.supports.storageInspection,"browser.storage.read","storage inspection"),pe(r,n,e.supports.pageErrorInspection,"browser.page-errors.read","page-error inspection"),pe(r,n,e.supports.recordings,"browser.record.start","recording start"),pe(r,n,e.supports.recordings,"browser.record.stop","recording stop"),n.has("browser.upload")&&J(r,"policy.upload",e.policyEnforcement.upload,"Upload policy is enforced"),n.has("browser.download")&&J(r,"policy.download",e.policyEnforcement.download,"Download policy is enforced"),[...n].some(o=>o.startsWith("browser."))&&(J(r,"policy.redirect",e.policyEnforcement.redirect,"Redirect policy is enforced"),J(r,"control.handback",e.supports.deterministicHandback,"Deterministic hand-back is supported")),[...n].some(o=>o.startsWith("computer."))&&(J(r,"control.stop",e.supports.immediateStop,"Immediate human stop is supported"),J(r,"privacy.redaction",e.supports.sensitiveRegionRedaction,"Sensitive-region redaction is supported")),J(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 Kc(e){let r=Ri(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 pe(e,t,r,n,o){let i=t.has(n);J(e,`capability.${n}`,r===i,r===i?`${o} declaration matches the operation catalog`:`${o} declaration does not match ${n}`)}function Oi(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 J(e,t,r,n){e.push({id:t,status:r?"pass":"fail",message:n})}var _i=6e4,Ni=48*1024*1024,Be=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;ownedView;constructor(t){if(this.endpoint=ki(t.baseUrl),this.token=Xi(t.token),this.timeoutMs=Fr(t.timeoutMs??_i,1e3,3e5,"timeoutMs"),this.maxResponseBytes=Fr(t.maxResponseBytes??Ni,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(),W(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=Mi(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 Tt(l,i.signal),A=await Tt(Di(y,this.maxResponseBytes,i.signal),i.signal);if(!y.ok){let p=Li(A);throw new d("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${t}: ${p.message}`,{status:y.status,route:t,adapterCode:p.code})}if(!Ct(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 ki(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 Xi(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 Di(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 Tt(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 Tt(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 Li(e){return Ct(e)&&Ct(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 Mi(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 Fr(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 Ct(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var od=["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 Be{driver;constructor(t){super(t),this.driver=t.driver}async manifest(){let t=await super.manifest();if(U(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}};import{existsSync as wn,readFileSync as In}from"node:fs";import{randomUUID as Ja}from"node:crypto";import{homedir as Ka}from"node:os";import{join as hn,resolve as Ce}from"node:path";import{randomUUID as tn}from"node:crypto";import{mkdir as rn,open as Yr,readFile as Ji,stat as nn,unlink as Ki}from"node:fs/promises";import{basename as Zr,dirname as Qr,join as Yi,resolve as Zi}from"node:path";import*as $ from"node:fs/promises";var Vr=Symbol.for("@xenosystem/agent-sdk/file-cache"),jr=globalThis,xt=jr[Vr]??{entries:new Map,counters:{reads:0,hits:0}};jr[Vr]=xt;var ad=xt.entries,sd=xt.counters;var Ui=new Set(["EACCES","EBUSY","EPERM"]),Bi=[10,20,40,80,160,320,640];async function Hr(e,t){for(let r=0;;r+=1)try{await $.rename(e,t);return}catch(n){let o=n.code,i=Bi[r];if(process.platform!=="win32"||!o||!Ui.has(o)||i===void 0)throw n;await new Promise(a=>setTimeout(a,i))}}import{mkdirSync as $i,readFileSync as Fi,rmSync as zr,writeFileSync as Vi}from"node:fs";import{hostname as Wr}from"node:os";import{dirname as ji}from"node:path";function Hi(){return new Date().toISOString()}function Gi(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function qr(e){try{return JSON.parse(Fi(e,"utf8"))}catch{return null}}function zi(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Wi(e){return e.hostname!==Wr()?!0:zi(e.pid)}function Gr(e,t){$i(ji(e),{recursive:!0}),Vi(e,JSON.stringify(t,null,2)+`
937
- `,{encoding:"utf8",flag:"wx"})}function qi(e,t){let r=qr(e);r?.pid!==t.pid||r.hostname!==t.hostname||zr(e,{force:!0})}function Jr(e,t,r){let n=Hi(),o={schemaVersion:1,name:t,pid:process.pid,hostname:Wr(),processStartedAt:Gi(),version:r,acquiredAt:n,updatedAt:n};try{Gr(e,o)}catch(i){if(i.code!=="EEXIST")throw i;let c=qr(e);if(c&&Wi(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);zr(e,{force:!0}),Gr(e,o)}return{record:o,release:()=>{qi(e,o)}}}var Kr="0.10.43";var on=1,Qi="repository.v1.json",ea=5e3,ta=20,ra=64*1024*1024,$e=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??Qi;if(Zr(r)!==r||!/^[A-Za-z0-9_.-]+$/.test(r))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=Zi(t.directory),this.snapshotPath=Yi(this.directory,r),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Pt(t.lockTimeoutMs,ea,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Pt(t.lockRetryMs,ta,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Pt(t.maxSnapshotBytes,ra,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 Jr(this.lockPath,`artifact-repository:${Zr(this.snapshotPath)}`,Kr)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;r=n,await sa(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=Fe(i)}if(!r&&(t||await aa(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,Fe(i)])}):i}if(!r&&t)throw t;let o=r?.state??{schemaVersion:1,records:[]};return{repository:new ve({now:this.now,idFactory:i=>`${i}_${tn()}`,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:on,generation:t.generation,createdAt:t.createdAt,updatedAt:r,state:t.repository.exportState()},generation:t.generation+1},i=oa(o),a=`${JSON.stringify(i,null,2)}
937
+ `,{encoding:"utf8",flag:"wx"})}function qi(e,t){let r=qr(e);r?.pid!==t.pid||r.hostname!==t.hostname||zr(e,{force:!0})}function Jr(e,t,r){let n=Hi(),o={schemaVersion:1,name:t,pid:process.pid,hostname:Wr(),processStartedAt:Gi(),version:r,acquiredAt:n,updatedAt:n};try{Gr(e,o)}catch(i){if(i.code!=="EEXIST")throw i;let c=qr(e);if(c&&Wi(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);zr(e,{force:!0}),Gr(e,o)}return{record:o,release:()=>{qi(e,o)}}}var Kr="0.10.45";var on=1,Qi="repository.v1.json",ea=5e3,ta=20,ra=64*1024*1024,$e=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??Qi;if(Zr(r)!==r||!/^[A-Za-z0-9_.-]+$/.test(r))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=Zi(t.directory),this.snapshotPath=Yi(this.directory,r),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Pt(t.lockTimeoutMs,ea,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Pt(t.lockRetryMs,ta,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Pt(t.maxSnapshotBytes,ra,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 Jr(this.lockPath,`artifact-repository:${Zr(this.snapshotPath)}`,Kr)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;r=n,await sa(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=Fe(i)}if(!r&&(t||await aa(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,Fe(i)])}):i}if(!r&&t)throw t;let o=r?.state??{schemaVersion:1,records:[]};return{repository:new ve({now:this.now,idFactory:i=>`${i}_${tn()}`,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:on,generation:t.generation,createdAt:t.createdAt,updatedAt:r,state:t.repository.exportState()},generation:t.generation+1},i=oa(o),a=`${JSON.stringify(i,null,2)}
938
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 rn(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await en(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
939
939
  `),await en(this.snapshotPath,a)}async readSnapshot(t,r){let n;try{n=await nn(t)}catch(o){if(!r&&Ot(o,"ENOENT")||r&&Ot(o,"ENOENT"))return;throw _t("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 Ji(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return na(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof f?o:_t("Unable to parse artifact repository snapshot",t,o,!0)}}};function na(e,t){if(!Rt(e)||e.schemaVersion!==on||!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))||!Rt(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!Rt(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=ia(r),o=an(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 ve({initialState:r.state}),structuredClone(r)}function oa(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:an(e)}}}function ia(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function an(e){return re(JSON.stringify(e)).value}async function en(e,t){await rn(Qr(e),{recursive:!0,mode:448});let r=`${e}.tmp.${process.pid}.${tn()}`,n;try{n=await Yr(r,"wx",384),await n.writeFile(t,{encoding:"utf8"}),await n.sync(),await n.close(),n=void 0,await Hr(r,e);try{let o=await Yr(Qr(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{n&&await n.close().catch(()=>{}),await Ki(r).catch(()=>{})}}function Pt(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 Rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ot(e,t){return e instanceof Error&&e.code===t}async function aa(e){try{return(await nn(e)).isFile()}catch(t){if(Ot(t,"ENOENT"))return!1;throw _t("Unable to inspect artifact repository backup",e,t)}}function Fe(e){return e instanceof Error?e:new Error(String(e))}function _t(e,t,r,n=!1){return new f(n?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${Fe(r).message}`,{snapshotPath:t},{cause:Fe(r)})}function sa(e){return new Promise(t=>setTimeout(t,e))}import{homedir as ca,platform as da,release as la}from"node:os";var Nd=da();var kd=la(),Xd=ca();var $d=10080*60*1e3;var ua=2,Nt=["publish","deploy","push","send","purchase","sign","file-legal","change-infrastructure"];function pa(e){return Array.from(new Set((e??[]).map(t=>t.trim()).filter(Boolean)))}function H(e){return{schemaVersion:ua,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:pa(e.tags)}}var Gd=[H({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
940
  `),toolPolicy:{mode:"inherit"},skills:[],memoryScope:"user",evidence:["file-references"],currentTurnApproval:[...Nt],color:"cyan",glyph:"\u25A0",tags:["general","primary"]}),H({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(`
@@ -1 +1 @@
1
- {"inputs":{"src/automation/types.ts":{"bytes":7650,"imports":[],"format":"esm"},"src/automation/operations.ts":{"bytes":3367,"imports":[],"format":"esm"},"src/automation/errors.ts":{"bytes":899,"imports":[],"format":"esm"},"src/security/path-policy.ts":{"bytes":5541,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/windows-process-containment.ts":{"bytes":56741,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/linux-process-containment.ts":{"bytes":5665,"imports":[{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/containment-certification.ts":{"bytes":13312,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/environment-policy.ts":{"bytes":1195,"imports":[],"format":"esm"},"src/security/mxc-containment.ts":{"bytes":28272,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:url","kind":"import-statement","external":true},{"path":"src/security/environment-policy.ts","kind":"import-statement","original":"./environment-policy.js"},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"}],"format":"esm"},"src/security/process-containment.ts":{"bytes":17360,"imports":[{"path":"src/security/windows-process-containment.ts","kind":"import-statement","original":"./windows-process-containment.js"},{"path":"src/security/linux-process-containment.ts","kind":"import-statement","original":"./linux-process-containment.js"},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"},{"path":"src/security/containment-certification.ts","kind":"import-statement","original":"./containment-certification.js"},{"path":"src/security/mxc-containment.ts","kind":"import-statement","original":"./mxc-containment.js"}],"format":"esm"},"src/security/secure-execution-contract.ts":{"bytes":24510,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"},{"path":"src/security/process-containment.ts","kind":"import-statement","original":"./process-containment.js"}],"format":"esm"},"src/automation/policy.ts":{"bytes":16203,"imports":[{"path":"src/security/secure-execution-contract.ts","kind":"import-statement","original":"../security/secure-execution-contract.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/artifacts/types.ts":{"bytes":11227,"imports":[],"format":"esm"},"src/artifacts/hash.ts":{"bytes":1489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/utils/custom-names.ts":{"bytes":2210,"imports":[],"format":"esm"},"src/artifacts/validation.ts":{"bytes":25271,"imports":[{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"},{"path":"node:buffer","kind":"import-statement","external":true},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"./hash.js"},{"path":"src/utils/custom-names.ts","kind":"import-statement","original":"../utils/custom-names.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/artifacts/repository.ts":{"bytes":29289,"imports":[{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/artifacts/validation.ts","kind":"import-statement","original":"./validation.js"}],"format":"esm"},"src/automation/evidence.ts":{"bytes":8618,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/artifacts/repository.ts","kind":"import-statement","original":"../artifacts/repository.js"},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"../artifacts/types.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"}],"format":"esm"},"src/automation/durable-execution.ts":{"bytes":4647,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"}],"format":"esm"},"src/automation/executor.ts":{"bytes":19396,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/durable-execution.ts","kind":"import-statement","original":"./durable-execution.js"},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"}],"format":"esm"},"src/automation/execution-journal.ts":{"bytes":7254,"imports":[{"path":"node:path","kind":"import-statement","external":true},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"node:sqlite","kind":"dynamic-import","external":true}],"format":"esm"},"src/automation/conformance.ts":{"bytes":4331,"imports":[{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/automation/http-adapter.ts":{"bytes":13925,"imports":[{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"}],"format":"esm"},"src/automation/browser-control-plane-adapter.ts":{"bytes":2368,"imports":[{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/http-adapter.ts","kind":"import-statement","original":"./http-adapter.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"}],"format":"esm"},"src/utils/file-cache.ts":{"bytes":6195,"imports":[{"path":"node:fs","kind":"import-statement","external":true}],"format":"esm"},"src/utils/fs.ts":{"bytes":13885,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/file-cache.ts","kind":"import-statement","original":"./file-cache.js"}],"format":"esm"},"src/control-plane/lock.ts":{"bytes":2496,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/version.ts":{"bytes":195,"imports":[],"format":"esm"},"src/artifacts/file-repository.ts":{"bytes":16401,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/fs.ts","kind":"import-statement","original":"../utils/fs.js"},{"path":"src/control-plane/lock.ts","kind":"import-statement","original":"../control-plane/lock.js"},{"path":"src/version.ts","kind":"import-statement","original":"../version.js"},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"./hash.js"},{"path":"src/artifacts/repository.ts","kind":"import-statement","original":"./repository.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/utils/yaml.ts":{"bytes":5506,"imports":[],"format":"esm"},"src/runtime/process-tree-kill.ts":{"bytes":9124,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/utils/platform.ts":{"bytes":9633,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/runtime/process-tree-kill.ts","kind":"import-statement","original":"../runtime/process-tree-kill.js"}],"format":"esm"},"src/agents/definitions.ts":{"bytes":25020,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"../utils/yaml.js"},{"path":"src/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"}],"format":"esm"},"src/agents/profiles.ts":{"bytes":33891,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"}],"format":"esm"},"src/security/capability-lease.ts":{"bytes":29318,"imports":[{"path":"src/agents/profiles.ts","kind":"import-statement","original":"../agents/profiles.js"},{"path":"src/utils/custom-names.ts","kind":"import-statement","original":"../utils/custom-names.js"}],"format":"esm"},"src/automation/tool-pack.ts":{"bytes":19556,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"}],"format":"esm"},"src/security/tool-authorization.ts":{"bytes":2746,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/automation/host-runtime.ts":{"bytes":41060,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/artifacts/file-repository.ts","kind":"import-statement","original":"../artifacts/file-repository.js"},{"path":"src/security/capability-lease.ts","kind":"import-statement","original":"../security/capability-lease.js"},{"path":"src/security/secure-execution-contract.ts","kind":"import-statement","original":"../security/secure-execution-contract.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/automation/executor.ts","kind":"import-statement","original":"./executor.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/tool-pack.ts","kind":"import-statement","original":"./tool-pack.js"},{"path":"src/automation/browser-control-plane-adapter.ts","kind":"import-statement","original":"./browser-control-plane-adapter.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"},{"path":"src/security/tool-authorization.ts","kind":"import-statement","original":"../security/tool-authorization.js"}],"format":"esm"},"src/automation/index.ts":{"bytes":449,"imports":[{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/executor.ts","kind":"import-statement","original":"./executor.js"},{"path":"src/automation/execution-journal.ts","kind":"import-statement","original":"./execution-journal.js"},{"path":"src/automation/durable-execution.ts","kind":"import-statement","original":"./durable-execution.js"},{"path":"src/automation/conformance.ts","kind":"import-statement","original":"./conformance.js"},{"path":"src/automation/http-adapter.ts","kind":"import-statement","original":"./http-adapter.js"},{"path":"src/automation/browser-control-plane-adapter.ts","kind":"import-statement","original":"./browser-control-plane-adapter.js"},{"path":"src/automation/host-runtime.ts","kind":"import-statement","original":"./host-runtime.js"},{"path":"src/automation/tool-pack.ts","kind":"import-statement","original":"./tool-pack.js"}],"format":"esm"}},"outputs":{"dist/automation/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:url","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:buffer","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:sqlite","kind":"dynamic-import","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/automation/index.ts","inputs":{"src/automation/index.ts":{"bytesInOutput":1466},"src/automation/types.ts":{"bytesInOutput":9},"src/automation/operations.ts":{"bytesInOutput":1656},"src/automation/errors.ts":{"bytesInOutput":129},"src/security/secure-execution-contract.ts":{"bytesInOutput":10453},"src/security/path-policy.ts":{"bytesInOutput":2595},"src/security/windows-process-containment.ts":{"bytesInOutput":48432},"src/security/linux-process-containment.ts":{"bytesInOutput":1931},"src/security/containment-certification.ts":{"bytesInOutput":6152},"src/security/mxc-containment.ts":{"bytesInOutput":6578},"src/security/process-containment.ts":{"bytesInOutput":6527},"src/automation/policy.ts":{"bytesInOutput":8211},"src/automation/evidence.ts":{"bytesInOutput":4454},"src/artifacts/types.ts":{"bytesInOutput":825},"src/artifacts/validation.ts":{"bytesInOutput":13385},"src/artifacts/hash.ts":{"bytesInOutput":130},"src/utils/custom-names.ts":{"bytesInOutput":125},"src/artifacts/repository.ts":{"bytesInOutput":13761},"src/automation/executor.ts":{"bytesInOutput":8390},"src/automation/durable-execution.ts":{"bytesInOutput":2222},"src/automation/execution-journal.ts":{"bytesInOutput":4239},"src/automation/conformance.ts":{"bytesInOutput":2207},"src/automation/http-adapter.ts":{"bytesInOutput":7343},"src/automation/browser-control-plane-adapter.ts":{"bytesInOutput":861},"src/automation/host-runtime.ts":{"bytesInOutput":17687},"src/artifacts/file-repository.ts":{"bytesInOutput":6752},"src/utils/fs.ts":{"bytesInOutput":319},"src/utils/file-cache.ts":{"bytesInOutput":166},"src/control-plane/lock.ts":{"bytesInOutput":1067},"src/version.ts":{"bytesInOutput":17},"src/utils/platform.ts":{"bytesInOutput":95},"src/agents/definitions.ts":{"bytesInOutput":20},"src/agents/profiles.ts":{"bytesInOutput":8624},"src/security/capability-lease.ts":{"bytesInOutput":14569},"src/automation/tool-pack.ts":{"bytesInOutput":10303},"src/security/tool-authorization.ts":{"bytesInOutput":1117}},"bytes":214602}}}
1
+ {"inputs":{"src/automation/types.ts":{"bytes":7650,"imports":[],"format":"esm"},"src/automation/operations.ts":{"bytes":3367,"imports":[],"format":"esm"},"src/automation/errors.ts":{"bytes":899,"imports":[],"format":"esm"},"src/security/path-policy.ts":{"bytes":5541,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/windows-process-containment.ts":{"bytes":56741,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/linux-process-containment.ts":{"bytes":5665,"imports":[{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/containment-certification.ts":{"bytes":13312,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/security/environment-policy.ts":{"bytes":1195,"imports":[],"format":"esm"},"src/security/mxc-containment.ts":{"bytes":28272,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:url","kind":"import-statement","external":true},{"path":"src/security/environment-policy.ts","kind":"import-statement","original":"./environment-policy.js"},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"}],"format":"esm"},"src/security/process-containment.ts":{"bytes":17360,"imports":[{"path":"src/security/windows-process-containment.ts","kind":"import-statement","original":"./windows-process-containment.js"},{"path":"src/security/linux-process-containment.ts","kind":"import-statement","original":"./linux-process-containment.js"},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"},{"path":"src/security/containment-certification.ts","kind":"import-statement","original":"./containment-certification.js"},{"path":"src/security/mxc-containment.ts","kind":"import-statement","original":"./mxc-containment.js"}],"format":"esm"},"src/security/secure-execution-contract.ts":{"bytes":24510,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"src/security/path-policy.ts","kind":"import-statement","original":"./path-policy.js"},{"path":"src/security/process-containment.ts","kind":"import-statement","original":"./process-containment.js"}],"format":"esm"},"src/automation/policy.ts":{"bytes":16203,"imports":[{"path":"src/security/secure-execution-contract.ts","kind":"import-statement","original":"../security/secure-execution-contract.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/artifacts/types.ts":{"bytes":11227,"imports":[],"format":"esm"},"src/artifacts/hash.ts":{"bytes":1489,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/utils/custom-names.ts":{"bytes":2210,"imports":[],"format":"esm"},"src/artifacts/validation.ts":{"bytes":25271,"imports":[{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"},{"path":"node:buffer","kind":"import-statement","external":true},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"./hash.js"},{"path":"src/utils/custom-names.ts","kind":"import-statement","original":"../utils/custom-names.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/artifacts/repository.ts":{"bytes":29289,"imports":[{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/artifacts/validation.ts","kind":"import-statement","original":"./validation.js"}],"format":"esm"},"src/automation/evidence.ts":{"bytes":8618,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/artifacts/repository.ts","kind":"import-statement","original":"../artifacts/repository.js"},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"../artifacts/hash.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"../artifacts/types.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"}],"format":"esm"},"src/automation/durable-execution.ts":{"bytes":4647,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"}],"format":"esm"},"src/automation/executor.ts":{"bytes":19396,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/durable-execution.ts","kind":"import-statement","original":"./durable-execution.js"},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"}],"format":"esm"},"src/automation/execution-journal.ts":{"bytes":7254,"imports":[{"path":"node:path","kind":"import-statement","external":true},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"node:sqlite","kind":"dynamic-import","external":true}],"format":"esm"},"src/automation/conformance.ts":{"bytes":4331,"imports":[{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/automation/http-adapter.ts":{"bytes":13925,"imports":[{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"}],"format":"esm"},"src/automation/browser-control-plane-adapter.ts":{"bytes":2368,"imports":[{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/http-adapter.ts","kind":"import-statement","original":"./http-adapter.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"}],"format":"esm"},"src/utils/file-cache.ts":{"bytes":6195,"imports":[{"path":"node:fs","kind":"import-statement","external":true}],"format":"esm"},"src/utils/fs.ts":{"bytes":13885,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/file-cache.ts","kind":"import-statement","original":"./file-cache.js"}],"format":"esm"},"src/control-plane/lock.ts":{"bytes":2496,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/version.ts":{"bytes":195,"imports":[],"format":"esm"},"src/artifacts/file-repository.ts":{"bytes":16401,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/fs.ts","kind":"import-statement","original":"../utils/fs.js"},{"path":"src/control-plane/lock.ts","kind":"import-statement","original":"../control-plane/lock.js"},{"path":"src/version.ts","kind":"import-statement","original":"../version.js"},{"path":"src/artifacts/hash.ts","kind":"import-statement","original":"./hash.js"},{"path":"src/artifacts/repository.ts","kind":"import-statement","original":"./repository.js"},{"path":"src/artifacts/types.ts","kind":"import-statement","original":"./types.js"}],"format":"esm"},"src/utils/yaml.ts":{"bytes":7264,"imports":[],"format":"esm"},"src/runtime/process-tree-kill.ts":{"bytes":9124,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/utils/platform.ts":{"bytes":9633,"imports":[{"path":"node:os","kind":"import-statement","external":true},{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/runtime/process-tree-kill.ts","kind":"import-statement","original":"../runtime/process-tree-kill.js"}],"format":"esm"},"src/agents/definitions.ts":{"bytes":25020,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/utils/yaml.ts","kind":"import-statement","original":"../utils/yaml.js"},{"path":"src/utils/platform.ts","kind":"import-statement","original":"../utils/platform.js"}],"format":"esm"},"src/agents/profiles.ts":{"bytes":33891,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/agents/definitions.ts","kind":"import-statement","original":"./definitions.js"}],"format":"esm"},"src/security/capability-lease.ts":{"bytes":29318,"imports":[{"path":"src/agents/profiles.ts","kind":"import-statement","original":"../agents/profiles.js"},{"path":"src/utils/custom-names.ts","kind":"import-statement","original":"../utils/custom-names.js"}],"format":"esm"},"src/automation/tool-pack.ts":{"bytes":19556,"imports":[{"path":"node:crypto","kind":"import-statement","external":true},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"}],"format":"esm"},"src/security/tool-authorization.ts":{"bytes":2746,"imports":[{"path":"node:crypto","kind":"import-statement","external":true}],"format":"esm"},"src/automation/host-runtime.ts":{"bytes":41060,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:crypto","kind":"import-statement","external":true},{"path":"node:os","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"src/artifacts/file-repository.ts","kind":"import-statement","original":"../artifacts/file-repository.js"},{"path":"src/security/capability-lease.ts","kind":"import-statement","original":"../security/capability-lease.js"},{"path":"src/security/secure-execution-contract.ts","kind":"import-statement","original":"../security/secure-execution-contract.js"},{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/automation/executor.ts","kind":"import-statement","original":"./executor.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/tool-pack.ts","kind":"import-statement","original":"./tool-pack.js"},{"path":"src/automation/browser-control-plane-adapter.ts","kind":"import-statement","original":"./browser-control-plane-adapter.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"},{"path":"src/security/tool-authorization.ts","kind":"import-statement","original":"../security/tool-authorization.js"}],"format":"esm"},"src/automation/index.ts":{"bytes":449,"imports":[{"path":"src/automation/types.ts","kind":"import-statement","original":"./types.js"},{"path":"src/automation/operations.ts","kind":"import-statement","original":"./operations.js"},{"path":"src/automation/errors.ts","kind":"import-statement","original":"./errors.js"},{"path":"src/automation/policy.ts","kind":"import-statement","original":"./policy.js"},{"path":"src/automation/evidence.ts","kind":"import-statement","original":"./evidence.js"},{"path":"src/automation/executor.ts","kind":"import-statement","original":"./executor.js"},{"path":"src/automation/execution-journal.ts","kind":"import-statement","original":"./execution-journal.js"},{"path":"src/automation/durable-execution.ts","kind":"import-statement","original":"./durable-execution.js"},{"path":"src/automation/conformance.ts","kind":"import-statement","original":"./conformance.js"},{"path":"src/automation/http-adapter.ts","kind":"import-statement","original":"./http-adapter.js"},{"path":"src/automation/browser-control-plane-adapter.ts","kind":"import-statement","original":"./browser-control-plane-adapter.js"},{"path":"src/automation/host-runtime.ts","kind":"import-statement","original":"./host-runtime.js"},{"path":"src/automation/tool-pack.ts","kind":"import-statement","original":"./tool-pack.js"}],"format":"esm"}},"outputs":{"dist/automation/index.cjs":{"imports":[{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:url","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:buffer","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:sqlite","kind":"dynamic-import","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:fs","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"node:os","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/automation/index.ts","inputs":{"src/automation/index.ts":{"bytesInOutput":1466},"src/automation/types.ts":{"bytesInOutput":9},"src/automation/operations.ts":{"bytesInOutput":1656},"src/automation/errors.ts":{"bytesInOutput":129},"src/security/secure-execution-contract.ts":{"bytesInOutput":10453},"src/security/path-policy.ts":{"bytesInOutput":2595},"src/security/windows-process-containment.ts":{"bytesInOutput":48432},"src/security/linux-process-containment.ts":{"bytesInOutput":1931},"src/security/containment-certification.ts":{"bytesInOutput":6152},"src/security/mxc-containment.ts":{"bytesInOutput":6578},"src/security/process-containment.ts":{"bytesInOutput":6527},"src/automation/policy.ts":{"bytesInOutput":8211},"src/automation/evidence.ts":{"bytesInOutput":4454},"src/artifacts/types.ts":{"bytesInOutput":825},"src/artifacts/validation.ts":{"bytesInOutput":13385},"src/artifacts/hash.ts":{"bytesInOutput":130},"src/utils/custom-names.ts":{"bytesInOutput":125},"src/artifacts/repository.ts":{"bytesInOutput":13761},"src/automation/executor.ts":{"bytesInOutput":8390},"src/automation/durable-execution.ts":{"bytesInOutput":2222},"src/automation/execution-journal.ts":{"bytesInOutput":4239},"src/automation/conformance.ts":{"bytesInOutput":2207},"src/automation/http-adapter.ts":{"bytesInOutput":7343},"src/automation/browser-control-plane-adapter.ts":{"bytesInOutput":861},"src/automation/host-runtime.ts":{"bytesInOutput":17687},"src/artifacts/file-repository.ts":{"bytesInOutput":6752},"src/utils/fs.ts":{"bytesInOutput":319},"src/utils/file-cache.ts":{"bytesInOutput":166},"src/control-plane/lock.ts":{"bytesInOutput":1067},"src/version.ts":{"bytesInOutput":17},"src/utils/platform.ts":{"bytesInOutput":95},"src/agents/definitions.ts":{"bytesInOutput":20},"src/agents/profiles.ts":{"bytesInOutput":8624},"src/security/capability-lease.ts":{"bytesInOutput":14569},"src/automation/tool-pack.ts":{"bytesInOutput":10303},"src/security/tool-authorization.ts":{"bytesInOutput":1117}},"bytes":214602}}}