@xenosystem/agent-sdk 0.9.21 → 0.9.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -8
- package/dist/artifacts/index.cjs +1 -1
- package/dist/artifacts/index.js +1 -1
- package/dist/automation/index.cjs +16 -3
- package/dist/automation/index.d.cts +367 -1
- package/dist/automation/index.d.ts +367 -1
- package/dist/automation/index.js +16 -3
- package/dist/automation/metafile-cjs.json +1 -1
- package/dist/automation/metafile-esm.json +1 -1
- package/dist/control-plane/index.cjs +1 -1
- package/dist/control-plane/index.js +1 -1
- package/dist/control-room/index.d.cts +1 -1
- package/dist/control-room/index.d.ts +1 -1
- package/dist/control-room/metafile-cjs.json +1 -1
- package/dist/control-room/metafile-esm.json +1 -1
- package/dist/coordination/index.cjs +2 -0
- package/dist/coordination/index.d.cts +395 -0
- package/dist/coordination/index.d.ts +395 -0
- package/dist/coordination/index.js +2 -0
- package/dist/coordination/metafile-cjs.json +1 -0
- package/dist/coordination/metafile-esm.json +1 -0
- package/dist/electron/index.cjs +123 -119
- package/dist/electron/index.d.cts +61 -0
- package/dist/electron/index.d.ts +61 -0
- package/dist/electron/index.js +118 -114
- package/dist/electron/metafile-cjs.json +1 -1
- package/dist/electron/metafile-esm.json +1 -1
- package/dist/governance/index.d.cts +29 -0
- package/dist/governance/index.d.ts +29 -0
- package/dist/hosted/index.cjs +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/hosted/metafile-cjs.json +1 -1
- package/dist/hosted/metafile-esm.json +1 -1
- package/dist/index.cjs +359 -351
- package/dist/index.d.cts +1964 -1254
- package/dist/index.d.ts +1964 -1254
- package/dist/index.js +359 -351
- package/dist/mcp/index.d.cts +28 -0
- package/dist/mcp/index.d.ts +28 -0
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/providers/metafile-cjs.json +1 -1
- package/dist/providers/metafile-esm.json +1 -1
- package/dist/session/index.cjs +56 -54
- package/dist/session/index.d.cts +69 -1
- package/dist/session/index.d.ts +69 -1
- package/dist/session/index.js +56 -54
- package/dist/session/metafile-cjs.json +1 -1
- package/dist/session/metafile-esm.json +1 -1
- package/dist/skills/index.d.cts +28 -0
- package/dist/skills/index.d.ts +28 -0
- package/dist/ui/index.d.cts +28 -0
- package/dist/ui/index.d.ts +28 -0
- package/dist/utils/index.cjs +17 -16
- package/dist/utils/index.d.cts +31 -1
- package/dist/utils/index.d.ts +31 -1
- package/dist/utils/index.js +14 -13
- package/dist/utils/metafile-cjs.json +1 -1
- package/dist/utils/metafile-esm.json +1 -1
- package/package.json +6 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var tt=Object.defineProperty;var wn=Object.getOwnPropertyDescriptor;var En=Object.getOwnPropertyNames;var vn=Object.prototype.hasOwnProperty;var Sn=(e,t)=>{for(var r in t)tt(e,r,{get:t[r],enumerable:!0})},Tn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of En(t))!vn.call(e,o)&&o!==r&&tt(e,o,{get:()=>t[o],enumerable:!(n=wn(t,o))||n.enumerable});return e};var Cn=e=>Tn(tt({},"__esModule",{value:!0}),e);var va={};Sn(va,{CliGovernedAutomationRuntime:()=>Qe,XENO_AUTOMATION_OPERATIONS:()=>de,XENO_AUTOMATION_PROTOCOL_VERSION:()=>J,XENO_BROWSER_CONTROL_PLANE_OPERATIONS:()=>Xe,XenoAutomationError:()=>l,XenoBrowserControlPlaneAdapter:()=>Ae,XenoGovernedAutomationExecutor:()=>ke,XenoHostGovernedAutomationRuntime:()=>Qe,XenoLoopbackAutomationAdapter:()=>Ot,assertRequiredXenoAutomationEvidence:()=>Ne,assertValidXenoAutomationAdapterManifest:()=>Ce,assertValidXenoAutomationRequest:()=>yt,assertXenoAutomationAdapterConformant:()=>Fo,assertXenoAutomationAuthority:()=>Ve,buildXenoAutomationCapabilityUse:()=>bt,createCliAutomationAuditSink:()=>na,createCliGovernedAutomationRuntime:()=>ra,createXenoAutomationConformanceReport:()=>Br,createXenoGovernedAutomationTools:()=>Bt,createXenoHostAutomationAuditSink:()=>na,createXenoHostGovernedAutomationRuntime:()=>ra,describeXenoAutomationOperation:()=>X,inspectCliAutomationStatus:()=>oa,inspectXenoHostAutomationStatus:()=>oa,isXenoAutomationOperation:()=>Le,materializeXenoAutomationEvidence:()=>He,persistXenoAutomationEvidence:()=>Ge,readCliAutomationEnvironment:()=>Wt,readXenoHostAutomationEnvironment:()=>Wt,renderCliAutomationStatus:()=>Ea,renderXenoHostAutomationStatus:()=>Ea,resolveXenoAutomationEvidencePolicy:()=>wt});module.exports=Cn(va);var J=1;var rt=new Set(["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read"]),nt=new Set(["browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download","browser.record.start","browser.record.stop"]),ot=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),it=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),de=[...rt,...nt,...ot,...it];function X(e){if(rt.has(e))return{operation:e,surface:"browser",effect:"observe",evidence:{before:"disabled",after:e==="browser.wait"||e==="browser.tabs.list"?"optional":"required",recording:"optional"}};if(nt.has(e)){let t=e==="browser.record.start"||e==="browser.record.stop";return{operation:e,surface:"browser",effect:"act",evidence:{before:"required",after:"required",recording:e==="browser.record.stop"?"required":"optional"}}}if(ot.has(e))return{operation:e,surface:"computer",effect:"observe",evidence:{before:"disabled",after:e==="computer.wait"?"optional":"required",recording:"optional"}};if(it.has(e))return{operation:e,surface:"computer",effect:"act",evidence:{before:"required",after:"required",recording:"optional"}};throw new TypeError(`Unsupported XENO automation operation: ${e}`)}function Le(e){return rt.has(e)||nt.has(e)||ot.has(e)||it.has(e)}var l=class extends Error{constructor(r,n,o,i){super(n,i);this.code=r;this.detail=o;this.name="XenoAutomationError"}code;detail};var mr=require("node:crypto"),gr=require("node:os");var we=require("node:fs"),D=require("node:path"),Pn=/^(?:con|prn|aux|nul|clock\$|com[1-9]|lpt[1-9])(?:\..*)?$/i;function Rn(e){return e.replace(/\//g,"\\")}function _n(e){let t=[],r=Rn(e),n=r.toLowerCase();if(r.startsWith("\\\\?\\")||r.startsWith("\\\\.\\")||r.startsWith("\\??\\"))return t.push({code:"DEVICE_PATH",message:"Extended-length, NT, and Windows device paths are not accepted at security boundaries."}),t;if(r.startsWith("\\\\"))return t.push({code:"UNC_PATH",message:"UNC paths are not accepted at security boundaries."}),t;/^[a-z]:($|[^\\])/i.test(r)?t.push({code:"DRIVE_RELATIVE_PATH",message:"Drive-relative Windows paths are ambiguous and are not accepted."}):/^\\(?!\\)/.test(r)&&t.push({code:"ROOT_RELATIVE_PATH",message:"Root-relative Windows paths are ambiguous and are not accepted."});let o=/^[a-z]:/i.test(r)?2:0;r.slice(o).includes(":")&&t.push({code:"ALTERNATE_DATA_STREAM",message:"Windows alternate data stream paths are not accepted."});for(let i of r.split("\\"))!i||i==="."||i===".."||/^[a-z]:$/i.test(i)||((i.endsWith(".")||i.endsWith(" "))&&t.push({code:"NON_CANONICAL_SEGMENT",message:`Windows path segment has an ambiguous trailing character: ${i}`}),Pn.test(i)&&t.push({code:"RESERVED_DEVICE_NAME",message:`Windows reserved device name is not accepted: ${i}`}));return(n.includes("\\globalroot\\")||n.includes("\\device\\"))&&t.push({code:"DEVICE_PATH",message:"Windows object-manager device paths are not accepted."}),t}function xn(e,t=process.platform){return e.length===0?[{code:"EMPTY_PATH",message:"Empty paths are not accepted."}]:e.includes("\0")?[{code:"NUL_BYTE",message:"Paths containing NUL bytes are not accepted."}]:t==="win32"||/^[a-z]:/i.test(e)||e.startsWith("\\")?_n(e):[]}function On(e){let r=(0,D.resolve)(e),n=[];for(;!(0,we.existsSync)(r);){let i=(0,D.dirname)(r);if(i===r)break;n.unshift(r.slice(i.length).replace(/^[/\\]+/,"")),r=i}let o=(0,we.existsSync)(r)?we.realpathSync.native(r):r;return{canonicalPath:n.reduce((i,a)=>(0,D.join)(i,a),o),existingAncestor:o}}function Q(e,t){let r=t?.platform??process.platform,n=xn(e,r);if(n.length>0){let a=new Error(`${n[0].code}: ${n[0].message}`);throw a.name="SecurityPathError",a}let o=(0,D.isAbsolute)(e)?(0,D.resolve)(e):(0,D.resolve)(t?.baseDirectory??process.cwd(),e),i=On(o);return{input:e,absolutePath:o,...i}}function zt(e){let t=(0,D.resolve)(e);return process.platform==="win32"?t.toLowerCase():t}function Jt(e,t){let r;try{r=zt(Q(e).canonicalPath)}catch{return!1}for(let n of t){let o;try{o=zt(Q(n).canonicalPath)}catch{continue}if(r===o||r.startsWith(o+D.sep))return!0}return!1}var ee=require("node:fs");var at=require("node:path"),_a=String.raw`
|
|
2
2
|
using System;
|
|
3
3
|
using System.ComponentModel;
|
|
4
4
|
using System.Runtime.InteropServices;
|
|
@@ -896,7 +896,7 @@ namespace Xeno.Security
|
|
|
896
896
|
}
|
|
897
897
|
}
|
|
898
898
|
}
|
|
899
|
-
`,
|
|
899
|
+
`,xa=String.raw`
|
|
900
900
|
public static class Program
|
|
901
901
|
{
|
|
902
902
|
private static string Decode(string name)
|
|
@@ -922,4 +922,17 @@ public static class Program
|
|
|
922
922
|
return Xeno.Security.RestrictedProcessLauncher.Run(command, cwd, lowIntegrity, restrictedToken, tokenProbe);
|
|
923
923
|
}
|
|
924
924
|
}
|
|
925
|
-
`;var qt=512*1024,Kt=744*60*60*1e3,Yt=Object.freeze(["allowedFilesystemRead","allowedFilesystemWrite","outsideFilesystemReadDenied","outsideFilesystemWriteDenied","unlistedFilesystemReadDenied","unlistedFilesystemWriteDenied","symlinkEscapeDenied","networkDefaultDeny","environmentSecretsExcluded","childProcessPolicyInherited","standardCommandLaunch","processTreeCleanup","timeoutEnforced","hostPolicyRecoveryClean","uiRestrictionsEnforced"]);var nr=10*6e4,or=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"}),ir=Object.freeze({"win32-x64-wxc-host-prep.exe":"531fb3cdb4b0c964908fd71b71d40961417afb399cbab72f92a25e95309a6416","win32-arm64-wxc-host-prep.exe":"3ef702332286a39153fc259310b5021e3de3c191751d7522684f6475f73af5ef"});var Er=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),wr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!0,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!0,environmentSanitization:!0}),yr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),vr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!0,networkIsolation:!0,inheritedHandleAllowlist:!0,environmentSanitization:!0}),Tr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0});var Fe=1,j=class extends Error{constructor(r,n){super(n);this.code=r;this.name="XenoSecureExecutionContractError"}code};function He(e){let t=[];if(!e||typeof e!="object")return["Contract must be an object"];if(e.schemaVersion!==Fe&&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"),le(e.createdAt)||t.push("createdAt must be an ISO 8601 timestamp"),e.expiresAt&&(!le(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,je(r)!==e.fingerprint&&t.push("Contract fingerprint does not match content")}return t}function pe(e){let t=He(e);if(t.length>0){let r=t.includes("Contract fingerprint does not match content");throw new j(r?"SECURITY_CONTRACT_FINGERPRINT_MISMATCH":"SECURITY_CONTRACT_INVALID",t.join("; "))}}function je(e){return(0,ue.createHash)("sha256").update(JSON.stringify(G(e))).digest("hex")}function G(e){return Array.isArray(e)?e.map(G):!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,G(r)]))}function le(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}var Ge=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,fe=1048576;function z(e){(!e||typeof e!="object")&&h("Automation request must be an object"),e.protocolVersion!==1&&h("Unsupported automation protocol version"),w(e.operationId,"operationId"),w(e.idempotencyKey,"idempotencyKey"),w(e.capabilityLeaseId,"capabilityLeaseId"),w(e.governingToolName,"governingToolName"),(!Number.isSafeInteger(e.expectedLeaseVersion)||e.expectedLeaseVersion<1)&&h("expectedLeaseVersion must be a positive safe integer"),ge(e.requestedAt)||h("requestedAt must be an ISO 8601 timestamp"),R(e.operation)||h(`Unsupported automation operation: ${e.operation}`),(!e.parameters||typeof e.parameters!="object"||Array.isArray(e.parameters))&&h("parameters must be a JSON object");let t;try{t=Buffer.byteLength(JSON.stringify(e.parameters),"utf8")}catch(r){throw new i("AUTOMATION_REQUEST_INVALID","parameters must be serializable JSON",void 0,{cause:r})}if(t>fe&&h(`parameters exceed ${fe} bytes`),w(e.identity?.runId,"identity.runId"),w(e.identity?.agentId,"identity.agentId"),pe(e.executionContract),We(e),!e.executionContract.capabilityLeaseIds.includes(e.capabilityLeaseId))throw new i("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 i("AUTOMATION_CONTRACT_EXPIRED","Execution contract has expired")}function T(e){(!e||typeof e!="object")&&f("Adapter manifest must be an object"),e.protocolVersion!==1&&f("Adapter protocol version is unsupported"),N(e.adapterId,"adapterId"),N(e.adapterVersion,"adapterVersion"),N(e.platform,"platform"),N(e.architecture,"architecture"),e.targetBinding!=="atomic-preflight"&&f("Adapter must implement atomic preflight target binding"),(!Array.isArray(e.operations)||e.operations.length===0)&&f("Adapter must declare operations");let t=new Set;for(let r of e.operations)R(r)||f(`Adapter declares unknown operation ${r}`),t.has(r)&&f(`Adapter declares duplicate operation ${r}`),t.add(r);e.certified&&!e.certificationArtifactId&&f("A certified automation adapter requires a certification artifact"),Array.isArray(e.limitations)||f("Adapter limitations must be an array"),e.operations.some(r=>r.startsWith("browser."))&&(!e.policyEnforcement.domain||!e.policyEnforcement.scheme||!e.policyEnforcement.port)&&f("Browser adapters must enforce domain, scheme, and port policy"),e.operations.some(r=>r.startsWith("computer."))&&!e.supports.immediateStop&&f("Computer-use adapters must support immediate stop")}function O(e,t,r){let n=I(e.operation);if(!t.operations.includes(e.operation))throw new i("AUTOMATION_OPERATION_UNSUPPORTED",`Adapter ${t.adapterId} does not support ${e.operation}`);if(n.surface==="browser"){let o=e.executionContract.browser.mode;if(o==="none"||n.effect==="act"&&o!=="act")throw new i("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(ze(e,r,n.effect==="act"),e.operation==="browser.download"&&e.executionContract.browser.downloads==="deny")throw new i("AUTOMATION_POLICY_DENIED","Execution contract denies browser downloads");if(e.operation==="browser.upload"&&e.executionContract.browser.uploads==="deny")throw new i("AUTOMATION_POLICY_DENIED","Execution contract denies browser uploads");if(e.operation.startsWith("browser.record.")&&e.executionContract.browser.recording!=="bounded")throw new i("AUTOMATION_POLICY_DENIED","Execution contract denies browser recording")}else{let o=e.executionContract.computer.mode;if(o==="none"||n.effect==="act"&&o!=="act")throw new i("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);let a=e.executionContract.computer.allowedApplications,c=e.operation==="computer.launch"?qe(e):r.applicationId??e.declaredTarget?.applicationId;if((e.operation==="computer.launch"||a.length>0)&&(!c||!a.includes(c)))throw new i("AUTOMATION_POLICY_DENIED",`Application ${c??"<unknown>"} is not allowed`)}}function J(e,t){let r=I(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,...me(e,t)?{resource:me(e,t)}:{},...Ae(t)?{destination:Ae(t)}:{}}}function me(e,t){return e.declaredTarget?.resource??Je(t)}function q(e){let t=I(e.operation).evidence,r=e.evidencePolicy??{},n=W(t.before,r.before),o=W(t.after,r.after),a=W(t.recording,r.recording),c=r.retainUntil;return c&&!ge(c)&&h("evidencePolicy.retainUntil must be an ISO 8601 timestamp"),{before:n,after:o,recording:a,sensitivity:r.sensitivity??"confidential",...c?{retainUntil:c}:{},...r.legalHold!==void 0?{legalHold:r.legalHold}:{}}}function We(e){let t=e.executionContract.identity,r=["runId","agentId","sessionId","turnId","taskId","workspaceId"];for(let n of r){let o=t[n],a=e.identity[n];if(o!==void 0&&o!==a)throw new i("AUTOMATION_IDENTITY_MISMATCH",`Automation identity ${n} does not match the execution contract`)}}function ze(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 i("AUTOMATION_PREFLIGHT_INVALID","Browser preflight did not bind an effective URL")}let o;try{o=new URL(n)}catch{throw new i("AUTOMATION_POLICY_DENIED","Browser target URL is invalid")}if(o.username||o.password)throw new i("AUTOMATION_POLICY_DENIED","Browser target URLs cannot contain credentials");let a=o.protocol.replace(/:$/,"");a!=="http"&&a!=="https"&&E(`Browser scheme ${o.protocol} is not supported`);let c=a,s=o.hostname.toLowerCase().replace(/\.$/,""),l=o.port?Number(o.port):c==="https"?443:80,d=e.executionContract.browser,p=Ke(s);if(he(s,d.deniedDomains)&&E(`Browser domain ${s} is denied`),Ie(o,e.executionContract.network.denyDestinations)&&E(`Network policy explicitly denies ${c}://${s}:${l}`),p&&d.allowLoopbackDevelopment)return;d.allowedSchemes.includes(c)||E(`Browser scheme ${o.protocol} is not allowed`),d.allowedPorts.includes(l)||E(`Browser port ${l} is not allowed`);let m=r?d.actAllowedDomains:d.readAllowedDomains;he(s,m)||E(`Browser domain ${s} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&(Ie(o,e.executionContract.network.allowDestinations)||E(`Network policy does not allow ${c}://${s}:${l}`))}function Ie(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(a=>{let c=a.scheme?.replace(/^custom:/,"");return a.host===n&&(a.port===void 0||a.port===o)&&(c===void 0||c===r)})}function Je(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function Ae(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function qe(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 he(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 Ke(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function W(e,t){let r={disabled:0,optional:1,required:2};return!t||r[t]<=r[e]?e:t}function w(e,t){(typeof e!="string"||!Ge.test(e))&&h(`${t} is invalid`)}function N(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&f(`${t} is invalid`)}function ge(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}function E(e){throw new i("AUTOMATION_POLICY_DENIED",e)}function h(e){throw new i("AUTOMATION_REQUEST_INVALID",e)}function f(e){throw new i("AUTOMATION_OPERATION_UNSUPPORTED",e)}var _e=require("node:crypto");var be=["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"],Ee=["draft","pending_review","approved","rejected","superseded","archived"],we=["public","internal","confidential","restricted"],ye=["agent","tool","user","system","integration"],ve=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],Te=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var Se=require("node:crypto");function P(e){return{algorithm:"sha256",value:(0,Se.createHash)("sha256").update(e).digest("hex")}}var Ye="[\\u0000-\\u001f\\u007f]",jr=new RegExp(Ye);var Gr=new Set(Ee),Wr=new Set(we),zr=new Set(ye),Jr=new Set(be),qr=new Set(ve),Kr=new Set(Te);var x=class extends Error{constructor(r,n,o,a){super(n,a);this.code=r;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail};var Y=32*1024*1024,Ze=1024*1024*1024,Qe=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function X(e){let r=(e.now??(()=>new Date().toISOString()))(),n=new Set;return e.evidence.map((o,a)=>{if(tt(o),n.has(o.evidenceId))throw new i("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${o.evidenceId}`);n.add(o.evidenceId);let c=et(o),s=(0,_e.createHash)("sha256").update(`${e.request.operationId}\0${o.evidenceId}\0${c.hash.value}`).digest("hex").slice(0,32);return{schemaVersion:1,artifactId:`automation_${s}`,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:c,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:a}},...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 k(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 x&&o.code==="ARTIFACT_ALREADY_EXISTS"){let a=await e.require(n.artifactId,n.revision);if(a.artifact.content.hash.value===n.content.hash.value){r.push(a.artifact);continue}}throw new i("AUTOMATION_EVIDENCE_PERSISTENCE_FAILED",`Failed to persist automation evidence ${n.artifactId}`,{artifactId:n.artifactId},{cause:o})}return r}function S(e,t,r){if(t[r]==="required"&&!e.some(n=>n.phase===r))throw new i("AUTOMATION_EVIDENCE_REQUIRED",`Automation operation requires ${r} evidence before it can be trusted`)}function et(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return Ce(t),{hash:P(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=rt(e.content.base64);return Ce(t.byteLength),{hash:P(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>Ze)throw new i("AUTOMATION_EVIDENCE_INVALID","Referenced evidence size is invalid");if(!e.content.hash?.algorithm||!e.content.hash.value)throw new i("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 i("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 tt(e){(!e||typeof e!="object")&&g("Evidence must be an object"),Qe.test(e.evidenceId)||g("Evidence ID is invalid"),["before","action","after","recording","diagnostic"].includes(e.phase)||g("Evidence phase is invalid"),(!e.kind||!e.title?.trim()||e.title.length>512)&&g("Evidence kind and title are required"),/^[\w!#$&^_.+-]+\/[\w!#$&^_.+-]+(?:;.*)?$/.test(e.mediaType)||g("Evidence media type is invalid")}function rt(e){(e.length===0||e.length>Math.ceil(Y/3)*4+4)&&g("Inline base64 evidence is empty or too large"),(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)&&g("Inline evidence is not canonical base64");let t=Buffer.from(e,"base64");return t.toString("base64")!==e&&g("Inline evidence is not canonical base64"),t}function Ce(e){e>Y&&g(`Inline evidence exceeds ${Y} bytes`)}function g(e){throw new i("AUTOMATION_EVIDENCE_INVALID",e)}var Ne=require("node:crypto");var Re=3e4,nt=1e3,ee=class{adapter;leaseAuthority;artifactRepository;now;executions=new Map;active=new Map;constructor(t){this.adapter=t.adapter,this.leaseAuthority=t.leaseAuthority,this.artifactRepository=t.artifactRepository,this.now=t.now??(()=>new Date().toISOString())}execute(t,r){let n=ct(t),o=this.executions.get(t.operationId);if(o){if(o.fingerprint!==n)throw new i("AUTOMATION_OPERATION_CONFLICT",`Operation ${t.operationId} was already submitted with different authority or parameters`);return o.promise}let a=new AbortController,c=dt(r,a);this.active.set(t.operationId,a);let s=this.executeFresh(t,a.signal).finally(()=>{c(),this.active.delete(t.operationId)});return this.executions.set(t.operationId,{fingerprint:n,promise:s}),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){z(t),Q(r);let n=await this.adapter.manifest();T(n);let o=I(t.operation),a=q(t),c=this.now(),s=await this.adapter.preflight(t,r);ot(s,this.now()),O(t,n,s.observedTarget),Q(r);let l=s.evidence??[];S(l,a,"before");let d=await k(this.artifactRepository,X({request:t,manifest:n,policy:a,evidence:l,now:this.now}));if(Q(r),Date.parse(s.expiresAt)<=Date.parse(this.now()))throw new i("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let p=J(t,s.observedTarget),m=await this.leaseAuthority.consume(t.capabilityLeaseId,t.expectedLeaseVersion,p),ae={contractFingerprint:t.executionContract.fingerprint,lease:m,capabilityUse:p},u;try{u=await this.adapter.execute(t,s,ae,r)}catch(A){return Z({request:t,manifest:n,descriptorEffect:o.effect,target:s.observedTarget,lease:m,artifacts:d,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":lt(A)})}it(u);let se=at(s.observedTarget,u.observedTarget),D;try{O(t,n,u.observedTarget)}catch(A){D=A instanceof Error?A:new Error(String(A))}let C=u.evidence??[];st(l,C);let ce=[],U;try{S(C,a,"after"),S([...l,...C],a,"recording"),ce=await k(this.artifactRepository,X({request:t,manifest:n,policy:a,evidence:C,now:this.now}))}catch(A){U=A instanceof Error?A:new Error(String(A))}let M=[...d,...ce];return se||D?Z({request:t,manifest:n,descriptorEffect:o.effect,target:u.observedTarget,lease:m,artifacts:M,startedAt:u.startedAt,completedAt:u.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:se??D.message}):U?Z({request:t,manifest:n,descriptorEffect:o.effect,target:u.observedTarget,lease:m,artifacts:M,startedAt:u.startedAt,completedAt:u.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:U.message}):{operationId:t.operationId,status:u.status,effect:o.effect,startedAt:u.startedAt,completedAt:u.completedAt,adapter:Oe(n),target:structuredClone(u.observedTarget),...u.data!==void 0?{data:structuredClone(u.data)}:{},artifacts:M,lease:Pe(m),...u.error?{error:{...u.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>nt;){let t=this.executions.keys().next().value;if(!t||this.active.has(t))break;this.executions.delete(t)}}};function ot(e,t){if(!e||typeof e!="object"||!e.token?.trim())throw new i("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 i("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an expired or invalid preflight window");if(n-r>Re)throw new i("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${Re} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new i("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function it(e){if(!e||typeof e!="object")throw new i("AUTOMATION_REQUEST_INVALID","Adapter returned no result");if(!["ok","denied","cancelled","error"].includes(e.status))throw new i("AUTOMATION_REQUEST_INVALID","Adapter returned an invalid status");if(!Number.isFinite(Date.parse(e.startedAt))||!Number.isFinite(Date.parse(e.completedAt)))throw new i("AUTOMATION_REQUEST_INVALID","Adapter result timestamps are invalid");if(Date.parse(e.completedAt)<Date.parse(e.startedAt))throw new i("AUTOMATION_REQUEST_INVALID","Adapter completion precedes its start");if(!e.observedTarget||typeof e.observedTarget!="object")throw new i("AUTOMATION_REQUEST_INVALID","Adapter result has no observed target")}function at(e,t){let r=["tabId","deviceId","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 st(e,t){let r=new Set(e.map(n=>n.evidenceId));for(let n of t){if(r.has(n.evidenceId))throw new i("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${n.evidenceId}`);r.add(n.evidenceId)}}function Z(e){return{operationId:e.request.operationId,status:e.status,effect:e.descriptorEffect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:Oe(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:Pe(e.lease),error:{code:e.code,message:e.message}}}function Oe(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function Pe(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function ct(e){return(0,Ne.createHash)("sha256").update(JSON.stringify(te(e))).digest("hex")}function te(e){return Array.isArray(e)?e.map(te):!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,te(r)]))}function dt(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 Q(e){if(e.aborted)throw new i("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function lt(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}function xe(e,t=()=>new Date().toISOString()){let r=[];pt(r,"manifest.valid",()=>T(e));let n=new Set(e.operations);return y(r,n,e.supports.consoleInspection,"browser.console.read","console inspection"),y(r,n,e.supports.networkInspection,"browser.network.read","network inspection"),y(r,n,e.supports.storageInspection,"browser.storage.read","storage inspection"),y(r,n,e.supports.pageErrorInspection,"browser.page-errors.read","page-error inspection"),y(r,n,e.supports.recordings,"browser.record.start","recording start"),y(r,n,e.supports.recordings,"browser.record.stop","recording stop"),n.has("browser.upload")&&b(r,"policy.upload",e.policyEnforcement.upload,"Upload policy is enforced"),n.has("browser.download")&&b(r,"policy.download",e.policyEnforcement.download,"Download policy is enforced"),[...n].some(o=>o.startsWith("browser."))&&(b(r,"policy.redirect",e.policyEnforcement.redirect,"Redirect policy is enforced"),b(r,"control.handback",e.supports.deterministicHandback,"Deterministic hand-back is supported")),[...n].some(o=>o.startsWith("computer."))&&(b(r,"control.stop",e.supports.immediateStop,"Immediate human stop is supported"),b(r,"privacy.redaction",e.supports.sensitiveRegionRedaction,"Sensitive-region redaction is supported")),b(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 ut(e){let r=xe(e).checks.filter(n=>n.status==="fail");if(r.length>0)throw new i("AUTOMATION_OPERATION_UNSUPPORTED",r.map(n=>`${n.id}: ${n.message}`).join("; "))}function y(e,t,r,n,o){let a=t.has(n);b(e,`capability.${n}`,r===a,r===a?`${o} declaration matches the operation catalog`:`${o} declaration does not match ${n}`)}function pt(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 b(e,t,r,n){e.push({id:t,status:r?"pass":"fail",message:n})}var ft=6e4,mt=48*1024*1024,re=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(t){if(this.endpoint=It(t.baseUrl),this.token=At(t.token),this.timeoutMs=Xe(t.timeoutMs??ft,1e3,3e5,"timeoutMs"),this.maxResponseBytes=Xe(t.maxResponseBytes??mt,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=t.fetch??globalThis.fetch,typeof this.fetchImpl!="function")throw new i("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}preflight(t,r){return this.request("preflight","POST",t,r)}execute(t,r,n,o){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 a=new AbortController,c=bt(o,a),s=setTimeout(()=>a.abort(new Error("automation transport timeout")),this.timeoutMs);s.unref?.();try{let l=new URL(t,this.endpoint),d=await this.fetchImpl(l,{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:a.signal}),p=await ht(d,this.maxResponseBytes);if(!d.ok){let m=gt(p);throw new i("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${t}: ${m.message}`,{status:d.status,route:t,adapterCode:m.code})}if(!ne(p)||p.ok!==!0||!("result"in p))throw new i("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${t} envelope`);return p.result}catch(l){if(l instanceof i)throw l;let d=o?.aborted;throw new i(d?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",d?"Automation transport was stopped":`XENO Browser ${t} transport failed`,{route:t},{cause:l})}finally{clearTimeout(s),c()}}};function It(e){let t;try{t=new URL(e)}catch(n){throw new i("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL is invalid",void 0,{cause:n})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new i("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires HTTP(S)");if(t.username||t.password||t.search||t.hash)throw new i("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 i("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport must use a loopback host");if(!t.port)throw new i("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires an explicit port");return t.pathname="/v1/automation/",t}function At(e){if(typeof e!="string"||e.length<32||e.length>512||/\s/.test(e))throw new i("AUTOMATION_TRANSPORT_ERROR","XENO Browser session token is invalid");return e}async function ht(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new i("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);if(e.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new i("AUTOMATION_RESPONSE_INVALID","XENO Browser response is not application/json");if(!e.body)throw new i("AUTOMATION_RESPONSE_INVALID","XENO Browser response body is missing");let o=e.body.getReader(),a=[],c=0;for(;;){let{done:d,value:p}=await o.read();if(d)break;if(c+=p.byteLength,c>t)throw await o.cancel("response too large"),new i("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);a.push(p)}let s=new Uint8Array(c),l=0;for(let d of a)s.set(d,l),l+=d.byteLength;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch(d){throw new i("AUTOMATION_RESPONSE_INVALID","XENO Browser response contains invalid JSON",void 0,{cause:d})}}function gt(e){return ne(e)&&ne(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 bt(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 Xe(e,t,r,n){if(!Number.isSafeInteger(e)||e<t||e>r)throw new i("AUTOMATION_TRANSPORT_ERROR",`${n} must be an integer from ${t} to ${r}`);return e}function ne(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var L=require("node:crypto");var Et=8*1024*1024,wt=4;function yt(e){return Lt(e.operations??_).map(r=>vt(r,e.runtime))}function vt(e,t){return{definition:{name:e,description:Rt(e),input_schema:Tt(e)},projectPolicyInput(r){let n=Pt(e,r),o=Ot(e,r);return{observabilityInput:n,permissionInput:o,permissionPreview:xt(e,r),approvalKey:`xeno-automation:${e}:${Dt(r)}`,riskLevel:Nt(e)}},async execute(r,n){let o=n?.authorization;if(!o||o.toolName!==e)return{success:!1,output:"",error:"Governed automation requires a host-issued authorization receipt",errorCode:"AUTOMATION_AUTHORIZATION_RECEIPT_REQUIRED",retryable:!1};let a=n.operationId??`automation_${(0,L.randomUUID)()}`,c=ie(e,r);n.reportProgress?.({activity:"state",message:`Authorizing ${e}`});try{let s=await t.execute({operation:e,governingToolName:e,operationId:a,idempotencyKey:a,parameters:structuredClone(r),...c?{declaredTarget:c}:{},authorization:o,...n.signal?{signal:n.signal}:{},...n.reportProgress?{reportProgress:n.reportProgress}:{}}),l=s.status==="ok";return{success:l,output:JSON.stringify(Xt(s)),...l?{}:{error:s.error?.message??`Governed automation ended with ${s.status}`,errorCode:s.error?.code??`AUTOMATION_${s.status.toUpperCase().replaceAll("-","_")}`},assistantContent:kt(s),evidence:s.artifacts.map(d=>({id:d.artifactId,kind:"artifact",status:s.status==="evidence-incomplete"?"failed":"verified",observedAt:d.updatedAt??d.createdAt,operationId:a,detail:{artifact_kind:d.kind,revision:d.revision,sensitivity:d.sensitivity}})),retryable:s.error?.retryable??!1}}catch(s){let l=n.signal?.aborted===!0;return{success:!1,output:"",error:l?"Governed automation was stopped":Ut(s),errorCode:l?"AUTOMATION_CANCELLED":Mt(s),retryable:!l}}}}}function Tt(e){let t=St(e),r=Ct(e);return{type:"object",properties:t,...r.length>0?{required:r}:{},...e==="browser.locate"?{oneOf:[{required:["selector"]},{required:["text"]}]}:{},additionalProperties:!1}}function St(e){let t=(c,s=8192)=>({type:"string",minLength:1,maxLength:s,description:c}),r={type:"number"},n={type:"boolean"},o={type:"object",properties:{x:r,y:r},required:["x","y"],additionalProperties:!1},a={deviceId:t("Target xeno-use device ID.",256),applicationId:t("Expected or launch-target application ID.",512),displayId:t("Target display ID.",256)};switch(e){case"browser.navigate":return{url:t("Destination URL."),waitUntil:{enum:["load","none"]},tabId:t("Expected active tab ID. Hosts with multiple visible tabs should require this.",256)};case"browser.wait":return{until:{enum:["load","ms"]},value:{type:"integer",minimum:0,maximum:6e4}};case"browser.snapshot":return{mode:{enum:["text","html","markdown","a11y"]},tabId:t("Expected active tab ID.",256)};case"browser.screenshot":return{tabId:t("Expected active tab ID.",256)};case"browser.locate":return{selector:t("CSS selector."),text:t("Visible text to locate.")};case"browser.click":return{selector:t("CSS selector returned by browser.snapshot or browser.locate."),tabId:t("Expected active tab ID.",256)};case"browser.type":return{selector:t("CSS selector."),text:{type:"string",maxLength:65536},clear:n,submit:n,tabId:t("Expected active tab ID.",256)};case"browser.key":return{combo:t("Key combo such as Control+a or Enter.",256),tabId:t("Expected active tab ID.",256)};case"browser.select":return{selector:t("CSS selector."),value:t("Option value."),tabId:t("Expected active tab ID.",256)};case"browser.scroll":return{selector:t("Optional CSS selector."),dx:r,dy:r,tabId:t("Expected active tab ID.",256)};case"browser.tabs.open":return{url:t("URL to open in an isolated browser tab.")};case"browser.tabs.close":return{tabId:t("Tab ID to close.",256)};case"browser.console.read":case"browser.network.read":case"browser.page-errors.read":return{limit:{type:"integer",minimum:1,maximum:1e3},clear:n,tabId:t("Expected active tab ID.",256)};case"browser.storage.read":return{tabId:t("Expected active tab ID.",256)};case"browser.upload":return{selector:t("File input or drop-target selector."),backendNodeId:{type:"integer",minimum:1},hostPaths:{type:"array",items:t("Host file path.",32768),minItems:1,maxItems:64},drop:n,tabId:t("Expected active tab ID.",256)};case"browser.download":return{toPath:t("Approved destination path.",32768),trigger:{type:"object",properties:{url:t("Download URL."),selector:t("Download trigger selector.")},oneOf:[{required:["url"]},{required:["selector"]}],additionalProperties:!1},tabId:t("Expected active tab ID.",256)};case"browser.record.start":return{maxDurationMs:{type:"integer",minimum:1e3,maximum:6e4},intervalMs:{type:"integer",minimum:100,maximum:5e3},tabId:t("Expected active tab ID.",256)};case"browser.record.stop":return{tabId:t("Expected active tab ID.",256)};case"computer.observe":case"computer.screenshot":case"computer.window-state":return a;case"computer.point":return{...a,point:o,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.click":return{...a,point:o,button:{enum:["left","right","middle"]},modifiers:_t()};case"computer.double-click":case"computer.right-click":return{...a,point:o};case"computer.drag":return{...a,from:o,to:o,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.type":return{...a,text:{type:"string",maxLength:65536}};case"computer.key":return{...a,combo:t("Key combo such as Control+a or Enter.",256)};case"computer.scroll":return{...a,at:o,delta:o};case"computer.wait":return{...a,milliseconds:{type:"integer",minimum:0,maximum:3e5}};case"computer.launch":return{...a,applicationId:t("Explicitly allowlisted application ID.",512)};case"browser.back":case"browser.forward":case"browser.reload":return{tabId:t("Expected active tab ID.",256)};case"browser.tabs.list":return{}}}function Ct(e){switch(e){case"browser.navigate":case"browser.tabs.open":return["url"];case"browser.click":return["selector"];case"browser.type":return["selector","text"];case"browser.key":return["combo"];case"browser.select":return["selector","value"];case"browser.upload":return["hostPaths"];case"browser.download":return["toPath","trigger"];case"computer.point":case"computer.click":case"computer.double-click":case"computer.right-click":return["point"];case"computer.drag":return["from","to"];case"computer.type":return["text"];case"computer.key":return["combo"];case"computer.scroll":return["at","delta"];case"computer.launch":return["applicationId"];default:return[]}}function _t(){return{type:"object",properties:{shift:{type:"boolean"},ctrl:{type:"boolean"},alt:{type:"boolean"},meta:{type:"boolean"}},additionalProperties:!1}}function Rt(e){let t=I(e),r=e.split(".").slice(1).join(" ");return`${t.effect==="act"?"Act on":"Inspect"} the ${t.surface} using governed ${r} automation. The host requires policy approval, an exact capability lease, target-bound preflight, and durable evidence.`}function Nt(e){return I(e).effect==="observe"?e==="browser.navigate"||e==="browser.tabs.open"?"medium":"low":["browser.type","browser.upload","browser.download","computer.type","computer.key","computer.launch"].includes(e)?"high":"medium"}function Ot(e,t){let r=ie(e,t),n={operation:e};r&&(n.target=r);for(let o of["selector","clear","submit","combo","value","dx","dy","point","from","to","at","delta","milliseconds"])t[o]!==void 0&&(n[o]=structuredClone(t[o]));return typeof t.text=="string"&&(n.text=`[redacted ${t.text.length} characters]`),Array.isArray(t.hostPaths)&&(n.hostPaths=t.hostPaths.map(()=>"[redacted host path]")),typeof t.toPath=="string"&&(n.toPath="[redacted destination path]"),n}function Pt(e,t){let r=structuredClone(t);return typeof r.text=="string"&&(r.text=`[redacted ${r.text.length} characters]`),Array.isArray(r.hostPaths)&&(r.hostPaths=r.hostPaths.map(()=>"[redacted host path]")),typeof r.toPath=="string"&&(r.toPath="[redacted destination path]"),Le(r.trigger)&&typeof r.trigger.url=="string"&&(r.trigger={...r.trigger,url:ke(r.trigger.url)}),typeof r.url=="string"&&(r.url=ke(r.url)),{operation:e,...r}}function xt(e,t){let r=ie(e,t),n=r?.url??r?.applicationId??r?.deviceId??r?.tabId??r?.resource??"current target";return`${e} on ${n}`}function ie(e,t){let r={};return typeof t.url=="string"&&(r.url=t.url),typeof t.tabId=="string"&&(r.tabId=t.tabId),typeof t.deviceId=="string"&&(r.deviceId=t.deviceId),typeof t.applicationId=="string"&&(r.applicationId=t.applicationId),typeof t.displayId=="string"&&(r.displayId=t.displayId),(e==="browser.navigate"||e==="browser.tabs.list"||e==="browser.tabs.open")&&(r.resource="browser-tabs"),Object.keys(r).length>0?r:void 0}function Xt(e){return{operationId:e.operationId,status:e.status,effect:e.effect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:e.adapter,target:e.target,...e.data!==void 0?{data:e.data}:{},artifacts:e.artifacts.map(t=>({artifactId:t.artifactId,revision:t.revision,kind:t.kind,title:t.title,state:t.state,mediaType:t.mediaType,sensitivity:t.sensitivity,hash:t.content.hash,sizeBytes:t.content.sizeBytes})),lease:e.lease,...e.error?{error:e.error}:{}}}function kt(e){let t=[];for(let r of e.artifacts){if(t.length>=wt||!r.mediaType.startsWith("image/"))continue;let n=r.content.storage;if(n.type!=="inline"||typeof n.base64!="string")continue;let o=Math.floor(n.base64.length*.75);o<=0||o>Et||t.push({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${n.base64}`,detail:"high"}})}return t}function Lt(e){let t=new Set(_),r=new Set;for(let n of e){if(!t.has(n))throw new TypeError(`Unsupported XENO automation operation: ${String(n)}`);r.add(n)}return Array.from(r)}function Dt(e){return(0,L.createHash)("sha256").update(oe(e)).digest("hex")}function oe(e){return Array.isArray(e)?`[${e.map(oe).join(",")}]`:Le(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${oe(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function ke(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid URL]"}}function Ut(e){return e instanceof Error?e.message:String(e)}function Mt(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:"AUTOMATION_EXECUTION_FAILED"}function Le(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}0&&(module.exports={XENO_AUTOMATION_OPERATIONS,XENO_AUTOMATION_PROTOCOL_VERSION,XenoAutomationError,XenoGovernedAutomationExecutor,XenoLoopbackAutomationAdapter,assertRequiredXenoAutomationEvidence,assertValidXenoAutomationAdapterManifest,assertValidXenoAutomationRequest,assertXenoAutomationAdapterConformant,assertXenoAutomationAuthority,buildXenoAutomationCapabilityUse,createXenoAutomationConformanceReport,createXenoGovernedAutomationTools,describeXenoAutomationOperation,isXenoAutomationOperation,materializeXenoAutomationEvidence,persistXenoAutomationEvidence,resolveXenoAutomationEvidencePolicy});
|
|
925
|
+
`;function Kt(){let e=process.env.SystemRoot??process.env.WINDIR;if(e){let t=(0,at.join)(e,"Microsoft.NET","Framework64","v4.0.30319","csc.exe");if((0,ee.existsSync)(t))return t;let r=(0,at.join)(e,"Microsoft.NET","Framework","v4.0.30319","csc.exe");if((0,ee.existsSync)(r))return r}return null}var ct=require("node:child_process"),V=require("node:fs"),K=require("node:path"),Qt="XENO_BWRAP_PROFILE_OK",Yt=5e3,st;function Zt(e){try{return!(0,V.existsSync)(e)||!(0,V.statSync)(e).isFile()?null:((0,V.accessSync)(e,V.constants.X_OK),(0,V.realpathSync)(e))}catch{return null}}function Nn(){let e=process.env.XENO_BWRAP_PATH?.trim();if(e)return Zt((0,K.isAbsolute)(e)?e:(0,K.resolve)(e));let t=["/usr/bin/bwrap","/bin/bwrap",...(process.env.PATH??"").split(K.delimiter).filter(Boolean).map(r=>(0,K.join)(r,"bwrap"))];for(let r of new Set(t)){let n=Zt(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 ${Qt}`]}function er(){let e=[process.platform,process.env.XENO_BWRAP_PATH??"",process.env.PATH??""].join("\0");if(st?.key===e)return{...st.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=Nn();if(!r)t={available:!1,reason:"bubblewrap is not installed or is not executable."};else{let n=(0,ct.spawnSync)(r,["--version"],{encoding:"utf8",timeout:Yt}),o=(0,ct.spawnSync)(r,kn(),{encoding:"utf8",timeout:Yt,env:process.env}),i=n.status===0?n.stdout.trim():void 0;if(o.status===0&&o.stdout===Qt)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 st={key:e,capability:t},{...t}}var le=require("node:crypto"),Me=require("node:fs"),rr=require("node:path"),dt="xeno.containment-certification.v1",tr=512*1024,Xn=744*60*60*1e3,nr=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 Dn(e){let t={...e};return delete t.signature,Buffer.from(JSON.stringify(ut(t)),"utf8")}function or(e,t,r=new Date){if(!(0,rr.isAbsolute)(e.manifestPath))throw new I("manifestPath must be absolute");Ee(e.candidateSha256,"candidateSha256");let n=(0,Me.statSync)(e.manifestPath);if(!n.isFile())throw new I("manifestPath must reference a regular file");if(n.size<=0||n.size>tr)throw new I(`manifest size must be between 1 and ${tr} bytes`);let o=(0,Me.readFileSync)(e.manifestPath),i;try{i=JSON.parse(o.toString("utf8"))}catch{throw new I("manifest is not valid JSON")}let a=Ln(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 s=lt(a.issuedAt,"issuedAt"),c=lt(a.expiresAt,"expiresAt");if(c<=s)throw new I("expiresAt must be later than issuedAt");if(c-s>Xn)throw new I("certification lifetime exceeds 31 days");if(r.getTime()<s-5*6e4)throw new I("certification is not active yet");if(r.getTime()>=c)throw new I("certification has expired");for(let A of nr)if(a.conformance.checks[A]!==!0)throw new I(`required conformance check did not pass: ${A}`);if(!a.approvals.some(A=>A.role==="security-reviewer"&&A.subject!==a.issuedBy))throw new I("an independent security-reviewer approval is required");let d=e.trustedPublicKeys[a.signature.keyId];if(!d)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 g=!1;try{g=(0,le.verify)(null,Dn(a),(0,le.createPublicKey)(d),y)}catch{throw new I("signature key or value is invalid")}if(!g)throw new I("signature verification failed");return{manifest:a,manifestSha256:(0,le.createHash)("sha256").update(o).digest("hex")}}function Ln(e){let t=Y(e,"manifest");if(t.schemaVersion!==dt)throw new I(`schemaVersion must be ${dt}`);let r=b(t.certificationId,"certificationId"),n=Y(t.candidate,"candidate"),o=Y(t.adapter,"adapter"),i=Y(t.platform,"platform"),a=Y(t.conformance,"conformance"),s=Y(a.checks,"conformance.checks"),c=Y(t.signature,"signature"),d=t.approvals;if(!Array.isArray(d)||d.length===0)throw new I("approvals must contain at least one approval");let y=d.map((k,w)=>{let j=Y(k,`approvals[${w}]`),ye=b(j.role,`approvals[${w}].role`);if(ye!=="security-reviewer"&&ye!=="release-reviewer")throw new I(`approvals[${w}].role is invalid`);let De=ye;lt(b(j.approvedAt,`approvals[${w}].approvedAt`),`approvals[${w}].approvedAt`);let be=b(j.approvalSha256,`approvals[${w}].approvalSha256`);return Ee(be,`approvals[${w}].approvalSha256`),{subject:b(j.subject,`approvals[${w}].subject`),role:De,approvedAt:j.approvedAt,approvalArtifactId:b(j.approvalArtifactId,`approvals[${w}].approvalArtifactId`),approvalSha256:be}}),g=b(o.backend,"adapter.backend");if(g!=="processcontainer"&&g!=="bubblewrap"&&g!=="seatbelt")throw new I("adapter.backend is invalid");let A=b(i.os,"platform.os"),m=b(i.arch,"platform.arch");if(b(c.algorithm,"signature.algorithm")!=="ed25519")throw new I("signature.algorithm must be ed25519");let v={};for(let k of nr){if(s[k]!==!0)throw new I(`conformance.checks.${k} must be true`);v[k]=!0}let T=b(o.nativeBinarySha256,"adapter.nativeBinarySha256"),U=b(n.sha256,"candidate.sha256"),L=b(a.reportSha256,"conformance.reportSha256");if(Ee(T,"adapter.nativeBinarySha256"),Ee(U,"candidate.sha256"),Ee(L,"conformance.reportSha256"),a.passed!==!0)throw new I("conformance.passed must be true");return{schemaVersion:dt,certificationId:r,candidate:{product:b(n.product,"candidate.product"),version:b(n.version,"candidate.version"),sha256:U},adapter:{name:o.name==="microsoft-mxc"?"microsoft-mxc":Mn(),version:b(o.version,"adapter.version"),backend:g,isolationTier:b(o.isolationTier,"adapter.isolationTier"),nativeBinarySha256:T},platform:{os:A,arch:m},conformance:{reportArtifactId:b(a.reportArtifactId,"conformance.reportArtifactId"),reportSha256:L,passed:!0,checks:v},issuedAt:b(t.issuedAt,"issuedAt"),expiresAt:b(t.expiresAt,"expiresAt"),issuedBy:b(t.issuedBy,"issuedBy"),approvals:y,signature:{algorithm:"ed25519",keyId:b(c.keyId,"signature.keyId"),value:b(c.value,"signature.value")}}}function Mn(){throw new I("adapter.name must be microsoft-mxc")}function Y(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new I(`${t} must be an object`);return e}function b(e,t){if(typeof e!="string"||e.trim().length===0)throw new I(`${t} must be a non-empty string`);return e}function Ee(e,t){if(!/^[a-f0-9]{64}$/i.test(e))throw new I(`${t} must be a SHA-256 hex digest`)}function lt(e,t){let r=Date.parse(e);if(!Number.isFinite(r))throw new I(`${t} must be an ISO timestamp`);return r}function ut(e){return Array.isArray(e)?e.map(ut):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ut(r)])):e}var te=require("node:crypto"),h=require("node:fs"),sr=require("node:os"),P=require("node:path"),mt=require("node:child_process"),cr=require("node:url");var ir="microsoft-mxc",ve="0.7.0";var Un="@microsoft/mxc-sdk",$n="sha512-EWhz2pKkcPluZHAOI1yneV+JK0NO/3hdh7nABBb0x4PjyUWMeSWPTBAjtIu+BhtMYOqlaijSPZMZ0Hs/J4ZL4A==",Ua=10*6e4,Vn=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"}),$a=Object.freeze({"win32-x64-wxc-host-prep.exe":"531fb3cdb4b0c964908fd71b71d40961417afb399cbab72f92a25e95309a6416","win32-arm64-wxc-host-prep.exe":"3ef702332286a39153fc259310b5021e3de3c191751d7522684f6475f73af5ef"});function Bn(e){return e.some(t=>t.includes("wxc-host-prep prepare-system-drive")||t.includes("wxc-host-prep prepare-null-device"))}function Fn(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=Vn[`${e}-${t}-${r}`];return n?{platform:e,arch:t,binaryName:r,sha256:n}:void 0}var pt;function dr(e={}){if(pt&&!e.refresh)return ar(pt);let t=jn();return pt=t,ar(t)}function jn(){let e=process.platform,t=process.arch,r=Fn(e,t),n=!!r,o=Hn();if(!o)return n?x(`reviewed MXC ${ve} native assets are not installed`,!1,!0):x(ft(e,t),!1,!1);let i=(0,P.dirname)(o);if(!n)return x(ft(e,t),!0,!1,{packageRoot:i});let a="";try{let A=JSON.parse((0,h.readFileSync)(o,"utf8"));if(a=String(A.version??""),A.sourcePackage?.name!==Un||A.sourcePackage.version!==ve||A.sourcePackage.integrity!==$n)return x("MXC native asset provenance metadata is invalid",!0,!0,{packageRoot:i})}catch{return x("MXC package metadata is unreadable",!0,!0,{packageRoot:i})}if(a!==ve)return x(`MXC version ${a||"unknown"} is installed; XENO requires exactly ${ve}`,!0,!0,{packageRoot:i});if(!r)return x(ft(e,t),!0,!1,{packageRoot:i});let s=(0,P.join)(i,"bin",t,r.binaryName);if(!(0,h.existsSync)(s)||!(0,h.statSync)(s).isFile())return x(`MXC native binary is missing: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a});let c=s;try{c=Gn(s,r)}catch(A){return x(`MXC packaged native binary could not be materialized: ${A instanceof Error?A.message:String(A)}`,!0,!0,{packageRoot:i,version:a})}if(e!=="win32")try{(0,h.accessSync)(c,h.constants.X_OK)}catch{return x(`MXC native binary is not executable: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a})}let d=(0,te.createHash)("sha256").update((0,h.readFileSync)(c)).digest("hex"),y=r.sha256;if(!y||d!==y)return x(`MXC native binary digest is not trusted for ${e}/${t}`,!0,!0,{packageRoot:i,version:a});if(e==="win32"){let A=(0,mt.spawnSync)(c,["--probe"],{encoding:"utf8",timeout:5e3,windowsHide:!0});if(A.error||A.status!==0)return x(`MXC native probe failed: ${A.error?.message??(A.stderr.trim()||`exit ${A.status}`)}`,!0,!0,{packageRoot:i,version:a});let m;try{m=JSON.parse(A.stdout)}catch{return x("MXC native probe returned invalid JSON",!0,!0,{packageRoot:i,version:a})}let N=typeof m.tier=="string"?m.tier:"unknown",v=Array.isArray(m.warnings)?m.warnings.filter(L=>typeof L=="string"):[],T=m.probes&&typeof m.probes=="object"?m.probes:void 0,U=T?.uiCapabilities&&typeof T.uiCapabilities=="object"?Object.fromEntries(Object.entries(T.uiCapabilities).filter(L=>typeof L[1]=="boolean")):void 0;return{installed:!0,supported:!0,available:!0,name:ir,version:a,packageRoot:i,nativeBinaryPath:c,nativeBinarySha256:d,backend:"processcontainer",isolationTier:N,platform:e,arch:t,warnings:v,needsHostPreparation:Bn(v),reason:`MXC ${a} processcontainer is installed (${N}).`,...U?{uiCapabilities:U}:{}}}if(e==="linux"){let A=(0,mt.spawnSync)("bwrap",["--version"],{encoding:"utf8",timeout:5e3});if(A.error||A.status!==0)return x("MXC requires bubblewrap on PATH for the stable Linux process adapter",!0,!0,{packageRoot:i,version:a})}let g=e==="darwin"?"seatbelt":"bubblewrap";return{installed:!0,supported:!0,available:!0,name:ir,version:a,packageRoot:i,nativeBinaryPath:c,nativeBinarySha256:d,backend:g,isolationTier:g,platform:e,arch:t,warnings:[],needsHostPreparation:!1,reason:`MXC ${a} ${g} adapter is installed.`}}function Hn(){let e=process.resourcesPath,t=process.env.XENO_MXC_ASSET_ROOT?.trim(),r=typeof __dirname=="string"?__dirname:(0,P.dirname)((0,cr.fileURLToPath)(void 0)),n=[...e&&(0,P.isAbsolute)(e)?[(0,P.join)(e,"mxc","package.json")]:[],...t&&(0,P.isAbsolute)(t)?[(0,P.join)(t,"package.json")]:[],(0,P.join)(r,"..","native","mxc","package.json"),(0,P.join)(r,"..","..","native","mxc","package.json")];for(let o of n){if(!(0,h.existsSync)(o))continue;let i=(0,h.lstatSync)(o);if(!(!i.isFile()||i.isSymbolicLink()))return(0,h.realpathSync)(o)}}function Gn(e,t){if(!!!process.pkg)return e;let n=(0,P.join)((0,sr.tmpdir)(),"xeno-mxc",ve,t.sha256);(0,h.mkdirSync)(n,{recursive:!0,mode:448});let o=(0,P.join)(n,t.binaryName);if((0,h.existsSync)(o)){let c=(0,h.lstatSync)(o);if(!c.isFile()||c.isSymbolicLink())throw new Error("materialized MXC path is not a regular file");if((0,te.createHash)("sha256").update((0,h.readFileSync)(o)).digest("hex")!==t.sha256)throw new Error("materialized MXC binary digest is invalid");return process.platform!=="win32"&&(0,h.chmodSync)(o,448),o}let i=(0,h.readFileSync)(e);if((0,te.createHash)("sha256").update(i).digest("hex")!==t.sha256)throw new Error("embedded MXC binary digest is invalid");let s=`${o}.${process.pid}.${(0,te.randomUUID)()}.tmp`;(0,h.writeFileSync)(s,i,{flag:"wx",mode:448});try{(0,h.renameSync)(s,o)}catch(c){try{(0,h.unlinkSync)(s)}catch{}if(!(0,h.existsSync)(o))throw c;let d=(0,h.lstatSync)(o);if((d.isFile()&&!d.isSymbolicLink()?(0,te.createHash)("sha256").update((0,h.readFileSync)(o)).digest("hex"):"")!==t.sha256)throw c}return process.platform!=="win32"&&(0,h.chmodSync)(o,448),o}function ft(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 x(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 re=class extends Error{code;constructor(t,r){super(`${t}: ${r}`),this.name="ExecutionSecurityError",this.code=t}},Wn=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),qn=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!0,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!0,environmentSanitization:!0}),zn=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),Jn=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!0,networkIsolation:!0,inheritedHandleAllowlist:!0,environmentSanitization:!0}),gt=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0});function Kn(e){let t=e?.executionLevel;if(e?.requireOsContainment&&t&&t!=="contained")throw new re("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 Yn(e){return e?.trustMode??"trusted-workspace"}function lr(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:{...Wn},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"&&Kt())return{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"windows-restricted-token-job",isolation:"process-hardening",certified:!0,capabilities:{...qn},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=er();return o.available?{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"linux-bubblewrap",isolation:"process-hardening",certified:!0,capabilities:{...zn},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:{...gt},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:{...gt},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 Ue(t,`Native containment for ${t} cannot be certified from a ${process.platform} host.`);let n=dr();if(!n.available||!n.name||!n.version||!n.backend||!n.isolationTier||!n.nativeBinarySha256||!n.platform||!n.arch)return Ue(t,n.reason,n);if(!r)return Ue(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=or(r,o);return{available:!0,requestedLevel:e,effectiveLevel:"contained",adapter:"microsoft-mxc",isolation:"filesystem-network",certified:!0,capabilities:{...Jn},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 Ue(t,o instanceof Error?o.message:"Containment certification validation failed.",n)}}function Zn(e,t){if(Yn(e)==="untrusted"&&t!=="contained")throw new re("UNTRUSTED_EXECUTION_DISABLED","Untrusted execution requires certified contained mode; policy-only and process-hardened modes are trusted-workspace features.")}function Qn(e){let t=e.requestedLevel==="contained"?"CONTAINMENT_UNAVAILABLE":"PROCESS_HARDENING_UNAVAILABLE";return new re(t,e.reason)}function ur(e,t=process.platform){let r=Kn(e);Zn(e,r);let n=lr(r,t,e.containmentCertification);if(!n.available)throw Qn(n);if(r==="process-hardened"&&e.allowNetwork!==!0)throw new re("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=Q(e.workingDirectory??process.cwd()).canonicalPath,i=[...e.allowedDirectories,...e.temporaryDirectories??[]];if(!Jt(o,i))throw new re("SECURITY_POLICY_INVALID",`Secured process working directory is outside the canonical allowed directories: ${o}`)}return n}function Ue(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:{...gt},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 Ar=1,S=class extends Error{constructor(r,n){super(n);this.code=r;this.name="XenoSecureExecutionContractError"}code};function hr(e){let t=e.platform??process.platform,r=e.policy.executionLevel??(e.policy.requireOsContainment?"contained":"policy-only"),n=e.adapterStatus??ur(e.policy,t);if(!n.available||n.effectiveLevel==="unavailable")throw new S("SECURITY_CONTRACT_UNAVAILABLE",n.reason);if(n.requestedLevel!==r||n.effectiveLevel!==r)throw new S("SECURITY_CONTRACT_INVALID","Execution adapter status does not match the requested security level");let i=(e.now??(()=>new Date().toISOString()))(),a=Se([...e.policy.allowedDirectories,...e.policy.temporaryDirectories??[],e.policy.workingDirectory??process.cwd()],e.policy.workingDirectory,t),s=Se(e.filesystem?.readRoots??a,e.policy.workingDirectory,t),c=e.profile.capabilities.permissionProfile==="read-only",d=c?[]:Se(e.filesystem?.writeRoots??a,e.policy.workingDirectory,t),y=c?[]:Se(e.filesystem?.executeRoots??a,e.policy.workingDirectory,t),g=Se(e.filesystem?.deniedRoots??e.policy.deniedDirectories??[],e.policy.workingDirectory,t),A=n.capabilities.filesystemIsolation?"os":"policy",m=n.capabilities.networkIsolation?"os":r==="process-hardened"?"none":"policy",N=r==="contained"?"deny":e.network?.default??(e.policy.allowNetwork?"allow":"deny"),v=m==="none";if(v&&(!e.policy.allowNetwork||N!=="allow"))throw new S("SECURITY_CONTRACT_INVALID","An adapter without network isolation requires explicit unrestricted-network acknowledgement");if(c&&(e.browser?.mode==="act"||e.computer?.mode==="act"||(e.secrets?.length??0)>0))throw new S("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 S("SECURITY_CONTRACT_INVALID","Requested certification artifact does not match the adapter certification");if(r==="contained"&&!T)throw new S("SECURITY_CONTRACT_INVALID","Contained execution requires a candidate-bound certification artifact");let U=ue(e.environment?.deniedKeys??[]),L=new Set(U),k=Te(e.browser?.allowedDomains??[]),w=Te(e.browser?.readAllowedDomains??k),j=Te(e.browser?.actAllowedDomains??k),ye=Te([...k,...w,...j]),De={schemaVersion:Ar,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:A,readRoots:s,writeRoots:d,executeRoots:y,deniedRoots:g},network:{enforcement:m,default:N,allowDestinations:pr(e.network?.allowDestinations??[]),denyDestinations:pr(e.network?.denyDestinations??[]),dns:e.network?.dns??((e.network?.allowDestinations?.length??0)>0||N==="allow"?"system":"disabled"),...e.network?.proxyUrl?{proxyUrl:e.network.proxyUrl}:{},downloads:e.network?.downloads??"deny",acknowledgedUnrestricted:v},process:{processTreeControl:n.capabilities.processTreeControl,cleanup:n.capabilities.processTreeControl?"kill-tree":"best-effort",inheritedHandleAllowlist:n.capabilities.inheritedHandleAllowlist,...oo(e.process)},environment:{inheritance:e.environment?.inheritance??"allowlist",allowedKeys:ue(e.environment?.allowedKeys??e.policy.containedEnvironmentAllowlist??[]).filter(bn=>!L.has(bn)),deniedKeys:U},secrets:no(e.secrets??[]),externalActions:{default:e.profile.capabilities.externalActions.default,overrides:{...e.profile.capabilities.externalActions.overrides},requireCurrentTurnApproval:ue(e.profile.capabilities.externalActions.requireCurrentTurnApproval),requireCapabilityLease:!0},browser:{mode:e.browser?.mode??"none",profile:e.browser?.profile??"ephemeral",allowedDomains:ye,readAllowedDomains:w,actAllowedDomains:j,deniedDomains:Te(e.browser?.deniedDomains??[]),allowedSchemes:to(e.browser?.allowedSchemes??["https"]),allowedPorts:ro(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:ue(e.computer?.allowedApplications??[]),sensitiveRegionRedaction:e.computer?.sensitiveRegionRedaction??!0,humanStopRequired:e.computer?.humanStopRequired??!0},capabilityLeaseIds:ue(e.capabilityLeaseIds??[]),adapter:{id:n.adapter,version:e.adapterVersion??n.adapterVersion??"1",platform:t,architecture:e.architecture??(0,gr.arch)(),certified:n.certified,...T?{certificationArtifactId:T}:{},capabilities:{...n.capabilities},limitations:[...n.limitations]},...e.auditEventIds?{auditEventIds:ue(e.auditEventIds)}:{}},be={...De,fingerprint:Ir(De)};return ht(be),be}function eo(e){let t=[];if(!e||typeof e!="object")return["Contract must be an object"];if(e.schemaVersion!==Ar&&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"),fr(e.createdAt)||t.push("createdAt must be an ISO 8601 timestamp"),e.expiresAt&&(!fr(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,Ir(r)!==e.fingerprint&&t.push("Contract fingerprint does not match content")}return t}function ht(e){let t=eo(e);if(t.length>0){let r=t.includes("Contract fingerprint does not match content");throw new S(r?"SECURITY_CONTRACT_FINGERPRINT_MISMATCH":"SECURITY_CONTRACT_INVALID",t.join("; "))}}function Ir(e){return(0,mr.createHash)("sha256").update(JSON.stringify(At(e))).digest("hex")}function ue(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort().map(t=>t)}function Se(e,t,r){return[...new Set(e.map(n=>Q(n,{baseDirectory:t,platform:r}).canonicalPath))].sort((n,o)=>n.localeCompare(o))}function pr(e){let t=new Map;for(let r of e){if(!r.host?.trim())throw new S("SECURITY_CONTRACT_INVALID","Network destinations require a host");if(r.host.includes("*"))throw new S("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 S("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 Te(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 S("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 S("SECURITY_CONTRACT_INVALID",`Browser domain rule is invalid: ${r}`);t.add(n)}return[...t].sort((r,n)=>r.localeCompare(n))}function to(e){for(let t of e)if(t!=="http"&&t!=="https")throw new S("SECURITY_CONTRACT_INVALID",`Browser scheme is invalid: ${t}`);return[...new Set(e)].sort()}function ro(e){for(let t of e)if(!Number.isInteger(t)||t<1||t>65535)throw new S("SECURITY_CONTRACT_INVALID",`Browser port is invalid: ${t}`);return[...new Set(e)].sort((t,r)=>t-r)}function no(e){let t=new Map;for(let r of e){if(!r.secretId?.trim())throw new S("SECURITY_CONTRACT_INVALID","Secret projections require an ID");if(t.has(r.secretId))throw new S("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 oo(e){let t={};for(let[r,n]of Object.entries(e??{})){if(!Number.isSafeInteger(n)||Number(n)<1)throw new S("SECURITY_CONTRACT_INVALID",`${r} must be a positive safe integer`);Object.assign(t,{[r]:n})}return t}function At(e){return Array.isArray(e)?e.map(At):!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,At(r)]))}function fr(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}var io=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,yr=1048576;function yt(e){(!e||typeof e!="object")&&H("Automation request must be an object"),e.protocolVersion!==1&&H("Unsupported automation protocol version"),pe(e.operationId,"operationId"),pe(e.idempotencyKey,"idempotencyKey"),pe(e.capabilityLeaseId,"capabilityLeaseId"),pe(e.governingToolName,"governingToolName"),(!Number.isSafeInteger(e.expectedLeaseVersion)||e.expectedLeaseVersion<1)&&H("expectedLeaseVersion must be a positive safe integer"),Sr(e.requestedAt)||H("requestedAt must be an ISO 8601 timestamp"),Le(e.operation)||H(`Unsupported automation operation: ${e.operation}`),(!e.parameters||typeof e.parameters!="object"||Array.isArray(e.parameters))&&H("parameters must be a JSON object");let t;try{t=Buffer.byteLength(JSON.stringify(e.parameters),"utf8")}catch(r){throw new l("AUTOMATION_REQUEST_INVALID","parameters must be serializable JSON",void 0,{cause:r})}if(t>yr&&H(`parameters exceed ${yr} bytes`),pe(e.identity?.runId,"identity.runId"),pe(e.identity?.agentId,"identity.agentId"),ht(e.executionContract),ao(e),!e.executionContract.capabilityLeaseIds.includes(e.capabilityLeaseId))throw new l("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 l("AUTOMATION_CONTRACT_EXPIRED","Execution contract has expired")}function Ce(e){(!e||typeof e!="object")&&$("Adapter manifest must be an object"),e.protocolVersion!==1&&$("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"&&$("Adapter must implement atomic preflight target binding"),(!Array.isArray(e.operations)||e.operations.length===0)&&$("Adapter must declare operations");let t=new Set;for(let r of e.operations)Le(r)||$(`Adapter declares unknown operation ${r}`),t.has(r)&&$(`Adapter declares duplicate operation ${r}`),t.add(r);e.certified&&!e.certificationArtifactId&&$("A certified automation adapter requires a certification artifact"),Array.isArray(e.limitations)||$("Adapter limitations must be an array"),e.operations.some(r=>r.startsWith("browser."))&&(!e.policyEnforcement.domain||!e.policyEnforcement.scheme||!e.policyEnforcement.port)&&$("Browser adapters must enforce domain, scheme, and port policy"),e.operations.some(r=>r.startsWith("computer."))&&!e.supports.immediateStop&&$("Computer-use adapters must support immediate stop")}function Ve(e,t,r){let n=X(e.operation);if(!t.operations.includes(e.operation))throw new l("AUTOMATION_OPERATION_UNSUPPORTED",`Adapter ${t.adapterId} does not support ${e.operation}`);if(n.surface==="browser"){let o=e.executionContract.browser.mode;if(o==="none"||n.effect==="act"&&o!=="act")throw new l("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(so(e,r,n.effect==="act"),e.operation==="browser.download"&&e.executionContract.browser.downloads==="deny")throw new l("AUTOMATION_POLICY_DENIED","Execution contract denies browser downloads");if(e.operation==="browser.upload"&&e.executionContract.browser.uploads==="deny")throw new l("AUTOMATION_POLICY_DENIED","Execution contract denies browser uploads");if(e.operation.startsWith("browser.record.")&&e.executionContract.browser.recording!=="bounded")throw new l("AUTOMATION_POLICY_DENIED","Execution contract denies browser recording")}else{let o=e.executionContract.computer.mode;if(o==="none"||n.effect==="act"&&o!=="act")throw new l("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);let i=e.executionContract.computer.allowedApplications,a=e.operation==="computer.launch"?lo(e):r.applicationId??e.declaredTarget?.applicationId;if((e.operation==="computer.launch"||i.length>0)&&(!a||!i.includes(a)))throw new l("AUTOMATION_POLICY_DENIED",`Application ${a??"<unknown>"} is not allowed`)}}function bt(e,t){let r=X(e.operation),n=r.surface==="browser"?r.effect==="act"?"browser-act":"browser-read":r.effect==="act"?"computer-act":"computer-observe";return{subject:{runId:e.identity.runId,agentId:e.identity.agentId,...e.identity.turnId?{turnId:e.identity.turnId}:{},toolName:e.governingToolName,operationId:e.operationId},kind:n,operation:e.operation,...br(e,t)?{resource:br(e,t)}:{},...Er(t)?{destination:Er(t)}:{}}}function br(e,t){return e.declaredTarget?.resource??co(t)}function wt(e){let t=X(e.operation).evidence,r=e.evidencePolicy??{},n=It(t.before,r.before),o=It(t.after,r.after),i=It(t.recording,r.recording),a=r.retainUntil;return a&&!Sr(a)&&H("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 ao(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 l("AUTOMATION_IDENTITY_MISMATCH",`Automation identity ${n} does not match the execution contract`)}}function so(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 l("AUTOMATION_PREFLIGHT_INVALID","Browser preflight did not bind an effective URL")}let o;try{o=new URL(n)}catch{throw new l("AUTOMATION_POLICY_DENIED","Browser target URL is invalid")}if(o.username||o.password)throw new l("AUTOMATION_POLICY_DENIED","Browser target URLs cannot contain credentials");let i=o.protocol.replace(/:$/,"");i!=="http"&&i!=="https"&&ne(`Browser scheme ${o.protocol} is not supported`);let a=i,s=o.hostname.toLowerCase().replace(/\.$/,""),c=o.port?Number(o.port):a==="https"?443:80,d=e.executionContract.browser,y=uo(s);if(vr(s,d.deniedDomains)&&ne(`Browser domain ${s} is denied`),wr(o,e.executionContract.network.denyDestinations)&&ne(`Network policy explicitly denies ${a}://${s}:${c}`),y&&d.allowLoopbackDevelopment)return;d.allowedSchemes.includes(a)||ne(`Browser scheme ${o.protocol} is not allowed`),d.allowedPorts.includes(c)||ne(`Browser port ${c} is not allowed`);let g=r?d.actAllowedDomains:d.readAllowedDomains;vr(s,g)||ne(`Browser domain ${s} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&(wr(o,e.executionContract.network.allowDestinations)||ne(`Network policy does not allow ${a}://${s}:${c}`))}function wr(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 co(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function Er(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function lo(e){let t=e.parameters.target,r=t&&typeof t=="object"&&!Array.isArray(t)?t.app_id:void 0,n=e.parameters.applicationId??r??e.declaredTarget?.applicationId;return typeof n=="string"&&n.length>0?n:void 0}function vr(e,t){return t.some(r=>{let n=r.toLowerCase();if(n.startsWith(".")){let o=n.slice(1);return e===o||e.endsWith(`.${o}`)}return e===n})}function uo(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function It(e,t){let r={disabled:0,optional:1,required:2};return!t||r[t]<=r[e]?e:t}function pe(e,t){(typeof e!="string"||!io.test(e))&&H(`${t} is invalid`)}function $e(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&$(`${t} is invalid`)}function Sr(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}function ne(e){throw new l("AUTOMATION_POLICY_DENIED",e)}function H(e){throw new l("AUTOMATION_REQUEST_INVALID",e)}function $(e){throw new l("AUTOMATION_OPERATION_UNSUPPORTED",e)}var Lr=require("node:crypto");var Tr=["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"],Cr=["draft","pending_review","approved","rejected","superseded","archived"],Pr=["public","internal","confidential","restricted"],Rr=["agent","tool","user","system","integration"],_r=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],xr=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var Et=require("node:buffer");var Or=require("node:crypto");function oe(e){return{algorithm:"sha256",value:(0,Or.createHash)("sha256").update(e).digest("hex")}}var po=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Be="custom:";function Pe(e,t=Be){return e.startsWith(t)?po.test(e.slice(t.length)):!1}var fe=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,r){super(t),this.name="XenoArtifactValidationError",this.issues=r.map(n=>({...n}))}},vt=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"},fo={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},mo="[\\u0000-\\u001f\\u007f]",go=new RegExp(mo),Nr=/^[a-f0-9]{64}$/,Ao=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ho=new Set(Cr),Io=new Set(Pr),yo=new Set(Rr),bo=new Set(Tr),wo=new Set(_r),Eo=new Set(xr);function u(e,t,r,n){e.push({path:t,code:r,message:n})}function f(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`),go.test(e)&&u(r,t,"control_character","Value must not contain control characters"),!0)}function Re(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 ie(e,t,r,n){typeof e=="string"&&e.startsWith(t)&&(Pe(e,t)||u(n,r,"invalid_custom_name",`Custom name after ${t} is invalid`))}function kr(e,t,r){if(!e||typeof e!="object"){u(r,t,"missing_actor","Actor is required");return}f(e.kind,`${t}.kind`,r,64),yo.has(e.kind)||u(r,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),f(e.id,`${t}.id`,r,512),e?.displayName!==void 0&&f(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 St(e,t,r){if(!e||typeof e!="object"){u(r,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":f(e.path,`${t}.path`,r,4096);break;case"source-line":f(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":f(e.path,`${t}.path`,r,4096),f(e.hunkId,`${t}.hunkId`,r,512);break;case"symbol":f(e.path,`${t}.path`,r,4096),f(e.symbol,`${t}.symbol`,r,1024);break;case"dom-node":f(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":f(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":f(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":f(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"):ie(e.kind,"custom:",`${t}.kind`,r)}}function _e(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)=>_e(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"):_e(i,`${t}.${o}`,r,n);n.delete(e)}}function vo(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}`),f(e.artifactId,"artifactId",t,512),(!Number.isInteger(e.revision)||e.revision<1)&&u(t,"revision","invalid_revision","revision must be a positive integer"),f(e.kind,"kind",t,160),typeof e.kind=="string"&&!bo.has(e.kind)&&!e.kind.startsWith("custom:")&&u(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),ie(e.kind,"custom:","kind",t),f(e.title,"title",t,1024),e.description!==void 0&&f(e.description,"description",t,32768),f(e.state,"state",t,64),ho.has(e.state)||u(t,"state","unknown_state","Artifact state is not supported"),f(e.createdAt,"createdAt",t,128),Re(e.createdAt,"createdAt",t),Re(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"),f(e.mediaType,"mediaType",t,255),f(e.sensitivity,"sensitivity",t,64),Io.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&&f(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"):(f(e.content.hash.algorithm,"content.hash.algorithm",t,128),ie(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"),f(e.content.hash.value,"content.hash.value",t,512),e.content.hash.algorithm==="sha256"&&!Nr.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=Et.Buffer.from(n.text,"utf8"):n.base64!==void 0&&(Ao.test(n.base64)?o=Et.Buffer.from(n.base64,"base64"):u(t,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),o&&e.content.sizeBytes!==o.byteLength&&u(t,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),o&&e.content.hash.algorithm==="sha256"&&oe(o).value!==e.content.hash.value&&u(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else n.type==="file"?f(n.path,"content.storage.path",t,4096):n.type==="blob"?f(n.uri,"content.storage.uri",t,8192):n.type==="git"?(f(n.commit,"content.storage.commit",t,512),f(n.path,"content.storage.path",t,4096)):n.type==="url"?(f(n.url,"content.storage.url",t,8192),Re(n.expiresAt,"content.storage.expiresAt",t)):n.type==="external"?(f(n.provider,"content.storage.provider",t,255),f(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"),ie(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?u(t,"provenance","missing_provenance","provenance is required"):(kr(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((n,o)=>f(n,`provenance.capabilityLeaseIds[${o}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((n,o)=>f(n,`provenance.sourceArtifactIds[${o}]`,t,512)),e.provenance.attributes&&_e(e.provenance.attributes,"provenance.attributes",t,new Set));let r=new Set;return e.relationships?.forEach((n,o)=>{let i=`relationships[${o}]`;f(n.relation,`${i}.relation`,t,160),typeof n.relation=="string"&&!Eo.has(n.relation)&&!n.relation.startsWith("custom:")&&u(t,`${i}.relation`,"unknown_relationship","Relationship type is not supported"),ie(n.relation,"custom:",`${i}.relation`,t),f(n.target?.type,`${i}.target.type`,t,160),typeof n.target?.type=="string"&&!wo.has(n.target.type)&&!n.target.type.startsWith("custom:")&&u(t,`${i}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),ie(n.target?.type,"custom:",`${i}.target.type`,t),f(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&&_e(n.attributes,`${i}.attributes`,t,new Set)}),e.anchors?.forEach((n,o)=>St(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"),Re(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&&_e(e.extensions,"extensions",t,new Set),t}function Fe(e){let t=vo(e);if(t.length>0)throw new fe("XENO artifact validation failed",t)}function So(e,t){return fo[e].includes(t)}function je(e,t){if(!So(e,t))throw new vt(e,t)}function Tt(e,t){let r=[];return e.schemaVersion!==1&&u(r,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),f(e.eventId,"eventId",r,512),f(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"),f(e.recordedAt,"recordedAt",r,128),Re(e.recordedAt,"recordedAt",r),kr(e.actor,"actor",r),!e.artifactHash||typeof e.artifactHash!="object"?u(r,"artifactHash","missing_hash","Artifact hash is required"):(f(e.artifactHash.algorithm,"artifactHash.algorithm",r,128),ie(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",r),f(e.artifactHash.value,"artifactHash.value",r,512),e.artifactHash.algorithm==="sha256"&&!Nr.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"?(f(e.commentId,"commentId",r,512),f(e.body,"body",r,65536),e.anchor&&St(e.anchor,"anchor",r)):e.type==="comment-resolved"||e.type==="comment-reopened"?f(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&&St(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 Ct(e){let t="not_requested",r,n,o,i=0,a=new Set,s=new Set;for(let c of[...e].sort((d,y)=>d.sequence-y.sequence))o=c.recordedAt,c.type==="review-requested"?t="pending":c.type==="review-withdrawn"?t="withdrawn":c.type==="comment-added"?(a.add(c.commentId),s.delete(c.commentId),t==="not_requested"&&(t="pending")):c.type==="comment-resolved"?s.add(c.commentId):c.type==="comment-reopened"?s.delete(c.commentId):c.type==="decision-recorded"&&(c.scope?i+=1:(r=c.decision,n=c.eventId,t=c.decision));return{status:t,totalComments:a.size,unresolvedComments:[...a].filter(c=>!s.has(c)).length,...r?{latestDecision:r}:{},...n?{latestDecisionEventId:n}:{},...i>0?{scopedDecisionCount:i}:{},...o?{lastReviewedAt:o}:{}}}var p=class extends Error{constructor(r,n,o,i){super(n,i);this.code=r;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},Oe=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(Xr).map(r=>({artifact:xe(r.artifact),recordVersion:r.recordVersion,lifecycleEvents:structuredClone(r.lifecycleEvents),reviewEvents:structuredClone(r.reviewEvents)}));return{schemaVersion:1,records:t}}async create(t){if(Fe(t),this.assertInitialState(t),t.revision!==1)throw new p("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 p("ARTIFACT_ALREADY_EXISTS",`Artifact ${t.artifactId} already exists`,{artifactId:t.artifactId});let r=xe(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),ae(o)}async createRevision(t,r={}){Fe(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 p("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(Co(t,n.artifact))throw new p("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 p("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:t.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){je(n.artifact.state,"superseded");let c=this.now(),d=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:c});n.artifact.state="superseded",n.artifact.updatedAt=c,n.lifecycleEvents.push(d),n.recordVersion+=1}let i=xe(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}`}),s={artifact:i,recordVersion:1,lifecycleEvents:[a],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,s),this.currentRevisions.set(i.artifactId,i.revision),ae(s)}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?ae(i):void 0}async require(t,r){let n=await this.get(t,r);if(!n)throw new p("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=>Po(n.artifact,t)).sort(Xr).map(ae)}async listRevisions(t){let r=this.records.get(t);return r?[...r.values()].sort((n,o)=>n.artifact.revision-o.artifact.revision).map(ae):[]}async transition(t){let r=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(r,t.expectedRecordVersion),je(r.artifact.state,t.toState),t.toState==="approved"||t.toState==="rejected"){let a=t.reviewEventId?r.reviewEvents.find(c=>c.eventId===t.reviewEventId&&c.type==="decision-recorded"):void 0,s=Ct(r.reviewEvents);if(!a||a.decision!==t.toState||s.latestDecisionEventId!==a.eventId)throw new p("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${t.toState} requires a matching decision event`,{artifactId:t.artifactId,revision:r.artifact.revision});if(t.toState==="approved"&&s.unresolvedComments>0)throw new p("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:t.artifactId,revision:r.artifact.revision,unresolvedComments:s.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,ae(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 p("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 p("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=Tt(o,n.artifact);if(i.length>0)throw new fe("XENO artifact review event validation failed",i);return n.reviewEvents.push(o),n.recordVersion+=1,ae(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 p("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 p("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 p("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 p("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 p("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 p("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} does not exist`);let o=Ro(t.reviewEvents,r.commentId);if(r.type==="comment-resolved"&&o.resolved)throw new p("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} is already resolved`);if(r.type==="comment-reopened"&&!o.resolved)throw new p("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 p("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 p("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=To(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 p("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,s)=>a.artifact.revision-s.artifact.revision);for(let a=0;a<i.length;a+=1){let s=i[a],c=a+1;if(s.artifact.revision!==c)throw new p("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${c}`);if(a===0&&s.artifact.predecessorRevision!==void 0)throw new p("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(a>0&&s.artifact.predecessorRevision!==c-1)throw new p("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${c} has an invalid predecessor`);if(a<i.length-1&&s.artifact.state!=="superseded")throw new p("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${c} must be superseded`)}}}};function To(e,t){if(Fe(e.artifact),!Number.isInteger(e.recordVersion)||e.recordVersion<1)throw new p("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 p("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 p("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 p("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 p("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:e.artifact.artifactId,revision:e.artifact.revision})}else je(n,a.toState);t.add(a.eventId),n=a.toState}if(n!==e.artifact.state)throw new p("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 p("ARTIFACT_REVIEW_INVALID",`Persisted review event ${i+1} has an invalid sequence or duplicate ID`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let s=Tt(a,e.artifact);if(s.length>0)throw new fe("Persisted XENO artifact review event validation failed",s);if(a.type==="comment-added"){if(o.has(a.commentId)||a.parentCommentId!==void 0&&!o.has(a.parentCommentId))throw new p("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 c=o.get(a.commentId);if(c===void 0||a.type==="comment-resolved"&&c||a.type==="comment-reopened"&&!c)throw new p("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:xe(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function Co(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function Po(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 Xr(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function Ro(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 xe(e){return structuredClone(e)}function ae(e){return{artifact:xe(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:Ct(e.reviewEvents)}}var Pt=32*1024*1024,_o=1024*1024*1024,xo=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function He(e){let r=(e.now??(()=>new Date().toISOString()))(),n=new Set;return e.evidence.map((o,i)=>{if(No(o),n.has(o.evidenceId))throw new l("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${o.evidenceId}`);n.add(o.evidenceId);let a=Oo(o),s=(0,Lr.createHash)("sha256").update(`${e.request.operationId}\0${o.evidenceId}\0${a.hash.value}`).digest("hex").slice(0,32);return{schemaVersion:1,artifactId:`automation_${s}`,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 Ge(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 p&&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 l("AUTOMATION_EVIDENCE_PERSISTENCE_FAILED",`Failed to persist automation evidence ${n.artifactId}`,{artifactId:n.artifactId},{cause:o})}return r}function Ne(e,t,r){if(t[r]==="required"&&!e.some(n=>n.phase===r))throw new l("AUTOMATION_EVIDENCE_REQUIRED",`Automation operation requires ${r} evidence before it can be trusted`)}function Oo(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return Dr(t),{hash:oe(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=ko(e.content.base64);return Dr(t.byteLength),{hash:oe(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>_o)throw new l("AUTOMATION_EVIDENCE_INVALID","Referenced evidence size is invalid");if(!e.content.hash?.algorithm||!e.content.hash.value)throw new l("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 l("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 No(e){(!e||typeof e!="object")&&G("Evidence must be an object"),xo.test(e.evidenceId)||G("Evidence ID is invalid"),["before","action","after","recording","diagnostic"].includes(e.phase)||G("Evidence phase is invalid"),(!e.kind||!e.title?.trim()||e.title.length>512)&&G("Evidence kind and title are required"),/^[\w!#$&^_.+-]+\/[\w!#$&^_.+-]+(?:;.*)?$/.test(e.mediaType)||G("Evidence media type is invalid")}function ko(e){(e.length===0||e.length>Math.ceil(Pt/3)*4+4)&&G("Inline base64 evidence is empty or too large"),(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)&&G("Inline evidence is not canonical base64");let t=Buffer.from(e,"base64");return t.toString("base64")!==e&&G("Inline evidence is not canonical base64"),t}function Dr(e){e>Pt&&G(`Inline evidence exceeds ${Pt} bytes`)}function G(e){throw new l("AUTOMATION_EVIDENCE_INVALID",e)}var Ur=require("node:crypto");var Mr=3e4,Xo=1e3,ke=class{adapter;leaseAuthority;artifactRepository;now;executions=new Map;active=new Map;constructor(t){this.adapter=t.adapter,this.leaseAuthority=t.leaseAuthority,this.artifactRepository=t.artifactRepository,this.now=t.now??(()=>new Date().toISOString())}execute(t,r){let n=$o(t),o=this.executions.get(t.operationId);if(o){if(o.fingerprint!==n)throw new l("AUTOMATION_OPERATION_CONFLICT",`Operation ${t.operationId} was already submitted with different authority or parameters`);return o.promise}let i=new AbortController,a=Vo(r,i);this.active.set(t.operationId,i);let s=this.executeFresh(t,i.signal).finally(()=>{a(),this.active.delete(t.operationId)});return this.executions.set(t.operationId,{fingerprint:n,promise:s}),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){yt(t),_t(r);let n=await this.adapter.manifest();Ce(n);let o=X(t.operation),i=wt(t),a=this.now(),s=await this.adapter.preflight(t,r);Do(s,this.now()),Ve(t,n,s.observedTarget),_t(r);let c=s.evidence??[];Ne(c,i,"before");let d=await Ge(this.artifactRepository,He({request:t,manifest:n,policy:i,evidence:c,now:this.now}));if(_t(r),Date.parse(s.expiresAt)<=Date.parse(this.now()))throw new l("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let y=bt(t,s.observedTarget),g=await this.leaseAuthority.consume(t.capabilityLeaseId,t.expectedLeaseVersion,y),A={contractFingerprint:t.executionContract.fingerprint,lease:g,capabilityUse:y},m;try{m=await this.adapter.execute(t,s,A,r)}catch(w){return Rt({request:t,manifest:n,descriptorEffect:o.effect,target:s.observedTarget,lease:g,artifacts:d,startedAt:a,completedAt:this.now(),status:r.aborted?"cancelled":"error",code:r.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_ADAPTER_ERROR",message:r.aborted?"Automation operation was stopped":Bo(w)})}Lo(m);let N=Mo(s.observedTarget,m.observedTarget),v;try{Ve(t,n,m.observedTarget)}catch(w){v=w instanceof Error?w:new Error(String(w))}let T=m.evidence??[];Uo(c,T);let U=[],L;try{Ne(T,i,"after"),Ne([...c,...T],i,"recording"),U=await Ge(this.artifactRepository,He({request:t,manifest:n,policy:i,evidence:T,now:this.now}))}catch(w){L=w instanceof Error?w:new Error(String(w))}let k=[...d,...U];return N||v?Rt({request:t,manifest:n,descriptorEffect:o.effect,target:m.observedTarget,lease:g,artifacts:k,startedAt:m.startedAt,completedAt:m.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:N??v.message}):L?Rt({request:t,manifest:n,descriptorEffect:o.effect,target:m.observedTarget,lease:g,artifacts:k,startedAt:m.startedAt,completedAt:m.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:L.message}):{operationId:t.operationId,status:m.status,effect:o.effect,startedAt:m.startedAt,completedAt:m.completedAt,adapter:$r(n),target:structuredClone(m.observedTarget),...m.data!==void 0?{data:structuredClone(m.data)}:{},artifacts:k,lease:Vr(g),...m.error?{error:{...m.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>Xo;){let t=this.executions.keys().next().value;if(!t||this.active.has(t))break;this.executions.delete(t)}}};function Do(e,t){if(!e||typeof e!="object"||!e.token?.trim())throw new l("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 l("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an expired or invalid preflight window");if(n-r>Mr)throw new l("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${Mr} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new l("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function Lo(e){if(!e||typeof e!="object")throw new l("AUTOMATION_REQUEST_INVALID","Adapter returned no result");if(!["ok","denied","cancelled","error"].includes(e.status))throw new l("AUTOMATION_REQUEST_INVALID","Adapter returned an invalid status");if(!Number.isFinite(Date.parse(e.startedAt))||!Number.isFinite(Date.parse(e.completedAt)))throw new l("AUTOMATION_REQUEST_INVALID","Adapter result timestamps are invalid");if(Date.parse(e.completedAt)<Date.parse(e.startedAt))throw new l("AUTOMATION_REQUEST_INVALID","Adapter completion precedes its start");if(!e.observedTarget||typeof e.observedTarget!="object")throw new l("AUTOMATION_REQUEST_INVALID","Adapter result has no observed target")}function Mo(e,t){let r=["tabId","deviceId","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 Uo(e,t){let r=new Set(e.map(n=>n.evidenceId));for(let n of t){if(r.has(n.evidenceId))throw new l("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${n.evidenceId}`);r.add(n.evidenceId)}}function Rt(e){return{operationId:e.request.operationId,status:e.status,effect:e.descriptorEffect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:$r(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:Vr(e.lease),error:{code:e.code,message:e.message}}}function $r(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function Vr(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function $o(e){return(0,Ur.createHash)("sha256").update(JSON.stringify(xt(e))).digest("hex")}function xt(e){return Array.isArray(e)?e.map(xt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,xt(r)]))}function Vo(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 _t(e){if(e.aborted)throw new l("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function Bo(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}function Br(e,t=()=>new Date().toISOString()){let r=[];jo(r,"manifest.valid",()=>Ce(e));let n=new Set(e.operations);return me(r,n,e.supports.consoleInspection,"browser.console.read","console inspection"),me(r,n,e.supports.networkInspection,"browser.network.read","network inspection"),me(r,n,e.supports.storageInspection,"browser.storage.read","storage inspection"),me(r,n,e.supports.pageErrorInspection,"browser.page-errors.read","page-error inspection"),me(r,n,e.supports.recordings,"browser.record.start","recording start"),me(r,n,e.supports.recordings,"browser.record.stop","recording stop"),n.has("browser.upload")&&Z(r,"policy.upload",e.policyEnforcement.upload,"Upload policy is enforced"),n.has("browser.download")&&Z(r,"policy.download",e.policyEnforcement.download,"Download policy is enforced"),[...n].some(o=>o.startsWith("browser."))&&(Z(r,"policy.redirect",e.policyEnforcement.redirect,"Redirect policy is enforced"),Z(r,"control.handback",e.supports.deterministicHandback,"Deterministic hand-back is supported")),[...n].some(o=>o.startsWith("computer."))&&(Z(r,"control.stop",e.supports.immediateStop,"Immediate human stop is supported"),Z(r,"privacy.redaction",e.supports.sensitiveRegionRedaction,"Sensitive-region redaction is supported")),Z(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 Fo(e){let r=Br(e).checks.filter(n=>n.status==="fail");if(r.length>0)throw new l("AUTOMATION_OPERATION_UNSUPPORTED",r.map(n=>`${n.id}: ${n.message}`).join("; "))}function me(e,t,r,n,o){let i=t.has(n);Z(e,`capability.${n}`,r===i,r===i?`${o} declaration matches the operation catalog`:`${o} declaration does not match ${n}`)}function jo(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 Z(e,t,r,n){e.push({id:t,status:r?"pass":"fail",message:n})}var Ho=6e4,Go=48*1024*1024,Ot=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(t){if(this.endpoint=Wo(t.baseUrl),this.token=qo(t.token),this.timeoutMs=Fr(t.timeoutMs??Ho,1e3,3e5,"timeoutMs"),this.maxResponseBytes=Fr(t.maxResponseBytes??Go,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=t.fetch??globalThis.fetch,typeof this.fetchImpl!="function")throw new l("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}preflight(t,r){return this.request("preflight","POST",t,r)}execute(t,r,n,o){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=Ko(o,i),s=setTimeout(()=>i.abort(new Error("automation transport timeout")),this.timeoutMs);s.unref?.();try{let c=new URL(t,this.endpoint),d=await this.fetchImpl(c,{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}),y=await zo(d,this.maxResponseBytes);if(!d.ok){let g=Jo(y);throw new l("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${t}: ${g.message}`,{status:d.status,route:t,adapterCode:g.code})}if(!Nt(y)||y.ok!==!0||!("result"in y))throw new l("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${t} envelope`);return y.result}catch(c){if(c instanceof l)throw c;let d=o?.aborted;throw new l(d?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",d?"Automation transport was stopped":`XENO Browser ${t} transport failed`,{route:t},{cause:c})}finally{clearTimeout(s),a()}}};function Wo(e){let t;try{t=new URL(e)}catch(n){throw new l("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL is invalid",void 0,{cause:n})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new l("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires HTTP(S)");if(t.username||t.password||t.search||t.hash)throw new l("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 l("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport must use a loopback host");if(!t.port)throw new l("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires an explicit port");return t.pathname="/v1/automation/",t}function qo(e){if(typeof e!="string"||e.length<32||e.length>512||/\s/.test(e))throw new l("AUTOMATION_TRANSPORT_ERROR","XENO Browser session token is invalid");return e}async function zo(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new l("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);if(e.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new l("AUTOMATION_RESPONSE_INVALID","XENO Browser response is not application/json");if(!e.body)throw new l("AUTOMATION_RESPONSE_INVALID","XENO Browser response body is missing");let o=e.body.getReader(),i=[],a=0;for(;;){let{done:d,value:y}=await o.read();if(d)break;if(a+=y.byteLength,a>t)throw await o.cancel("response too large"),new l("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);i.push(y)}let s=new Uint8Array(a),c=0;for(let d of i)s.set(d,c),c+=d.byteLength;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch(d){throw new l("AUTOMATION_RESPONSE_INVALID","XENO Browser response contains invalid JSON",void 0,{cause:d})}}function Jo(e){return Nt(e)&&Nt(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 Ko(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 l("AUTOMATION_TRANSPORT_ERROR",`${n} must be an integer from ${t} to ${r}`);return e}function Nt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var zr=require("node:crypto"),Xe=["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"],Ae=class{constructor(t){this.options=t;if(this.base=Qo(t.baseUrl),this.fetchImpl=t.fetch??globalThis.fetch,this.timeoutMs=t.timeoutMs??6e4,!ei(t.token))throw new Error("XENO browser control-plane token is invalid")}options;base;fetchImpl;timeoutMs;async manifest(){let t=await this.call("health",void 0),r=Xe.filter(n=>t.verbs?.includes(jr(n))??!1);return{protocolVersion:1,adapterId:this.options.driver==="extension"?"xeno-extension-native":"xeno-browser-native",adapterVersion:t.version??"unknown",platform:process.platform,architecture:process.arch,operations:r,targetBinding:"atomic-preflight",profileIsolation:this.options.driver==="browser"?"both":"none",supports:{accessibilitySnapshots:!0,screenshots:!0,recordings:!1,consoleInspection:!0,networkInspection:!0,storageInspection:r.includes("browser.storage.read"),pageErrorInspection:!0,visibleCoControl:!0,deterministicHandback:!0,immediateStop:!0,sensitiveRegionRedaction:!1},policyEnforcement:{domain:!0,scheme:!0,port:!0,redirect:!0,upload:r.includes("browser.upload"),download:r.includes("browser.download")},certified:!1,limitations:[`${this.options.driver==="extension"?"Extension":"Browser"} transport is policy-enforced but not release-certified`,"sensitive-region screenshot redaction is not available"]}}async preflight(t,r){Zo(t.operation);let n=await this.call("health",void 0,r);if(!n.verbs?.includes(jr(t.operation)))throw new Error(`${this.options.driver} driver does not support ${t.operation}`);let o=qr(n.activeTab),i=ge(t.parameters.tabId)??t.declaredTarget?.tabId;if(i&&o&&i!==o)throw new Error(`Requested tab ${i} is not the active browser tab ${o}`);let a=Hr(t,o);Gr(t,a);let s=new Date;return{token:`${t.operationId}:${o??"unbound"}:${(0,zr.randomUUID)()}`,preparedAt:s.toISOString(),expiresAt:new Date(s.getTime()+2e4).toISOString(),observedTarget:a,...Kr(t.operation)?{evidence:[await this.snapshotEvidence(t,"before",r)]}:{},adapterState:{activeTab:o??null,driver:this.options.driver}}}async execute(t,r,n,o){let i=new Date().toISOString(),a=await this.call("health",void 0,o),s=qr(a.activeTab);if(r.observedTarget.tabId&&s!==r.observedTarget.tabId)throw new Error("Active browser tab changed after atomic preflight");Gr(t,r.observedTarget);try{let c=Jr(t.operation,t.parameters),d=await this.call(c.verb,c.params,o),y=Hr(t,s),g=t.operation==="browser.wait"||t.operation==="browser.tabs.list"?[]:[await this.resultEvidence(t,d,o)];return{status:"ok",startedAt:i,completedAt:new Date().toISOString(),observedTarget:y,data:ri(d),...g.length?{evidence:g}:{}}}catch(c){let d={code:oi(c),message:ni(c),retryable:!1};return{status:ii(c),startedAt:i,completedAt:new Date().toISOString(),observedTarget:r.observedTarget,error:d,evidence:[{evidenceId:`${t.operationId}-after-failure`,phase:"after",kind:"browser-snapshot",title:`${t.operation} failed attempt`,mediaType:"application/json",content:{type:"text",text:JSON.stringify({error:d})},sensitivity:"restricted"}]}}}async stop(t,r){await this.call("stop",{})}async resultEvidence(t,r,n){return t.operation==="browser.screenshot"?Yo(t,"after",r):this.snapshotEvidence(t,"after",n)}async snapshotEvidence(t,r,n){let o=await this.call("observe",{limit:1e3},n);return{evidenceId:`${t.operationId}-${r}`,phase:r,kind:"browser-snapshot",title:`${t.operation} ${r} state`,mediaType:"application/json",content:{type:"text",text:JSON.stringify(o)},sensitivity:"restricted"}}async call(t,r,n){let o=new AbortController,i=()=>o.abort(n?.reason);n?.aborted?i():n?.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>o.abort(new Error("browser control-plane timeout")),this.timeoutMs);a.unref?.();try{let s=await this.fetchImpl(new URL(`/v1/browser/${t}`,this.base),{method:t==="health"?"GET":"POST",redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.options.token}`,accept:"application/json",...t==="health"?{}:{"content-type":"application/json"}},...t==="health"?{}:{body:JSON.stringify(r??{})},signal:o.signal}),c=await s.json();if(!s.ok||c.ok!==!0)throw Object.assign(new Error(c.error?.message??`Browser ${t} failed with HTTP ${s.status}`),{code:c.error?.code??`HTTP_${s.status}`,status:s.status});return c.result}finally{clearTimeout(a),n?.removeEventListener("abort",i)}}};function jr(e){return Jr(e,{}).verb}function Jr(e,t){let r=Object.fromEntries(Object.entries(t).filter(([n])=>n!=="tabId"));switch(e){case"browser.navigate":return{verb:"navigate",params:r};case"browser.back":return{verb:"back",params:{}};case"browser.forward":return{verb:"forward",params:{}};case"browser.reload":return{verb:"reload",params:{}};case"browser.wait":return{verb:"wait",params:t.until==="ms"?{milliseconds:t.value??0}:{until:"load",timeout_ms:t.value??3e4}};case"browser.snapshot":return{verb:"observe",params:{limit:t.limit??1e3}};case"browser.screenshot":return{verb:"screenshot",params:{}};case"browser.locate":return{verb:"find",params:r};case"browser.tabs.list":return{verb:"tabs_list",params:{}};case"browser.tabs.open":return{verb:"tabs_new",params:r};case"browser.tabs.close":return{verb:"tabs_close",params:{id:t.tabId}};case"browser.console.read":return{verb:"console_log",params:r};case"browser.network.read":return{verb:"network_log",params:r};case"browser.page-errors.read":return{verb:"console_log",params:{...r,level:"error"}};case"browser.storage.read":return{verb:"storage",params:{}};case"browser.click":return{verb:"click",params:r};case"browser.type":return{verb:"type",params:{selector:t.selector,text:t.text,clear_first:t.clear,press_enter:t.submit}};case"browser.key":return{verb:"key",params:{combo:t.combo}};case"browser.select":return{verb:"select",params:r};case"browser.scroll":return{verb:"scroll",params:r};case"browser.upload":return{verb:"attach_file",params:{selector:t.selector,backendNodeId:t.backendNodeId,host_paths:t.hostPaths,drop:t.drop}};case"browser.download":return{verb:"download",params:{to_path:t.toPath,trigger:t.trigger}};default:throw new Error(`Unsupported browser operation ${e}`)}}function Yo(e,t,r){let n=We(r)?r:{},o=ge(n.base64)??ti(ge(n.screenshot));if(!o)throw new Error("Browser screenshot did not return image bytes");let i=ge(n.format)??(ge(n.screenshot)?.startsWith("data:image/jpeg")?"jpeg":"png");return{evidenceId:`${e.operationId}-${t}`,phase:t,kind:"screenshot",title:`${e.operation} result`,mediaType:i==="jpeg"?"image/jpeg":"image/png",content:{type:"base64",base64:o},sensitivity:"restricted"}}function Hr(e,t){let r=ge(e.parameters.url)??e.declaredTarget?.url;return{...e.declaredTarget??{},...r?{url:r}:{},...t?{tabId:t}:{}}}function Gr(e,t){if(e.operation==="browser.upload"&&e.executionContract.browser.uploads==="deny")throw Object.assign(new Error("Browser uploads are denied by the execution contract"),{code:"POLICY_DENIED"});if(e.operation==="browser.download"&&e.executionContract.browser.downloads==="deny")throw Object.assign(new Error("Browser downloads are denied by the execution contract"),{code:"POLICY_DENIED"});let r=t.url??t.origin;if(!r)return;let n=new URL(r),o=e.executionContract.browser,i=n.protocol.replace(/:$/,"");if(!o.allowedSchemes?.includes(i))throw Object.assign(new Error(`Browser scheme ${i} is denied`),{code:"POLICY_DENIED"});let a=n.port?Number(n.port):i==="http"?80:443;if(!o.allowedPorts?.includes(a))throw Object.assign(new Error(`Browser port ${a} is denied`),{code:"POLICY_DENIED"});let s=n.hostname.toLowerCase();if(o.deniedDomains?.some(d=>Wr(s,d)))throw Object.assign(new Error(`Browser domain ${s} is denied`),{code:"POLICY_DENIED"});let c=e.operation.startsWith("browser.")&&Kr(e.operation)?o.actAllowedDomains:o.readAllowedDomains;if(c&&c.length>0&&!c.some(d=>Wr(s,d)))throw Object.assign(new Error(`Browser domain ${s} is outside the allowed scope`),{code:"POLICY_DENIED"})}function Wr(e,t){let r=t.toLowerCase().replace(/^\*\./,".");return r.startsWith(".")?e.endsWith(r)||e===r.slice(1):e===r}function Kr(e){return["browser.navigate","browser.back","browser.forward","browser.reload","browser.tabs.open","browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download"].includes(e)}function Zo(e){if(!Xe.includes(e))throw new Error(`Unsupported browser operation ${e}`)}function Qo(e){let t=new URL(e),r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(t.protocol!=="http:"||!["localhost","127.0.0.1","::1"].includes(r)||!t.port)throw new Error("Browser control plane must be an explicit HTTP loopback URL");return t}function ei(e){return typeof e=="string"&&e.length>=32&&e.length<=512&&!/\s/.test(e)}function qr(e){return typeof e=="string"||typeof e=="number"?String(e):void 0}function ge(e){return typeof e=="string"&&e.length>0?e:void 0}function ti(e){return e?.match(/^data:image\/(?:png|jpeg);base64,(.+)$/)?.[1]}function ri(e){return JSON.parse(JSON.stringify(e??null))}function We(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ni(e){return e instanceof Error?e.message.slice(0,1024):String(e).slice(0,1024)}function oi(e){return We(e)&&typeof e.code=="string"?e.code:"BROWSER_OPERATION_FAILED"}function ii(e){return We(e)&&(e.status===403||e.status===409||e.code==="POLICY_DENIED")?"denied":We(e)&&e.name==="AbortError"?"cancelled":"error"}var Ie=require("node:fs"),pn=require("node:os"),z=require("node:path");var Ut=require("node:crypto"),_=require("node:fs/promises"),B=require("node:path");var W=require("node:fs"),kt=require("node:os"),Zr=require("node:path");function ai(){return new Date().toISOString()}function si(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function Qr(e){try{return JSON.parse((0,W.readFileSync)(e,"utf8"))}catch{return null}}function ci(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function di(e){return e.hostname!==(0,kt.hostname)()?!0:ci(e.pid)}function Yr(e,t){(0,W.mkdirSync)((0,Zr.dirname)(e),{recursive:!0}),(0,W.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
926
|
+
`,{encoding:"utf8",flag:"wx"})}function li(e,t){let r=Qr(e);r?.pid!==t.pid||r.hostname!==t.hostname||(0,W.rmSync)(e,{force:!0})}function en(e,t,r){let n=ai(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,kt.hostname)(),processStartedAt:si(),version:r,acquiredAt:n,updatedAt:n};try{Yr(e,o)}catch(i){if(i.code!=="EEXIST")throw i;let s=Qr(e);if(s&&di(s))throw new Error(`${t} is already locked by PID ${s.pid} on ${s.hostname}.`);(0,W.rmSync)(e,{force:!0}),Yr(e,o)}return{record:o,release:()=>{li(e,o)}}}var tn="0.9.24";var nn=1,ui="repository.v1.json",pi=5e3,fi=20,mi=64*1024*1024,qe=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??ui;if((0,B.basename)(r)!==r||!/^[A-Za-z0-9_.-]+$/.test(r))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,B.resolve)(t.directory),this.snapshotPath=(0,B.join)(this.directory,r),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Xt(t.lockTimeoutMs,pi,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Xt(t.lockRetryMs,fi,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Xt(t.maxSnapshotBytes,mi,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 en(this.lockPath,`artifact-repository:${(0,B.basename)(this.snapshotPath)}`,tn)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;r=n,await yi(this.lockRetryMs)}throw new p("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=ze(i)}if(!r&&(t||await Ii(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 p("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,ze(i)])}):i}if(!r&&t)throw t;let o=r?.state??{schemaVersion:1,records:[]};return{repository:new Oe({now:this.now,idFactory:i=>`${i}_${(0,Ut.randomUUID)()}`,initialState:o}),generation:r?.generation??0,createdAt:r?.createdAt??this.now(),hasSnapshot:r!==void 0,recoveredFromBackup:n,...r?{sourceSnapshot:r}:{}}}async persist(t){let r=this.now(),o={...{schemaVersion:nn,generation:t.generation,createdAt:t.createdAt,updatedAt:r,state:t.repository.exportState()},generation:t.generation+1},i=Ai(o),a=`${JSON.stringify(i,null,2)}
|
|
927
|
+
`;if(Buffer.byteLength(a,"utf8")>this.maxSnapshotBytes)throw new p("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await(0,_.mkdir)(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await rn(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
|
|
928
|
+
`),await rn(this.snapshotPath,a)}async readSnapshot(t,r){let n;try{n=await(0,_.stat)(t)}catch(o){if(!r&&Lt(o,"ENOENT")||r&&Lt(o,"ENOENT"))return;throw Mt("Unable to inspect artifact repository snapshot",t,o)}if(!n.isFile()||n.size>this.maxSnapshotBytes)throw new p("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:t,sizeBytes:n.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await(0,_.readFile)(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return gi(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof p?o:Mt("Unable to parse artifact repository snapshot",t,o,!0)}}};function gi(e,t){if(!Dt(e)||e.schemaVersion!==nn||!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))||!Dt(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!Dt(e.checksum)||e.checksum.algorithm!=="sha256"||typeof e.checksum.value!="string")throw new p("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:t});let r=e,n=hi(r),o=on(n);if(r.checksum.value!==o)throw new p("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new Oe({initialState:r.state}),structuredClone(r)}function Ai(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:on(e)}}}function hi(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function on(e){return oe(JSON.stringify(e)).value}async function rn(e,t){await(0,_.mkdir)((0,B.dirname)(e),{recursive:!0,mode:448});let r=`${e}.tmp.${process.pid}.${(0,Ut.randomUUID)()}`,n;try{n=await(0,_.open)(r,"wx",384),await n.writeFile(t,{encoding:"utf8"}),await n.sync(),await n.close(),n=void 0,await(0,_.rename)(r,e);try{let o=await(0,_.open)((0,B.dirname)(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{n&&await n.close().catch(()=>{}),await(0,_.unlink)(r).catch(()=>{})}}function Xt(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 Dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lt(e,t){return e instanceof Error&&e.code===t}async function Ii(e){try{return(await(0,_.stat)(e)).isFile()}catch(t){if(Lt(t,"ENOENT"))return!1;throw Mt("Unable to inspect artifact repository backup",e,t)}}function ze(e){return e instanceof Error?e:new Error(String(e))}function Mt(e,t,r,n=!1){return new p(n?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${ze(r).message}`,{snapshotPath:t},{cause:ze(r)})}function yi(e){return new Promise(t=>setTimeout(t,e))}var he=require("node:os");var Bs=(0,he.platform)();var Fs=(0,he.release)(),js=(0,he.homedir)();var bi=2,$t=["publish","deploy","push","send","purchase","sign","file-legal","change-infrastructure"];function wi(e){return Array.from(new Set((e??[]).map(t=>t.trim()).filter(Boolean)))}function q(e){return{schemaVersion:bi,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:wi(e.tags)}}var Zs=[q({id:"assistant",displayName:"Assistant",description:"General-purpose XENO collaborator for mixed research, planning, and implementation work.",prompt:["Work as a thoughtful generalist. Establish the user's actual outcome, inspect relevant context, and take scoped action.","Escalate into a narrower specialist profile when domain risk or task depth warrants it."].join(`
|
|
929
|
+
`),toolPolicy:{mode:"inherit"},skills:[],memoryScope:"user",evidence:["file-references"],currentTurnApproval:[...$t],color:"cyan",glyph:"\u25A0",tags:["general","primary"]}),q({id:"swe",displayName:"Software Engineer",description:"Repository-aware software engineer for careful implementation, debugging, refactoring, and verification.",prompt:["Inspect the repository before editing. Follow project instructions and preserve unrelated work.","Trace the smallest root cause, implement the narrowest coherent change, and verify from focused checks outward.","Do not claim completion without concrete test, typecheck, build, or runtime evidence appropriate to the risk."].join(`
|
|
930
|
+
`),toolPolicy:{mode:"default"},skills:["debug","run","verify"],permissionProfile:"trusted-dev",soul:"learn",evidence:["file-references","tests","typecheck","build","diff"],currentTurnApproval:["publish","deploy","push","change-infrastructure"],color:"green",glyph:"\u25C6",tags:["engineering","implementation"]}),q({id:"reviewer",displayName:"Code Reviewer",description:"Read-only reviewer focused on correctness, regressions, safety, tests, and maintainability.",prompt:["Lead with concrete findings ordered by severity. Cite exact file locations and explain impact.","Do not edit code. Distinguish confirmed defects from risks and questions. State when no material finding is present."].join(`
|
|
931
|
+
`),kind:"subagent",toolPolicy:{mode:"readOnly"},skills:["code-review","verify"],permissionProfile:"read-only",memoryScope:"session",soul:"read",allowedModes:["chat","review"],defaultMode:"review",evidence:["file-references","diff"],externalDefault:"deny",color:"yellow",glyph:"\u25C7",tags:["engineering","review","read-only"]}),q({id:"writer",displayName:"Writer",description:"Audience-aware writer and editor for clear, accurate, structurally coherent content.",prompt:["Determine audience, purpose, voice, format, and source constraints before drafting.","Preserve factual meaning, avoid invented claims, and revise for clarity, rhythm, consistency, and usefulness."].join(`
|
|
932
|
+
`),toolPolicy:{mode:"default",allow:["Read","Glob","Grep","LS","Write","Edit","WebSearch","WebFetch","Think","AskUser","Skill"]},skills:["verify"],evidence:["sources","file-references","diff"],currentTurnApproval:["send","publish"],color:"magenta",glyph:"\u2726",tags:["writing","editing"]}),q({id:"research",displayName:"Researcher",description:"Evidence-first researcher for questions, comparisons, synthesis, and source-backed analysis.",prompt:["Break the question into verifiable claims. Prefer primary and authoritative sources, compare dates, and cite near each claim.","Separate sourced fact, inference, uncertainty, and recommendation. Do not make changes unless the user explicitly expands scope."].join(`
|
|
933
|
+
`),toolPolicy:{mode:"readOnly"},skills:["verify"],permissionProfile:"default",memoryScope:"session",soul:"read",allowedModes:["chat","plan","review"],evidence:["sources","file-references"],primarySources:!0,currentInformation:!0,externalDefault:"deny",color:"blue",glyph:"\u25C8",tags:["research","qa","read-only"]}),q({id:"product",displayName:"Product",description:"Product strategist for problem framing, requirements, sequencing, metrics, and trade-off decisions.",prompt:["Start from the user problem and observable outcome. Distinguish evidence, assumptions, constraints, and open decisions.","Translate strategy into testable requirements, acceptance criteria, telemetry, risks, and a sequenced delivery path."].join(`
|
|
934
|
+
`),toolPolicy:{mode:"default",allow:["Read","Glob","Grep","LS","Write","Edit","WebSearch","WebFetch","Think","AskUser","Skill"]},skills:["verify"],evidence:["sources","file-references","diff"],currentTurnApproval:["send","publish","change-infrastructure"],color:"cyan",glyph:"\u25A3",tags:["product","planning"]}),q({id:"ci",displayName:"CI Engineer",description:"Continuous-integration specialist for reproducing, repairing, and hardening automated gates.",prompt:["Identify the exact failing job and command. Reproduce it locally or in an equivalent immutable environment before patching.","Fix only the underlying failure, retain logs as evidence, and rerun the matching gate before broader validation."].join(`
|
|
935
|
+
`),toolPolicy:{mode:"default"},skills:["ci-repair","debug","run","verify"],permissionProfile:"trusted-dev",soul:"learn",evidence:["tests","typecheck","build","diff"],currentTurnApproval:["push","deploy","change-infrastructure"],color:"green",glyph:"\u25A4",tags:["engineering","ci","automation"]}),q({id:"devops",displayName:"DevOps and Release",description:"Dry-run-first infrastructure and release specialist with explicit external-action gates.",prompt:["Inspect the release or infrastructure contract first. Build an immutable candidate and produce reproducible evidence.","Default to plan, preview, dry-run, and local verification. Never publish, deploy, push, sign, purchase, or mutate infrastructure unless the current user turn explicitly authorizes that exact action and target.","For releases, preserve SDK-before-CLI dependency order and verify the public artifact after publication."].join(`
|
|
936
|
+
`),toolPolicy:{mode:"default"},skills:["release","run","verify"],permissionProfile:"default",memoryScope:"project",soul:"learn",isolation:"worktree",defaultMode:"plan",defaultDryRun:!0,evidence:["tests","build","diff","deployment-proof","human-review"],humanReview:!0,currentTurnApproval:["publish","deploy","push","purchase","sign","change-infrastructure"],color:"yellow",glyph:"\u2B22",tags:["devops","release","infrastructure"]}),q({id:"legal-research",displayName:"Legal Research",description:"Restricted legal-information researcher that produces sourced analysis for qualified human review.",prompt:["Identify jurisdiction, effective date, parties, and the precise legal question before analyzing it.","Use current primary legal sources wherever possible. Cite each material proposition and distinguish law, interpretation, uncertainty, and practical next steps.","Provide legal information, not professional representation. Never sign, file, submit, contact a party, accept terms, or make a payment."].join(`
|
|
937
|
+
`),toolPolicy:{mode:"readOnly"},skills:["verify"],permissionProfile:"default",memoryScope:"session",soul:"disabled",allowedModes:["chat","plan","review"],defaultMode:"review",evidence:["sources","human-review"],primarySources:!0,currentInformation:!0,humanReview:!0,externalDefault:"deny",color:"red",glyph:"\xA7",tags:["legal","research","restricted","read-only"],stopConditions:["The jurisdiction or effective date is unknown and materially changes the answer.","The task requires legal representation, filing, signature, payment, or contact with a third party.","The sourced analysis is complete and clearly marked for qualified human review."]})];var Ei=1,C=class extends Error{constructor(r,n,o){super(n);this.code=r;this.detail=o;this.name="XenoCapabilityLeaseError"}code;detail},vi=new Set(["filesystem-write","process-execute","network-connect","secret-use","external-action","browser-act","computer-act"]),Si=new Set($t),Ti=new Set(["filesystem-read","filesystem-write","process-execute","network-connect","secret-use","external-action","browser-read","browser-act","computer-observe","computer-act","tool-invoke"]),Ci=new Set(["cli","hub","ide","api","hosted"]),Pi=/^[a-f0-9]{64}$/;function Ri(e,t){_i(e);let r=e.scope,n=r.governingToolName??e.subject.toolName;if(r.kind!=="external-action"){if(!n)return{eligible:!1,approvalRequirement:"principal",reason:"Non-external capability requests must identify the governing tool."};let o=xi(t,n,r.effect);if(!o.eligible)return o}if(t.capabilities.permissionProfile==="read-only"&&r.effect!=="read")return{eligible:!1,approvalRequirement:"principal",reason:"The active read-only permission profile cannot request mutating, executable, or external authority."};if(r.kind==="external-action"){let o=r.externalAction;if(!o)return{eligible:!1,approvalRequirement:"current-turn",reason:"External-action capability requests require an exact action."};let i=t.capabilities.externalActions,a=i.overrides?.[o]??i.default;if(a==="deny")return{eligible:!1,approvalRequirement:"current-turn",profileDecision:a,reason:`Agent Profile ${t.profile.id} denies external action ${o}.`};let s=a==="ask"||i.requireCurrentTurnApproval.includes(o);return s&&!e.subject.turnId?{eligible:!1,approvalRequirement:"current-turn",profileDecision:a,reason:`External action ${o} requires a subject turn ID for current-turn approval.`}:{eligible:!0,approvalRequirement:s?"current-turn":"principal",profileDecision:a,reason:s?`External action ${o} requires approval in the active turn.`:`External action ${o} is requestable but still requires a bounded lease approval.`}}return{eligible:!0,approvalRequirement:"principal",reason:`Capability ${r.kind} is requestable within Agent Profile ${t.profile.id}.`}}function _i(e){if(!e||typeof e!="object")throw E("Capability lease request must be an object");if(M(e.subject?.runId,"subject.runId"),M(e.subject?.agentId,"subject.agentId"),e.subject?.turnId!==void 0&&M(e.subject.turnId,"subject.turnId"),M(e.reason,"reason",8192),Je(e.requestedBy,"requestedBy"),Oi(e.scope),e.policyFingerprints?.forEach(t=>sn(t,"policyFingerprints")),e.maxUses!==void 0&&(!Number.isInteger(e.maxUses)||e.maxUses<1))throw E("maxUses must be a positive integer");if(e.durationMs!==void 0&&(!Number.isSafeInteger(e.durationMs)||e.durationMs<1))throw E("durationMs must be a positive safe integer");if(e.requestTtlMs!==void 0&&(!Number.isSafeInteger(e.requestTtlMs)||e.requestTtlMs<1))throw E("requestTtlMs must be a positive safe integer")}var Ke=class{leases=new Map;now;idFactory;maximumDurationMs;maximumRequestTtlMs;maximumUses;idCounter=0;constructor(t={}){this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(()=>`lease_${Date.now().toString(36)}_${(++this.idCounter).toString(36)}`),this.maximumDurationMs=t.maximumDurationMs??15*6e4,this.maximumRequestTtlMs=t.maximumRequestTtlMs??5*6e4,this.maximumUses=t.maximumUses??100}request(t,r){let n=Ri(t,r);if(!n.eligible)throw new C("LEASE_NOT_REQUESTABLE",n.reason);let o=t.leaseId??this.idFactory();if(M(o,"leaseId"),this.leases.has(o))throw new C("LEASE_CONFLICT",`Capability lease ${o} already exists`);let i=this.now(),a=Math.min(t.durationMs??6e4,this.maximumDurationMs),s=Math.min(t.requestTtlMs??5*6e4,this.maximumRequestTtlMs),c=Math.min(t.maxUses??1,this.maximumUses),d={schemaVersion:Ei,leaseId:o,version:1,state:"requested",subject:Xi(t.subject),scope:Di(t.scope),reason:t.reason,requestedAt:i,requestExpiresAt:an(i,s),durationMs:a,maxUses:c,useCount:0,childInheritance:t.childInheritance??"none",approvalRequirement:n.approvalRequirement,requestedBy:{...t.requestedBy},profileFingerprint:r.fingerprint,policyFingerprints:ce(t.policyFingerprints??[]),...t.auditEventIds?{auditEventIds:ce(t.auditEventIds)}:{},...t.evidenceArtifactIds?{evidenceArtifactIds:ce(t.evidenceArtifactIds)}:{}};return this.leases.set(o,d),se(d)}approve(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="requested")throw new C("LEASE_CONFLICT",`Capability lease ${r.leaseId} is ${r.state}`);if(Je(t.approvedBy,"approvedBy"),ki(t.approvalContext),r.approvalRequirement==="current-turn"&&(!r.subject.turnId||t.approvalContext.turnId!==r.subject.turnId))throw new C("LEASE_APPROVAL_REQUIRED","Capability lease requires approval bound to the requesting turn");let n=this.now();return r.state="active",r.version+=1,r.activatedAt=n,r.expiresAt=an(n,r.durationMs),r.approvedBy={...t.approvedBy},r.approvalContext={...t.approvalContext},se(r)}deny(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="requested")throw new C("LEASE_CONFLICT",`Capability lease ${r.leaseId} is ${r.state}`);return Je(t.deniedBy,"deniedBy"),r.state="denied",r.version+=1,r.deniedAt=this.now(),r.deniedBy={...t.deniedBy},se(r)}revoke(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="active")throw new C("LEASE_CONFLICT",`Only active leases can be revoked; ${r.leaseId} is ${r.state}`);return Je(t.revokedBy,"revokedBy"),r.state="revoked",r.version+=1,r.revokedAt=this.now(),r.revokedBy={...t.revokedBy},se(r)}consume(t,r,n){let o=this.requireMutable(t);if(this.assertVersion(o,r),this.refreshState(o),o.state==="requested")throw new C("LEASE_APPROVAL_REQUIRED",`Capability lease ${t} is not approved`);if(o.state==="expired")throw new C("LEASE_EXPIRED",`Capability lease ${t} expired`);if(o.state==="revoked")throw new C("LEASE_REVOKED",`Capability lease ${t} was revoked`);if(o.state==="exhausted")throw new C("LEASE_EXHAUSTED",`Capability lease ${t} is exhausted`);if(o.state!=="active")throw new C("LEASE_SCOPE_MISMATCH",`Capability lease ${t} is ${o.state}`);return Ni(o,n),o.useCount+=1,o.version+=1,o.useCount>=o.maxUses&&(o.state="exhausted",o.exhaustedAt=this.now()),se(o)}get(t){let r=this.leases.get(t);if(r)return this.refreshState(r),se(r)}list(t){let r=[];for(let n of this.leases.values())this.refreshState(n),!(t?.runId&&n.subject.runId!==t.runId)&&(t?.agentId&&n.subject.agentId!==t.agentId||t?.turnId&&n.subject.turnId!==t.turnId||r.push(se(n)));return r.sort((n,o)=>n.requestedAt.localeCompare(o.requestedAt)||n.leaseId.localeCompare(o.leaseId))}requireMutable(t){let r=this.leases.get(t);if(!r)throw new C("LEASE_NOT_FOUND",`Capability lease ${t} was not found`);return r}assertVersion(t,r){if(t.version!==r)throw new C("LEASE_CONFLICT",`Expected capability lease version ${r}, found ${t.version}`,{leaseId:t.leaseId,expectedVersion:r,actualVersion:t.version})}refreshState(t){let r=Date.parse(this.now()),n=t.state==="requested"?Date.parse(t.requestExpiresAt):Date.parse(t.expiresAt??"");(t.state==="requested"||t.state==="active")&&Number.isFinite(n)&&r>=n&&(t.state="expired",t.version+=1,t.expiredAt=this.now())}};function xi(e,t,r){let n=e.capabilities.tools,o=t.trim().toLowerCase(),i=a=>a?.some(s=>s==="*"||s.trim().toLowerCase()===o)??!1;return n.mode==="none"||i(n.deny)?{eligible:!1,approvalRequirement:"principal",reason:`Agent Profile ${e.profile.id} denies tool ${t}.`}:n.allow&&!i(n.allow)?{eligible:!1,approvalRequirement:"principal",reason:`Tool ${t} is outside the Agent Profile allowlist.`}:n.mode==="readOnly"&&r!=="read"?{eligible:!1,approvalRequirement:"principal",reason:`Tool ${t} cannot request ${r} authority in read-only mode.`}:{eligible:!0,approvalRequirement:"principal",reason:`Tool ${t} is requestable.`}}function Oi(e){if(!e||typeof e!="object")throw E("scope is required");if(M(e.kind,"scope.kind"),!Ti.has(e.kind)&&!e.kind.startsWith("custom:"))throw E("scope.kind is not supported");if(e.kind.startsWith(Be)&&!Pe(e.kind))throw E("Custom capability kind is invalid");if(!["read","write","execute","external"].includes(e.effect))throw E("scope.effect is invalid");let t={"filesystem-read":"read","filesystem-write":"write","process-execute":"execute","network-connect":"external","secret-use":"external","external-action":"external","browser-read":"read","browser-act":"external","computer-observe":"read","computer-act":"external"};if(t[e.kind]&&t[e.kind]!==e.effect)throw E(`${e.kind} capability scopes must use ${t[e.kind]} effect`);if(!Array.isArray(e.operations)||e.operations.length===0)throw E("scope.operations must contain at least one operation");if(e.operations.forEach(r=>M(r,"scope.operations")),e.resources?.forEach(r=>M(r,"scope.resources",8192)),e.destinations?.forEach(r=>M(r,"scope.destinations",8192)),e.secretIds?.forEach(r=>M(r,"scope.secretIds",512)),e.kind==="external-action"){if(!e.externalAction||!Si.has(e.externalAction))throw E("External-action scopes require a supported exact action");if(e.effect!=="external")throw E("External-action scopes must use external effect")}if(e.kind==="network-connect"&&(!e.destinations||e.destinations.length===0))throw E("Network capability scopes require at least one destination");if(e.kind==="secret-use"&&(!e.secretIds||e.secretIds.length===0))throw E("Secret capability scopes require at least one secret ID");if(vi.has(e.kind)&&[...e.resources??[],...e.destinations??[],...e.secretIds??[]].some(n=>n.includes("*")))throw E("High-impact capability scopes cannot use wildcard resources")}function Ni(e,t){let r=e.subject;if(r.runId!==t.subject.runId||r.agentId!==t.subject.agentId)throw O(e,"run or agent subject");if(r.turnId&&r.turnId!==t.subject.turnId)throw O(e,"turn subject");if(r.toolName&&r.toolName!==t.subject.toolName)throw O(e,"tool subject");if(r.operationId&&r.operationId!==t.subject.operationId)throw O(e,"operation subject");if(e.scope.kind!==t.kind)throw O(e,"capability kind");if(!e.scope.operations.includes(t.operation))throw O(e,"operation");if(e.scope.resources?.length&&!t.resource)throw O(e,"resource");if(e.scope.destinations?.length&&!t.destination)throw O(e,"destination");if(e.scope.secretIds?.length&&!t.secretId)throw O(e,"secret");if(e.scope.externalAction&&!t.externalAction)throw O(e,"external action");if(t.resource&&!e.scope.resources?.includes(t.resource))throw O(e,"resource");if(t.destination&&!e.scope.destinations?.includes(t.destination))throw O(e,"destination");if(t.secretId&&!e.scope.secretIds?.includes(t.secretId))throw O(e,"secret");if(t.externalAction&&e.scope.externalAction!==t.externalAction)throw O(e,"external action")}function ki(e){if(!e||typeof e!="object")throw E("approvalContext is required");if(M(e.surface,"approvalContext.surface"),!Ci.has(e.surface)&&!e.surface.startsWith("custom:"))throw E("approvalContext.surface is not supported");if(e.surface.startsWith(Be)&&!Pe(e.surface))throw E("Custom approval surface is invalid");e.promptHash!==void 0&&sn(e.promptHash,"approvalContext.promptHash")}function Je(e,t){if(!e||typeof e!="object")throw E(`${t} is required`);if(!["agent","tool","user","system","integration"].includes(e.kind))throw E(`${t}.kind is invalid`);M(e.id,`${t}.id`)}function sn(e,t){if(!Pi.test(e))throw E(`${t} must be a 64-character lowercase hexadecimal fingerprint`)}function M(e,t,r=1024){if(typeof e!="string"||e.trim().length===0||e.length>r)throw E(`${t} must be a non-empty string no longer than ${r} characters`)}function E(e){return new C("LEASE_INVALID",e)}function O(e,t){return new C("LEASE_SCOPE_MISMATCH",`Capability use is outside lease ${e.leaseId} ${t} scope`)}function an(e,t){return new Date(Date.parse(e)+t).toISOString()}function ce(e){return[...new Set(e)]}function Xi(e){return{...e}}function Di(e){return{...e,operations:ce(e.operations),...e.resources?{resources:ce(e.resources)}:{},...e.destinations?{destinations:ce(e.destinations)}:{},...e.secretIds?{secretIds:ce(e.secretIds)}:{}}}function se(e){return structuredClone(e)}var Ye=require("node:crypto");var Li=8*1024*1024,Mi=4;function Bt(e){return Ki(e.operations??de).map(r=>Ui(r,e.runtime))}function Ui(e,t){return{definition:{name:e,description:ji(e),input_schema:$i(e)},projectPolicyInput(r){let n=Wi(e,r),o=Gi(e,r);return{observabilityInput:n,permissionInput:o,permissionPreview:qi(e,r),approvalKey:`xeno-automation:${e}:${Yi(r)}`,riskLevel:Hi(e)}},async execute(r,n){let o=n?.authorization;if(!o||o.toolName!==e)return{success:!1,output:"",error:"Governed automation requires a host-issued authorization receipt",errorCode:"AUTOMATION_AUTHORIZATION_RECEIPT_REQUIRED",retryable:!1};let i=n.operationId??`automation_${(0,Ye.randomUUID)()}`,a=Ft(e,r);n.reportProgress?.({activity:"state",message:`Authorizing ${e}`});try{let s=await t.execute({operation:e,governingToolName:e,operationId:i,idempotencyKey:i,parameters:structuredClone(r),...a?{declaredTarget:a}:{},authorization:o,...n.signal?{signal:n.signal}:{},...n.reportProgress?{reportProgress:n.reportProgress}:{}}),c=s.status==="ok";return{success:c,output:JSON.stringify(zi(s)),...c?{}:{error:s.error?.message??`Governed automation ended with ${s.status}`,errorCode:s.error?.code??`AUTOMATION_${s.status.toUpperCase().replaceAll("-","_")}`},assistantContent:Ji(s),evidence:s.artifacts.map(d=>({id:d.artifactId,kind:"artifact",status:s.status==="evidence-incomplete"?"failed":"verified",observedAt:d.updatedAt??d.createdAt,operationId:i,detail:{artifact_kind:d.kind,revision:d.revision,sensitivity:d.sensitivity}})),retryable:s.error?.retryable??!1}}catch(s){let c=n.signal?.aborted===!0;return{success:!1,output:"",error:c?"Governed automation was stopped":Zi(s),errorCode:c?"AUTOMATION_CANCELLED":Qi(s),retryable:!c}}}}}function $i(e){let t=Vi(e),r=Bi(e);return{type:"object",properties:t,...r.length>0?{required:r}:{},...e==="browser.locate"?{oneOf:[{required:["selector"]},{required:["text"]}]}:{},additionalProperties:!1}}function Vi(e){let t=(a,s=8192)=>({type:"string",minLength:1,maxLength:s,description:a}),r={type:"number"},n={type:"boolean"},o={type:"object",properties:{x:r,y:r},required:["x","y"],additionalProperties:!1},i={deviceId:t("Target xeno-use device ID.",256),applicationId:t("Expected or launch-target application ID.",512),displayId:t("Target display ID.",256)};switch(e){case"browser.navigate":return{url:t("Destination URL."),waitUntil:{enum:["load","none"]},tabId:t("Expected active tab ID. Hosts with multiple visible tabs should require this.",256)};case"browser.wait":return{until:{enum:["load","ms"]},value:{type:"integer",minimum:0,maximum:6e4}};case"browser.snapshot":return{mode:{enum:["text","html","markdown","a11y"]},tabId:t("Expected active tab ID.",256)};case"browser.screenshot":return{tabId:t("Expected active tab ID.",256)};case"browser.locate":return{selector:t("CSS selector."),text:t("Visible text to locate.")};case"browser.click":return{selector:t("CSS selector returned by browser.snapshot or browser.locate."),tabId:t("Expected active tab ID.",256)};case"browser.type":return{selector:t("CSS selector."),text:{type:"string",maxLength:65536},clear:n,submit:n,tabId:t("Expected active tab ID.",256)};case"browser.key":return{combo:t("Key combo such as Control+a or Enter.",256),tabId:t("Expected active tab ID.",256)};case"browser.select":return{selector:t("CSS selector."),value:t("Option value."),tabId:t("Expected active tab ID.",256)};case"browser.scroll":return{selector:t("Optional CSS selector."),dx:r,dy:r,tabId:t("Expected active tab ID.",256)};case"browser.tabs.open":return{url:t("URL to open in an isolated browser tab.")};case"browser.tabs.close":return{tabId:t("Tab ID to close.",256)};case"browser.console.read":case"browser.network.read":case"browser.page-errors.read":return{limit:{type:"integer",minimum:1,maximum:1e3},clear:n,tabId:t("Expected active tab ID.",256)};case"browser.storage.read":return{tabId:t("Expected active tab ID.",256)};case"browser.upload":return{selector:t("File input or drop-target selector."),backendNodeId:{type:"integer",minimum:1},hostPaths:{type:"array",items:t("Host file path.",32768),minItems:1,maxItems:64},drop:n,tabId:t("Expected active tab ID.",256)};case"browser.download":return{toPath:t("Approved destination path.",32768),trigger:{type:"object",properties:{url:t("Download URL."),selector:t("Download trigger selector.")},oneOf:[{required:["url"]},{required:["selector"]}],additionalProperties:!1},tabId:t("Expected active tab ID.",256)};case"browser.record.start":return{maxDurationMs:{type:"integer",minimum:1e3,maximum:6e4},intervalMs:{type:"integer",minimum:100,maximum:5e3},tabId:t("Expected active tab ID.",256)};case"browser.record.stop":return{tabId:t("Expected active tab ID.",256)};case"computer.observe":case"computer.screenshot":case"computer.window-state":return i;case"computer.point":return{...i,point:o,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.click":return{...i,point:o,button:{enum:["left","right","middle"]},modifiers:Fi()};case"computer.double-click":case"computer.right-click":return{...i,point:o};case"computer.drag":return{...i,from:o,to:o,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.type":return{...i,text:{type:"string",maxLength:65536}};case"computer.key":return{...i,combo:t("Key combo such as Control+a or Enter.",256)};case"computer.scroll":return{...i,at:o,delta:o};case"computer.wait":return{...i,milliseconds:{type:"integer",minimum:0,maximum:3e5}};case"computer.launch":return{...i,applicationId:t("Explicitly allowlisted application ID.",512)};case"browser.back":case"browser.forward":case"browser.reload":return{tabId:t("Expected active tab ID.",256)};case"browser.tabs.list":return{}}}function Bi(e){switch(e){case"browser.navigate":case"browser.tabs.open":return["url"];case"browser.click":return["selector"];case"browser.type":return["selector","text"];case"browser.key":return["combo"];case"browser.select":return["selector","value"];case"browser.upload":return["hostPaths"];case"browser.download":return["toPath","trigger"];case"computer.point":case"computer.click":case"computer.double-click":case"computer.right-click":return["point"];case"computer.drag":return["from","to"];case"computer.type":return["text"];case"computer.key":return["combo"];case"computer.scroll":return["at","delta"];case"computer.launch":return["applicationId"];default:return[]}}function Fi(){return{type:"object",properties:{shift:{type:"boolean"},ctrl:{type:"boolean"},alt:{type:"boolean"},meta:{type:"boolean"}},additionalProperties:!1}}function ji(e){let t=X(e),r=e.split(".").slice(1).join(" ");return`${t.effect==="act"?"Act on":"Inspect"} the ${t.surface} using governed ${r} automation. The host requires policy approval, an exact capability lease, target-bound preflight, and durable evidence.`}function Hi(e){return X(e).effect==="observe"?e==="browser.navigate"||e==="browser.tabs.open"?"medium":"low":["browser.type","browser.upload","browser.download","computer.type","computer.key","computer.launch"].includes(e)?"high":"medium"}function Gi(e,t){let r=Ft(e,t),n={operation:e};r&&(n.target=r);for(let o of["selector","clear","submit","combo","value","dx","dy","point","from","to","at","delta","milliseconds"])t[o]!==void 0&&(n[o]=structuredClone(t[o]));return typeof t.text=="string"&&(n.text=`[redacted ${t.text.length} characters]`),Array.isArray(t.hostPaths)&&(n.hostPaths=t.hostPaths.map(()=>"[redacted host path]")),typeof t.toPath=="string"&&(n.toPath="[redacted destination path]"),n}function Wi(e,t){let r=structuredClone(t);return typeof r.text=="string"&&(r.text=`[redacted ${r.text.length} characters]`),Array.isArray(r.hostPaths)&&(r.hostPaths=r.hostPaths.map(()=>"[redacted host path]")),typeof r.toPath=="string"&&(r.toPath="[redacted destination path]"),dn(r.trigger)&&typeof r.trigger.url=="string"&&(r.trigger={...r.trigger,url:cn(r.trigger.url)}),typeof r.url=="string"&&(r.url=cn(r.url)),{operation:e,...r}}function qi(e,t){let r=Ft(e,t),n=r?.url??r?.applicationId??r?.deviceId??r?.tabId??r?.resource??"current target";return`${e} on ${n}`}function Ft(e,t){let r={};return typeof t.url=="string"&&(r.url=t.url),typeof t.tabId=="string"&&(r.tabId=t.tabId),typeof t.deviceId=="string"&&(r.deviceId=t.deviceId),typeof t.applicationId=="string"&&(r.applicationId=t.applicationId),typeof t.displayId=="string"&&(r.displayId=t.displayId),(e==="browser.navigate"||e==="browser.tabs.list"||e==="browser.tabs.open")&&(r.resource="browser-tabs"),Object.keys(r).length>0?r:void 0}function zi(e){return{operationId:e.operationId,status:e.status,effect:e.effect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:e.adapter,target:e.target,...e.data!==void 0?{data:e.data}:{},artifacts:e.artifacts.map(t=>({artifactId:t.artifactId,revision:t.revision,kind:t.kind,title:t.title,state:t.state,mediaType:t.mediaType,sensitivity:t.sensitivity,hash:t.content.hash,sizeBytes:t.content.sizeBytes})),lease:e.lease,...e.error?{error:e.error}:{}}}function Ji(e){let t=[];for(let r of e.artifacts){if(t.length>=Mi||!r.mediaType.startsWith("image/"))continue;let n=r.content.storage;if(n.type!=="inline"||typeof n.base64!="string")continue;let o=Math.floor(n.base64.length*.75);o<=0||o>Li||t.push({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${n.base64}`,detail:"high"}})}return t}function Ki(e){let t=new Set(de),r=new Set;for(let n of e){if(!t.has(n))throw new TypeError(`Unsupported XENO automation operation: ${String(n)}`);r.add(n)}return Array.from(r)}function Yi(e){return(0,Ye.createHash)("sha256").update(Vt(e)).digest("hex")}function Vt(e){return Array.isArray(e)?`[${e.map(Vt).join(",")}]`:dn(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Vt(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function cn(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid URL]"}}function Zi(e){return e instanceof Error?e.message:String(e)}function Qi(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:"AUTOMATION_EXECUTION_FAILED"}function dn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var fn=[...Xe],ea=fn.filter(e=>!["browser.storage.read","browser.upload","browser.download"].includes(e)),ta=de.filter(e=>e.startsWith("computer.")),jt=6e4,Qe=class{constructor(t){this.options=t;this.environment=t.environment??Wt()}options;leases=new Ke({maximumDurationMs:jt,maximumUses:1});activeExecutors=new Map;environment;browserAdapter;computerAdapter;register(t){if(this.options.safeMode)return 0;let r=[];return Ht(this.environment.browser)&&r.push(...ca(this.environment.browser.driver)),Gt(this.environment.computer)&&r.push(...ta),r.length===0?0:(t.registerAll(Bt({runtime:this,operations:r})),r.length)}async execute(t){if(this.options.safeMode)throw new Error("Governed automation is disabled in safe mode");ha(t);let r=X(t.operation),n=this.options.profile(),o={runId:this.options.runId,agentId:this.options.agentId??"agent-main",...this.options.sessionId?{sessionId:this.options.sessionId}:{},turnId:t.authorization.turnId,...this.options.workspaceId?{workspaceId:this.options.workspaceId}:{}},i=ma(t.operation,t.declaredTarget,this.environment),a=r.surface==="browser"?r.effect==="act"?"browser-act":"browser-read":r.effect==="act"?"computer-act":"computer-observe",s=r.effect==="act"?"external":"read",c=ga(i),d=Aa(i),y=this.leases.request({subject:{...o,toolName:t.governingToolName,operationId:t.operationId},scope:{kind:a,effect:s,operations:[t.operation],...c?{resources:[c]}:{},...d?{destinations:[d]}:{},governingToolName:t.governingToolName},reason:`${t.operation} authorized by the CLI policy and permission layers`,requestedBy:{kind:"agent",id:o.agentId,profileFingerprint:n.fingerprint},durationMs:jt,requestTtlMs:3e4,maxUses:1,childInheritance:"none",policyFingerprints:[n.fingerprint]},n),g=this.leases.approve({leaseId:y.leaseId,expectedVersion:y.version,approvedBy:{kind:"integration",id:`xeno-${this.options.surface}-permission-engine`,displayName:`XENO ${this.options.surface.toUpperCase()} permission engine`},approvalContext:{surface:this.options.surface,turnId:t.authorization.turnId,messageId:t.authorization.toolCallId}}),A=await this.adapterFor(r.surface),m=hr({contractId:`contract-${t.operationId}`,identity:o,policy:this.securityPolicy(),profile:n,...this.options.securityStatus?{adapterStatus:this.options.securityStatus}:{},filesystem:{readRoots:[(0,z.resolve)(this.options.cwd())],writeRoots:[(0,z.resolve)(this.options.cwd())],executeRoots:[(0,z.resolve)(this.options.cwd())]},network:fa(i,this.environment),browser:r.surface==="browser"?ua(r.effect,i,this.environment):{mode:"none"},computer:r.surface==="computer"?pa(r.effect,this.environment):{mode:"none"},capabilityLeaseIds:[g.leaseId],expiresAt:new Date(Date.now()+jt).toISOString()});await this.audit({eventType:"automation_lease_approved",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:g.leaseId,contractFingerprint:m.fingerprint,permissionReason:t.authorization.permission.reason});let N=new ke({adapter:A,leaseAuthority:this.leases,artifactRepository:new qe({directory:(0,z.resolve)(this.options.cwd(),".xeno","artifacts")})});this.activeExecutors.set(t.operationId,N),t.reportProgress?.({activity:"state",message:`Executing governed ${t.operation}`});try{let v=await N.execute({protocolVersion:1,operationId:t.operationId,idempotencyKey:t.idempotencyKey,requestedAt:new Date().toISOString(),identity:o,governingToolName:t.governingToolName,operation:t.operation,parameters:Ia(t.parameters),...i?{declaredTarget:i}:{},executionContract:m,capabilityLeaseId:g.leaseId,expectedLeaseVersion:g.version},t.signal);return await this.audit({eventType:v.status==="ok"?"automation_completed":"automation_failed",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:g.leaseId,contractFingerprint:m.fingerprint,status:v.status,artifactIds:v.artifacts.map(T=>T.artifactId)}),v}catch(v){throw await this.audit({eventType:"automation_failed",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:g.leaseId,contractFingerprint:m.fingerprint,status:v instanceof Error?v.name:"error"}),v}finally{this.activeExecutors.delete(t.operationId)}}async stop(t,r="human-stop"){let n=this.activeExecutors.get(t);return n?n.stop(t,r):!1}securityPolicy(){let t=this.options.securityPolicy?.();if(t)return t;let r=(0,z.resolve)(this.options.cwd());return{allowedDirectories:[r],workingDirectory:r,capabilities:{terminal:!0,fileRead:!0,fileWrite:!0,appLaunch:!0},executionLevel:"policy-only",trustMode:"trusted-workspace",allowNetwork:!1}}adapterFor(t){if(t==="browser"){let n=this.environment.browser;if(!Ht(n))throw new Error(gn(n));return this.browserAdapter??=new Ae({baseUrl:n.baseUrl,token:n.token,driver:n.driver}),this.browserAdapter}let r=this.environment.computer;if(!Gt(r))throw new Error(An(r));return this.computerAdapter??=mn(r),this.computerAdapter}async audit(t){try{await this.options.onAudit?.(t)}catch{}}};function ra(e){return new Qe(e)}function na(e){if(e)return async t=>{let r=X(t.operation).effect;await e.append({trace_id:t.traceId,event_type:t.eventType,actor:"system",risk_level:r==="act"?"high":"low",...t.eventType==="automation_lease_approved"?{decision:"allow"}:{},status:t.eventType==="automation_failed"?"error":"ok",...t.eventType==="automation_failed"&&t.status?{reason:t.status}:{},metadata:{operation:t.operation,operation_id:t.operationId,lease_id:t.leaseId,contract_fingerprint:t.contractFingerprint,result_status:t.status,artifact_ids:t.artifactIds,permission_reason:t.permissionReason}})}}async function oa(e=Wt()){let t=await Promise.all([ln("browser",e),ln("computer",e)]);return{schemaVersion:1,protocolVersion:1,enabled:t.some(r=>r.configured),surfaces:t,docs:"docs/GOVERNED_AUTOMATION.md"}}function Wt(e=process.env){let t=e.XENO_BROWSER_DRIVER==="extension"?"extension":"browser",r=aa(e,t),n=F(e.XENO_BROWSER_AUTOMATION_URL)??r?.baseUrl,o=F(e.XENO_BROWSER_AUTOMATION_TOKEN)??r?.token,i=F(e.XENO_USE_BASE_URL),a=F(e.XENO_USE_TOKEN)??ia(e.XENO_USE_TOKEN_FILE),s=F(e.XENO_USE_DEVICE_ID);return{browser:{driver:t,...n?{baseUrl:n}:{},...o?{token:o}:{},readDomains:Ze(e.XENO_BROWSER_READ_DOMAINS),actDomains:Ze(e.XENO_BROWSER_ACT_DOMAINS),deniedDomains:Ze(e.XENO_BROWSER_DENIED_DOMAINS),ports:ba(e.XENO_BROWSER_ALLOWED_PORTS,[443]),allowLoopbackDevelopment:e.XENO_BROWSER_ALLOW_LOOPBACK_DEVELOPMENT==="1",uploads:un(e.XENO_BROWSER_UPLOADS,"prompt"),downloads:un(e.XENO_BROWSER_DOWNLOADS,"prompt"),recording:e.XENO_BROWSER_RECORDING==="bounded"?"bounded":"disabled"},computer:{...i?{baseUrl:i}:{},...a?{token:a}:{},...s?{deviceId:s}:{},allowedApplications:Ze(e.XENO_USE_ALLOWED_APPLICATIONS)}}}function ia(e){let t=F(e);if(!(!t||!(0,Ie.existsSync)(t)))try{return F((0,Ie.readFileSync)(t,"utf8"))}catch{return}}function aa(e,t){let n=F(e.XENO_BROWSER_SESSION_FILE)??(t==="extension"?F(e.XENO_EXTENSION_SESSION_FILE)??(0,z.join)((0,pn.homedir)(),".xeno","use-drivers","xeno-extension.json"):F(e.XENO_SESSION_FILE)??(e.APPDATA?(0,z.join)(e.APPDATA,"xeno-browser","session.json"):void 0));if(!(!n||!(0,Ie.existsSync)(n)))try{let o=JSON.parse((0,Ie.readFileSync)(n,"utf8")),i=Number(o.port),a=typeof o.token=="string"?o.token:"",s=typeof o.driver=="string"?o.driver:void 0;return!Number.isSafeInteger(i)||i<=0||i>65535||!sa(a)||s&&s!==(t==="extension"?"xeno-extension-native":"xeno-browser-loopback")?void 0:{baseUrl:`http://127.0.0.1:${i}`,token:a}}catch{return}}function sa(e){return e.length>=32&&e.length<=512&&!/\s/.test(e)}function ca(e){return e==="extension"?[...ea]:[...fn]}async function ln(e,t){let r=e==="browser"?t.browser:t.computer,n=e==="browser"?Ht(t.browser):Gt(t.computer),o=!!r&&Object.values(r).some(i=>typeof i=="string"&&i.length>0);if(!n)return{surface:e,configured:!1,available:!1,certified:!1,operations:[],limitations:["Adapter credentials are not completely configured."],...o?{error:e==="browser"?gn(t.browser):An(t.computer)}:{}};try{let a=await(e==="browser"?new Ae({baseUrl:t.browser.baseUrl,token:t.browser.token,driver:t.browser.driver}):await mn(t.computer)).manifest();return la(e,a)}catch(i){return{surface:e,configured:!0,available:!1,certified:!1,operations:[],limitations:["Configured adapter is unavailable."],error:qt(i)}}}async function mn(e){let t=await da(),r=new t.Use({baseUrl:e.baseUrl,token:e.token});return new t.XenoUseComputerAutomationAdapter({use:r,...e.deviceId?{defaultDeviceId:e.deviceId}:{}})}async function da(){try{let e="@xeno-use/sdk",t="@xeno-use/agent-sdk-pack",[r,n]=await Promise.all([import(e),import(t)]);if(typeof r.Use!="function"||typeof n.XenoUseComputerAutomationAdapter!="function")throw new Error("installed xeno-use packages do not expose the governed adapter contract");return{Use:r.Use,XenoUseComputerAutomationAdapter:n.XenoUseComputerAutomationAdapter}}catch(e){throw new Error(`Computer automation requires @xeno-use/sdk and @xeno-use/agent-sdk-pack: ${qt(e)}`)}}function la(e,t){return{surface:e,configured:!0,available:!0,certified:t.certified,adapterId:t.adapterId,adapterVersion:t.adapterVersion,operations:[...t.operations],limitations:[...t.limitations]}}function ua(e,t,r){let n=r.browser,o=hn(t),i=o&&!ya(o.hostname)?o.hostname:void 0,a=et([...n.readDomains,...i?[i]:[]]),s=et([...n.actDomains,...e==="act"&&i?[i]:[]]),c=yn([...n.ports,...o?[In(o)]:[]]);return{mode:e==="act"?"act":"read",profile:"ephemeral",readAllowedDomains:a,actAllowedDomains:s,deniedDomains:n.deniedDomains,allowedSchemes:n.allowLoopbackDevelopment?["https","http"]:["https"],allowedPorts:c,redirectPolicy:"policy",allowLoopbackDevelopment:n.allowLoopbackDevelopment,uploads:n.uploads,downloads:n.downloads,recording:n.recording}}function pa(e,t){return{mode:e==="act"?"act":"observe",allowedApplications:t.computer?.allowedApplications??[],sensitiveRegionRedaction:!0,humanStopRequired:!0}}function fa(e,t){let r=[],n=hn(e);n&&r.push({scheme:n.protocol.replace(/:$/,""),host:n.hostname.toLowerCase(),port:In(n)});for(let o of et([...t.browser?.readDomains??[],...t.browser?.actDomains??[]]))if(!(o.startsWith(".")||o.includes("*")))for(let i of t.browser?.ports??[443])r.push({scheme:i===80?"http":"https",host:o,port:i});return{default:"deny",allowDestinations:wa(r)}}function ma(e,t,r){if(!e.startsWith("computer."))return t;let n=t?.deviceId??r.computer?.deviceId,o=t?.applicationId;if(!(!n&&!o&&!t))return{...t??{},...n?{deviceId:n}:{}}}function ga(e){return e?.resource??e?.tabId??e?.pageId??e?.deviceId??e?.applicationId}function Aa(e){let t=e?.origin??e?.url;if(!t)return e?.domain;try{return new URL(t).origin}catch{return t}}function ha(e){let t=e.authorization;if(!t||t.toolName!==e.governingToolName||!t.permission.allowed||!t.policy.allowed)throw new Error("Automation authorization receipt does not match the governing tool")}function Ia(e){try{return JSON.parse(JSON.stringify(e))}catch(t){throw new Error(`Automation parameters are not JSON serializable: ${qt(t)}`)}}function Ht(e){return!!e?.baseUrl&&!!e.token}function Gt(e){return!!e?.baseUrl&&!!e.token&&!!e.deviceId}function gn(e){return`Browser automation configuration is incomplete; missing ${[e?.baseUrl?"":"XENO_BROWSER_AUTOMATION_URL",e?.token?"":"XENO_BROWSER_AUTOMATION_TOKEN"].filter(Boolean).join(", ")}`}function An(e){return`Computer automation configuration is incomplete; missing ${[e?.baseUrl?"":"XENO_USE_BASE_URL",e?.token?"":"XENO_USE_TOKEN",e?.deviceId?"":"XENO_USE_DEVICE_ID"].filter(Boolean).join(", ")}`}function hn(e){let t=e?.url??e?.origin;if(t)try{return new URL(t)}catch{return}}function In(e){return e.port?Number(e.port):e.protocol==="http:"?80:443}function ya(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"}function Ze(e){return et((e??"").split(",").map(t=>t.trim().toLowerCase()).filter(Boolean))}function ba(e,t){let r=(e??"").split(",").map(n=>Number(n.trim())).filter(n=>Number.isSafeInteger(n)&&n>0&&n<=65535);return r.length>0?yn(r):t}function un(e,t){return e==="deny"||e==="prompt"||e==="allow"?e:t}function F(e){let t=e?.trim();return t||void 0}function et(e){return[...new Set(e)]}function yn(e){return[...new Set(e)].sort((t,r)=>t-r)}function wa(e){let t=new Set;return e.filter(r=>{let n=`${r.scheme??""}:${r.host}:${r.port??""}`;return t.has(n)?!1:(t.add(n),!0)})}function qt(e){return e instanceof Error?e.message:String(e)}function Ea(e){let t=["XENO governed automation",""];for(let r of e.surfaces){let n=r.configured?r.available?"available":"unavailable":"not configured",o=r.certified?"certified":"not release-certified";t.push(`${r.surface}: ${n}; ${o}`),r.adapterId&&t.push(` adapter: ${r.adapterId}@${r.adapterVersion??"unknown"}`),r.operations.length>0&&t.push(` operations: ${r.operations.length}`);for(let i of r.limitations)t.push(` limitation: ${i}`);r.error&&t.push(` error: ${r.error}`)}return t.push("",`Docs: ${e.docs}`),t.join(`
|
|
938
|
+
`)}0&&(module.exports={CliGovernedAutomationRuntime,XENO_AUTOMATION_OPERATIONS,XENO_AUTOMATION_PROTOCOL_VERSION,XENO_BROWSER_CONTROL_PLANE_OPERATIONS,XenoAutomationError,XenoBrowserControlPlaneAdapter,XenoGovernedAutomationExecutor,XenoHostGovernedAutomationRuntime,XenoLoopbackAutomationAdapter,assertRequiredXenoAutomationEvidence,assertValidXenoAutomationAdapterManifest,assertValidXenoAutomationRequest,assertXenoAutomationAdapterConformant,assertXenoAutomationAuthority,buildXenoAutomationCapabilityUse,createCliAutomationAuditSink,createCliGovernedAutomationRuntime,createXenoAutomationConformanceReport,createXenoGovernedAutomationTools,createXenoHostAutomationAuditSink,createXenoHostGovernedAutomationRuntime,describeXenoAutomationOperation,inspectCliAutomationStatus,inspectXenoHostAutomationStatus,isXenoAutomationOperation,materializeXenoAutomationEvidence,persistXenoAutomationEvidence,readCliAutomationEnvironment,readXenoHostAutomationEnvironment,renderCliAutomationStatus,renderXenoHostAutomationStatus,resolveXenoAutomationEvidencePolicy});
|