@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
package/dist/automation/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var B=1;var $e=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"]),Ve=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"]),Be=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),Fe=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),ae=[...$e,...Ve,...Be,...Fe];function N(e){if($e.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(Ve.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(Be.has(e))return{operation:e,surface:"computer",effect:"observe",evidence:{before:"disabled",after:e==="computer.wait"?"optional":"required",recording:"optional"}};if(Fe.has(e))return{operation:e,surface:"computer",effect:"act",evidence:{before:"required",after:"required",recording:"optional"}};throw new TypeError(`Unsupported XENO automation operation: ${e}`)}function je(e){return $e.has(e)||Ve.has(e)||Be.has(e)||Fe.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};import{createHash as ho}from"node:crypto";import{arch as Io}from"node:os";import{existsSync as Tt,realpathSync as pn}from"node:fs";import{dirname as fn,isAbsolute as mn,join as gn,resolve as be,sep as An}from"node:path";var hn=/^(?:con|prn|aux|nul|clock\$|com[1-9]|lpt[1-9])(?:\..*)?$/i;function In(e){return e.replace(/\//g,"\\")}function yn(e){let t=[],r=In(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}`}),hn.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 bn(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("\\")?yn(e):[]}function wn(e){let r=be(e),n=[];for(;!Tt(r);){let i=fn(r);if(i===r)break;n.unshift(r.slice(i.length).replace(/^[/\\]+/,"")),r=i}let o=Tt(r)?pn.native(r):r;return{canonicalPath:n.reduce((i,a)=>gn(i,a),o),existingAncestor:o}}function H(e,t){let r=t?.platform??process.platform,n=bn(e,r);if(n.length>0){let a=new Error(`${n[0].code}: ${n[0].message}`);throw a.name="SecurityPathError",a}let o=mn(e)?be(e):be(t?.baseDirectory??process.cwd(),e),i=wn(o);return{input:e,absolutePath:o,...i}}function Ct(e){let t=be(e);return process.platform==="win32"?t.toLowerCase():t}function Pt(e,t){let r;try{r=Ct(H(e).canonicalPath)}catch{return!1}for(let n of t){let o;try{o=Ct(H(n).canonicalPath)}catch{continue}if(r===o||r.startsWith(o+An))return!0}return!1}import{existsSync as Rt,mkdirSync as ds,renameSync as ls,rmSync as us,writeFileSync as ps}from"node:fs";import{join as _t}from"node:path";var ms=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
|
+
`,gs=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 Vt=512*1024,Bt=744*60*60*1e3,$t=Object.freeze(["allowedFilesystemRead","allowedFilesystemWrite","outsideFilesystemReadDenied","outsideFilesystemWriteDenied","unlistedFilesystemReadDenied","unlistedFilesystemWriteDenied","symlinkEscapeDenied","networkDefaultDeny","environmentSecretsExcluded","childProcessPolicyInherited","standardCommandLaunch","processTreeCleanup","timeoutEnforced","hostPolicyRecoveryClean","uiRestrictionsEnforced"]);var zt=10*6e4,Jt=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"}),qt=Object.freeze({"win32-x64-wxc-host-prep.exe":"531fb3cdb4b0c964908fd71b71d40961417afb399cbab72f92a25e95309a6416","win32-arm64-wxc-host-prep.exe":"3ef702332286a39153fc259310b5021e3de3c191751d7522684f6475f73af5ef"});var lr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),ur=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!0,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!0,environmentSanitization:!0}),pr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),fr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!0,networkIsolation:!0,inheritedHandleAllowlist:!0,environmentSanitization:!0}),mr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0});var Oe=1,V=class extends Error{constructor(r,n){super(n);this.code=r;this.name="XenoSecureExecutionContractError"}code};function Pe(e){let t=[];if(!e||typeof e!="object")return["Contract must be an object"];if(e.schemaVersion!==Oe&&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"),ne(e.createdAt)||t.push("createdAt must be an ISO 8601 timestamp"),e.expiresAt&&(!ne(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,xe(r)!==e.fingerprint&&t.push("Contract fingerprint does not match content")}return t}function oe(e){let t=Pe(e);if(t.length>0){let r=t.includes("Contract fingerprint does not match content");throw new V(r?"SECURITY_CONTRACT_FINGERPRINT_MISMATCH":"SECURITY_CONTRACT_INVALID",t.join("; "))}}function xe(e){return Ne("sha256").update(JSON.stringify(B(e))).digest("hex")}function B(e){return Array.isArray(e)?e.map(B):!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,B(r)]))}function ne(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}var Xe=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,ie=1048576;function le(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"),fe(e.requestedAt)||h("requestedAt must be an ISO 8601 timestamp"),M(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>ie&&h(`parameters exceed ${ie} bytes`),w(e.identity?.runId,"identity.runId"),w(e.identity?.agentId,"identity.agentId"),oe(e.executionContract),ke(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 C(e){(!e||typeof e!="object")&&f("Adapter manifest must be an object"),e.protocolVersion!==1&&f("Adapter protocol version is unsupported"),S(e.adapterId,"adapterId"),S(e.adapterVersion,"adapterVersion"),S(e.platform,"platform"),S(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)M(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 F(e,t,r){let n=A(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(Le(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"?Ue(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 ue(e,t){let r=A(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,...ae(e,t)?{resource:ae(e,t)}:{},...ce(t)?{destination:ce(t)}:{}}}function ae(e,t){return e.declaredTarget?.resource??De(t)}function pe(e){let t=A(e.operation).evidence,r=e.evidencePolicy??{},n=$(t.before,r.before),o=$(t.after,r.after),a=$(t.recording,r.recording),c=r.retainUntil;return c&&!fe(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 ke(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 Le(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=Me(s);if(de(s,d.deniedDomains)&&E(`Browser domain ${s} is denied`),se(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;de(s,m)||E(`Browser domain ${s} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&(se(o,e.executionContract.network.allowDestinations)||E(`Network policy does not allow ${c}://${s}:${l}`))}function se(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 De(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function ce(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function Ue(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 de(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 Me(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function $(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"||!Xe.test(e))&&h(`${t} is invalid`)}function S(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&f(`${t} is invalid`)}function fe(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)}import{createHash as $e}from"node:crypto";var me=["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"],Ie=["draft","pending_review","approved","rejected","superseded","archived"],Ae=["public","internal","confidential","restricted"],he=["agent","tool","user","system","integration"],ge=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],be=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];import{createHash as Ve}from"node:crypto";function _(e){return{algorithm:"sha256",value:Ve("sha256").update(e).digest("hex")}}var Be="[\\u0000-\\u001f\\u007f]",Dr=new RegExp(Be);var Ur=new Set(Ie),Mr=new Set(Ae),Vr=new Set(he),Br=new Set(me),$r=new Set(ge),Fr=new Set(be);var R=class extends Error{constructor(r,n,o,a){super(n,a);this.code=r;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail};var j=32*1024*1024,Fe=1024*1024*1024,He=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function G(e){let r=(e.now??(()=>new Date().toISOString()))(),n=new Set;return e.evidence.map((o,a)=>{if(Ge(o),n.has(o.evidenceId))throw new i("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${o.evidenceId}`);n.add(o.evidenceId);let c=je(o),s=$e("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 W(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 R&&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 N(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 je(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return Ee(t),{hash:_(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=We(e.content.base64);return Ee(t.byteLength),{hash:_(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>Fe)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 Ge(e){(!e||typeof e!="object")&&g("Evidence must be an object"),He.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 We(e){(e.length===0||e.length>Math.ceil(j/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 Ee(e){e>j&&g(`Inline evidence exceeds ${j} bytes`)}function g(e){throw new i("AUTOMATION_EVIDENCE_INVALID",e)}import{createHash as ze}from"node:crypto";var we=3e4,Je=1e3,ye=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=Qe(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=et(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){le(t),J(r);let n=await this.adapter.manifest();C(n);let o=A(t.operation),a=pe(t),c=this.now(),s=await this.adapter.preflight(t,r);qe(s,this.now()),F(t,n,s.observedTarget),J(r);let l=s.evidence??[];N(l,a,"before");let d=await W(this.artifactRepository,G({request:t,manifest:n,policy:a,evidence:l,now:this.now}));if(J(r),Date.parse(s.expiresAt)<=Date.parse(this.now()))throw new i("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let p=ue(t,s.observedTarget),m=await this.leaseAuthority.consume(t.capabilityLeaseId,t.expectedLeaseVersion,p),Q={contractFingerprint:t.executionContract.fingerprint,lease:m,capabilityUse:p},u;try{u=await this.adapter.execute(t,s,Q,r)}catch(I){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":tt(I)})}Ke(u);let ee=Ye(s.observedTarget,u.observedTarget),O;try{F(t,n,u.observedTarget)}catch(I){O=I instanceof Error?I:new Error(String(I))}let T=u.evidence??[];Ze(l,T);let te=[],P;try{N(T,a,"after"),N([...l,...T],a,"recording"),te=await W(this.artifactRepository,G({request:t,manifest:n,policy:a,evidence:T,now:this.now}))}catch(I){P=I instanceof Error?I:new Error(String(I))}let x=[...d,...te];return ee||O?z({request:t,manifest:n,descriptorEffect:o.effect,target:u.observedTarget,lease:m,artifacts:x,startedAt:u.startedAt,completedAt:u.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:ee??O.message}):P?z({request:t,manifest:n,descriptorEffect:o.effect,target:u.observedTarget,lease:m,artifacts:x,startedAt:u.startedAt,completedAt:u.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:P.message}):{operationId:t.operationId,status:u.status,effect:o.effect,startedAt:u.startedAt,completedAt:u.completedAt,adapter:ve(n),target:structuredClone(u.observedTarget),...u.data!==void 0?{data:structuredClone(u.data)}:{},artifacts:x,lease:Te(m),...u.error?{error:{...u.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>Je;){let t=this.executions.keys().next().value;if(!t||this.active.has(t))break;this.executions.delete(t)}}};function qe(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>we)throw new i("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${we} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new i("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function Ke(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 Ye(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 Ze(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:ve(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:Te(e.lease),error:{code:e.code,message:e.message}}}function ve(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function Te(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function Qe(e){return ze("sha256").update(JSON.stringify(q(e))).digest("hex")}function q(e){return Array.isArray(e)?e.map(q):!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,q(r)]))}function et(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 J(e){if(e.aborted)throw new i("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function tt(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}function rt(e,t=()=>new Date().toISOString()){let r=[];nt(r,"manifest.valid",()=>C(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 mn(e){let r=rt(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 nt(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 ot=6e4,it=48*1024*1024,Se=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(t){if(this.endpoint=at(t.baseUrl),this.token=st(t.token),this.timeoutMs=Ce(t.timeoutMs??ot,1e3,3e5,"timeoutMs"),this.maxResponseBytes=Ce(t.maxResponseBytes??it,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=lt(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 ct(d,this.maxResponseBytes);if(!d.ok){let m=dt(p);throw new i("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${t}: ${m.message}`,{status:d.status,route:t,adapterCode:m.code})}if(!K(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 at(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 st(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 ct(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 dt(e){return K(e)&&K(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 lt(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 Ce(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 K(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}import{createHash as ut,randomUUID as pt}from"node:crypto";var ft=8*1024*1024,mt=4;function En(e){return _t(e.operations??U).map(r=>It(r,e.runtime))}function It(e,t){return{definition:{name:e,description:Et(e),input_schema:At(e)},projectPolicyInput(r){let n=vt(e,r),o=yt(e,r);return{observabilityInput:n,permissionInput:o,permissionPreview:Tt(e,r),approvalKey:`xeno-automation:${e}:${Rt(r)}`,riskLevel:wt(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_${pt()}`,c=Z(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(St(s)),...l?{}:{error:s.error?.message??`Governed automation ended with ${s.status}`,errorCode:s.error?.code??`AUTOMATION_${s.status.toUpperCase().replaceAll("-","_")}`},assistantContent:Ct(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":Nt(s),errorCode:l?"AUTOMATION_CANCELLED":Ot(s),retryable:!l}}}}}function At(e){let t=ht(e),r=gt(e);return{type:"object",properties:t,...r.length>0?{required:r}:{},...e==="browser.locate"?{oneOf:[{required:["selector"]},{required:["text"]}]}:{},additionalProperties:!1}}function ht(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:bt()};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 gt(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 bt(){return{type:"object",properties:{shift:{type:"boolean"},ctrl:{type:"boolean"},alt:{type:"boolean"},meta:{type:"boolean"}},additionalProperties:!1}}function Et(e){let t=A(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 wt(e){return A(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 yt(e,t){let r=Z(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 vt(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]"),Re(r.trigger)&&typeof r.trigger.url=="string"&&(r.trigger={...r.trigger,url:_e(r.trigger.url)}),typeof r.url=="string"&&(r.url=_e(r.url)),{operation:e,...r}}function Tt(e,t){let r=Z(e,t),n=r?.url??r?.applicationId??r?.deviceId??r?.tabId??r?.resource??"current target";return`${e} on ${n}`}function Z(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 St(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 Ct(e){let t=[];for(let r of e.artifacts){if(t.length>=mt||!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>ft||t.push({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${n.base64}`,detail:"high"}})}return t}function _t(e){let t=new Set(U),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 Rt(e){return ut("sha256").update(Y(e)).digest("hex")}function Y(e){return Array.isArray(e)?`[${e.map(Y).join(",")}]`:Re(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Y(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function _e(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid URL]"}}function Nt(e){return e instanceof Error?e.message:String(e)}function Ot(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:"AUTOMATION_EXECUTION_FAILED"}function Re(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}export{U as XENO_AUTOMATION_OPERATIONS,v as XENO_AUTOMATION_PROTOCOL_VERSION,i as XenoAutomationError,ye as XenoGovernedAutomationExecutor,Se as XenoLoopbackAutomationAdapter,N as assertRequiredXenoAutomationEvidence,C as assertValidXenoAutomationAdapterManifest,le as assertValidXenoAutomationRequest,mn as assertXenoAutomationAdapterConformant,F as assertXenoAutomationAuthority,ue as buildXenoAutomationCapabilityUse,rt as createXenoAutomationConformanceReport,En as createXenoGovernedAutomationTools,A as describeXenoAutomationOperation,M as isXenoAutomationOperation,G as materializeXenoAutomationEvidence,W as persistXenoAutomationEvidence,pe as resolveXenoAutomationEvidencePolicy};
|
|
925
|
+
`;function xt(){let e=process.env.SystemRoot??process.env.WINDIR;if(e){let t=_t(e,"Microsoft.NET","Framework64","v4.0.30319","csc.exe");if(Rt(t))return t;let r=_t(e,"Microsoft.NET","Framework","v4.0.30319","csc.exe");if(Rt(r))return r}return null}import{spawnSync as Ot}from"node:child_process";import{accessSync as En,constants as vn,existsSync as Sn,realpathSync as Tn,statSync as Cn}from"node:fs";import{delimiter as Pn,isAbsolute as Rn,join as _n,resolve as xn}from"node:path";var Xt="XENO_BWRAP_PROFILE_OK",Nt=5e3,He;function kt(e){try{return!Sn(e)||!Cn(e).isFile()?null:(En(e,vn.X_OK),Tn(e))}catch{return null}}function On(){let e=process.env.XENO_BWRAP_PATH?.trim();if(e)return kt(Rn(e)?e:xn(e));let t=["/usr/bin/bwrap","/bin/bwrap",...(process.env.PATH??"").split(Pn).filter(Boolean).map(r=>_n(r,"bwrap"))];for(let r of new Set(t)){let n=kt(r);if(n)return n}return null}function Nn(){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 ${Xt}`]}function Dt(){let e=[process.platform,process.env.XENO_BWRAP_PATH??"",process.env.PATH??""].join("\0");if(He?.key===e)return{...He.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=On();if(!r)t={available:!1,reason:"bubblewrap is not installed or is not executable."};else{let n=Ot(r,["--version"],{encoding:"utf8",timeout:Nt}),o=Ot(r,Nn(),{encoding:"utf8",timeout:Nt,env:process.env}),i=n.status===0?n.stdout.trim():void 0;if(o.status===0&&o.stdout===Xt)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 He={key:e,capability:t},{...t}}import{createHash as kn,createPublicKey as Xn,verify as Dn}from"node:crypto";import{readFileSync as Ln,statSync as Mn}from"node:fs";import{isAbsolute as Un}from"node:path";var Ge="xeno.containment-certification.v1",Lt=512*1024,$n=744*60*60*1e3,Mt=Object.freeze(["allowedFilesystemRead","allowedFilesystemWrite","outsideFilesystemReadDenied","outsideFilesystemWriteDenied","unlistedFilesystemReadDenied","unlistedFilesystemWriteDenied","symlinkEscapeDenied","networkDefaultDeny","environmentSecretsExcluded","childProcessPolicyInherited","standardCommandLaunch","processTreeCleanup","timeoutEnforced","hostPolicyRecoveryClean","uiRestrictionsEnforced"]),h=class extends Error{constructor(t){super(`CONTAINMENT_CERTIFICATION_INVALID: ${t}`),this.name="ContainmentCertificationError"}};function Vn(e){let t={...e};return delete t.signature,Buffer.from(JSON.stringify(qe(t)),"utf8")}function Ut(e,t,r=new Date){if(!Un(e.manifestPath))throw new h("manifestPath must be absolute");se(e.candidateSha256,"candidateSha256");let n=Mn(e.manifestPath);if(!n.isFile())throw new h("manifestPath must reference a regular file");if(n.size<=0||n.size>Lt)throw new h(`manifest size must be between 1 and ${Lt} bytes`);let o=Ln(e.manifestPath),i;try{i=JSON.parse(o.toString("utf8"))}catch{throw new h("manifest is not valid JSON")}let a=Bn(i);if(e.expectedCertificationId&&a.certificationId!==e.expectedCertificationId)throw new h("certificationId does not match the host binding");if(a.candidate.sha256.toLowerCase()!==e.candidateSha256.toLowerCase())throw new h("candidate digest does not match the running candidate binding");if(a.platform.os!==t.platform||a.platform.arch!==t.arch)throw new h("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 h("certified adapter identity does not match the installed native adapter");let s=We(a.issuedAt,"issuedAt"),c=We(a.expiresAt,"expiresAt");if(c<=s)throw new h("expiresAt must be later than issuedAt");if(c-s>$n)throw new h("certification lifetime exceeds 31 days");if(r.getTime()<s-5*6e4)throw new h("certification is not active yet");if(r.getTime()>=c)throw new h("certification has expired");for(let A of Mt)if(a.conformance.checks[A]!==!0)throw new h(`required conformance check did not pass: ${A}`);if(!a.approvals.some(A=>A.role==="security-reviewer"&&A.subject!==a.issuedBy))throw new h("an independent security-reviewer approval is required");let d=e.trustedPublicKeys[a.signature.keyId];if(!d)throw new h("signature key is not trusted by this host");let I;try{I=Buffer.from(a.signature.value,"base64")}catch{throw new h("signature is not valid base64")}if(I.length!==64)throw new h("Ed25519 signature must be 64 bytes");let g=!1;try{g=Dn(null,Vn(a),Xn(d),I)}catch{throw new h("signature key or value is invalid")}if(!g)throw new h("signature verification failed");return{manifest:a,manifestSha256:kn("sha256").update(o).digest("hex")}}function Bn(e){let t=F(e,"manifest");if(t.schemaVersion!==Ge)throw new h(`schemaVersion must be ${Ge}`);let r=y(t.certificationId,"certificationId"),n=F(t.candidate,"candidate"),o=F(t.adapter,"adapter"),i=F(t.platform,"platform"),a=F(t.conformance,"conformance"),s=F(a.checks,"conformance.checks"),c=F(t.signature,"signature"),d=t.approvals;if(!Array.isArray(d)||d.length===0)throw new h("approvals must contain at least one approval");let I=d.map((x,b)=>{let M=F(x,`approvals[${b}]`),oe=y(M.role,`approvals[${b}].role`);if(oe!=="security-reviewer"&&oe!=="release-reviewer")throw new h(`approvals[${b}].role is invalid`);let ye=oe;We(y(M.approvedAt,`approvals[${b}].approvedAt`),`approvals[${b}].approvedAt`);let ie=y(M.approvalSha256,`approvals[${b}].approvalSha256`);return se(ie,`approvals[${b}].approvalSha256`),{subject:y(M.subject,`approvals[${b}].subject`),role:ye,approvedAt:M.approvedAt,approvalArtifactId:y(M.approvalArtifactId,`approvals[${b}].approvalArtifactId`),approvalSha256:ie}}),g=y(o.backend,"adapter.backend");if(g!=="processcontainer"&&g!=="bubblewrap"&&g!=="seatbelt")throw new h("adapter.backend is invalid");let A=y(i.os,"platform.os"),m=y(i.arch,"platform.arch");if(y(c.algorithm,"signature.algorithm")!=="ed25519")throw new h("signature.algorithm must be ed25519");let E={};for(let x of Mt){if(s[x]!==!0)throw new h(`conformance.checks.${x} must be true`);E[x]=!0}let S=y(o.nativeBinarySha256,"adapter.nativeBinarySha256"),X=y(n.sha256,"candidate.sha256"),O=y(a.reportSha256,"conformance.reportSha256");if(se(S,"adapter.nativeBinarySha256"),se(X,"candidate.sha256"),se(O,"conformance.reportSha256"),a.passed!==!0)throw new h("conformance.passed must be true");return{schemaVersion:Ge,certificationId:r,candidate:{product:y(n.product,"candidate.product"),version:y(n.version,"candidate.version"),sha256:X},adapter:{name:o.name==="microsoft-mxc"?"microsoft-mxc":Fn(),version:y(o.version,"adapter.version"),backend:g,isolationTier:y(o.isolationTier,"adapter.isolationTier"),nativeBinarySha256:S},platform:{os:A,arch:m},conformance:{reportArtifactId:y(a.reportArtifactId,"conformance.reportArtifactId"),reportSha256:O,passed:!0,checks:E},issuedAt:y(t.issuedAt,"issuedAt"),expiresAt:y(t.expiresAt,"expiresAt"),issuedBy:y(t.issuedBy,"issuedBy"),approvals:I,signature:{algorithm:"ed25519",keyId:y(c.keyId,"signature.keyId"),value:y(c.value,"signature.value")}}}function Fn(){throw new h("adapter.name must be microsoft-mxc")}function F(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new h(`${t} must be an object`);return e}function y(e,t){if(typeof e!="string"||e.trim().length===0)throw new h(`${t} must be a non-empty string`);return e}function se(e,t){if(!/^[a-f0-9]{64}$/i.test(e))throw new h(`${t} must be a SHA-256 hex digest`)}function We(e,t){let r=Date.parse(e);if(!Number.isFinite(r))throw new h(`${t} must be an ISO timestamp`);return r}function qe(e){return Array.isArray(e)?e.map(qe):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,qe(r)])):e}import{createHash as we,randomUUID as jn}from"node:crypto";import{accessSync as Hn,chmodSync as $t,constants as Gn,existsSync as Ee,lstatSync as Ke,mkdirSync as Wn,readFileSync as de,realpathSync as qn,renameSync as zn,statSync as Jn,unlinkSync as Kn,writeFileSync as Yn}from"node:fs";import{tmpdir as Zn}from"node:os";import{dirname as Ht,isAbsolute as Vt,join as G,parse as Os}from"node:path";import{spawnSync as Bt}from"node:child_process";import{fileURLToPath as Qn}from"node:url";var Ft="microsoft-mxc",ce="0.7.0";var eo="@microsoft/mxc-sdk",to="sha512-EWhz2pKkcPluZHAOI1yneV+JK0NO/3hdh7nABBb0x4PjyUWMeSWPTBAjtIu+BhtMYOqlaijSPZMZ0Hs/J4ZL4A==",Ls=10*6e4,ro=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"}),Ms=Object.freeze({"win32-x64-wxc-host-prep.exe":"531fb3cdb4b0c964908fd71b71d40961417afb399cbab72f92a25e95309a6416","win32-arm64-wxc-host-prep.exe":"3ef702332286a39153fc259310b5021e3de3c191751d7522684f6475f73af5ef"});function no(e){return e.some(t=>t.includes("wxc-host-prep prepare-system-drive")||t.includes("wxc-host-prep prepare-null-device"))}function oo(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=ro[`${e}-${t}-${r}`];return n?{platform:e,arch:t,binaryName:r,sha256:n}:void 0}var ze;function Gt(e={}){if(ze&&!e.refresh)return jt(ze);let t=io();return ze=t,jt(t)}function io(){let e=process.platform,t=process.arch,r=oo(e,t),n=!!r,o=ao();if(!o)return n?P(`reviewed MXC ${ce} native assets are not installed`,!1,!0):P(Je(e,t),!1,!1);let i=Ht(o);if(!n)return P(Je(e,t),!0,!1,{packageRoot:i});let a="";try{let A=JSON.parse(de(o,"utf8"));if(a=String(A.version??""),A.sourcePackage?.name!==eo||A.sourcePackage.version!==ce||A.sourcePackage.integrity!==to)return P("MXC native asset provenance metadata is invalid",!0,!0,{packageRoot:i})}catch{return P("MXC package metadata is unreadable",!0,!0,{packageRoot:i})}if(a!==ce)return P(`MXC version ${a||"unknown"} is installed; XENO requires exactly ${ce}`,!0,!0,{packageRoot:i});if(!r)return P(Je(e,t),!0,!1,{packageRoot:i});let s=G(i,"bin",t,r.binaryName);if(!Ee(s)||!Jn(s).isFile())return P(`MXC native binary is missing: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a});let c=s;try{c=so(s,r)}catch(A){return P(`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{Hn(c,Gn.X_OK)}catch{return P(`MXC native binary is not executable: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a})}let d=we("sha256").update(de(c)).digest("hex"),I=r.sha256;if(!I||d!==I)return P(`MXC native binary digest is not trusted for ${e}/${t}`,!0,!0,{packageRoot:i,version:a});if(e==="win32"){let A=Bt(c,["--probe"],{encoding:"utf8",timeout:5e3,windowsHide:!0});if(A.error||A.status!==0)return P(`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 P("MXC native probe returned invalid JSON",!0,!0,{packageRoot:i,version:a})}let _=typeof m.tier=="string"?m.tier:"unknown",E=Array.isArray(m.warnings)?m.warnings.filter(O=>typeof O=="string"):[],S=m.probes&&typeof m.probes=="object"?m.probes:void 0,X=S?.uiCapabilities&&typeof S.uiCapabilities=="object"?Object.fromEntries(Object.entries(S.uiCapabilities).filter(O=>typeof O[1]=="boolean")):void 0;return{installed:!0,supported:!0,available:!0,name:Ft,version:a,packageRoot:i,nativeBinaryPath:c,nativeBinarySha256:d,backend:"processcontainer",isolationTier:_,platform:e,arch:t,warnings:E,needsHostPreparation:no(E),reason:`MXC ${a} processcontainer is installed (${_}).`,...X?{uiCapabilities:X}:{}}}if(e==="linux"){let A=Bt("bwrap",["--version"],{encoding:"utf8",timeout:5e3});if(A.error||A.status!==0)return P("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:Ft,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 ao(){let e=process.resourcesPath,t=process.env.XENO_MXC_ASSET_ROOT?.trim(),r=typeof __dirname=="string"?__dirname:Ht(Qn(import.meta.url)),n=[...e&&Vt(e)?[G(e,"mxc","package.json")]:[],...t&&Vt(t)?[G(t,"package.json")]:[],G(r,"..","native","mxc","package.json"),G(r,"..","..","native","mxc","package.json")];for(let o of n){if(!Ee(o))continue;let i=Ke(o);if(!(!i.isFile()||i.isSymbolicLink()))return qn(o)}}function so(e,t){if(!!!process.pkg)return e;let n=G(Zn(),"xeno-mxc",ce,t.sha256);Wn(n,{recursive:!0,mode:448});let o=G(n,t.binaryName);if(Ee(o)){let c=Ke(o);if(!c.isFile()||c.isSymbolicLink())throw new Error("materialized MXC path is not a regular file");if(we("sha256").update(de(o)).digest("hex")!==t.sha256)throw new Error("materialized MXC binary digest is invalid");return process.platform!=="win32"&&$t(o,448),o}let i=de(e);if(we("sha256").update(i).digest("hex")!==t.sha256)throw new Error("embedded MXC binary digest is invalid");let s=`${o}.${process.pid}.${jn()}.tmp`;Yn(s,i,{flag:"wx",mode:448});try{zn(s,o)}catch(c){try{Kn(s)}catch{}if(!Ee(o))throw c;let d=Ke(o);if((d.isFile()&&!d.isSymbolicLink()?we("sha256").update(de(o)).digest("hex"):"")!==t.sha256)throw c}return process.platform!=="win32"&&$t(o,448),o}function Je(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 P(e,t=!1,r=!1,n={}){return{...n,installed:t,supported:r,available:!1,warnings:[],needsHostPreparation:!1,reason:e}}function jt(e){return{...e,warnings:[...e.warnings],...e.uiCapabilities?{uiCapabilities:{...e.uiCapabilities}}:{}}}var W=class extends Error{code;constructor(t,r){super(`${t}: ${r}`),this.name="ExecutionSecurityError",this.code=t}},co=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),lo=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!0,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!0,environmentSanitization:!0}),uo=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),po=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!0,networkIsolation:!0,inheritedHandleAllowlist:!0,environmentSanitization:!0}),Ye=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0});function fo(e){let t=e?.executionLevel;if(e?.requireOsContainment&&t&&t!=="contained")throw new W("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 mo(e){return e?.trustMode??"trusted-workspace"}function Wt(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:{...co},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"&&xt())return{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"windows-restricted-token-job",isolation:"process-hardening",certified:!0,capabilities:{...lo},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=Dt();return o.available?{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"linux-bubblewrap",isolation:"process-hardening",certified:!0,capabilities:{...uo},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:{...Ye},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:{...Ye},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 ve(t,`Native containment for ${t} cannot be certified from a ${process.platform} host.`);let n=Gt();if(!n.available||!n.name||!n.version||!n.backend||!n.isolationTier||!n.nativeBinarySha256||!n.platform||!n.arch)return ve(t,n.reason,n);if(!r)return ve(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=Ut(r,o);return{available:!0,requestedLevel:e,effectiveLevel:"contained",adapter:"microsoft-mxc",isolation:"filesystem-network",certified:!0,capabilities:{...po},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 ve(t,o instanceof Error?o.message:"Containment certification validation failed.",n)}}function go(e,t){if(mo(e)==="untrusted"&&t!=="contained")throw new W("UNTRUSTED_EXECUTION_DISABLED","Untrusted execution requires certified contained mode; policy-only and process-hardened modes are trusted-workspace features.")}function Ao(e){let t=e.requestedLevel==="contained"?"CONTAINMENT_UNAVAILABLE":"PROCESS_HARDENING_UNAVAILABLE";return new W(t,e.reason)}function qt(e,t=process.platform){let r=fo(e);go(e,r);let n=Wt(r,t,e.containmentCertification);if(!n.available)throw Ao(n);if(r==="process-hardened"&&e.allowNetwork!==!0)throw new W("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=H(e.workingDirectory??process.cwd()).canonicalPath,i=[...e.allowedDirectories,...e.temporaryDirectories??[]];if(!Pt(o,i))throw new W("SECURITY_POLICY_INVALID",`Secured process working directory is outside the canonical allowed directories: ${o}`)}return n}function ve(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:{...Ye},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 Kt=1,v=class extends Error{constructor(r,n){super(n);this.code=r;this.name="XenoSecureExecutionContractError"}code};function Yt(e){let t=e.platform??process.platform,r=e.policy.executionLevel??(e.policy.requireOsContainment?"contained":"policy-only"),n=e.adapterStatus??qt(e.policy,t);if(!n.available||n.effectiveLevel==="unavailable")throw new v("SECURITY_CONTRACT_UNAVAILABLE",n.reason);if(n.requestedLevel!==r||n.effectiveLevel!==r)throw new v("SECURITY_CONTRACT_INVALID","Execution adapter status does not match the requested security level");let i=(e.now??(()=>new Date().toISOString()))(),a=le([...e.policy.allowedDirectories,...e.policy.temporaryDirectories??[],e.policy.workingDirectory??process.cwd()],e.policy.workingDirectory,t),s=le(e.filesystem?.readRoots??a,e.policy.workingDirectory,t),c=e.profile.capabilities.permissionProfile==="read-only",d=c?[]:le(e.filesystem?.writeRoots??a,e.policy.workingDirectory,t),I=c?[]:le(e.filesystem?.executeRoots??a,e.policy.workingDirectory,t),g=le(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",_=r==="contained"?"deny":e.network?.default??(e.policy.allowNetwork?"allow":"deny"),E=m==="none";if(E&&(!e.policy.allowNetwork||_!=="allow"))throw new v("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 v("SECURITY_CONTRACT_INVALID","Read-only Agent Profiles cannot receive browser action, computer action, or secret projection authority");let S=e.certificationArtifactId??n.certificationArtifactId;if(e.certificationArtifactId&&n.certificationArtifactId&&e.certificationArtifactId!==n.certificationArtifactId)throw new v("SECURITY_CONTRACT_INVALID","Requested certification artifact does not match the adapter certification");if(r==="contained"&&!S)throw new v("SECURITY_CONTRACT_INVALID","Contained execution requires a candidate-bound certification artifact");let X=Q(e.environment?.deniedKeys??[]),O=new Set(X),x=ue(e.browser?.allowedDomains??[]),b=ue(e.browser?.readAllowedDomains??x),M=ue(e.browser?.actAllowedDomains??x),oe=ue([...x,...b,...M]),ye={schemaVersion:Kt,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:I,deniedRoots:g},network:{enforcement:m,default:_,allowDestinations:zt(e.network?.allowDestinations??[]),denyDestinations:zt(e.network?.denyDestinations??[]),dns:e.network?.dns??((e.network?.allowDestinations?.length??0)>0||_==="allow"?"system":"disabled"),...e.network?.proxyUrl?{proxyUrl:e.network.proxyUrl}:{},downloads:e.network?.downloads??"deny",acknowledgedUnrestricted:E},process:{processTreeControl:n.capabilities.processTreeControl,cleanup:n.capabilities.processTreeControl?"kill-tree":"best-effort",inheritedHandleAllowlist:n.capabilities.inheritedHandleAllowlist,...vo(e.process)},environment:{inheritance:e.environment?.inheritance??"allowlist",allowedKeys:Q(e.environment?.allowedKeys??e.policy.containedEnvironmentAllowlist??[]).filter(un=>!O.has(un)),deniedKeys:X},secrets:Eo(e.secrets??[]),externalActions:{default:e.profile.capabilities.externalActions.default,overrides:{...e.profile.capabilities.externalActions.overrides},requireCurrentTurnApproval:Q(e.profile.capabilities.externalActions.requireCurrentTurnApproval),requireCapabilityLease:!0},browser:{mode:e.browser?.mode??"none",profile:e.browser?.profile??"ephemeral",allowedDomains:oe,readAllowedDomains:b,actAllowedDomains:M,deniedDomains:ue(e.browser?.deniedDomains??[]),allowedSchemes:bo(e.browser?.allowedSchemes??["https"]),allowedPorts:wo(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:Q(e.computer?.allowedApplications??[]),sensitiveRegionRedaction:e.computer?.sensitiveRegionRedaction??!0,humanStopRequired:e.computer?.humanStopRequired??!0},capabilityLeaseIds:Q(e.capabilityLeaseIds??[]),adapter:{id:n.adapter,version:e.adapterVersion??n.adapterVersion??"1",platform:t,architecture:e.architecture??Io(),certified:n.certified,...S?{certificationArtifactId:S}:{},capabilities:{...n.capabilities},limitations:[...n.limitations]},...e.auditEventIds?{auditEventIds:Q(e.auditEventIds)}:{}},ie={...ye,fingerprint:Zt(ye)};return Qe(ie),ie}function yo(e){let t=[];if(!e||typeof e!="object")return["Contract must be an object"];if(e.schemaVersion!==Kt&&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"),Jt(e.createdAt)||t.push("createdAt must be an ISO 8601 timestamp"),e.expiresAt&&(!Jt(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,Zt(r)!==e.fingerprint&&t.push("Contract fingerprint does not match content")}return t}function Qe(e){let t=yo(e);if(t.length>0){let r=t.includes("Contract fingerprint does not match content");throw new v(r?"SECURITY_CONTRACT_FINGERPRINT_MISMATCH":"SECURITY_CONTRACT_INVALID",t.join("; "))}}function Zt(e){return ho("sha256").update(JSON.stringify(Ze(e))).digest("hex")}function Q(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort().map(t=>t)}function le(e,t,r){return[...new Set(e.map(n=>H(n,{baseDirectory:t,platform:r}).canonicalPath))].sort((n,o)=>n.localeCompare(o))}function zt(e){let t=new Map;for(let r of e){if(!r.host?.trim())throw new v("SECURITY_CONTRACT_INVALID","Network destinations require a host");if(r.host.includes("*"))throw new v("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 v("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 ue(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 v("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 v("SECURITY_CONTRACT_INVALID",`Browser domain rule is invalid: ${r}`);t.add(n)}return[...t].sort((r,n)=>r.localeCompare(n))}function bo(e){for(let t of e)if(t!=="http"&&t!=="https")throw new v("SECURITY_CONTRACT_INVALID",`Browser scheme is invalid: ${t}`);return[...new Set(e)].sort()}function wo(e){for(let t of e)if(!Number.isInteger(t)||t<1||t>65535)throw new v("SECURITY_CONTRACT_INVALID",`Browser port is invalid: ${t}`);return[...new Set(e)].sort((t,r)=>t-r)}function Eo(e){let t=new Map;for(let r of e){if(!r.secretId?.trim())throw new v("SECURITY_CONTRACT_INVALID","Secret projections require an ID");if(t.has(r.secretId))throw new v("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 vo(e){let t={};for(let[r,n]of Object.entries(e??{})){if(!Number.isSafeInteger(n)||Number(n)<1)throw new v("SECURITY_CONTRACT_INVALID",`${r} must be a positive safe integer`);Object.assign(t,{[r]:n})}return t}function Ze(e){return Array.isArray(e)?e.map(Ze):!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,Ze(r)]))}function Jt(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}var So=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,Qt=1048576;function or(e){(!e||typeof e!="object")&&U("Automation request must be an object"),e.protocolVersion!==1&&U("Unsupported automation protocol version"),ee(e.operationId,"operationId"),ee(e.idempotencyKey,"idempotencyKey"),ee(e.capabilityLeaseId,"capabilityLeaseId"),ee(e.governingToolName,"governingToolName"),(!Number.isSafeInteger(e.expectedLeaseVersion)||e.expectedLeaseVersion<1)&&U("expectedLeaseVersion must be a positive safe integer"),sr(e.requestedAt)||U("requestedAt must be an ISO 8601 timestamp"),je(e.operation)||U(`Unsupported automation operation: ${e.operation}`),(!e.parameters||typeof e.parameters!="object"||Array.isArray(e.parameters))&&U("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>Qt&&U(`parameters exceed ${Qt} bytes`),ee(e.identity?.runId,"identity.runId"),ee(e.identity?.agentId,"identity.agentId"),Qe(e.executionContract),To(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 Te(e){(!e||typeof e!="object")&&D("Adapter manifest must be an object"),e.protocolVersion!==1&&D("Adapter protocol version is unsupported"),Se(e.adapterId,"adapterId"),Se(e.adapterVersion,"adapterVersion"),Se(e.platform,"platform"),Se(e.architecture,"architecture"),e.targetBinding!=="atomic-preflight"&&D("Adapter must implement atomic preflight target binding"),(!Array.isArray(e.operations)||e.operations.length===0)&&D("Adapter must declare operations");let t=new Set;for(let r of e.operations)je(r)||D(`Adapter declares unknown operation ${r}`),t.has(r)&&D(`Adapter declares duplicate operation ${r}`),t.add(r);e.certified&&!e.certificationArtifactId&&D("A certified automation adapter requires a certification artifact"),Array.isArray(e.limitations)||D("Adapter limitations must be an array"),e.operations.some(r=>r.startsWith("browser."))&&(!e.policyEnforcement.domain||!e.policyEnforcement.scheme||!e.policyEnforcement.port)&&D("Browser adapters must enforce domain, scheme, and port policy"),e.operations.some(r=>r.startsWith("computer."))&&!e.supports.immediateStop&&D("Computer-use adapters must support immediate stop")}function tt(e,t,r){let n=N(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(Co(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"?Ro(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 ir(e,t){let r=N(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,...er(e,t)?{resource:er(e,t)}:{},...rr(t)?{destination:rr(t)}:{}}}function er(e,t){return e.declaredTarget?.resource??Po(t)}function ar(e){let t=N(e.operation).evidence,r=e.evidencePolicy??{},n=et(t.before,r.before),o=et(t.after,r.after),i=et(t.recording,r.recording),a=r.retainUntil;return a&&!sr(a)&&U("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 To(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 Co(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"&&q(`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,I=_o(s);if(nr(s,d.deniedDomains)&&q(`Browser domain ${s} is denied`),tr(o,e.executionContract.network.denyDestinations)&&q(`Network policy explicitly denies ${a}://${s}:${c}`),I&&d.allowLoopbackDevelopment)return;d.allowedSchemes.includes(a)||q(`Browser scheme ${o.protocol} is not allowed`),d.allowedPorts.includes(c)||q(`Browser port ${c} is not allowed`);let g=r?d.actAllowedDomains:d.readAllowedDomains;nr(s,g)||q(`Browser domain ${s} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&(tr(o,e.executionContract.network.allowDestinations)||q(`Network policy does not allow ${a}://${s}:${c}`))}function tr(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 Po(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function rr(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function Ro(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 nr(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 _o(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function et(e,t){let r={disabled:0,optional:1,required:2};return!t||r[t]<=r[e]?e:t}function ee(e,t){(typeof e!="string"||!So.test(e))&&U(`${t} is invalid`)}function Se(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&D(`${t} is invalid`)}function sr(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}function q(e){throw new l("AUTOMATION_POLICY_DENIED",e)}function U(e){throw new l("AUTOMATION_REQUEST_INVALID",e)}function D(e){throw new l("AUTOMATION_OPERATION_UNSUPPORTED",e)}import{createHash as zo}from"node:crypto";var cr=["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"],dr=["draft","pending_review","approved","rejected","superseded","archived"],lr=["public","internal","confidential","restricted"],ur=["agent","tool","user","system","integration"],pr=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],fr=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];import{Buffer as mr}from"node:buffer";import{createHash as xo}from"node:crypto";function z(e){return{algorithm:"sha256",value:xo("sha256").update(e).digest("hex")}}var Oo=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Ce="custom:";function pe(e,t=Ce){return e.startsWith(t)?Oo.test(e.slice(t.length)):!1}var te=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,r){super(t),this.name="XenoArtifactValidationError",this.issues=r.map(n=>({...n}))}},rt=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"},No={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},ko="[\\u0000-\\u001f\\u007f]",Xo=new RegExp(ko),gr=/^[a-f0-9]{64}$/,Do=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Lo=new Set(dr),Mo=new Set(lr),Uo=new Set(ur),$o=new Set(cr),Vo=new Set(pr),Bo=new Set(fr);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`),Xo.test(e)&&u(r,t,"control_character","Value must not contain control characters"),!0)}function fe(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 J(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 Ar(e,t,r){if(!e||typeof e!="object"){u(r,t,"missing_actor","Actor is required");return}f(e.kind,`${t}.kind`,r,64),Uo.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 nt(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"):J(e.kind,"custom:",`${t}.kind`,r)}}function me(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)=>me(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"):me(i,`${t}.${o}`,r,n);n.delete(e)}}function Fo(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"&&!$o.has(e.kind)&&!e.kind.startsWith("custom:")&&u(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),J(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),Lo.has(e.state)||u(t,"state","unknown_state","Artifact state is not supported"),f(e.createdAt,"createdAt",t,128),fe(e.createdAt,"createdAt",t),fe(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),Mo.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),J(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"&&!gr.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=mr.from(n.text,"utf8"):n.base64!==void 0&&(Do.test(n.base64)?o=mr.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"&&z(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),fe(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"),J(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?u(t,"provenance","missing_provenance","provenance is required"):(Ar(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&&me(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"&&!Bo.has(n.relation)&&!n.relation.startsWith("custom:")&&u(t,`${i}.relation`,"unknown_relationship","Relationship type is not supported"),J(n.relation,"custom:",`${i}.relation`,t),f(n.target?.type,`${i}.target.type`,t,160),typeof n.target?.type=="string"&&!Vo.has(n.target.type)&&!n.target.type.startsWith("custom:")&&u(t,`${i}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),J(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&&me(n.attributes,`${i}.attributes`,t,new Set)}),e.anchors?.forEach((n,o)=>nt(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"),fe(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&&me(e.extensions,"extensions",t,new Set),t}function Pe(e){let t=Fo(e);if(t.length>0)throw new te("XENO artifact validation failed",t)}function jo(e,t){return No[e].includes(t)}function Re(e,t){if(!jo(e,t))throw new rt(e,t)}function ot(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),fe(e.recordedAt,"recordedAt",r),Ar(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),J(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",r),f(e.artifactHash.value,"artifactHash.value",r,512),e.artifactHash.algorithm==="sha256"&&!gr.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&&nt(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&&nt(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 it(e){let t="not_requested",r,n,o,i=0,a=new Set,s=new Set;for(let c of[...e].sort((d,I)=>d.sequence-I.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},Ae=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(hr).map(r=>({artifact:ge(r.artifact),recordVersion:r.recordVersion,lifecycleEvents:structuredClone(r.lifecycleEvents),reviewEvents:structuredClone(r.reviewEvents)}));return{schemaVersion:1,records:t}}async create(t){if(Pe(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=ge(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),K(o)}async createRevision(t,r={}){Pe(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(Go(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"){Re(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=ge(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),K(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?K(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=>Wo(n.artifact,t)).sort(hr).map(K)}async listRevisions(t){let r=this.records.get(t);return r?[...r.values()].sort((n,o)=>n.artifact.revision-o.artifact.revision).map(K):[]}async transition(t){let r=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(r,t.expectedRecordVersion),Re(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=it(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,K(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=ot(o,n.artifact);if(i.length>0)throw new te("XENO artifact review event validation failed",i);return n.reviewEvents.push(o),n.recordVersion+=1,K(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=qo(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=Ho(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 Ho(e,t){if(Pe(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 Re(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=ot(a,e.artifact);if(s.length>0)throw new te("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:ge(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function Go(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function Wo(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 hr(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function qo(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 ge(e){return structuredClone(e)}function K(e){return{artifact:ge(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:it(e.reviewEvents)}}var at=32*1024*1024,Jo=1024*1024*1024,Ko=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function st(e){let r=(e.now??(()=>new Date().toISOString()))(),n=new Set;return e.evidence.map((o,i)=>{if(Zo(o),n.has(o.evidenceId))throw new l("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${o.evidenceId}`);n.add(o.evidenceId);let a=Yo(o),s=zo("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 ct(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 _e(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 Yo(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return Ir(t),{hash:z(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=Qo(e.content.base64);return Ir(t.byteLength),{hash:z(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>Jo)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 Zo(e){(!e||typeof e!="object")&&$("Evidence must be an object"),Ko.test(e.evidenceId)||$("Evidence ID is invalid"),["before","action","after","recording","diagnostic"].includes(e.phase)||$("Evidence phase is invalid"),(!e.kind||!e.title?.trim()||e.title.length>512)&&$("Evidence kind and title are required"),/^[\w!#$&^_.+-]+\/[\w!#$&^_.+-]+(?:;.*)?$/.test(e.mediaType)||$("Evidence media type is invalid")}function Qo(e){(e.length===0||e.length>Math.ceil(at/3)*4+4)&&$("Inline base64 evidence is empty or too large"),(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)&&$("Inline evidence is not canonical base64");let t=Buffer.from(e,"base64");return t.toString("base64")!==e&&$("Inline evidence is not canonical base64"),t}function Ir(e){e>at&&$(`Inline evidence exceeds ${at} bytes`)}function $(e){throw new l("AUTOMATION_EVIDENCE_INVALID",e)}import{createHash as ei}from"node:crypto";var yr=3e4,ti=1e3,xe=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=ai(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=si(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){or(t),lt(r);let n=await this.adapter.manifest();Te(n);let o=N(t.operation),i=ar(t),a=this.now(),s=await this.adapter.preflight(t,r);ri(s,this.now()),tt(t,n,s.observedTarget),lt(r);let c=s.evidence??[];_e(c,i,"before");let d=await ct(this.artifactRepository,st({request:t,manifest:n,policy:i,evidence:c,now:this.now}));if(lt(r),Date.parse(s.expiresAt)<=Date.parse(this.now()))throw new l("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let I=ir(t,s.observedTarget),g=await this.leaseAuthority.consume(t.capabilityLeaseId,t.expectedLeaseVersion,I),A={contractFingerprint:t.executionContract.fingerprint,lease:g,capabilityUse:I},m;try{m=await this.adapter.execute(t,s,A,r)}catch(b){return dt({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":ci(b)})}ni(m);let _=oi(s.observedTarget,m.observedTarget),E;try{tt(t,n,m.observedTarget)}catch(b){E=b instanceof Error?b:new Error(String(b))}let S=m.evidence??[];ii(c,S);let X=[],O;try{_e(S,i,"after"),_e([...c,...S],i,"recording"),X=await ct(this.artifactRepository,st({request:t,manifest:n,policy:i,evidence:S,now:this.now}))}catch(b){O=b instanceof Error?b:new Error(String(b))}let x=[...d,...X];return _||E?dt({request:t,manifest:n,descriptorEffect:o.effect,target:m.observedTarget,lease:g,artifacts:x,startedAt:m.startedAt,completedAt:m.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:_??E.message}):O?dt({request:t,manifest:n,descriptorEffect:o.effect,target:m.observedTarget,lease:g,artifacts:x,startedAt:m.startedAt,completedAt:m.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:O.message}):{operationId:t.operationId,status:m.status,effect:o.effect,startedAt:m.startedAt,completedAt:m.completedAt,adapter:br(n),target:structuredClone(m.observedTarget),...m.data!==void 0?{data:structuredClone(m.data)}:{},artifacts:x,lease:wr(g),...m.error?{error:{...m.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>ti;){let t=this.executions.keys().next().value;if(!t||this.active.has(t))break;this.executions.delete(t)}}};function ri(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>yr)throw new l("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${yr} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new l("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function ni(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 oi(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 ii(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 dt(e){return{operationId:e.request.operationId,status:e.status,effect:e.descriptorEffect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:br(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:wr(e.lease),error:{code:e.code,message:e.message}}}function br(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function wr(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function ai(e){return ei("sha256").update(JSON.stringify(ut(e))).digest("hex")}function ut(e){return Array.isArray(e)?e.map(ut):!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,ut(r)]))}function si(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 lt(e){if(e.aborted)throw new l("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function ci(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}function di(e,t=()=>new Date().toISOString()){let r=[];li(r,"manifest.valid",()=>Te(e));let n=new Set(e.operations);return re(r,n,e.supports.consoleInspection,"browser.console.read","console inspection"),re(r,n,e.supports.networkInspection,"browser.network.read","network inspection"),re(r,n,e.supports.storageInspection,"browser.storage.read","storage inspection"),re(r,n,e.supports.pageErrorInspection,"browser.page-errors.read","page-error inspection"),re(r,n,e.supports.recordings,"browser.record.start","recording start"),re(r,n,e.supports.recordings,"browser.record.stop","recording stop"),n.has("browser.upload")&&j(r,"policy.upload",e.policyEnforcement.upload,"Upload policy is enforced"),n.has("browser.download")&&j(r,"policy.download",e.policyEnforcement.download,"Download policy is enforced"),[...n].some(o=>o.startsWith("browser."))&&(j(r,"policy.redirect",e.policyEnforcement.redirect,"Redirect policy is enforced"),j(r,"control.handback",e.supports.deterministicHandback,"Deterministic hand-back is supported")),[...n].some(o=>o.startsWith("computer."))&&(j(r,"control.stop",e.supports.immediateStop,"Immediate human stop is supported"),j(r,"privacy.redaction",e.supports.sensitiveRegionRedaction,"Sensitive-region redaction is supported")),j(r,"certification.binding",!e.certified||!!e.certificationArtifactId,e.certified?"Certification artifact is bound":"Adapter does not claim certification"),{protocolVersion:1,adapter:{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture},generatedAt:t(),passed:r.every(o=>o.status==="pass"),checks:r}}function Nc(e){let r=di(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 re(e,t,r,n,o){let i=t.has(n);j(e,`capability.${n}`,r===i,r===i?`${o} declaration matches the operation catalog`:`${o} declaration does not match ${n}`)}function li(e,t,r){try{r(),e.push({id:t,status:"pass",message:"Manifest satisfies the protocol contract"})}catch(n){e.push({id:t,status:"fail",message:n instanceof Error?n.message:String(n)})}}function j(e,t,r,n){e.push({id:t,status:r?"pass":"fail",message:n})}var ui=6e4,pi=48*1024*1024,Er=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(t){if(this.endpoint=fi(t.baseUrl),this.token=mi(t.token),this.timeoutMs=vr(t.timeoutMs??ui,1e3,3e5,"timeoutMs"),this.maxResponseBytes=vr(t.maxResponseBytes??pi,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=hi(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}),I=await gi(d,this.maxResponseBytes);if(!d.ok){let g=Ai(I);throw new l("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${t}: ${g.message}`,{status:d.status,route:t,adapterCode:g.code})}if(!pt(I)||I.ok!==!0||!("result"in I))throw new l("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${t} envelope`);return I.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 fi(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 mi(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 gi(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:I}=await o.read();if(d)break;if(a+=I.byteLength,a>t)throw await o.cancel("response too large"),new l("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);i.push(I)}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 Ai(e){return pt(e)&&pt(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 hi(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 vr(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 pt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}import{randomUUID as Ii}from"node:crypto";var Ne=["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"],he=class{constructor(t){this.options=t;if(this.base=wi(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=Ne.filter(n=>t.verbs?.includes(Sr(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){bi(t.operation);let n=await this.call("health",void 0,r);if(!n.verbs?.includes(Sr(t.operation)))throw new Error(`${this.options.driver} driver does not support ${t.operation}`);let o=Rr(n.activeTab),i=ne(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=Tr(t,o);Cr(t,a);let s=new Date;return{token:`${t.operationId}:${o??"unbound"}:${Ii()}`,preparedAt:s.toISOString(),expiresAt:new Date(s.getTime()+2e4).toISOString(),observedTarget:a,...xr(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=Rr(a.activeTab);if(r.observedTarget.tabId&&s!==r.observedTarget.tabId)throw new Error("Active browser tab changed after atomic preflight");Cr(t,r.observedTarget);try{let c=_r(t.operation,t.parameters),d=await this.call(c.verb,c.params,o),I=Tr(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:I,data:Si(d),...g.length?{evidence:g}:{}}}catch(c){let d={code:Ci(c),message:Ti(c),retryable:!1};return{status:Pi(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"?yi(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 Sr(e){return _r(e,{}).verb}function _r(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 yi(e,t,r){let n=Oe(r)?r:{},o=ne(n.base64)??vi(ne(n.screenshot));if(!o)throw new Error("Browser screenshot did not return image bytes");let i=ne(n.format)??(ne(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 Tr(e,t){let r=ne(e.parameters.url)??e.declaredTarget?.url;return{...e.declaredTarget??{},...r?{url:r}:{},...t?{tabId:t}:{}}}function Cr(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=>Pr(s,d)))throw Object.assign(new Error(`Browser domain ${s} is denied`),{code:"POLICY_DENIED"});let c=e.operation.startsWith("browser.")&&xr(e.operation)?o.actAllowedDomains:o.readAllowedDomains;if(c&&c.length>0&&!c.some(d=>Pr(s,d)))throw Object.assign(new Error(`Browser domain ${s} is outside the allowed scope`),{code:"POLICY_DENIED"})}function Pr(e,t){let r=t.toLowerCase().replace(/^\*\./,".");return r.startsWith(".")?e.endsWith(r)||e===r.slice(1):e===r}function xr(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 bi(e){if(!Ne.includes(e))throw new Error(`Unsupported browser operation ${e}`)}function wi(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 Rr(e){return typeof e=="string"||typeof e=="number"?String(e):void 0}function ne(e){return typeof e=="string"&&e.length>0?e:void 0}function vi(e){return e?.match(/^data:image\/(?:png|jpeg);base64,(.+)$/)?.[1]}function Si(e){return JSON.parse(JSON.stringify(e??null))}function Oe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ti(e){return e instanceof Error?e.message.slice(0,1024):String(e).slice(0,1024)}function Ci(e){return Oe(e)&&typeof e.code=="string"?e.code:"BROWSER_OPERATION_FAILED"}function Pi(e){return Oe(e)&&(e.status===403||e.status===409||e.code==="POLICY_DENIED")?"denied":Oe(e)&&e.name==="AbortError"?"cancelled":"error"}import{existsSync as en,readFileSync as tn}from"node:fs";import{homedir as La}from"node:os";import{join as Yr,resolve as Ie}from"node:path";import{randomUUID as Br}from"node:crypto";import{mkdir as Fr,open as Mr,readFile as Mi,rename as Ui,stat as jr,unlink as $i}from"node:fs/promises";import{basename as Ur,dirname as $r,join as Vi,resolve as Bi}from"node:path";import{mkdirSync as Ri,readFileSync as _i,rmSync as Nr,writeFileSync as xi}from"node:fs";import{hostname as kr}from"node:os";import{dirname as Oi}from"node:path";function Ni(){return new Date().toISOString()}function ki(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function Xr(e){try{return JSON.parse(_i(e,"utf8"))}catch{return null}}function Xi(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Di(e){return e.hostname!==kr()?!0:Xi(e.pid)}function Or(e,t){Ri(Oi(e),{recursive:!0}),xi(e,JSON.stringify(t,null,2)+`
|
|
926
|
+
`,{encoding:"utf8",flag:"wx"})}function Li(e,t){let r=Xr(e);r?.pid!==t.pid||r.hostname!==t.hostname||Nr(e,{force:!0})}function Dr(e,t,r){let n=Ni(),o={schemaVersion:1,name:t,pid:process.pid,hostname:kr(),processStartedAt:ki(),version:r,acquiredAt:n,updatedAt:n};try{Or(e,o)}catch(i){if(i.code!=="EEXIST")throw i;let s=Xr(e);if(s&&Di(s))throw new Error(`${t} is already locked by PID ${s.pid} on ${s.hostname}.`);Nr(e,{force:!0}),Or(e,o)}return{record:o,release:()=>{Li(e,o)}}}var Lr="0.9.24";var Hr=1,Fi="repository.v1.json",ji=5e3,Hi=20,Gi=64*1024*1024,ke=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??Fi;if(Ur(r)!==r||!/^[A-Za-z0-9_.-]+$/.test(r))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=Bi(t.directory),this.snapshotPath=Vi(this.directory,r),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=ft(t.lockTimeoutMs,ji,100,6e4,"lockTimeoutMs"),this.lockRetryMs=ft(t.lockRetryMs,Hi,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=ft(t.maxSnapshotBytes,Gi,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 Dr(this.lockPath,`artifact-repository:${Ur(this.snapshotPath)}`,Lr)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;r=n,await Ki(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=Xe(i)}if(!r&&(t||await Ji(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,Xe(i)])}):i}if(!r&&t)throw t;let o=r?.state??{schemaVersion:1,records:[]};return{repository:new Ae({now:this.now,idFactory:i=>`${i}_${Br()}`,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:Hr,generation:t.generation,createdAt:t.createdAt,updatedAt:r,state:t.repository.exportState()},generation:t.generation+1},i=qi(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 Fr(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await Vr(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
|
|
928
|
+
`),await Vr(this.snapshotPath,a)}async readSnapshot(t,r){let n;try{n=await jr(t)}catch(o){if(!r&>(o,"ENOENT")||r&>(o,"ENOENT"))return;throw At("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 Mi(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return Wi(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof p?o:At("Unable to parse artifact repository snapshot",t,o,!0)}}};function Wi(e,t){if(!mt(e)||e.schemaVersion!==Hr||!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))||!mt(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!mt(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=zi(r),o=Gr(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 Ae({initialState:r.state}),structuredClone(r)}function qi(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:Gr(e)}}}function zi(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function Gr(e){return z(JSON.stringify(e)).value}async function Vr(e,t){await Fr($r(e),{recursive:!0,mode:448});let r=`${e}.tmp.${process.pid}.${Br()}`,n;try{n=await Mr(r,"wx",384),await n.writeFile(t,{encoding:"utf8"}),await n.sync(),await n.close(),n=void 0,await Ui(r,e);try{let o=await Mr($r(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{n&&await n.close().catch(()=>{}),await $i(r).catch(()=>{})}}function ft(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 mt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gt(e,t){return e instanceof Error&&e.code===t}async function Ji(e){try{return(await jr(e)).isFile()}catch(t){if(gt(t,"ENOENT"))return!1;throw At("Unable to inspect artifact repository backup",e,t)}}function Xe(e){return e instanceof Error?e:new Error(String(e))}function At(e,t,r,n=!1){return new p(n?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${Xe(r).message}`,{snapshotPath:t},{cause:Xe(r)})}function Ki(e){return new Promise(t=>setTimeout(t,e))}import{homedir as Yi,platform as Zi,release as Qi}from"node:os";var ed=Zi();var td=Qi(),rd=Yi();var ea=2,ht=["publish","deploy","push","send","purchase","sign","file-legal","change-infrastructure"];function ta(e){return Array.from(new Set((e??[]).map(t=>t.trim()).filter(Boolean)))}function V(e){return{schemaVersion:ea,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:ta(e.tags)}}var ud=[V({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:[...ht],color:"cyan",glyph:"\u25A0",tags:["general","primary"]}),V({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"]}),V({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"]}),V({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"]}),V({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"]}),V({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"]}),V({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"]}),V({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"]}),V({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 ra=1,T=class extends Error{constructor(r,n,o){super(n);this.code=r;this.detail=o;this.name="XenoCapabilityLeaseError"}code;detail},na=new Set(["filesystem-write","process-execute","network-connect","secret-use","external-action","browser-act","computer-act"]),oa=new Set(ht),ia=new Set(["filesystem-read","filesystem-write","process-execute","network-connect","secret-use","external-action","browser-read","browser-act","computer-observe","computer-act","tool-invoke"]),aa=new Set(["cli","hub","ide","api","hosted"]),sa=/^[a-f0-9]{64}$/;function ca(e,t){da(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=la(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 da(e){if(!e||typeof e!="object")throw w("Capability lease request must be an object");if(k(e.subject?.runId,"subject.runId"),k(e.subject?.agentId,"subject.agentId"),e.subject?.turnId!==void 0&&k(e.subject.turnId,"subject.turnId"),k(e.reason,"reason",8192),De(e.requestedBy,"requestedBy"),ua(e.scope),e.policyFingerprints?.forEach(t=>qr(t,"policyFingerprints")),e.maxUses!==void 0&&(!Number.isInteger(e.maxUses)||e.maxUses<1))throw w("maxUses must be a positive integer");if(e.durationMs!==void 0&&(!Number.isSafeInteger(e.durationMs)||e.durationMs<1))throw w("durationMs must be a positive safe integer");if(e.requestTtlMs!==void 0&&(!Number.isSafeInteger(e.requestTtlMs)||e.requestTtlMs<1))throw w("requestTtlMs must be a positive safe integer")}var Le=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=ca(t,r);if(!n.eligible)throw new T("LEASE_NOT_REQUESTABLE",n.reason);let o=t.leaseId??this.idFactory();if(k(o,"leaseId"),this.leases.has(o))throw new T("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:ra,leaseId:o,version:1,state:"requested",subject:ma(t.subject),scope:ga(t.scope),reason:t.reason,requestedAt:i,requestExpiresAt:Wr(i,s),durationMs:a,maxUses:c,useCount:0,childInheritance:t.childInheritance??"none",approvalRequirement:n.approvalRequirement,requestedBy:{...t.requestedBy},profileFingerprint:r.fingerprint,policyFingerprints:Z(t.policyFingerprints??[]),...t.auditEventIds?{auditEventIds:Z(t.auditEventIds)}:{},...t.evidenceArtifactIds?{evidenceArtifactIds:Z(t.evidenceArtifactIds)}:{}};return this.leases.set(o,d),Y(d)}approve(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="requested")throw new T("LEASE_CONFLICT",`Capability lease ${r.leaseId} is ${r.state}`);if(De(t.approvedBy,"approvedBy"),fa(t.approvalContext),r.approvalRequirement==="current-turn"&&(!r.subject.turnId||t.approvalContext.turnId!==r.subject.turnId))throw new T("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=Wr(n,r.durationMs),r.approvedBy={...t.approvedBy},r.approvalContext={...t.approvalContext},Y(r)}deny(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="requested")throw new T("LEASE_CONFLICT",`Capability lease ${r.leaseId} is ${r.state}`);return De(t.deniedBy,"deniedBy"),r.state="denied",r.version+=1,r.deniedAt=this.now(),r.deniedBy={...t.deniedBy},Y(r)}revoke(t){let r=this.requireMutable(t.leaseId);if(this.assertVersion(r,t.expectedVersion),this.refreshState(r),r.state!=="active")throw new T("LEASE_CONFLICT",`Only active leases can be revoked; ${r.leaseId} is ${r.state}`);return De(t.revokedBy,"revokedBy"),r.state="revoked",r.version+=1,r.revokedAt=this.now(),r.revokedBy={...t.revokedBy},Y(r)}consume(t,r,n){let o=this.requireMutable(t);if(this.assertVersion(o,r),this.refreshState(o),o.state==="requested")throw new T("LEASE_APPROVAL_REQUIRED",`Capability lease ${t} is not approved`);if(o.state==="expired")throw new T("LEASE_EXPIRED",`Capability lease ${t} expired`);if(o.state==="revoked")throw new T("LEASE_REVOKED",`Capability lease ${t} was revoked`);if(o.state==="exhausted")throw new T("LEASE_EXHAUSTED",`Capability lease ${t} is exhausted`);if(o.state!=="active")throw new T("LEASE_SCOPE_MISMATCH",`Capability lease ${t} is ${o.state}`);return pa(o,n),o.useCount+=1,o.version+=1,o.useCount>=o.maxUses&&(o.state="exhausted",o.exhaustedAt=this.now()),Y(o)}get(t){let r=this.leases.get(t);if(r)return this.refreshState(r),Y(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(Y(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 T("LEASE_NOT_FOUND",`Capability lease ${t} was not found`);return r}assertVersion(t,r){if(t.version!==r)throw new T("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 la(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 ua(e){if(!e||typeof e!="object")throw w("scope is required");if(k(e.kind,"scope.kind"),!ia.has(e.kind)&&!e.kind.startsWith("custom:"))throw w("scope.kind is not supported");if(e.kind.startsWith(Ce)&&!pe(e.kind))throw w("Custom capability kind is invalid");if(!["read","write","execute","external"].includes(e.effect))throw w("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 w(`${e.kind} capability scopes must use ${t[e.kind]} effect`);if(!Array.isArray(e.operations)||e.operations.length===0)throw w("scope.operations must contain at least one operation");if(e.operations.forEach(r=>k(r,"scope.operations")),e.resources?.forEach(r=>k(r,"scope.resources",8192)),e.destinations?.forEach(r=>k(r,"scope.destinations",8192)),e.secretIds?.forEach(r=>k(r,"scope.secretIds",512)),e.kind==="external-action"){if(!e.externalAction||!oa.has(e.externalAction))throw w("External-action scopes require a supported exact action");if(e.effect!=="external")throw w("External-action scopes must use external effect")}if(e.kind==="network-connect"&&(!e.destinations||e.destinations.length===0))throw w("Network capability scopes require at least one destination");if(e.kind==="secret-use"&&(!e.secretIds||e.secretIds.length===0))throw w("Secret capability scopes require at least one secret ID");if(na.has(e.kind)&&[...e.resources??[],...e.destinations??[],...e.secretIds??[]].some(n=>n.includes("*")))throw w("High-impact capability scopes cannot use wildcard resources")}function pa(e,t){let r=e.subject;if(r.runId!==t.subject.runId||r.agentId!==t.subject.agentId)throw R(e,"run or agent subject");if(r.turnId&&r.turnId!==t.subject.turnId)throw R(e,"turn subject");if(r.toolName&&r.toolName!==t.subject.toolName)throw R(e,"tool subject");if(r.operationId&&r.operationId!==t.subject.operationId)throw R(e,"operation subject");if(e.scope.kind!==t.kind)throw R(e,"capability kind");if(!e.scope.operations.includes(t.operation))throw R(e,"operation");if(e.scope.resources?.length&&!t.resource)throw R(e,"resource");if(e.scope.destinations?.length&&!t.destination)throw R(e,"destination");if(e.scope.secretIds?.length&&!t.secretId)throw R(e,"secret");if(e.scope.externalAction&&!t.externalAction)throw R(e,"external action");if(t.resource&&!e.scope.resources?.includes(t.resource))throw R(e,"resource");if(t.destination&&!e.scope.destinations?.includes(t.destination))throw R(e,"destination");if(t.secretId&&!e.scope.secretIds?.includes(t.secretId))throw R(e,"secret");if(t.externalAction&&e.scope.externalAction!==t.externalAction)throw R(e,"external action")}function fa(e){if(!e||typeof e!="object")throw w("approvalContext is required");if(k(e.surface,"approvalContext.surface"),!aa.has(e.surface)&&!e.surface.startsWith("custom:"))throw w("approvalContext.surface is not supported");if(e.surface.startsWith(Ce)&&!pe(e.surface))throw w("Custom approval surface is invalid");e.promptHash!==void 0&&qr(e.promptHash,"approvalContext.promptHash")}function De(e,t){if(!e||typeof e!="object")throw w(`${t} is required`);if(!["agent","tool","user","system","integration"].includes(e.kind))throw w(`${t}.kind is invalid`);k(e.id,`${t}.id`)}function qr(e,t){if(!sa.test(e))throw w(`${t} must be a 64-character lowercase hexadecimal fingerprint`)}function k(e,t,r=1024){if(typeof e!="string"||e.trim().length===0||e.length>r)throw w(`${t} must be a non-empty string no longer than ${r} characters`)}function w(e){return new T("LEASE_INVALID",e)}function R(e,t){return new T("LEASE_SCOPE_MISMATCH",`Capability use is outside lease ${e.leaseId} ${t} scope`)}function Wr(e,t){return new Date(Date.parse(e)+t).toISOString()}function Z(e){return[...new Set(e)]}function ma(e){return{...e}}function ga(e){return{...e,operations:Z(e.operations),...e.resources?{resources:Z(e.resources)}:{},...e.destinations?{destinations:Z(e.destinations)}:{},...e.secretIds?{secretIds:Z(e.secretIds)}:{}}}function Y(e){return structuredClone(e)}import{createHash as Aa,randomUUID as ha}from"node:crypto";var Ia=8*1024*1024,ya=4;function Jr(e){return Na(e.operations??ae).map(r=>ba(r,e.runtime))}function ba(e,t){return{definition:{name:e,description:Ta(e),input_schema:wa(e)},projectPolicyInput(r){let n=Ra(e,r),o=Pa(e,r);return{observabilityInput:n,permissionInput:o,permissionPreview:_a(e,r),approvalKey:`xeno-automation:${e}:${ka(r)}`,riskLevel:Ca(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_${ha()}`,a=yt(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(xa(s)),...c?{}:{error:s.error?.message??`Governed automation ended with ${s.status}`,errorCode:s.error?.code??`AUTOMATION_${s.status.toUpperCase().replaceAll("-","_")}`},assistantContent:Oa(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":Xa(s),errorCode:c?"AUTOMATION_CANCELLED":Da(s),retryable:!c}}}}}function wa(e){let t=Ea(e),r=va(e);return{type:"object",properties:t,...r.length>0?{required:r}:{},...e==="browser.locate"?{oneOf:[{required:["selector"]},{required:["text"]}]}:{},additionalProperties:!1}}function Ea(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:Sa()};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 va(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 Sa(){return{type:"object",properties:{shift:{type:"boolean"},ctrl:{type:"boolean"},alt:{type:"boolean"},meta:{type:"boolean"}},additionalProperties:!1}}function Ta(e){let t=N(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 Ca(e){return N(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 Pa(e,t){let r=yt(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 Ra(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]"),Kr(r.trigger)&&typeof r.trigger.url=="string"&&(r.trigger={...r.trigger,url:zr(r.trigger.url)}),typeof r.url=="string"&&(r.url=zr(r.url)),{operation:e,...r}}function _a(e,t){let r=yt(e,t),n=r?.url??r?.applicationId??r?.deviceId??r?.tabId??r?.resource??"current target";return`${e} on ${n}`}function yt(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 xa(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 Oa(e){let t=[];for(let r of e.artifacts){if(t.length>=ya||!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>Ia||t.push({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${n.base64}`,detail:"high"}})}return t}function Na(e){let t=new Set(ae),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 ka(e){return Aa("sha256").update(It(e)).digest("hex")}function It(e){return Array.isArray(e)?`[${e.map(It).join(",")}]`:Kr(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${It(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function zr(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid URL]"}}function Xa(e){return e instanceof Error?e.message:String(e)}function Da(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:"AUTOMATION_EXECUTION_FAILED"}function Kr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var rn=[...Ne],Ma=rn.filter(e=>!["browser.storage.read","browser.upload","browser.download"].includes(e)),Ua=ae.filter(e=>e.startsWith("computer.")),bt=6e4,wt=class{constructor(t){this.options=t;this.environment=t.environment??nn()}options;leases=new Le({maximumDurationMs:bt,maximumUses:1});activeExecutors=new Map;environment;browserAdapter;computerAdapter;register(t){if(this.options.safeMode)return 0;let r=[];return Et(this.environment.browser)&&r.push(...Fa(this.environment.browser.driver)),vt(this.environment.computer)&&r.push(...Ua),r.length===0?0:(t.registerAll(Jr({runtime:this,operations:r})),r.length)}async execute(t){if(this.options.safeMode)throw new Error("Governed automation is disabled in safe mode");Ya(t);let r=N(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=za(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=Ja(i),d=Ka(i),I=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:bt,requestTtlMs:3e4,maxUses:1,childInheritance:"none",policyFingerprints:[n.fingerprint]},n),g=this.leases.approve({leaseId:I.leaseId,expectedVersion:I.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=Yt({contractId:`contract-${t.operationId}`,identity:o,policy:this.securityPolicy(),profile:n,...this.options.securityStatus?{adapterStatus:this.options.securityStatus}:{},filesystem:{readRoots:[Ie(this.options.cwd())],writeRoots:[Ie(this.options.cwd())],executeRoots:[Ie(this.options.cwd())]},network:qa(i,this.environment),browser:r.surface==="browser"?Ga(r.effect,i,this.environment):{mode:"none"},computer:r.surface==="computer"?Wa(r.effect,this.environment):{mode:"none"},capabilityLeaseIds:[g.leaseId],expiresAt:new Date(Date.now()+bt).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 _=new xe({adapter:A,leaseAuthority:this.leases,artifactRepository:new ke({directory:Ie(this.options.cwd(),".xeno","artifacts")})});this.activeExecutors.set(t.operationId,_),t.reportProgress?.({activity:"state",message:`Executing governed ${t.operation}`});try{let E=await _.execute({protocolVersion:1,operationId:t.operationId,idempotencyKey:t.idempotencyKey,requestedAt:new Date().toISOString(),identity:o,governingToolName:t.governingToolName,operation:t.operation,parameters:Za(t.parameters),...i?{declaredTarget:i}:{},executionContract:m,capabilityLeaseId:g.leaseId,expectedLeaseVersion:g.version},t.signal);return await this.audit({eventType:E.status==="ok"?"automation_completed":"automation_failed",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:g.leaseId,contractFingerprint:m.fingerprint,status:E.status,artifactIds:E.artifacts.map(S=>S.artifactId)}),E}catch(E){throw await this.audit({eventType:"automation_failed",traceId:t.authorization.turnId,operation:t.operation,operationId:t.operationId,leaseId:g.leaseId,contractFingerprint:m.fingerprint,status:E instanceof Error?E.name:"error"}),E}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=Ie(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(!Et(n))throw new Error(an(n));return this.browserAdapter??=new he({baseUrl:n.baseUrl,token:n.token,driver:n.driver}),this.browserAdapter}let r=this.environment.computer;if(!vt(r))throw new Error(sn(r));return this.computerAdapter??=on(r),this.computerAdapter}async audit(t){try{await this.options.onAudit?.(t)}catch{}}};function xd(e){return new wt(e)}function Od(e){if(e)return async t=>{let r=N(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 Nd(e=nn()){let t=await Promise.all([Zr("browser",e),Zr("computer",e)]);return{schemaVersion:1,protocolVersion:1,enabled:t.some(r=>r.configured),surfaces:t,docs:"docs/GOVERNED_AUTOMATION.md"}}function nn(e=process.env){let t=e.XENO_BROWSER_DRIVER==="extension"?"extension":"browser",r=Va(e,t),n=L(e.XENO_BROWSER_AUTOMATION_URL)??r?.baseUrl,o=L(e.XENO_BROWSER_AUTOMATION_TOKEN)??r?.token,i=L(e.XENO_USE_BASE_URL),a=L(e.XENO_USE_TOKEN)??$a(e.XENO_USE_TOKEN_FILE),s=L(e.XENO_USE_DEVICE_ID);return{browser:{driver:t,...n?{baseUrl:n}:{},...o?{token:o}:{},readDomains:Me(e.XENO_BROWSER_READ_DOMAINS),actDomains:Me(e.XENO_BROWSER_ACT_DOMAINS),deniedDomains:Me(e.XENO_BROWSER_DENIED_DOMAINS),ports:es(e.XENO_BROWSER_ALLOWED_PORTS,[443]),allowLoopbackDevelopment:e.XENO_BROWSER_ALLOW_LOOPBACK_DEVELOPMENT==="1",uploads:Qr(e.XENO_BROWSER_UPLOADS,"prompt"),downloads:Qr(e.XENO_BROWSER_DOWNLOADS,"prompt"),recording:e.XENO_BROWSER_RECORDING==="bounded"?"bounded":"disabled"},computer:{...i?{baseUrl:i}:{},...a?{token:a}:{},...s?{deviceId:s}:{},allowedApplications:Me(e.XENO_USE_ALLOWED_APPLICATIONS)}}}function $a(e){let t=L(e);if(!(!t||!en(t)))try{return L(tn(t,"utf8"))}catch{return}}function Va(e,t){let n=L(e.XENO_BROWSER_SESSION_FILE)??(t==="extension"?L(e.XENO_EXTENSION_SESSION_FILE)??Yr(La(),".xeno","use-drivers","xeno-extension.json"):L(e.XENO_SESSION_FILE)??(e.APPDATA?Yr(e.APPDATA,"xeno-browser","session.json"):void 0));if(!(!n||!en(n)))try{let o=JSON.parse(tn(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||!Ba(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 Ba(e){return e.length>=32&&e.length<=512&&!/\s/.test(e)}function Fa(e){return e==="extension"?[...Ma]:[...rn]}async function Zr(e,t){let r=e==="browser"?t.browser:t.computer,n=e==="browser"?Et(t.browser):vt(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"?an(t.browser):sn(t.computer)}:{}};try{let a=await(e==="browser"?new he({baseUrl:t.browser.baseUrl,token:t.browser.token,driver:t.browser.driver}):await on(t.computer)).manifest();return Ha(e,a)}catch(i){return{surface:e,configured:!0,available:!1,certified:!1,operations:[],limitations:["Configured adapter is unavailable."],error:St(i)}}}async function on(e){let t=await ja(),r=new t.Use({baseUrl:e.baseUrl,token:e.token});return new t.XenoUseComputerAutomationAdapter({use:r,...e.deviceId?{defaultDeviceId:e.deviceId}:{}})}async function ja(){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: ${St(e)}`)}}function Ha(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 Ga(e,t,r){let n=r.browser,o=cn(t),i=o&&!Qa(o.hostname)?o.hostname:void 0,a=Ue([...n.readDomains,...i?[i]:[]]),s=Ue([...n.actDomains,...e==="act"&&i?[i]:[]]),c=ln([...n.ports,...o?[dn(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 Wa(e,t){return{mode:e==="act"?"act":"observe",allowedApplications:t.computer?.allowedApplications??[],sensitiveRegionRedaction:!0,humanStopRequired:!0}}function qa(e,t){let r=[],n=cn(e);n&&r.push({scheme:n.protocol.replace(/:$/,""),host:n.hostname.toLowerCase(),port:dn(n)});for(let o of Ue([...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:ts(r)}}function za(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 Ja(e){return e?.resource??e?.tabId??e?.pageId??e?.deviceId??e?.applicationId}function Ka(e){let t=e?.origin??e?.url;if(!t)return e?.domain;try{return new URL(t).origin}catch{return t}}function Ya(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 Za(e){try{return JSON.parse(JSON.stringify(e))}catch(t){throw new Error(`Automation parameters are not JSON serializable: ${St(t)}`)}}function Et(e){return!!e?.baseUrl&&!!e.token}function vt(e){return!!e?.baseUrl&&!!e.token&&!!e.deviceId}function an(e){return`Browser automation configuration is incomplete; missing ${[e?.baseUrl?"":"XENO_BROWSER_AUTOMATION_URL",e?.token?"":"XENO_BROWSER_AUTOMATION_TOKEN"].filter(Boolean).join(", ")}`}function sn(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 cn(e){let t=e?.url??e?.origin;if(t)try{return new URL(t)}catch{return}}function dn(e){return e.port?Number(e.port):e.protocol==="http:"?80:443}function Qa(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"}function Me(e){return Ue((e??"").split(",").map(t=>t.trim().toLowerCase()).filter(Boolean))}function es(e,t){let r=(e??"").split(",").map(n=>Number(n.trim())).filter(n=>Number.isSafeInteger(n)&&n>0&&n<=65535);return r.length>0?ln(r):t}function Qr(e,t){return e==="deny"||e==="prompt"||e==="allow"?e:t}function L(e){let t=e?.trim();return t||void 0}function Ue(e){return[...new Set(e)]}function ln(e){return[...new Set(e)].sort((t,r)=>t-r)}function ts(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 St(e){return e instanceof Error?e.message:String(e)}function kd(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
|
+
`)}export{wt as CliGovernedAutomationRuntime,ae as XENO_AUTOMATION_OPERATIONS,B as XENO_AUTOMATION_PROTOCOL_VERSION,Ne as XENO_BROWSER_CONTROL_PLANE_OPERATIONS,l as XenoAutomationError,he as XenoBrowserControlPlaneAdapter,xe as XenoGovernedAutomationExecutor,wt as XenoHostGovernedAutomationRuntime,Er as XenoLoopbackAutomationAdapter,_e as assertRequiredXenoAutomationEvidence,Te as assertValidXenoAutomationAdapterManifest,or as assertValidXenoAutomationRequest,Nc as assertXenoAutomationAdapterConformant,tt as assertXenoAutomationAuthority,ir as buildXenoAutomationCapabilityUse,Od as createCliAutomationAuditSink,xd as createCliGovernedAutomationRuntime,di as createXenoAutomationConformanceReport,Jr as createXenoGovernedAutomationTools,Od as createXenoHostAutomationAuditSink,xd as createXenoHostGovernedAutomationRuntime,N as describeXenoAutomationOperation,Nd as inspectCliAutomationStatus,Nd as inspectXenoHostAutomationStatus,je as isXenoAutomationOperation,st as materializeXenoAutomationEvidence,ct as persistXenoAutomationEvidence,nn as readCliAutomationEnvironment,nn as readXenoHostAutomationEnvironment,kd as renderCliAutomationStatus,kd as renderXenoHostAutomationStatus,ar as resolveXenoAutomationEvidencePolicy};
|