@xenosystem/agent-sdk 0.9.16 → 0.9.19

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.
@@ -1,5 +1,5 @@
1
1
  "use strict";var xe=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var an=Object.getOwnPropertyNames;var cn=Object.prototype.hasOwnProperty;var dn=(e,t)=>{for(var n in t)xe(e,n,{get:t[n],enumerable:!0})},fn=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of an(t))!cn.call(e,o)&&o!==n&&xe(e,o,{get:()=>t[o],enumerable:!(i=sn(t,o))||i.enumerable});return e};var pn=e=>fn(xe({},"__esModule",{value:!0}),e);var ki={};dn(ki,{FileXenoArtifactRepository:()=>qe,InMemoryXenoArtifactRepository:()=>B,XENO_ARTIFACT_ACTOR_KINDS:()=>Pe,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION:()=>We,XENO_ARTIFACT_SCHEMA_VERSION:()=>h,XENO_ARTIFACT_SENSITIVITIES:()=>Ve,XENO_ARTIFACT_STATES:()=>Ne,XENO_BUILTIN_ARTIFACT_KINDS:()=>Ce,XENO_EVIDENCE_EDGE_TYPES:()=>ee,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION:()=>me,XENO_EVIDENCE_NODE_TYPES:()=>Q,XENO_REVIEW_DIMENSIONS:()=>Bt,XENO_REVIEW_EVIDENCE_KINDS:()=>Ut,XENO_REVIEW_REPORT_SCHEMA_VERSION:()=>ot,XENO_SPEC_EXECUTION_SCHEMA_VERSION:()=>ce,XENO_SPEC_SCHEMA_VERSION:()=>z,XenoArtifactRepositoryError:()=>u,XenoArtifactReviewService:()=>U,XenoArtifactStateTransitionError:()=>ve,XenoArtifactValidationError:()=>M,XenoDiffParseError:()=>X,XenoEvidenceGraphBuilder:()=>Le,XenoEvidenceGraphValidationError:()=>ye,XenoMultiAgentReviewCoordinator:()=>rt,XenoReviewValidationError:()=>E,XenoSpecLifecycleService:()=>Qe,XenoSpecValidationError:()=>w,assertValidXenoArtifact:()=>I,assertValidXenoEvidenceGraph:()=>J,assertValidXenoReviewPack:()=>st,assertValidXenoReviewReport:()=>fe,assertValidXenoReviewTarget:()=>at,assertValidXenoSpecDocument:()=>be,assertValidXenoSpecExecution:()=>it,assertXenoArtifactStateTransition:()=>ie,buildXenoArtifactReviewAnchor:()=>Ze,canTransitionXenoArtifactState:()=>yt,canonicalizeArtifactJson:()=>S,defaultXenoReviewPack:()=>ai,detectXenoSpecDrift:()=>ti,legacyAgentArtifactToXenoArtifact:()=>yi,normalizeRepositoryRelativePath:()=>Ft,parseUnifiedDiff:()=>Ke,sha256ArtifactBytes:()=>T,sha256ArtifactJson:()=>k,summarizeXenoArtifactReview:()=>ge,toolEvidenceToXenoArtifact:()=>wi,turnDiffSummaryToXenoArtifact:()=>Ri,unifiedDiffToXenoArtifact:()=>Ge,validateXenoArtifact:()=>At,validateXenoArtifactReviewEvent:()=>he,validateXenoEvidenceGraph:()=>wt,validateXenoSpecDocument:()=>Mt,xenoArtifactToDiffDocument:()=>Ye,xenoArtifactToLegacyAgentArtifact:()=>Ii,xenoArtifactToReviewReport:()=>di,xenoArtifactToSpecDocument:()=>tt,xenoArtifactToSpecExecution:()=>Ht,xenoArtifactToToolEvidence:()=>Ei,xenoArtifactToTurnDiffSummary:()=>Xi,xenoReviewReportToArtifact:()=>ci,xenoReviewReportToGitHubComments:()=>fi,xenoSpecArtifactIds:()=>W,xenoSpecExecutionToArtifact:()=>nt,xenoSpecToArtifactBundle:()=>et});module.exports=pn(ki);var h=1,me=1,Ce=["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"],Ne=["draft","pending_review","approved","rejected","superseded","archived"],Ve=["public","internal","confidential","restricted"],Pe=["agent","tool","user","system","integration"],Q=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],ee=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var De=require("node:buffer");var vt=require("node:crypto");function T(e){return{algorithm:"sha256",value:(0,vt.createHash)("sha256").update(e).digest("hex")}}function S(e){return JSON.stringify($e(e,new Set))}function k(e){return T(S(e))}function $e(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let i=e.map(o=>$e(o,t));return t.delete(e),i}let n={};for(let i of Object.keys(e).sort((o,r)=>o.localeCompare(r))){let o=e[i];if(o===void 0)throw new TypeError(`Artifact JSON property ${i} is undefined`);n[i]=$e(o,t)}return t.delete(e),n}var un=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Oe="custom:";function F(e,t=Oe){return e.startsWith(t)?un.test(e.slice(t.length)):!1}var M=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,n){super(t),this.name="XenoArtifactValidationError",this.issues=n.map(i=>({...i}))}},ve=class extends Error{constructor(n,i){super(`Artifact state cannot transition from ${n} to ${i}`);this.fromState=n;this.toState=i;this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},ln={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},mn="[\\u0000-\\u001f\\u007f]",vn=new RegExp(mn),ht=/^[a-f0-9]{64}$/,hn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,gn=new Set(Ne),An=new Set(Ve),yn=new Set(Pe),In=new Set(Ce),wn=new Set(Q),En=new Set(ee);function p(e,t,n,i){e.push({path:t,code:n,message:i})}function l(e,t,n,i=1024){return typeof e!="string"||e.trim().length===0?(p(n,t,"required_string","Value must be a non-empty string"),!1):(e.length>i&&p(n,t,"string_too_long",`Value must not exceed ${i} characters`),vn.test(e)&&p(n,t,"control_character","Value must not contain control characters"),!0)}function te(e,t,n){e!==void 0&&(!Number.isFinite(Date.parse(e))||!e.includes("T"))&&p(n,t,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function L(e,t,n,i){typeof e=="string"&&e.startsWith(t)&&(F(e,t)||p(i,n,"invalid_custom_name",`Custom name after ${t} is invalid`))}function gt(e,t,n){if(!e||typeof e!="object"){p(n,t,"missing_actor","Actor is required");return}l(e.kind,`${t}.kind`,n,64),yn.has(e.kind)||p(n,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),l(e.id,`${t}.id`,n,512),e?.displayName!==void 0&&l(e.displayName,`${t}.displayName`,n,512),e?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.profileFingerprint)&&p(n,`${t}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function Fe(e,t,n){if(!e||typeof e!="object"){p(n,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":l(e.path,`${t}.path`,n,4096);break;case"source-line":l(e.path,`${t}.path`,n,4096),(!Number.isInteger(e.startLine)||e.startLine<1)&&p(n,`${t}.startLine`,"invalid_line","startLine must be a positive integer"),e.endLine!==void 0&&(!Number.isInteger(e.endLine)||e.endLine<e.startLine)&&p(n,`${t}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":l(e.path,`${t}.path`,n,4096),l(e.hunkId,`${t}.hunkId`,n,512);break;case"symbol":l(e.path,`${t}.path`,n,4096),l(e.symbol,`${t}.symbol`,n,1024);break;case"dom-node":l(e.pageId,`${t}.pageId`,n,512),!e.selector&&!e.accessibilityId&&!e.snapshotArtifactId&&p(n,t,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":l(e.recordingArtifactId,`${t}.recordingArtifactId`,n,512),(!Number.isFinite(e.startMs)||e.startMs<0)&&p(n,`${t}.startMs`,"invalid_time","startMs must be a non-negative finite number"),e.endMs!==void 0&&(!Number.isFinite(e.endMs)||e.endMs<e.startMs)&&p(n,`${t}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":l(e.mediaArtifactId,`${t}.mediaArtifactId`,n,512),[e.x,e.y,e.width,e.height].every(Number.isFinite)?(e.width<=0||e.height<=0)&&p(n,t,"invalid_region_size","Region width and height must be positive"):p(n,t,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":l(e.artifactId,`${t}.artifactId`,n,512);break;default:typeof e.kind!="string"||!e.kind.startsWith("custom:")?p(n,`${t}.kind`,"unknown_anchor","Anchor kind is not supported"):L(e.kind,"custom:",`${t}.kind`,n)}}function ne(e,t,n,i){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||p(n,t,"non_finite_number","JSON numbers must be finite");return}if(typeof e!="object"){p(n,t,"non_json_value","Value must be JSON-serializable");return}if(i.has(e)){p(n,t,"cyclic_value","Value must not contain cycles");return}if(i.add(e),Array.isArray(e))e.forEach((o,r)=>ne(o,`${t}[${r}]`,n,i));else for(let[o,r]of Object.entries(e))r===void 0?p(n,`${t}.${o}`,"undefined_value","Undefined is not valid JSON"):ne(r,`${t}.${o}`,n,i);i.delete(e)}}function At(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_artifact",message:"Artifact must be an object"}];if(e.schemaVersion!==1&&p(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(e.artifactId,"artifactId",t,512),(!Number.isInteger(e.revision)||e.revision<1)&&p(t,"revision","invalid_revision","revision must be a positive integer"),l(e.kind,"kind",t,160),typeof e.kind=="string"&&!In.has(e.kind)&&!e.kind.startsWith("custom:")&&p(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),L(e.kind,"custom:","kind",t),l(e.title,"title",t,1024),e.description!==void 0&&l(e.description,"description",t,32768),l(e.state,"state",t,64),gn.has(e.state)||p(t,"state","unknown_state","Artifact state is not supported"),l(e.createdAt,"createdAt",t,128),te(e.createdAt,"createdAt",t),te(e.updatedAt,"updatedAt",t),e.updatedAt&&Number.isFinite(Date.parse(e.createdAt))&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&p(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt"),l(e.mediaType,"mediaType",t,255),l(e.sensitivity,"sensitivity",t,64),An.has(e.sensitivity)||p(t,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),e.identity)for(let[i,o]of Object.entries(e.identity))o!==void 0&&l(o,`identity.${i}`,t,512);if(!e.content||typeof e.content!="object")p(t,"content","missing_content","content descriptor is required");else{!e.content.hash||typeof e.content.hash!="object"?p(t,"content.hash","missing_hash","content hash is required"):(l(e.content.hash.algorithm,"content.hash.algorithm",t,128),L(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:")&&p(t,"content.hash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported"),l(e.content.hash.value,"content.hash.value",t,512),e.content.hash.algorithm==="sha256"&&!ht.test(e.content.hash.value)&&p(t,"content.hash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters")),(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0)&&p(t,"content.sizeBytes","invalid_size","sizeBytes must be a non-negative safe integer");let i=e.content.storage;if(!i||typeof i!="object")p(t,"content.storage","missing_storage","storage reference is required");else if(i.type==="inline")if(i.text===void 0==(i.base64===void 0))p(t,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;i.text!==void 0?o=De.Buffer.from(i.text,"utf8"):i.base64!==void 0&&(hn.test(i.base64)?o=De.Buffer.from(i.base64,"base64"):p(t,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),o&&e.content.sizeBytes!==o.byteLength&&p(t,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),o&&e.content.hash.algorithm==="sha256"&&T(o).value!==e.content.hash.value&&p(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else i.type==="file"?l(i.path,"content.storage.path",t,4096):i.type==="blob"?l(i.uri,"content.storage.uri",t,8192):i.type==="git"?(l(i.commit,"content.storage.commit",t,512),l(i.path,"content.storage.path",t,4096)):i.type==="url"?(l(i.url,"content.storage.url",t,8192),te(i.expiresAt,"content.storage.expiresAt",t)):i.type==="external"?(l(i.provider,"content.storage.provider",t,255),l(i.locator,"content.storage.locator",t,8192)):p(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:"))&&p(t,"content.encoding","unknown_encoding","Content encoding is not supported"),L(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?p(t,"provenance","missing_provenance","provenance is required"):(gt(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((i,o)=>l(i,`provenance.capabilityLeaseIds[${o}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((i,o)=>l(i,`provenance.sourceArtifactIds[${o}]`,t,512)),e.provenance.attributes&&ne(e.provenance.attributes,"provenance.attributes",t,new Set));let n=new Set;return e.relationships?.forEach((i,o)=>{let r=`relationships[${o}]`;l(i.relation,`${r}.relation`,t,160),typeof i.relation=="string"&&!En.has(i.relation)&&!i.relation.startsWith("custom:")&&p(t,`${r}.relation`,"unknown_relationship","Relationship type is not supported"),L(i.relation,"custom:",`${r}.relation`,t),l(i.target?.type,`${r}.target.type`,t,160),typeof i.target?.type=="string"&&!wn.has(i.target.type)&&!i.target.type.startsWith("custom:")&&p(t,`${r}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),L(i.target?.type,"custom:",`${r}.target.type`,t),l(i.target?.id,`${r}.target.id`,t,512);let a=`${i.relation}:${i.target?.type}:${i.target?.id}:${i.target?.revision??""}`;n.has(a)&&p(t,r,"duplicate_relationship","Duplicate relationship"),n.add(a),i.attributes&&ne(i.attributes,`${r}.attributes`,t,new Set)}),e.anchors?.forEach((i,o)=>Fe(i,`anchors[${o}]`,t)),e.revision===1&&e.predecessorRevision!==void 0&&p(t,"predecessorRevision","unexpected_predecessor","First revision cannot have a predecessor"),e.revision>1&&(!Number.isInteger(e.predecessorRevision)||(e.predecessorRevision??0)>=e.revision)&&p(t,"predecessorRevision","invalid_predecessor","Later revisions require an earlier predecessor revision"),te(e.retention?.retainUntil,"retention.retainUntil",t),e.retention?.legalHold!==void 0&&typeof e.retention.legalHold!="boolean"&&p(t,"retention.legalHold","invalid_boolean","legalHold must be a boolean"),e.extensions&&ne(e.extensions,"extensions",t,new Set),t}function I(e){let t=At(e);if(t.length>0)throw new M("XENO artifact validation failed",t)}function yt(e,t){return ln[e].includes(t)}function ie(e,t){if(!yt(e,t))throw new ve(e,t)}function he(e,t){let n=[];return e.schemaVersion!==1&&p(n,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(e.eventId,"eventId",n,512),l(e.artifactId,"artifactId",n,512),(!Number.isInteger(e.artifactRevision)||e.artifactRevision<1)&&p(n,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(e.sequence)||e.sequence<1)&&p(n,"sequence","invalid_sequence","sequence must be a positive integer"),l(e.recordedAt,"recordedAt",n,128),te(e.recordedAt,"recordedAt",n),gt(e.actor,"actor",n),!e.artifactHash||typeof e.artifactHash!="object"?p(n,"artifactHash","missing_hash","Artifact hash is required"):(l(e.artifactHash.algorithm,"artifactHash.algorithm",n,128),L(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",n),l(e.artifactHash.value,"artifactHash.value",n,512),e.artifactHash.algorithm==="sha256"&&!ht.test(e.artifactHash.value)&&p(n,"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:")&&p(n,"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)||p(n,"type","unknown_review_event","Review event type is not supported"),e.type==="comment-added"?(l(e.commentId,"commentId",n,512),l(e.body,"body",n,65536),e.anchor&&Fe(e.anchor,"anchor",n)):e.type==="comment-resolved"||e.type==="comment-reopened"?l(e.commentId,"commentId",n,512):e.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(e.decision)||p(n,"decision","unknown_review_decision","Review decision is not supported"),e.scope&&Fe(e.scope,"scope",n)),t&&(e.artifactId!==t.artifactId&&p(n,"artifactId","artifact_mismatch","Review event targets a different artifact"),e.artifactRevision!==t.revision&&p(n,"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)&&p(n,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),n}function ge(e){let t="not_requested",n,i,o,r=0,a=new Set,c=new Set;for(let s of[...e].sort((d,f)=>d.sequence-f.sequence))o=s.recordedAt,s.type==="review-requested"?t="pending":s.type==="review-withdrawn"?t="withdrawn":s.type==="comment-added"?(a.add(s.commentId),c.delete(s.commentId),t==="not_requested"&&(t="pending")):s.type==="comment-resolved"?c.add(s.commentId):s.type==="comment-reopened"?c.delete(s.commentId):s.type==="decision-recorded"&&(s.scope?r+=1:(n=s.decision,i=s.eventId,t=s.decision));return{status:t,totalComments:a.size,unresolvedComments:[...a].filter(s=>!c.has(s)).length,...n?{latestDecision:n}:{},...i?{latestDecisionEventId:i}:{},...r>0?{scopedDecisionCount:r}:{},...o?{lastReviewedAt:o}:{}}}var ye=class extends Error{code="EVIDENCE_GRAPH_INVALID";issues;constructor(t){super("XENO evidence graph validation failed"),this.name="XenoEvidenceGraphValidationError",this.issues=t.map(n=>({...n}))}},Rn=new Set(["depends_on","decomposes","supersedes"]),Xn=new Set(Q),Sn=new Set(ee);function A(e,t,n,i){e.push({path:t,code:n,message:i})}function re(e){return e.includes("T")&&Number.isFinite(Date.parse(e))}function It(e,t){return e.startsWith(Oe)?F(e):t.has(e)}function wt(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_graph",message:"Evidence graph must be an object"}];e.schemaVersion!==1&&A(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),(typeof e.graphId!="string"||e.graphId.trim().length===0)&&A(t,"graphId","required_string","graphId must be a non-empty string"),(!Number.isInteger(e.version)||e.version<1)&&A(t,"version","invalid_version","version must be a positive integer"),re(e.createdAt)||A(t,"createdAt","invalid_timestamp","createdAt must be an ISO 8601 timestamp"),re(e.updatedAt)||A(t,"updatedAt","invalid_timestamp","updatedAt must be an ISO 8601 timestamp"),re(e.createdAt)&&re(e.updatedAt)&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&A(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt");let n=new Map;Array.isArray(e.nodes)||A(t,"nodes","invalid_nodes","nodes must be an array"),(Array.isArray(e.nodes)?e.nodes:[]).forEach((f,g)=>{let R=`nodes[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(t,`${R}.id`,"required_string","Node ID must be a non-empty string"):n.has(f.id)?A(t,`${R}.id`,"duplicate_node",`Node ID ${f.id} is duplicated`):n.set(f.id,f),(typeof f.type!="string"||!It(f.type,Xn))&&A(t,`${R}.type`,"invalid_node_type","Node type is invalid"),f.artifactRevision!==void 0&&(!Number.isInteger(f.artifactRevision)||f.artifactRevision<1)&&A(t,`${R}.artifactRevision`,"invalid_revision","artifactRevision must be a positive integer")});let i=new Set,o=new Set;Array.isArray(e.edges)||A(t,"edges","invalid_edges","edges must be an array"),(Array.isArray(e.edges)?e.edges:[]).forEach((f,g)=>{let R=`edges[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(t,`${R}.id`,"required_string","Edge ID must be a non-empty string"):i.has(f.id)&&A(t,`${R}.id`,"duplicate_edge",`Edge ID ${f.id} is duplicated`),i.add(f.id),(typeof f.type!="string"||!It(f.type,Sn))&&A(t,`${R}.type`,"invalid_edge_type","Edge type is invalid");let O=`${f.type}:${f.from}:${f.to}`;o.has(O)&&A(t,R,"duplicate_edge_identity","Equivalent evidence edge is duplicated"),o.add(O),n.has(f.from)||A(t,`${R}.from`,"dangling_reference",`Source node ${f.from} does not exist`),n.has(f.to)||A(t,`${R}.to`,"dangling_reference",`Target node ${f.to} does not exist`),f.from===f.to&&A(t,R,"self_edge","Evidence edges cannot point to the same node"),re(f.createdAt)||A(t,`${R}.createdAt`,"invalid_timestamp","createdAt must be an ISO 8601 timestamp")});let r=(Array.isArray(e.edges)?e.edges:[]).filter(f=>Rn.has(f.type)),a=new Map;for(let f of r){let g=a.get(f.from)??[];g.push(f.to),a.set(f.from,g)}let c=new Set,s=new Set,d=f=>{if(c.has(f))return!0;if(s.has(f))return!1;c.add(f);for(let g of a.get(f)??[])if(d(g))return!0;return c.delete(f),s.add(f),!1};for(let f of n.keys())if(d(f)){A(t,"edges","cyclic_graph","Dependency, decomposition, and supersession edges must be acyclic");break}return t}function J(e){let t=wt(e);if(t.length>0)throw new ye(t)}var Le=class{now;graph;constructor(t){if("schemaVersion"in t)J(t),this.now=()=>new Date().toISOString(),this.graph=Ae(t);else{this.now=t.now??(()=>new Date().toISOString());let n=this.now();this.graph={schemaVersion:1,graphId:t.graphId,version:1,createdAt:n,updatedAt:n,nodes:[],edges:[]},J(this.graph)}}addNode(t){let n=Ae(this.graph);return n.nodes.push(Et(t)),this.touch(n),J(n),this.graph=n,this}addEdge(t){let n=Ae(this.graph);return n.edges.push(Rt(t)),this.touch(n),J(n),this.graph=n,this}build(){return J(this.graph),Ae(this.graph)}touch(t){t.version+=1,t.updatedAt=this.now()}};function Et(e){return{...e,...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function Rt(e){return{...e,...e.producer?{producer:{...e.producer}}:{},...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function Ae(e){return{...e,nodes:e.nodes.map(Et),edges:e.edges.map(Rt)}}var u=class extends Error{constructor(n,i,o,r){super(i,r);this.code=n;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},B=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??(n=>(this.idCounter+=1,`${n}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),t.initialState&&this.hydrate(t.initialState)}exportState(){let t=[...this.records.values()].flatMap(n=>[...n.values()]).sort(Xt).map(n=>({artifact:oe(n.artifact),recordVersion:n.recordVersion,lifecycleEvents:structuredClone(n.lifecycleEvents),reviewEvents:structuredClone(n.reviewEvents)}));return{schemaVersion:1,records:t}}async create(t){if(I(t),this.assertInitialState(t),t.revision!==1)throw new u("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 u("ARTIFACT_ALREADY_EXISTS",`Artifact ${t.artifactId} already exists`,{artifactId:t.artifactId});let n=oe(t),i=this.createLifecycleEvent({artifact:n,sequence:1,actor:n.provenance.producer,fromState:null,toState:n.state,reason:"artifact-created"}),o={artifact:n,recordVersion:1,lifecycleEvents:[i],reviewEvents:[]};return this.records.set(n.artifactId,new Map([[n.revision,o]])),this.currentRevisions.set(n.artifactId,n.revision),H(o)}async createRevision(t,n={}){I(t),this.assertInitialState(t);let i=this.getMutable(t.artifactId);this.assertVersion(i,n.expectedRecordVersion);let o=i.artifact.revision+1;if(t.revision!==o||t.predecessorRevision!==i.artifact.revision)throw new u("ARTIFACT_REVISION_INVALID",`Revision ${t.revision} does not follow current revision ${i.artifact.revision}`,{artifactId:t.artifactId,currentRevision:i.artifact.revision,requestedRevision:t.revision});if(_n(t,i.artifact))throw new u("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:t.artifactId,revision:t.revision});if(i.artifact.state==="archived")throw new u("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:t.artifactId,revision:i.artifact.revision});if(i.artifact.state!=="superseded"){ie(i.artifact.state,"superseded");let s=this.now(),d=this.createLifecycleEvent({artifact:i.artifact,sequence:i.lifecycleEvents.length+1,actor:n.actor??t.provenance.producer,fromState:i.artifact.state,toState:"superseded",reason:n.reason??`superseded-by-revision-${t.revision}`,recordedAt:s});i.artifact.state="superseded",i.artifact.updatedAt=s,i.lifecycleEvents.push(d),i.recordVersion+=1}let r=oe(t),a=this.createLifecycleEvent({artifact:r,sequence:1,actor:n.actor??r.provenance.producer,fromState:null,toState:r.state,reason:n.reason??`revision-created-from-${i.artifact.revision}`}),c={artifact:r,recordVersion:1,lifecycleEvents:[a],reviewEvents:[]};return this.records.get(r.artifactId)?.set(r.revision,c),this.currentRevisions.set(r.artifactId,r.revision),H(c)}async get(t,n){let i=this.records.get(t);if(!i)return;let o=n??this.currentRevisions.get(t);if(o===void 0)return;let r=i.get(o);return r?H(r):void 0}async require(t,n){let i=await this.get(t,n);if(!i)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:t,...n===void 0?{}:{revision:n}});return i}async list(t={}){let n=[];for(let[i,o]of this.records)if(!(t.artifactIds&&!t.artifactIds.includes(i)))if(t.includeSuperseded)n.push(...o.values());else{let r=this.currentRevisions.get(i);if(r!==void 0){let a=o.get(r);a&&n.push(a)}}return n.filter(i=>Tn(i.artifact,t)).sort(Xt).map(H)}async listRevisions(t){let n=this.records.get(t);return n?[...n.values()].sort((i,o)=>i.artifact.revision-o.artifact.revision).map(H):[]}async transition(t){let n=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(n,t.expectedRecordVersion),ie(n.artifact.state,t.toState),t.toState==="approved"||t.toState==="rejected"){let a=t.reviewEventId?n.reviewEvents.find(s=>s.eventId===t.reviewEventId&&s.type==="decision-recorded"):void 0,c=ge(n.reviewEvents);if(!a||a.decision!==t.toState||c.latestDecisionEventId!==a.eventId)throw new u("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${t.toState} requires a matching decision event`,{artifactId:t.artifactId,revision:n.artifact.revision});if(t.toState==="approved"&&c.unresolvedComments>0)throw new u("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${c.unresolvedComments} unresolved review comment(s)`,{artifactId:t.artifactId,revision:n.artifact.revision,unresolvedComments:c.unresolvedComments})}let i=this.now(),o=n.artifact.state,r=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor,fromState:o,toState:t.toState,reason:t.reason,reviewEventId:t.reviewEventId,recordedAt:i});return n.artifact.state=t.toState,n.artifact.updatedAt=i,n.lifecycleEvents.push(r),n.recordVersion+=1,H(n)}async appendReviewEvent(t){let n=t.event,i=this.getMutable(n.artifactId,n.artifactRevision);if(this.assertVersion(i,t.expectedRecordVersion),i.artifact.state==="archived"||i.artifact.state==="superseded")throw new u("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${i.artifact.state} artifact revision`,{artifactId:n.artifactId,revision:n.artifactRevision});if(this.assertReviewCommentState(i,n),(n.type==="review-requested"||n.type==="review-withdrawn"||n.type==="decision-recorded")&&i.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`${n.type} requires an artifact in pending_review state`,{artifactId:n.artifactId,revision:n.artifactRevision});let o={...structuredClone(n),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:i.reviewEvents.length+1,recordedAt:this.now()},r=he(o,i.artifact);if(r.length>0)throw new M("XENO artifact review event validation failed",r);return i.reviewEvents.push(o),i.recordVersion+=1,H(i)}getMutable(t,n){let i=this.records.get(t),o=n??this.currentRevisions.get(t),r=o===void 0?void 0:i?.get(o);if(!r)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:t,...n===void 0?{}:{revision:n}});return r}assertVersion(t,n){if(n!==void 0&&n!==t.recordVersion)throw new u("ARTIFACT_CONFLICT",`Expected record version ${n}, found ${t.recordVersion}`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision,expectedRecordVersion:n,actualRecordVersion:t.recordVersion})}assertInitialState(t){if(t.state!=="draft"&&t.state!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:t.artifactId,revision:t.revision})}assertReviewCommentState(t,n){if(n.type==="comment-added"){if(t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} already exists`);if(n.parentCommentId&&!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Parent comment ${n.parentCommentId} does not exist`);return}if(n.type!=="comment-resolved"&&n.type!=="comment-reopened")return;if(!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} does not exist`);let o=kn(t.reviewEvents,n.commentId);if(n.type==="comment-resolved"&&o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} is already resolved`);if(n.type==="comment-reopened"&&!o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.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 n=this.idFactory(t);if(typeof n!="string"||n.trim().length===0||this.eventIds.has(n))throw new u("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${t} ID`);return this.eventIds.add(n),n}hydrate(t){if(t.schemaVersion!==1||!Array.isArray(t.records))throw new u("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let n=[...t.records].sort((i,o)=>i.artifact.artifactId.localeCompare(o.artifact.artifactId)||i.artifact.revision-o.artifact.revision);for(let i of n){let o=bn(i,this.eventIds),r=this.records.get(o.artifact.artifactId);if(r||(r=new Map,this.records.set(o.artifact.artifactId,r)),r.has(o.artifact.revision))throw new u("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${o.artifact.artifactId}:${o.artifact.revision}`);r.set(o.artifact.revision,o),this.currentRevisions.set(o.artifact.artifactId,o.artifact.revision)}for(let[i,o]of this.records){let r=[...o.values()].sort((a,c)=>a.artifact.revision-c.artifact.revision);for(let a=0;a<r.length;a+=1){let c=r[a],s=a+1;if(c.artifact.revision!==s)throw new u("ARTIFACT_REVISION_INVALID",`Persisted artifact ${i} is missing revision ${s}`);if(a===0&&c.artifact.predecessorRevision!==void 0)throw new u("ARTIFACT_REVISION_INVALID",`Initial revision for ${i} cannot declare a predecessor`);if(a>0&&c.artifact.predecessorRevision!==s-1)throw new u("ARTIFACT_REVISION_INVALID",`Persisted revision ${i}:${s} has an invalid predecessor`);if(a<r.length-1&&c.artifact.state!=="superseded")throw new u("ARTIFACT_REVISION_INVALID",`Non-current revision ${i}:${s} must be superseded`)}}}};function bn(e,t){if(I(e.artifact),!Number.isInteger(e.recordVersion)||e.recordVersion<1)throw new u("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 u("ARTIFACT_REVISION_INVALID","Persisted artifact records require lifecycle and review event arrays",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let n=e.lifecycleEvents.length+e.reviewEvents.length;if(e.recordVersion!==n)throw new u("ARTIFACT_REVISION_INVALID",`Persisted record version ${e.recordVersion} does not match ${n} mutations`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let i=null;for(let r=0;r<e.lifecycleEvents.length;r+=1){let a=e.lifecycleEvents[r];if(a.schemaVersion!==1||a.artifactId!==e.artifact.artifactId||a.revision!==e.artifact.revision||a.sequence!==r+1||a.fromState!==i||typeof a.eventId!="string"||a.eventId.length===0||t.has(a.eventId)||!Number.isFinite(Date.parse(a.recordedAt)))throw new u("ARTIFACT_REVISION_INVALID",`Persisted lifecycle event ${r+1} is invalid`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(i===null){if(a.toState!=="draft"&&a.toState!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:e.artifact.artifactId,revision:e.artifact.revision})}else ie(i,a.toState);t.add(a.eventId),i=a.toState}if(i!==e.artifact.state)throw new u("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 r=0;r<e.reviewEvents.length;r+=1){let a=e.reviewEvents[r];if(a.sequence!==r+1||t.has(a.eventId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted review event ${r+1} has an invalid sequence or duplicate ID`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let c=he(a,e.artifact);if(c.length>0)throw new M("Persisted XENO artifact review event validation failed",c);if(a.type==="comment-added"){if(o.has(a.commentId)||a.parentCommentId!==void 0&&!o.has(a.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted comment ${a.commentId} has an invalid identity or parent`);o.set(a.commentId,!1)}else if(a.type==="comment-resolved"||a.type==="comment-reopened"){let s=o.get(a.commentId);if(s===void 0||a.type==="comment-resolved"&&s||a.type==="comment-reopened"&&!s)throw new u("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:oe(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function _n(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function Tn(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 Xt(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function kn(e,t){let n=!1;for(let i of e)(i.type==="comment-resolved"||i.type==="comment-reopened")&&i.commentId===t&&(n=i.type==="comment-resolved");return{resolved:n}}function oe(e){return structuredClone(e)}function H(e){return{artifact:oe(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:ge(e.reviewEvents)}}var Ue=require("node:crypto"),b=require("node:fs/promises"),N=require("node:path");var V=require("node:fs"),Me=require("node:os"),bt=require("node:path");function xn(){return new Date().toISOString()}function Cn(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function _t(e){try{return JSON.parse((0,V.readFileSync)(e,"utf8"))}catch{return null}}function Nn(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Vn(e){return e.hostname!==(0,Me.hostname)()?!0:Nn(e.pid)}function St(e,t){(0,V.mkdirSync)((0,bt.dirname)(e),{recursive:!0}),(0,V.writeFileSync)(e,JSON.stringify(t,null,2)+`
2
- `,{encoding:"utf8",flag:"wx"})}function Pn(e,t){let n=_t(e);n?.pid!==t.pid||n.hostname!==t.hostname||(0,V.rmSync)(e,{force:!0})}function Tt(e,t,n){let i=xn(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,Me.hostname)(),processStartedAt:Cn(),version:n,acquiredAt:i,updatedAt:i};try{St(e,o)}catch(r){if(r.code!=="EEXIST")throw r;let c=_t(e);if(c&&Vn(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);(0,V.rmSync)(e,{force:!0}),St(e,o)}return{record:o,release:()=>{Pn(e,o)}}}var kt="0.9.16";var We=1,$n="repository.v1.json",On=5e3,Dn=20,Fn=64*1024*1024,qe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(t){if(!t||typeof t.directory!="string"||t.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let n=t.snapshotFileName??$n;if((0,N.basename)(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,N.resolve)(t.directory),this.snapshotPath=(0,N.join)(this.directory,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=He(t.lockTimeoutMs,On,100,6e4,"lockTimeoutMs"),this.lockRetryMs=He(t.lockRetryMs,Dn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=He(t.maxSnapshotBytes,Fn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(n=>n.create(t))}async createRevision(t,n){return this.mutate(i=>i.createRevision(t,n))}async get(t,n){return(await this.load()).repository.get(t,n)}async require(t,n){return(await this.load()).repository.require(t,n)}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(n=>n.transition(t))}async appendReviewEvent(t){return this.mutate(n=>n.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await t(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(t){let n=this.mutationTail.then(t,t);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let t=Date.now(),n;for(;Date.now()-t<=this.lockTimeoutMs;)try{return Tt(this.lockPath,`artifact-repository:${(0,N.basename)(this.snapshotPath)}`,kt)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await qn(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let t,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){t=Ie(r)}if(!n&&(t||await jn(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:t?.message??"primary snapshot missing"}),n=r,i=!0)}catch(r){throw t?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,Ie(r)])}):r}if(!n&&t)throw t;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new B({now:this.now,idFactory:r=>`${r}_${(0,Ue.randomUUID)()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(t){let n=this.now(),o={...{schemaVersion:We,generation:t.generation,createdAt:t.createdAt,updatedAt:n,state:t.repository.exportState()},generation:t.generation+1},r=Mn(o),a=`${JSON.stringify(r,null,2)}
2
+ `,{encoding:"utf8",flag:"wx"})}function Pn(e,t){let n=_t(e);n?.pid!==t.pid||n.hostname!==t.hostname||(0,V.rmSync)(e,{force:!0})}function Tt(e,t,n){let i=xn(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,Me.hostname)(),processStartedAt:Cn(),version:n,acquiredAt:i,updatedAt:i};try{St(e,o)}catch(r){if(r.code!=="EEXIST")throw r;let c=_t(e);if(c&&Vn(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);(0,V.rmSync)(e,{force:!0}),St(e,o)}return{record:o,release:()=>{Pn(e,o)}}}var kt="0.9.19";var We=1,$n="repository.v1.json",On=5e3,Dn=20,Fn=64*1024*1024,qe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(t){if(!t||typeof t.directory!="string"||t.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let n=t.snapshotFileName??$n;if((0,N.basename)(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,N.resolve)(t.directory),this.snapshotPath=(0,N.join)(this.directory,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=He(t.lockTimeoutMs,On,100,6e4,"lockTimeoutMs"),this.lockRetryMs=He(t.lockRetryMs,Dn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=He(t.maxSnapshotBytes,Fn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(n=>n.create(t))}async createRevision(t,n){return this.mutate(i=>i.createRevision(t,n))}async get(t,n){return(await this.load()).repository.get(t,n)}async require(t,n){return(await this.load()).repository.require(t,n)}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(n=>n.transition(t))}async appendReviewEvent(t){return this.mutate(n=>n.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await t(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(t){let n=this.mutationTail.then(t,t);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let t=Date.now(),n;for(;Date.now()-t<=this.lockTimeoutMs;)try{return Tt(this.lockPath,`artifact-repository:${(0,N.basename)(this.snapshotPath)}`,kt)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await qn(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let t,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){t=Ie(r)}if(!n&&(t||await jn(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:t?.message??"primary snapshot missing"}),n=r,i=!0)}catch(r){throw t?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,Ie(r)])}):r}if(!n&&t)throw t;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new B({now:this.now,idFactory:r=>`${r}_${(0,Ue.randomUUID)()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(t){let n=this.now(),o={...{schemaVersion:We,generation:t.generation,createdAt:t.createdAt,updatedAt:n,state:t.repository.exportState()},generation:t.generation+1},r=Mn(o),a=`${JSON.stringify(r,null,2)}
3
3
  `;if(Buffer.byteLength(a,"utf8")>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await(0,b.mkdir)(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await xt(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
4
4
  `),await xt(this.snapshotPath,a)}async readSnapshot(t,n){let i;try{i=await(0,b.stat)(t)}catch(o){if(!n&&Je(o,"ENOENT")||n&&Je(o,"ENOENT"))return;throw Be("Unable to inspect artifact repository snapshot",t,o)}if(!i.isFile()||i.size>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:t,sizeBytes:i.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await(0,b.readFile)(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return Ln(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof u?o:Be("Unable to parse artifact repository snapshot",t,o,!0)}}};function Ln(e,t){if(!je(e)||e.schemaVersion!==We||!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))||!je(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!je(e.checksum)||e.checksum.algorithm!=="sha256"||typeof e.checksum.value!="string")throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:t});let n=e,i=Hn(n),o=Ct(i);if(n.checksum.value!==o)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new B({initialState:n.state}),structuredClone(n)}function Mn(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:Ct(e)}}}function Hn(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function Ct(e){return T(JSON.stringify(e)).value}async function xt(e,t){await(0,b.mkdir)((0,N.dirname)(e),{recursive:!0,mode:448});let n=`${e}.tmp.${process.pid}.${(0,Ue.randomUUID)()}`,i;try{i=await(0,b.open)(n,"wx",384),await i.writeFile(t,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,await(0,b.rename)(n,e);try{let o=await(0,b.open)((0,N.dirname)(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{i&&await i.close().catch(()=>{}),await(0,b.unlink)(n).catch(()=>{})}}function He(e,t,n,i,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<n||e>i)throw new TypeError(`${o} must be an integer between ${n} and ${i}`);return e}function je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Je(e,t){return e instanceof Error&&e.code===t}async function jn(e){try{return(await(0,b.stat)(e)).isFile()}catch(t){if(Je(t,"ENOENT"))return!1;throw Be("Unable to inspect artifact repository backup",e,t)}}function Ie(e){return e instanceof Error?e:new Error(String(e))}function Be(e,t,n,i=!1){return new u(i?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${Ie(n).message}`,{snapshotPath:t},{cause:Ie(n)})}function qn(e){return new Promise(t=>setTimeout(t,e))}var ze=require("node:buffer");var Jn=16*1024*1024,Bn=5e3,Un=1e5,Wn=1e6,zn=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,X=class extends Error{constructor(n,i){super(i===void 0?n:`${n} at diff line ${i}`);this.line=i;this.name="XenoDiffParseError"}line;code="XENO_DIFF_INVALID"};function Ke(e,t={}){if(typeof e!="string")throw new TypeError("Unified diff must be a string");let n=we(t.maxBytes,Jn,1024,256*1024*1024,"maxBytes"),i=we(t.maxFiles,Bn,1,1e5,"maxFiles"),o=we(t.maxHunks,Un,1,1e6,"maxHunks"),r=we(t.maxLines,Wn,1,5e6,"maxLines");if(ze.Buffer.byteLength(e,"utf8")>n)throw new X(`Unified diff exceeds ${n} bytes`);let a=e.replace(/\r\n/g,`
5
5
  `).replace(/\r/g,`
@@ -1,5 +1,5 @@
1
1
  var h=1,oe=1,He=["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"],je=["draft","pending_review","approved","rejected","superseded","archived"],qe=["public","internal","confidential","restricted"],Je=["agent","tool","user","system","integration"],se=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],ae=["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 Be}from"node:buffer";import{createHash as zt}from"node:crypto";function _(e){return{algorithm:"sha256",value:zt("sha256").update(e).digest("hex")}}function S(e){return JSON.stringify(Ee(e,new Set))}function T(e){return _(S(e))}function Ee(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let i=e.map(o=>Ee(o,t));return t.delete(e),i}let n={};for(let i of Object.keys(e).sort((o,r)=>o.localeCompare(r))){let o=e[i];if(o===void 0)throw new TypeError(`Artifact JSON property ${i} is undefined`);n[i]=Ee(o,t)}return t.delete(e),n}var Kt=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Re="custom:";function $(e,t=Re){return e.startsWith(t)?Kt.test(e.slice(t.length)):!1}var M=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,n){super(t),this.name="XenoArtifactValidationError",this.issues=n.map(i=>({...i}))}},Xe=class extends Error{constructor(n,i){super(`Artifact state cannot transition from ${n} to ${i}`);this.fromState=n;this.toState=i;this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},Gt={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},Yt="[\\u0000-\\u001f\\u007f]",Zt=new RegExp(Yt),Ue=/^[a-f0-9]{64}$/,Qt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,en=new Set(je),tn=new Set(qe),nn=new Set(Je),rn=new Set(He),on=new Set(se),sn=new Set(ae);function p(e,t,n,i){e.push({path:t,code:n,message:i})}function l(e,t,n,i=1024){return typeof e!="string"||e.trim().length===0?(p(n,t,"required_string","Value must be a non-empty string"),!1):(e.length>i&&p(n,t,"string_too_long",`Value must not exceed ${i} characters`),Zt.test(e)&&p(n,t,"control_character","Value must not contain control characters"),!0)}function B(e,t,n){e!==void 0&&(!Number.isFinite(Date.parse(e))||!e.includes("T"))&&p(n,t,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function O(e,t,n,i){typeof e=="string"&&e.startsWith(t)&&($(e,t)||p(i,n,"invalid_custom_name",`Custom name after ${t} is invalid`))}function We(e,t,n){if(!e||typeof e!="object"){p(n,t,"missing_actor","Actor is required");return}l(e.kind,`${t}.kind`,n,64),nn.has(e.kind)||p(n,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),l(e.id,`${t}.id`,n,512),e?.displayName!==void 0&&l(e.displayName,`${t}.displayName`,n,512),e?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.profileFingerprint)&&p(n,`${t}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function Se(e,t,n){if(!e||typeof e!="object"){p(n,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":l(e.path,`${t}.path`,n,4096);break;case"source-line":l(e.path,`${t}.path`,n,4096),(!Number.isInteger(e.startLine)||e.startLine<1)&&p(n,`${t}.startLine`,"invalid_line","startLine must be a positive integer"),e.endLine!==void 0&&(!Number.isInteger(e.endLine)||e.endLine<e.startLine)&&p(n,`${t}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":l(e.path,`${t}.path`,n,4096),l(e.hunkId,`${t}.hunkId`,n,512);break;case"symbol":l(e.path,`${t}.path`,n,4096),l(e.symbol,`${t}.symbol`,n,1024);break;case"dom-node":l(e.pageId,`${t}.pageId`,n,512),!e.selector&&!e.accessibilityId&&!e.snapshotArtifactId&&p(n,t,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":l(e.recordingArtifactId,`${t}.recordingArtifactId`,n,512),(!Number.isFinite(e.startMs)||e.startMs<0)&&p(n,`${t}.startMs`,"invalid_time","startMs must be a non-negative finite number"),e.endMs!==void 0&&(!Number.isFinite(e.endMs)||e.endMs<e.startMs)&&p(n,`${t}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":l(e.mediaArtifactId,`${t}.mediaArtifactId`,n,512),[e.x,e.y,e.width,e.height].every(Number.isFinite)?(e.width<=0||e.height<=0)&&p(n,t,"invalid_region_size","Region width and height must be positive"):p(n,t,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":l(e.artifactId,`${t}.artifactId`,n,512);break;default:typeof e.kind!="string"||!e.kind.startsWith("custom:")?p(n,`${t}.kind`,"unknown_anchor","Anchor kind is not supported"):O(e.kind,"custom:",`${t}.kind`,n)}}function U(e,t,n,i){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||p(n,t,"non_finite_number","JSON numbers must be finite");return}if(typeof e!="object"){p(n,t,"non_json_value","Value must be JSON-serializable");return}if(i.has(e)){p(n,t,"cyclic_value","Value must not contain cycles");return}if(i.add(e),Array.isArray(e))e.forEach((o,r)=>U(o,`${t}[${r}]`,n,i));else for(let[o,r]of Object.entries(e))r===void 0?p(n,`${t}.${o}`,"undefined_value","Undefined is not valid JSON"):U(r,`${t}.${o}`,n,i);i.delete(e)}}function an(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_artifact",message:"Artifact must be an object"}];if(e.schemaVersion!==1&&p(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(e.artifactId,"artifactId",t,512),(!Number.isInteger(e.revision)||e.revision<1)&&p(t,"revision","invalid_revision","revision must be a positive integer"),l(e.kind,"kind",t,160),typeof e.kind=="string"&&!rn.has(e.kind)&&!e.kind.startsWith("custom:")&&p(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),O(e.kind,"custom:","kind",t),l(e.title,"title",t,1024),e.description!==void 0&&l(e.description,"description",t,32768),l(e.state,"state",t,64),en.has(e.state)||p(t,"state","unknown_state","Artifact state is not supported"),l(e.createdAt,"createdAt",t,128),B(e.createdAt,"createdAt",t),B(e.updatedAt,"updatedAt",t),e.updatedAt&&Number.isFinite(Date.parse(e.createdAt))&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&p(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt"),l(e.mediaType,"mediaType",t,255),l(e.sensitivity,"sensitivity",t,64),tn.has(e.sensitivity)||p(t,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),e.identity)for(let[i,o]of Object.entries(e.identity))o!==void 0&&l(o,`identity.${i}`,t,512);if(!e.content||typeof e.content!="object")p(t,"content","missing_content","content descriptor is required");else{!e.content.hash||typeof e.content.hash!="object"?p(t,"content.hash","missing_hash","content hash is required"):(l(e.content.hash.algorithm,"content.hash.algorithm",t,128),O(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:")&&p(t,"content.hash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported"),l(e.content.hash.value,"content.hash.value",t,512),e.content.hash.algorithm==="sha256"&&!Ue.test(e.content.hash.value)&&p(t,"content.hash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters")),(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0)&&p(t,"content.sizeBytes","invalid_size","sizeBytes must be a non-negative safe integer");let i=e.content.storage;if(!i||typeof i!="object")p(t,"content.storage","missing_storage","storage reference is required");else if(i.type==="inline")if(i.text===void 0==(i.base64===void 0))p(t,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;i.text!==void 0?o=Be.from(i.text,"utf8"):i.base64!==void 0&&(Qt.test(i.base64)?o=Be.from(i.base64,"base64"):p(t,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),o&&e.content.sizeBytes!==o.byteLength&&p(t,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),o&&e.content.hash.algorithm==="sha256"&&_(o).value!==e.content.hash.value&&p(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else i.type==="file"?l(i.path,"content.storage.path",t,4096):i.type==="blob"?l(i.uri,"content.storage.uri",t,8192):i.type==="git"?(l(i.commit,"content.storage.commit",t,512),l(i.path,"content.storage.path",t,4096)):i.type==="url"?(l(i.url,"content.storage.url",t,8192),B(i.expiresAt,"content.storage.expiresAt",t)):i.type==="external"?(l(i.provider,"content.storage.provider",t,255),l(i.locator,"content.storage.locator",t,8192)):p(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:"))&&p(t,"content.encoding","unknown_encoding","Content encoding is not supported"),O(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?p(t,"provenance","missing_provenance","provenance is required"):(We(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((i,o)=>l(i,`provenance.capabilityLeaseIds[${o}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((i,o)=>l(i,`provenance.sourceArtifactIds[${o}]`,t,512)),e.provenance.attributes&&U(e.provenance.attributes,"provenance.attributes",t,new Set));let n=new Set;return e.relationships?.forEach((i,o)=>{let r=`relationships[${o}]`;l(i.relation,`${r}.relation`,t,160),typeof i.relation=="string"&&!sn.has(i.relation)&&!i.relation.startsWith("custom:")&&p(t,`${r}.relation`,"unknown_relationship","Relationship type is not supported"),O(i.relation,"custom:",`${r}.relation`,t),l(i.target?.type,`${r}.target.type`,t,160),typeof i.target?.type=="string"&&!on.has(i.target.type)&&!i.target.type.startsWith("custom:")&&p(t,`${r}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),O(i.target?.type,"custom:",`${r}.target.type`,t),l(i.target?.id,`${r}.target.id`,t,512);let a=`${i.relation}:${i.target?.type}:${i.target?.id}:${i.target?.revision??""}`;n.has(a)&&p(t,r,"duplicate_relationship","Duplicate relationship"),n.add(a),i.attributes&&U(i.attributes,`${r}.attributes`,t,new Set)}),e.anchors?.forEach((i,o)=>Se(i,`anchors[${o}]`,t)),e.revision===1&&e.predecessorRevision!==void 0&&p(t,"predecessorRevision","unexpected_predecessor","First revision cannot have a predecessor"),e.revision>1&&(!Number.isInteger(e.predecessorRevision)||(e.predecessorRevision??0)>=e.revision)&&p(t,"predecessorRevision","invalid_predecessor","Later revisions require an earlier predecessor revision"),B(e.retention?.retainUntil,"retention.retainUntil",t),e.retention?.legalHold!==void 0&&typeof e.retention.legalHold!="boolean"&&p(t,"retention.legalHold","invalid_boolean","legalHold must be a boolean"),e.extensions&&U(e.extensions,"extensions",t,new Set),t}function w(e){let t=an(e);if(t.length>0)throw new M("XENO artifact validation failed",t)}function cn(e,t){return Gt[e].includes(t)}function ce(e,t){if(!cn(e,t))throw new Xe(e,t)}function be(e,t){let n=[];return e.schemaVersion!==1&&p(n,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(e.eventId,"eventId",n,512),l(e.artifactId,"artifactId",n,512),(!Number.isInteger(e.artifactRevision)||e.artifactRevision<1)&&p(n,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(e.sequence)||e.sequence<1)&&p(n,"sequence","invalid_sequence","sequence must be a positive integer"),l(e.recordedAt,"recordedAt",n,128),B(e.recordedAt,"recordedAt",n),We(e.actor,"actor",n),!e.artifactHash||typeof e.artifactHash!="object"?p(n,"artifactHash","missing_hash","Artifact hash is required"):(l(e.artifactHash.algorithm,"artifactHash.algorithm",n,128),O(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",n),l(e.artifactHash.value,"artifactHash.value",n,512),e.artifactHash.algorithm==="sha256"&&!Ue.test(e.artifactHash.value)&&p(n,"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:")&&p(n,"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)||p(n,"type","unknown_review_event","Review event type is not supported"),e.type==="comment-added"?(l(e.commentId,"commentId",n,512),l(e.body,"body",n,65536),e.anchor&&Se(e.anchor,"anchor",n)):e.type==="comment-resolved"||e.type==="comment-reopened"?l(e.commentId,"commentId",n,512):e.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(e.decision)||p(n,"decision","unknown_review_decision","Review decision is not supported"),e.scope&&Se(e.scope,"scope",n)),t&&(e.artifactId!==t.artifactId&&p(n,"artifactId","artifact_mismatch","Review event targets a different artifact"),e.artifactRevision!==t.revision&&p(n,"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)&&p(n,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),n}function _e(e){let t="not_requested",n,i,o,r=0,a=new Set,c=new Set;for(let s of[...e].sort((d,f)=>d.sequence-f.sequence))o=s.recordedAt,s.type==="review-requested"?t="pending":s.type==="review-withdrawn"?t="withdrawn":s.type==="comment-added"?(a.add(s.commentId),c.delete(s.commentId),t==="not_requested"&&(t="pending")):s.type==="comment-resolved"?c.add(s.commentId):s.type==="comment-reopened"?c.delete(s.commentId):s.type==="decision-recorded"&&(s.scope?r+=1:(n=s.decision,i=s.eventId,t=s.decision));return{status:t,totalComments:a.size,unresolvedComments:[...a].filter(s=>!c.has(s)).length,...n?{latestDecision:n}:{},...i?{latestDecisionEventId:i}:{},...r>0?{scopedDecisionCount:r}:{},...o?{lastReviewedAt:o}:{}}}var Te=class extends Error{code="EVIDENCE_GRAPH_INVALID";issues;constructor(t){super("XENO evidence graph validation failed"),this.name="XenoEvidenceGraphValidationError",this.issues=t.map(n=>({...n}))}},dn=new Set(["depends_on","decomposes","supersedes"]),fn=new Set(se),pn=new Set(ae);function A(e,t,n,i){e.push({path:t,code:n,message:i})}function W(e){return e.includes("T")&&Number.isFinite(Date.parse(e))}function ze(e,t){return e.startsWith(Re)?$(e):t.has(e)}function un(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_graph",message:"Evidence graph must be an object"}];e.schemaVersion!==1&&A(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),(typeof e.graphId!="string"||e.graphId.trim().length===0)&&A(t,"graphId","required_string","graphId must be a non-empty string"),(!Number.isInteger(e.version)||e.version<1)&&A(t,"version","invalid_version","version must be a positive integer"),W(e.createdAt)||A(t,"createdAt","invalid_timestamp","createdAt must be an ISO 8601 timestamp"),W(e.updatedAt)||A(t,"updatedAt","invalid_timestamp","updatedAt must be an ISO 8601 timestamp"),W(e.createdAt)&&W(e.updatedAt)&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&A(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt");let n=new Map;Array.isArray(e.nodes)||A(t,"nodes","invalid_nodes","nodes must be an array"),(Array.isArray(e.nodes)?e.nodes:[]).forEach((f,g)=>{let I=`nodes[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(t,`${I}.id`,"required_string","Node ID must be a non-empty string"):n.has(f.id)?A(t,`${I}.id`,"duplicate_node",`Node ID ${f.id} is duplicated`):n.set(f.id,f),(typeof f.type!="string"||!ze(f.type,fn))&&A(t,`${I}.type`,"invalid_node_type","Node type is invalid"),f.artifactRevision!==void 0&&(!Number.isInteger(f.artifactRevision)||f.artifactRevision<1)&&A(t,`${I}.artifactRevision`,"invalid_revision","artifactRevision must be a positive integer")});let i=new Set,o=new Set;Array.isArray(e.edges)||A(t,"edges","invalid_edges","edges must be an array"),(Array.isArray(e.edges)?e.edges:[]).forEach((f,g)=>{let I=`edges[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(t,`${I}.id`,"required_string","Edge ID must be a non-empty string"):i.has(f.id)&&A(t,`${I}.id`,"duplicate_edge",`Edge ID ${f.id} is duplicated`),i.add(f.id),(typeof f.type!="string"||!ze(f.type,pn))&&A(t,`${I}.type`,"invalid_edge_type","Edge type is invalid");let V=`${f.type}:${f.from}:${f.to}`;o.has(V)&&A(t,I,"duplicate_edge_identity","Equivalent evidence edge is duplicated"),o.add(V),n.has(f.from)||A(t,`${I}.from`,"dangling_reference",`Source node ${f.from} does not exist`),n.has(f.to)||A(t,`${I}.to`,"dangling_reference",`Target node ${f.to} does not exist`),f.from===f.to&&A(t,I,"self_edge","Evidence edges cannot point to the same node"),W(f.createdAt)||A(t,`${I}.createdAt`,"invalid_timestamp","createdAt must be an ISO 8601 timestamp")});let r=(Array.isArray(e.edges)?e.edges:[]).filter(f=>dn.has(f.type)),a=new Map;for(let f of r){let g=a.get(f.from)??[];g.push(f.to),a.set(f.from,g)}let c=new Set,s=new Set,d=f=>{if(c.has(f))return!0;if(s.has(f))return!1;c.add(f);for(let g of a.get(f)??[])if(d(g))return!0;return c.delete(f),s.add(f),!1};for(let f of n.keys())if(d(f)){A(t,"edges","cyclic_graph","Dependency, decomposition, and supersession edges must be acyclic");break}return t}function z(e){let t=un(e);if(t.length>0)throw new Te(t)}var Ke=class{now;graph;constructor(t){if("schemaVersion"in t)z(t),this.now=()=>new Date().toISOString(),this.graph=de(t);else{this.now=t.now??(()=>new Date().toISOString());let n=this.now();this.graph={schemaVersion:1,graphId:t.graphId,version:1,createdAt:n,updatedAt:n,nodes:[],edges:[]},z(this.graph)}}addNode(t){let n=de(this.graph);return n.nodes.push(Ge(t)),this.touch(n),z(n),this.graph=n,this}addEdge(t){let n=de(this.graph);return n.edges.push(Ye(t)),this.touch(n),z(n),this.graph=n,this}build(){return z(this.graph),de(this.graph)}touch(t){t.version+=1,t.updatedAt=this.now()}};function Ge(e){return{...e,...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function Ye(e){return{...e,...e.producer?{producer:{...e.producer}}:{},...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function de(e){return{...e,nodes:e.nodes.map(Ge),edges:e.edges.map(Ye)}}var u=class extends Error{constructor(n,i,o,r){super(i,r);this.code=n;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},G=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??(n=>(this.idCounter+=1,`${n}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),t.initialState&&this.hydrate(t.initialState)}exportState(){let t=[...this.records.values()].flatMap(n=>[...n.values()]).sort(Ze).map(n=>({artifact:K(n.artifact),recordVersion:n.recordVersion,lifecycleEvents:structuredClone(n.lifecycleEvents),reviewEvents:structuredClone(n.reviewEvents)}));return{schemaVersion:1,records:t}}async create(t){if(w(t),this.assertInitialState(t),t.revision!==1)throw new u("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 u("ARTIFACT_ALREADY_EXISTS",`Artifact ${t.artifactId} already exists`,{artifactId:t.artifactId});let n=K(t),i=this.createLifecycleEvent({artifact:n,sequence:1,actor:n.provenance.producer,fromState:null,toState:n.state,reason:"artifact-created"}),o={artifact:n,recordVersion:1,lifecycleEvents:[i],reviewEvents:[]};return this.records.set(n.artifactId,new Map([[n.revision,o]])),this.currentRevisions.set(n.artifactId,n.revision),D(o)}async createRevision(t,n={}){w(t),this.assertInitialState(t);let i=this.getMutable(t.artifactId);this.assertVersion(i,n.expectedRecordVersion);let o=i.artifact.revision+1;if(t.revision!==o||t.predecessorRevision!==i.artifact.revision)throw new u("ARTIFACT_REVISION_INVALID",`Revision ${t.revision} does not follow current revision ${i.artifact.revision}`,{artifactId:t.artifactId,currentRevision:i.artifact.revision,requestedRevision:t.revision});if(mn(t,i.artifact))throw new u("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:t.artifactId,revision:t.revision});if(i.artifact.state==="archived")throw new u("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:t.artifactId,revision:i.artifact.revision});if(i.artifact.state!=="superseded"){ce(i.artifact.state,"superseded");let s=this.now(),d=this.createLifecycleEvent({artifact:i.artifact,sequence:i.lifecycleEvents.length+1,actor:n.actor??t.provenance.producer,fromState:i.artifact.state,toState:"superseded",reason:n.reason??`superseded-by-revision-${t.revision}`,recordedAt:s});i.artifact.state="superseded",i.artifact.updatedAt=s,i.lifecycleEvents.push(d),i.recordVersion+=1}let r=K(t),a=this.createLifecycleEvent({artifact:r,sequence:1,actor:n.actor??r.provenance.producer,fromState:null,toState:r.state,reason:n.reason??`revision-created-from-${i.artifact.revision}`}),c={artifact:r,recordVersion:1,lifecycleEvents:[a],reviewEvents:[]};return this.records.get(r.artifactId)?.set(r.revision,c),this.currentRevisions.set(r.artifactId,r.revision),D(c)}async get(t,n){let i=this.records.get(t);if(!i)return;let o=n??this.currentRevisions.get(t);if(o===void 0)return;let r=i.get(o);return r?D(r):void 0}async require(t,n){let i=await this.get(t,n);if(!i)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:t,...n===void 0?{}:{revision:n}});return i}async list(t={}){let n=[];for(let[i,o]of this.records)if(!(t.artifactIds&&!t.artifactIds.includes(i)))if(t.includeSuperseded)n.push(...o.values());else{let r=this.currentRevisions.get(i);if(r!==void 0){let a=o.get(r);a&&n.push(a)}}return n.filter(i=>vn(i.artifact,t)).sort(Ze).map(D)}async listRevisions(t){let n=this.records.get(t);return n?[...n.values()].sort((i,o)=>i.artifact.revision-o.artifact.revision).map(D):[]}async transition(t){let n=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(n,t.expectedRecordVersion),ce(n.artifact.state,t.toState),t.toState==="approved"||t.toState==="rejected"){let a=t.reviewEventId?n.reviewEvents.find(s=>s.eventId===t.reviewEventId&&s.type==="decision-recorded"):void 0,c=_e(n.reviewEvents);if(!a||a.decision!==t.toState||c.latestDecisionEventId!==a.eventId)throw new u("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${t.toState} requires a matching decision event`,{artifactId:t.artifactId,revision:n.artifact.revision});if(t.toState==="approved"&&c.unresolvedComments>0)throw new u("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${c.unresolvedComments} unresolved review comment(s)`,{artifactId:t.artifactId,revision:n.artifact.revision,unresolvedComments:c.unresolvedComments})}let i=this.now(),o=n.artifact.state,r=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor,fromState:o,toState:t.toState,reason:t.reason,reviewEventId:t.reviewEventId,recordedAt:i});return n.artifact.state=t.toState,n.artifact.updatedAt=i,n.lifecycleEvents.push(r),n.recordVersion+=1,D(n)}async appendReviewEvent(t){let n=t.event,i=this.getMutable(n.artifactId,n.artifactRevision);if(this.assertVersion(i,t.expectedRecordVersion),i.artifact.state==="archived"||i.artifact.state==="superseded")throw new u("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${i.artifact.state} artifact revision`,{artifactId:n.artifactId,revision:n.artifactRevision});if(this.assertReviewCommentState(i,n),(n.type==="review-requested"||n.type==="review-withdrawn"||n.type==="decision-recorded")&&i.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`${n.type} requires an artifact in pending_review state`,{artifactId:n.artifactId,revision:n.artifactRevision});let o={...structuredClone(n),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:i.reviewEvents.length+1,recordedAt:this.now()},r=be(o,i.artifact);if(r.length>0)throw new M("XENO artifact review event validation failed",r);return i.reviewEvents.push(o),i.recordVersion+=1,D(i)}getMutable(t,n){let i=this.records.get(t),o=n??this.currentRevisions.get(t),r=o===void 0?void 0:i?.get(o);if(!r)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:t,...n===void 0?{}:{revision:n}});return r}assertVersion(t,n){if(n!==void 0&&n!==t.recordVersion)throw new u("ARTIFACT_CONFLICT",`Expected record version ${n}, found ${t.recordVersion}`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision,expectedRecordVersion:n,actualRecordVersion:t.recordVersion})}assertInitialState(t){if(t.state!=="draft"&&t.state!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:t.artifactId,revision:t.revision})}assertReviewCommentState(t,n){if(n.type==="comment-added"){if(t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} already exists`);if(n.parentCommentId&&!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Parent comment ${n.parentCommentId} does not exist`);return}if(n.type!=="comment-resolved"&&n.type!=="comment-reopened")return;if(!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} does not exist`);let o=hn(t.reviewEvents,n.commentId);if(n.type==="comment-resolved"&&o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} is already resolved`);if(n.type==="comment-reopened"&&!o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.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 n=this.idFactory(t);if(typeof n!="string"||n.trim().length===0||this.eventIds.has(n))throw new u("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${t} ID`);return this.eventIds.add(n),n}hydrate(t){if(t.schemaVersion!==1||!Array.isArray(t.records))throw new u("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let n=[...t.records].sort((i,o)=>i.artifact.artifactId.localeCompare(o.artifact.artifactId)||i.artifact.revision-o.artifact.revision);for(let i of n){let o=ln(i,this.eventIds),r=this.records.get(o.artifact.artifactId);if(r||(r=new Map,this.records.set(o.artifact.artifactId,r)),r.has(o.artifact.revision))throw new u("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${o.artifact.artifactId}:${o.artifact.revision}`);r.set(o.artifact.revision,o),this.currentRevisions.set(o.artifact.artifactId,o.artifact.revision)}for(let[i,o]of this.records){let r=[...o.values()].sort((a,c)=>a.artifact.revision-c.artifact.revision);for(let a=0;a<r.length;a+=1){let c=r[a],s=a+1;if(c.artifact.revision!==s)throw new u("ARTIFACT_REVISION_INVALID",`Persisted artifact ${i} is missing revision ${s}`);if(a===0&&c.artifact.predecessorRevision!==void 0)throw new u("ARTIFACT_REVISION_INVALID",`Initial revision for ${i} cannot declare a predecessor`);if(a>0&&c.artifact.predecessorRevision!==s-1)throw new u("ARTIFACT_REVISION_INVALID",`Persisted revision ${i}:${s} has an invalid predecessor`);if(a<r.length-1&&c.artifact.state!=="superseded")throw new u("ARTIFACT_REVISION_INVALID",`Non-current revision ${i}:${s} must be superseded`)}}}};function ln(e,t){if(w(e.artifact),!Number.isInteger(e.recordVersion)||e.recordVersion<1)throw new u("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 u("ARTIFACT_REVISION_INVALID","Persisted artifact records require lifecycle and review event arrays",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let n=e.lifecycleEvents.length+e.reviewEvents.length;if(e.recordVersion!==n)throw new u("ARTIFACT_REVISION_INVALID",`Persisted record version ${e.recordVersion} does not match ${n} mutations`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let i=null;for(let r=0;r<e.lifecycleEvents.length;r+=1){let a=e.lifecycleEvents[r];if(a.schemaVersion!==1||a.artifactId!==e.artifact.artifactId||a.revision!==e.artifact.revision||a.sequence!==r+1||a.fromState!==i||typeof a.eventId!="string"||a.eventId.length===0||t.has(a.eventId)||!Number.isFinite(Date.parse(a.recordedAt)))throw new u("ARTIFACT_REVISION_INVALID",`Persisted lifecycle event ${r+1} is invalid`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(i===null){if(a.toState!=="draft"&&a.toState!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:e.artifact.artifactId,revision:e.artifact.revision})}else ce(i,a.toState);t.add(a.eventId),i=a.toState}if(i!==e.artifact.state)throw new u("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 r=0;r<e.reviewEvents.length;r+=1){let a=e.reviewEvents[r];if(a.sequence!==r+1||t.has(a.eventId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted review event ${r+1} has an invalid sequence or duplicate ID`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let c=be(a,e.artifact);if(c.length>0)throw new M("Persisted XENO artifact review event validation failed",c);if(a.type==="comment-added"){if(o.has(a.commentId)||a.parentCommentId!==void 0&&!o.has(a.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted comment ${a.commentId} has an invalid identity or parent`);o.set(a.commentId,!1)}else if(a.type==="comment-resolved"||a.type==="comment-reopened"){let s=o.get(a.commentId);if(s===void 0||a.type==="comment-resolved"&&s||a.type==="comment-reopened"&&!s)throw new u("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:K(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function mn(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function vn(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 Ze(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function hn(e,t){let n=!1;for(let i of e)(i.type==="comment-resolved"||i.type==="comment-reopened")&&i.commentId===t&&(n=i.type==="comment-resolved");return{resolved:n}}function K(e){return structuredClone(e)}function D(e){return{artifact:K(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:_e(e.reviewEvents)}}import{randomUUID as ft}from"node:crypto";import{mkdir as pt,open as ot,readFile as bn,rename as _n,stat as ut,unlink as Tn}from"node:fs/promises";import{basename as st,dirname as at,join as kn,resolve as xn}from"node:path";import{mkdirSync as gn,readFileSync as An,rmSync as et,writeFileSync as yn}from"node:fs";import{hostname as tt}from"node:os";import{dirname as In}from"node:path";function wn(){return new Date().toISOString()}function En(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function nt(e){try{return JSON.parse(An(e,"utf8"))}catch{return null}}function Rn(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Xn(e){return e.hostname!==tt()?!0:Rn(e.pid)}function Qe(e,t){gn(In(e),{recursive:!0}),yn(e,JSON.stringify(t,null,2)+`
2
- `,{encoding:"utf8",flag:"wx"})}function Sn(e,t){let n=nt(e);n?.pid!==t.pid||n.hostname!==t.hostname||et(e,{force:!0})}function it(e,t,n){let i=wn(),o={schemaVersion:1,name:t,pid:process.pid,hostname:tt(),processStartedAt:En(),version:n,acquiredAt:i,updatedAt:i};try{Qe(e,o)}catch(r){if(r.code!=="EEXIST")throw r;let c=nt(e);if(c&&Xn(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);et(e,{force:!0}),Qe(e,o)}return{record:o,release:()=>{Sn(e,o)}}}var rt="0.9.16";var lt=1,Cn="repository.v1.json",Nn=5e3,Vn=20,Pn=64*1024*1024,ct=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 n=t.snapshotFileName??Cn;if(st(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=xn(t.directory),this.snapshotPath=kn(this.directory,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=ke(t.lockTimeoutMs,Nn,100,6e4,"lockTimeoutMs"),this.lockRetryMs=ke(t.lockRetryMs,Vn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=ke(t.maxSnapshotBytes,Pn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(n=>n.create(t))}async createRevision(t,n){return this.mutate(i=>i.createRevision(t,n))}async get(t,n){return(await this.load()).repository.get(t,n)}async require(t,n){return(await this.load()).repository.require(t,n)}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(n=>n.transition(t))}async appendReviewEvent(t){return this.mutate(n=>n.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await t(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(t){let n=this.mutationTail.then(t,t);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let t=Date.now(),n;for(;Date.now()-t<=this.lockTimeoutMs;)try{return it(this.lockPath,`artifact-repository:${st(this.snapshotPath)}`,rt)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await Ln(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let t,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){t=fe(r)}if(!n&&(t||await Fn(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:t?.message??"primary snapshot missing"}),n=r,i=!0)}catch(r){throw t?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,fe(r)])}):r}if(!n&&t)throw t;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new G({now:this.now,idFactory:r=>`${r}_${ft()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(t){let n=this.now(),o={...{schemaVersion:lt,generation:t.generation,createdAt:t.createdAt,updatedAt:n,state:t.repository.exportState()},generation:t.generation+1},r=On(o),a=`${JSON.stringify(r,null,2)}
2
+ `,{encoding:"utf8",flag:"wx"})}function Sn(e,t){let n=nt(e);n?.pid!==t.pid||n.hostname!==t.hostname||et(e,{force:!0})}function it(e,t,n){let i=wn(),o={schemaVersion:1,name:t,pid:process.pid,hostname:tt(),processStartedAt:En(),version:n,acquiredAt:i,updatedAt:i};try{Qe(e,o)}catch(r){if(r.code!=="EEXIST")throw r;let c=nt(e);if(c&&Xn(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);et(e,{force:!0}),Qe(e,o)}return{record:o,release:()=>{Sn(e,o)}}}var rt="0.9.19";var lt=1,Cn="repository.v1.json",Nn=5e3,Vn=20,Pn=64*1024*1024,ct=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 n=t.snapshotFileName??Cn;if(st(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=xn(t.directory),this.snapshotPath=kn(this.directory,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=ke(t.lockTimeoutMs,Nn,100,6e4,"lockTimeoutMs"),this.lockRetryMs=ke(t.lockRetryMs,Vn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=ke(t.maxSnapshotBytes,Pn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(n=>n.create(t))}async createRevision(t,n){return this.mutate(i=>i.createRevision(t,n))}async get(t,n){return(await this.load()).repository.get(t,n)}async require(t,n){return(await this.load()).repository.require(t,n)}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(n=>n.transition(t))}async appendReviewEvent(t){return this.mutate(n=>n.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await t(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(t){let n=this.mutationTail.then(t,t);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let t=Date.now(),n;for(;Date.now()-t<=this.lockTimeoutMs;)try{return it(this.lockPath,`artifact-repository:${st(this.snapshotPath)}`,rt)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await Ln(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let t,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){t=fe(r)}if(!n&&(t||await Fn(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:t?.message??"primary snapshot missing"}),n=r,i=!0)}catch(r){throw t?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,fe(r)])}):r}if(!n&&t)throw t;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new G({now:this.now,idFactory:r=>`${r}_${ft()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(t){let n=this.now(),o={...{schemaVersion:lt,generation:t.generation,createdAt:t.createdAt,updatedAt:n,state:t.repository.exportState()},generation:t.generation+1},r=On(o),a=`${JSON.stringify(r,null,2)}
3
3
  `;if(Buffer.byteLength(a,"utf8")>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await pt(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await dt(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
4
4
  `),await dt(this.snapshotPath,a)}async readSnapshot(t,n){let i;try{i=await ut(t)}catch(o){if(!n&&Ce(o,"ENOENT")||n&&Ce(o,"ENOENT"))return;throw Ne("Unable to inspect artifact repository snapshot",t,o)}if(!i.isFile()||i.size>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:t,sizeBytes:i.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await bn(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return $n(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof u?o:Ne("Unable to parse artifact repository snapshot",t,o,!0)}}};function $n(e,t){if(!xe(e)||e.schemaVersion!==lt||!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))||!xe(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!xe(e.checksum)||e.checksum.algorithm!=="sha256"||typeof e.checksum.value!="string")throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:t});let n=e,i=Dn(n),o=mt(i);if(n.checksum.value!==o)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new G({initialState:n.state}),structuredClone(n)}function On(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:mt(e)}}}function Dn(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function mt(e){return _(JSON.stringify(e)).value}async function dt(e,t){await pt(at(e),{recursive:!0,mode:448});let n=`${e}.tmp.${process.pid}.${ft()}`,i;try{i=await ot(n,"wx",384),await i.writeFile(t,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,await _n(n,e);try{let o=await ot(at(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{i&&await i.close().catch(()=>{}),await Tn(n).catch(()=>{})}}function ke(e,t,n,i,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<n||e>i)throw new TypeError(`${o} must be an integer between ${n} and ${i}`);return e}function xe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ce(e,t){return e instanceof Error&&e.code===t}async function Fn(e){try{return(await ut(e)).isFile()}catch(t){if(Ce(t,"ENOENT"))return!1;throw Ne("Unable to inspect artifact repository backup",e,t)}}function fe(e){return e instanceof Error?e:new Error(String(e))}function Ne(e,t,n,i=!1){return new u(i?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${fe(n).message}`,{snapshotPath:t},{cause:fe(n)})}function Ln(e){return new Promise(t=>setTimeout(t,e))}import{Buffer as At}from"node:buffer";var Mn=16*1024*1024,Hn=5e3,jn=1e5,qn=1e6,Jn=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,X=class extends Error{constructor(n,i){super(i===void 0?n:`${n} at diff line ${i}`);this.line=i;this.name="XenoDiffParseError"}line;code="XENO_DIFF_INVALID"};function yt(e,t={}){if(typeof e!="string")throw new TypeError("Unified diff must be a string");let n=pe(t.maxBytes,Mn,1024,256*1024*1024,"maxBytes"),i=pe(t.maxFiles,Hn,1,1e5,"maxFiles"),o=pe(t.maxHunks,jn,1,1e6,"maxHunks"),r=pe(t.maxLines,qn,1,5e6,"maxLines");if(At.byteLength(e,"utf8")>n)throw new X(`Unified diff exceeds ${n} bytes`);let a=e.replace(/\r\n/g,`
5
5
  `).replace(/\r/g,`
@@ -1,4 +1,4 @@
1
- "use strict";var V=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Be=Object.prototype.hasOwnProperty;var Ve=(e,t)=>{for(var r in t)V(e,r,{get:t[r],enumerable:!0})},$e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Me(t))!Be.call(e,o)&&o!==r&&V(e,o,{get:()=>t[o],enumerable:!(n=Ue(t,o))||n.enumerable});return e};var Fe=e=>$e(V({},"__esModule",{value:!0}),e);var Ft={};Ve(Ft,{XENO_AUTOMATION_OPERATIONS:()=>R,XENO_AUTOMATION_PROTOCOL_VERSION:()=>T,XenoAutomationError:()=>i,XenoGovernedAutomationExecutor:()=>te,XenoLoopbackAutomationAdapter:()=>ne,assertRequiredXenoAutomationEvidence:()=>C,assertValidXenoAutomationAdapterManifest:()=>S,assertValidXenoAutomationRequest:()=>J,assertXenoAutomationAdapterConformant:()=>mt,assertXenoAutomationAuthority:()=>x,buildXenoAutomationCapabilityUse:()=>q,createXenoAutomationConformanceReport:()=>Xe,createXenoGovernedAutomationTools:()=>St,describeXenoAutomationOperation:()=>I,isXenoAutomationOperation:()=>N,materializeXenoAutomationEvidence:()=>L,persistXenoAutomationEvidence:()=>D,resolveXenoAutomationEvidencePolicy:()=>K});module.exports=Fe(Ft);var T=1;var $=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"]),F=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"]),H=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),j=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),R=[...$,...F,...H,...j];function I(e){if($.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(F.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(H.has(e))return{operation:e,surface:"computer",effect:"observe",evidence:{before:"disabled",after:e==="computer.wait"?"optional":"required",recording:"optional"}};if(j.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 N(e){return $.has(e)||F.has(e)||H.has(e)||j.has(e)}var i=class extends Error{constructor(r,n,o,a){super(n,a);this.code=r;this.detail=o;this.name="XenoAutomationError"}code;detail};var fe=require("node:crypto");function He(e,t){let r=0;for(let n=0;n<t;n+=1)r=r<<1|e>>>n&1;return r}function de(e,t=!1){let r=e.reduce((s,u)=>Math.max(s,u),0);if(r===0){if(t)return{tree:null,codes:e.map(()=>({bits:0,length:0}))};throw new Error("DEFLATE Huffman tree has no symbols")}if(r>15||e.some(s=>!Number.isInteger(s)||s<0||s>15))throw new Error("Invalid DEFLATE Huffman code length");let n=new Uint16Array(r+1);for(let s of e)s>0&&(n[s]+=1);let o=1;for(let s=1;s<=r;s+=1)if(o=(o<<1)-n[s],o<0)throw new Error("Oversubscribed DEFLATE Huffman tree");let a=new Uint32Array(r+1),d=0;for(let s=1;s<=r;s+=1)d=d+n[s-1]<<1,a[s]=d;let c=new Array(r+1),l=e.map(()=>({bits:0,length:0}));for(let s=0;s<e.length;s+=1){let u=e[s];if(u===0)continue;let p=a[u]++,v=He(p,u),f=c[u]??new Map;f.set(v,s),c[u]=f,l[s]={bits:v,length:u}}return{tree:{maxBits:r,byLength:c},codes:l}}function je(){let e=new Array(288).fill(0);for(let t=0;t<=143;t+=1)e[t]=8;for(let t=144;t<=255;t+=1)e[t]=9;for(let t=256;t<=279;t+=1)e[t]=7;for(let t=280;t<=287;t+=1)e[t]=8;return e}var Jt=de(je()),qt=de(new Array(32).fill(5));var Qt=String.raw`
1
+ "use strict";var V=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Me=Object.prototype.hasOwnProperty;var Ve=(e,t)=>{for(var r in t)V(e,r,{get:t[r],enumerable:!0})},Be=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ue(t))!Me.call(e,o)&&o!==r&&V(e,o,{get:()=>t[o],enumerable:!(n=De(t,o))||n.enumerable});return e};var $e=e=>Be(V({},"__esModule",{value:!0}),e);var Vt={};Ve(Vt,{XENO_AUTOMATION_OPERATIONS:()=>_,XENO_AUTOMATION_PROTOCOL_VERSION:()=>v,XenoAutomationError:()=>i,XenoGovernedAutomationExecutor:()=>ee,XenoLoopbackAutomationAdapter:()=>re,assertRequiredXenoAutomationEvidence:()=>S,assertValidXenoAutomationAdapterManifest:()=>T,assertValidXenoAutomationRequest:()=>z,assertXenoAutomationAdapterConformant:()=>ut,assertXenoAutomationAuthority:()=>O,buildXenoAutomationCapabilityUse:()=>J,createXenoAutomationConformanceReport:()=>xe,createXenoGovernedAutomationTools:()=>yt,describeXenoAutomationOperation:()=>I,isXenoAutomationOperation:()=>R,materializeXenoAutomationEvidence:()=>X,persistXenoAutomationEvidence:()=>k,resolveXenoAutomationEvidencePolicy:()=>q});module.exports=$e(Vt);var v=1;var B=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"]),$=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"]),F=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),H=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),_=[...B,...$,...F,...H];function I(e){if(B.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($.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(F.has(e))return{operation:e,surface:"computer",effect:"observe",evidence:{before:"disabled",after:e==="computer.wait"?"optional":"required",recording:"optional"}};if(H.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 R(e){return B.has(e)||$.has(e)||F.has(e)||H.has(e)}var i=class extends Error{constructor(r,n,o,a){super(n,a);this.code=r;this.detail=o;this.name="XenoAutomationError"}code;detail};var ue=require("node:crypto");var Gt=String.raw`
2
2
  using System;
3
3
  using System.ComponentModel;
4
4
  using System.Runtime.InteropServices;
@@ -896,4 +896,30 @@ namespace Xeno.Security
896
896
  }
897
897
  }
898
898
  }
899
- `;var rr=512*1024,nr=744*60*60*1e3,or=Object.freeze(["allowedFilesystemRead","allowedFilesystemWrite","outsideFilesystemReadDenied","outsideFilesystemWriteDenied","unlistedFilesystemReadDenied","unlistedFilesystemWriteDenied","symlinkEscapeDenied","networkDefaultDeny","environmentSecretsExcluded","childProcessPolicyInherited","standardCommandLaunch","processTreeCleanup","timeoutEnforced","hostPolicyRecoveryClean","uiRestrictionsEnforced"]);var lr=10*6e4,ur=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"}),fr=Object.freeze({"win32-x64-wxc-host-prep.exe":"531fb3cdb4b0c964908fd71b71d40961417afb399cbab72f92a25e95309a6416","win32-arm64-wxc-host-prep.exe":"3ef702332286a39153fc259310b5021e3de3c191751d7522684f6475f73af5ef"});var _r=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),Rr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!0,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!0,environmentSanitization:!0}),Nr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),Or=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!0,networkIsolation:!0,inheritedHandleAllowlist:!0,environmentSanitization:!0}),xr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0});var Ge=1,G=class extends Error{constructor(r,n){super(n);this.code=r;this.name="XenoSecureExecutionContractError"}code};function We(e){let t=[];if(!e||typeof e!="object")return["Contract must be an object"];if(e.schemaVersion!==Ge&&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"),ue(e.createdAt)||t.push("createdAt must be an ISO 8601 timestamp"),e.expiresAt&&(!ue(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,ze(r)!==e.fingerprint&&t.push("Contract fingerprint does not match content")}return t}function pe(e){let t=We(e);if(t.length>0){let r=t.includes("Contract fingerprint does not match content");throw new G(r?"SECURITY_CONTRACT_FINGERPRINT_MISMATCH":"SECURITY_CONTRACT_INVALID",t.join("; "))}}function ze(e){return(0,fe.createHash)("sha256").update(JSON.stringify(W(e))).digest("hex")}function W(e){return Array.isArray(e)?e.map(W):!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,W(r)]))}function ue(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}var Je=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,me=1048576;function J(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"),be(e.requestedAt)||h("requestedAt must be an ISO 8601 timestamp"),N(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>me&&h(`parameters exceed ${me} bytes`),w(e.identity?.runId,"identity.runId"),w(e.identity?.agentId,"identity.agentId"),pe(e.executionContract),qe(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 S(e){(!e||typeof e!="object")&&m("Adapter manifest must be an object"),e.protocolVersion!==1&&m("Adapter protocol version is unsupported"),O(e.adapterId,"adapterId"),O(e.adapterVersion,"adapterVersion"),O(e.platform,"platform"),O(e.architecture,"architecture"),e.targetBinding!=="atomic-preflight"&&m("Adapter must implement atomic preflight target binding"),(!Array.isArray(e.operations)||e.operations.length===0)&&m("Adapter must declare operations");let t=new Set;for(let r of e.operations)N(r)||m(`Adapter declares unknown operation ${r}`),t.has(r)&&m(`Adapter declares duplicate operation ${r}`),t.add(r);e.certified&&!e.certificationArtifactId&&m("A certified automation adapter requires a certification artifact"),Array.isArray(e.limitations)||m("Adapter limitations must be an array"),e.operations.some(r=>r.startsWith("browser."))&&(!e.policyEnforcement.domain||!e.policyEnforcement.scheme||!e.policyEnforcement.port)&&m("Browser adapters must enforce domain, scheme, and port policy"),e.operations.some(r=>r.startsWith("computer."))&&!e.supports.immediateStop&&m("Computer-use adapters must support immediate stop")}function x(e,t,r){let n=I(e.operation);if(!t.operations.includes(e.operation))throw new i("AUTOMATION_OPERATION_UNSUPPORTED",`Adapter ${t.adapterId} does not support ${e.operation}`);if(n.surface==="browser"){let o=e.executionContract.browser.mode;if(o==="none"||n.effect==="act"&&o!=="act")throw new i("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(Ke(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,d=e.operation==="computer.launch"?Ze(e):r.applicationId??e.declaredTarget?.applicationId;if((e.operation==="computer.launch"||a.length>0)&&(!d||!a.includes(d)))throw new i("AUTOMATION_POLICY_DENIED",`Application ${d??"<unknown>"} is not allowed`)}}function q(e,t){let r=I(e.operation),n=r.surface==="browser"?r.effect==="act"?"browser-act":"browser-read":r.effect==="act"?"computer-act":"computer-observe";return{subject:{runId:e.identity.runId,agentId:e.identity.agentId,...e.identity.turnId?{turnId:e.identity.turnId}:{},toolName:e.governingToolName,operationId:e.operationId},kind:n,operation:e.operation,...Ie(e,t)?{resource:Ie(e,t)}:{},...he(t)?{destination:he(t)}:{}}}function Ie(e,t){return e.declaredTarget?.resource??Ye(t)}function K(e){let t=I(e.operation).evidence,r=e.evidencePolicy??{},n=z(t.before,r.before),o=z(t.after,r.after),a=z(t.recording,r.recording),d=r.retainUntil;return d&&!be(d)&&h("evidencePolicy.retainUntil must be an ISO 8601 timestamp"),{before:n,after:o,recording:a,sensitivity:r.sensitivity??"confidential",...d?{retainUntil:d}:{},...r.legalHold!==void 0?{legalHold:r.legalHold}:{}}}function qe(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 Ke(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 d=a,c=o.hostname.toLowerCase().replace(/\.$/,""),l=o.port?Number(o.port):d==="https"?443:80,s=e.executionContract.browser,u=Qe(c);if(ge(c,s.deniedDomains)&&E(`Browser domain ${c} is denied`),Ae(o,e.executionContract.network.denyDestinations)&&E(`Network policy explicitly denies ${d}://${c}:${l}`),u&&s.allowLoopbackDevelopment)return;s.allowedSchemes.includes(d)||E(`Browser scheme ${o.protocol} is not allowed`),s.allowedPorts.includes(l)||E(`Browser port ${l} is not allowed`);let p=r?s.actAllowedDomains:s.readAllowedDomains;ge(c,p)||E(`Browser domain ${c} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&(Ae(o,e.executionContract.network.allowDestinations)||E(`Network policy does not allow ${d}://${c}:${l}`))}function Ae(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 d=a.scheme?.replace(/^custom:/,"");return a.host===n&&(a.port===void 0||a.port===o)&&(d===void 0||d===r)})}function Ye(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function he(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function Ze(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 ge(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 Qe(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function z(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"||!Je.test(e))&&h(`${t} is invalid`)}function O(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&m(`${t} is invalid`)}function be(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 m(e){throw new i("AUTOMATION_OPERATION_UNSUPPORTED",e)}var Re=require("node:crypto");var Ee=["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"],we=["draft","pending_review","approved","rejected","superseded","archived"],ye=["public","internal","confidential","restricted"],ve=["agent","tool","user","system","integration"],Te=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],Se=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var Ce=require("node:crypto");function P(e){return{algorithm:"sha256",value:(0,Ce.createHash)("sha256").update(e).digest("hex")}}var et="[\\u0000-\\u001f\\u007f]",Yr=new RegExp(et);var Zr=new Set(we),Qr=new Set(ye),en=new Set(ve),tn=new Set(Ee),rn=new Set(Te),nn=new Set(Se);var X=class extends Error{constructor(r,n,o,a){super(n,a);this.code=r;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail};var Z=32*1024*1024,tt=1024*1024*1024,rt=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function L(e){let r=(e.now??(()=>new Date().toISOString()))(),n=new Set;return e.evidence.map((o,a)=>{if(ot(o),n.has(o.evidenceId))throw new i("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${o.evidenceId}`);n.add(o.evidenceId);let d=nt(o),c=(0,Re.createHash)("sha256").update(`${e.request.operationId}\0${o.evidenceId}\0${d.hash.value}`).digest("hex").slice(0,32);return{schemaVersion:1,artifactId:`automation_${c}`,revision:1,kind:o.kind,title:o.title,...o.description?{description:o.description}:{},state:"draft",createdAt:r,mediaType:o.mediaType,sensitivity:o.sensitivity??e.policy.sensitivity,identity:{...e.request.identity},content:d,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 D(e,t){if(!e)return t.map(n=>structuredClone(n));let r=[];for(let n of t)try{let o=await e.create(n);r.push(o.artifact)}catch(o){if(o instanceof X&&o.code==="ARTIFACT_ALREADY_EXISTS"){let a=await e.require(n.artifactId,n.revision);if(a.artifact.content.hash.value===n.content.hash.value){r.push(a.artifact);continue}}throw new i("AUTOMATION_EVIDENCE_PERSISTENCE_FAILED",`Failed to persist automation evidence ${n.artifactId}`,{artifactId:n.artifactId},{cause:o})}return r}function C(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 nt(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return _e(t),{hash:P(e.content.text),sizeBytes:t,storage:{type:"inline",text:e.content.text},encoding:"utf8",...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}if(e.content.type==="base64"){let t=it(e.content.base64);return _e(t.byteLength),{hash:P(t),sizeBytes:t.byteLength,storage:{type:"inline",base64:e.content.base64},encoding:"base64",...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}if(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0||e.content.sizeBytes>tt)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 ot(e){(!e||typeof e!="object")&&g("Evidence must be an object"),rt.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 it(e){(e.length===0||e.length>Math.ceil(Z/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 _e(e){e>Z&&g(`Inline evidence exceeds ${Z} bytes`)}function g(e){throw new i("AUTOMATION_EVIDENCE_INVALID",e)}var Oe=require("node:crypto");var Ne=3e4,at=1e3,te=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=ut(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,d=ft(r,a);this.active.set(t.operationId,a);let c=this.executeFresh(t,a.signal).finally(()=>{d(),this.active.delete(t.operationId)});return this.executions.set(t.operationId,{fingerprint:n,promise:c}),this.trimIdempotencyRecords(),c}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){J(t),ee(r);let n=await this.adapter.manifest();S(n);let o=I(t.operation),a=K(t),d=this.now(),c=await this.adapter.preflight(t,r);st(c,this.now()),x(t,n,c.observedTarget),ee(r);let l=c.evidence??[];C(l,a,"before");let s=await D(this.artifactRepository,L({request:t,manifest:n,policy:a,evidence:l,now:this.now}));if(ee(r),Date.parse(c.expiresAt)<=Date.parse(this.now()))throw new i("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let u=q(t,c.observedTarget),p=await this.leaseAuthority.consume(t.capabilityLeaseId,t.expectedLeaseVersion,u),v={contractFingerprint:t.executionContract.fingerprint,lease:p,capabilityUse:u},f;try{f=await this.adapter.execute(t,c,v,r)}catch(A){return Q({request:t,manifest:n,descriptorEffect:o.effect,target:c.observedTarget,lease:p,artifacts:s,startedAt:d,completedAt:this.now(),status:r.aborted?"cancelled":"error",code:r.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_ADAPTER_ERROR",message:r.aborted?"Automation operation was stopped":pt(A)})}ct(f);let se=dt(c.observedTarget,f.observedTarget),U;try{x(t,n,f.observedTarget)}catch(A){U=A instanceof Error?A:new Error(String(A))}let _=f.evidence??[];lt(l,_);let ce=[],M;try{C(_,a,"after"),C([...l,..._],a,"recording"),ce=await D(this.artifactRepository,L({request:t,manifest:n,policy:a,evidence:_,now:this.now}))}catch(A){M=A instanceof Error?A:new Error(String(A))}let B=[...s,...ce];return se||U?Q({request:t,manifest:n,descriptorEffect:o.effect,target:f.observedTarget,lease:p,artifacts:B,startedAt:f.startedAt,completedAt:f.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:se??U.message}):M?Q({request:t,manifest:n,descriptorEffect:o.effect,target:f.observedTarget,lease:p,artifacts:B,startedAt:f.startedAt,completedAt:f.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:M.message}):{operationId:t.operationId,status:f.status,effect:o.effect,startedAt:f.startedAt,completedAt:f.completedAt,adapter:xe(n),target:structuredClone(f.observedTarget),...f.data!==void 0?{data:structuredClone(f.data)}:{},artifacts:B,lease:Pe(p),...f.error?{error:{...f.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>at;){let t=this.executions.keys().next().value;if(!t||this.active.has(t))break;this.executions.delete(t)}}};function st(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>Ne)throw new i("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${Ne} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new i("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function ct(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 dt(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 lt(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 Q(e){return{operationId:e.request.operationId,status:e.status,effect:e.descriptorEffect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:xe(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:Pe(e.lease),error:{code:e.code,message:e.message}}}function xe(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function Pe(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function ut(e){return(0,Oe.createHash)("sha256").update(JSON.stringify(re(e))).digest("hex")}function re(e){return Array.isArray(e)?e.map(re):!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,re(r)]))}function ft(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 ee(e){if(e.aborted)throw new i("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function pt(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}function Xe(e,t=()=>new Date().toISOString()){let r=[];It(r,"manifest.valid",()=>S(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 mt(e){let r=Xe(e).checks.filter(n=>n.status==="fail");if(r.length>0)throw new i("AUTOMATION_OPERATION_UNSUPPORTED",r.map(n=>`${n.id}: ${n.message}`).join("; "))}function y(e,t,r,n,o){let a=t.has(n);b(e,`capability.${n}`,r===a,r===a?`${o} declaration matches the operation catalog`:`${o} declaration does not match ${n}`)}function It(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 At=6e4,ht=48*1024*1024,ne=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(t){if(this.endpoint=gt(t.baseUrl),this.token=bt(t.token),this.timeoutMs=Le(t.timeoutMs??At,1e3,3e5,"timeoutMs"),this.maxResponseBytes=Le(t.maxResponseBytes??ht,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,d=yt(o,a),c=setTimeout(()=>a.abort(new Error("automation transport timeout")),this.timeoutMs);c.unref?.();try{let l=new URL(t,this.endpoint),s=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}),u=await Et(s,this.maxResponseBytes);if(!s.ok){let p=wt(u);throw new i("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${t}: ${p.message}`,{status:s.status,route:t,adapterCode:p.code})}if(!oe(u)||u.ok!==!0||!("result"in u))throw new i("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${t} envelope`);return u.result}catch(l){if(l instanceof i)throw l;let s=o?.aborted;throw new i(s?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",s?"Automation transport was stopped":`XENO Browser ${t} transport failed`,{route:t},{cause:l})}finally{clearTimeout(c),d()}}};function gt(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 bt(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 Et(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=[],d=0;for(;;){let{done:s,value:u}=await o.read();if(s)break;if(d+=u.byteLength,d>t)throw await o.cancel("response too large"),new i("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);a.push(u)}let c=new Uint8Array(d),l=0;for(let s of a)c.set(s,l),l+=s.byteLength;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c))}catch(s){throw new i("AUTOMATION_RESPONSE_INVALID","XENO Browser response contains invalid JSON",void 0,{cause:s})}}function wt(e){return oe(e)&&oe(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 yt(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 Le(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 oe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var k=require("node:crypto");var vt=8*1024*1024,Tt=4;function St(e){return Mt(e.operations??R).map(r=>Ct(r,e.runtime))}function Ct(e,t){return{definition:{name:e,description:xt(e),input_schema:_t(e)},projectPolicyInput(r){let n=Lt(e,r),o=Xt(e,r);return{observabilityInput:n,permissionInput:o,permissionPreview:Dt(e,r),approvalKey:`xeno-automation:${e}:${Bt(r)}`,riskLevel:Pt(e)}},async execute(r,n){let o=n?.authorization;if(!o||o.toolName!==e)return{success:!1,output:"",error:"Governed automation requires a host-issued authorization receipt",errorCode:"AUTOMATION_AUTHORIZATION_RECEIPT_REQUIRED",retryable:!1};let a=n.operationId??`automation_${(0,k.randomUUID)()}`,d=ae(e,r);n.reportProgress?.({activity:"state",message:`Authorizing ${e}`});try{let c=await t.execute({operation:e,governingToolName:e,operationId:a,idempotencyKey:a,parameters:structuredClone(r),...d?{declaredTarget:d}:{},authorization:o,...n.signal?{signal:n.signal}:{},...n.reportProgress?{reportProgress:n.reportProgress}:{}}),l=c.status==="ok";return{success:l,output:JSON.stringify(kt(c)),...l?{}:{error:c.error?.message??`Governed automation ended with ${c.status}`,errorCode:c.error?.code??`AUTOMATION_${c.status.toUpperCase().replaceAll("-","_")}`},assistantContent:Ut(c),evidence:c.artifacts.map(s=>({id:s.artifactId,kind:"artifact",status:c.status==="evidence-incomplete"?"failed":"verified",observedAt:s.updatedAt??s.createdAt,operationId:a,detail:{artifact_kind:s.kind,revision:s.revision,sensitivity:s.sensitivity}})),retryable:c.error?.retryable??!1}}catch(c){let l=n.signal?.aborted===!0;return{success:!1,output:"",error:l?"Governed automation was stopped":Vt(c),errorCode:l?"AUTOMATION_CANCELLED":$t(c),retryable:!l}}}}}function _t(e){let t=Rt(e),r=Nt(e);return{type:"object",properties:t,...r.length>0?{required:r}:{},...e==="browser.locate"?{oneOf:[{required:["selector"]},{required:["text"]}]}:{},additionalProperties:!1}}function Rt(e){let t=(d,c=8192)=>({type:"string",minLength:1,maxLength:c,description:d}),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:Ot()};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 Nt(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 Ot(){return{type:"object",properties:{shift:{type:"boolean"},ctrl:{type:"boolean"},alt:{type:"boolean"},meta:{type:"boolean"}},additionalProperties:!1}}function xt(e){let t=I(e),r=e.split(".").slice(1).join(" ");return`${t.effect==="act"?"Act on":"Inspect"} the ${t.surface} using governed ${r} automation. The host requires policy approval, an exact capability lease, target-bound preflight, and durable evidence.`}function Pt(e){return I(e).effect==="observe"?e==="browser.navigate"||e==="browser.tabs.open"?"medium":"low":["browser.type","browser.upload","browser.download","computer.type","computer.key","computer.launch"].includes(e)?"high":"medium"}function Xt(e,t){let r=ae(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 Lt(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]"),ke(r.trigger)&&typeof r.trigger.url=="string"&&(r.trigger={...r.trigger,url:De(r.trigger.url)}),typeof r.url=="string"&&(r.url=De(r.url)),{operation:e,...r}}function Dt(e,t){let r=ae(e,t),n=r?.url??r?.applicationId??r?.deviceId??r?.tabId??r?.resource??"current target";return`${e} on ${n}`}function ae(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 kt(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 Ut(e){let t=[];for(let r of e.artifacts){if(t.length>=Tt||!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>vt||t.push({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${n.base64}`,detail:"high"}})}return t}function Mt(e){let t=new Set(R),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 Bt(e){return(0,k.createHash)("sha256").update(ie(e)).digest("hex")}function ie(e){return Array.isArray(e)?`[${e.map(ie).join(",")}]`:ke(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ie(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function De(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid URL]"}}function Vt(e){return e instanceof Error?e.message:String(e)}function $t(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:"AUTOMATION_EXECUTION_FAILED"}function ke(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}0&&(module.exports={XENO_AUTOMATION_OPERATIONS,XENO_AUTOMATION_PROTOCOL_VERSION,XenoAutomationError,XenoGovernedAutomationExecutor,XenoLoopbackAutomationAdapter,assertRequiredXenoAutomationEvidence,assertValidXenoAutomationAdapterManifest,assertValidXenoAutomationRequest,assertXenoAutomationAdapterConformant,assertXenoAutomationAuthority,buildXenoAutomationCapabilityUse,createXenoAutomationConformanceReport,createXenoGovernedAutomationTools,describeXenoAutomationOperation,isXenoAutomationOperation,materializeXenoAutomationEvidence,persistXenoAutomationEvidence,resolveXenoAutomationEvidencePolicy});
899
+ `,Wt=String.raw`
900
+ public static class Program
901
+ {
902
+ private static string Decode(string name)
903
+ {
904
+ string value = Environment.GetEnvironmentVariable(name) ?? "";
905
+ return Encoding.UTF8.GetString(Convert.FromBase64String(value));
906
+ }
907
+
908
+ public static int Main()
909
+ {
910
+ string command = Decode("XENO_RESTRICTED_COMMAND");
911
+ string cwd = Decode("XENO_RESTRICTED_CWD");
912
+ bool lowIntegrity = Environment.GetEnvironmentVariable("XENO_RESTRICTED_LOW_INTEGRITY") == "1";
913
+ bool restrictedToken = Environment.GetEnvironmentVariable("XENO_RESTRICTED_USE_TOKEN") != "0";
914
+ string tokenProbe = Environment.GetEnvironmentVariable("XENO_CONTAINMENT_DIAGNOSTICS") == "1"
915
+ ? (Environment.GetEnvironmentVariable("XENO_RESTRICTED_TOKEN_PROBE") ?? "")
916
+ : "";
917
+ Environment.SetEnvironmentVariable("XENO_RESTRICTED_COMMAND", null);
918
+ Environment.SetEnvironmentVariable("XENO_RESTRICTED_CWD", null);
919
+ Environment.SetEnvironmentVariable("XENO_RESTRICTED_LOW_INTEGRITY", null);
920
+ Environment.SetEnvironmentVariable("XENO_RESTRICTED_USE_TOKEN", null);
921
+ Environment.SetEnvironmentVariable("XENO_RESTRICTED_TOKEN_PROBE", null);
922
+ return Xeno.Security.RestrictedProcessLauncher.Run(command, cwd, lowIntegrity, restrictedToken, tokenProbe);
923
+ }
924
+ }
925
+ `;var qt=512*1024,Kt=744*60*60*1e3,Yt=Object.freeze(["allowedFilesystemRead","allowedFilesystemWrite","outsideFilesystemReadDenied","outsideFilesystemWriteDenied","unlistedFilesystemReadDenied","unlistedFilesystemWriteDenied","symlinkEscapeDenied","networkDefaultDeny","environmentSecretsExcluded","childProcessPolicyInherited","standardCommandLaunch","processTreeCleanup","timeoutEnforced","hostPolicyRecoveryClean","uiRestrictionsEnforced"]);var nr=10*6e4,or=Object.freeze({"win32-x64-wxc-exec.exe":"db0a3422be9e1b396cc1b2547c70ff16b27412438a31c10a45abf370cac86ae2","win32-arm64-wxc-exec.exe":"e430d0e4f44f616e91db684f8d825a6dc93e06a1262b8d00bcaac7522a317aab","linux-x64-lxc-exec":"1efe3f817f5ae9ba9f9f2fd59142e79b2dde7a4dd024576b0ddb635fc87edeb5","linux-arm64-lxc-exec":"fdc00ccecf362ae3ddd8ccad93fd7c8b5b1f03c68897ab05ef1c9f1d327ea3fe","darwin-arm64-mxc-exec-mac":"77c07a86f483ed91dd5be290cd77878ac0c56fe113cdb8c764e7e5201c744ad2"}),ir=Object.freeze({"win32-x64-wxc-host-prep.exe":"531fb3cdb4b0c964908fd71b71d40961417afb399cbab72f92a25e95309a6416","win32-arm64-wxc-host-prep.exe":"3ef702332286a39153fc259310b5021e3de3c191751d7522684f6475f73af5ef"});var Er=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),wr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!0,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!0,environmentSanitization:!0}),yr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),vr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!0,networkIsolation:!0,inheritedHandleAllowlist:!0,environmentSanitization:!0}),Tr=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0});var Fe=1,j=class extends Error{constructor(r,n){super(n);this.code=r;this.name="XenoSecureExecutionContractError"}code};function He(e){let t=[];if(!e||typeof e!="object")return["Contract must be an object"];if(e.schemaVersion!==Fe&&t.push("Unsupported schemaVersion"),e.contractId?.trim()||t.push("contractId is required"),(!e.identity?.runId?.trim()||!e.identity?.agentId?.trim())&&t.push("runId and agentId are required"),le(e.createdAt)||t.push("createdAt must be an ISO 8601 timestamp"),e.expiresAt&&(!le(e.expiresAt)||Date.parse(e.expiresAt)<=Date.parse(e.createdAt))&&t.push("expiresAt must be later than createdAt"),e.requestedLevel!==e.effectiveLevel&&t.push("requestedLevel and effectiveLevel must match"),e.trustMode==="untrusted"&&e.effectiveLevel!=="contained"&&t.push("Untrusted execution requires contained mode"),e.effectiveLevel==="contained"&&(e.adapter.certified||t.push("Contained mode requires a certified adapter"),e.adapter.certificationArtifactId||t.push("Contained mode requires a certification artifact"),(!e.adapter.capabilities.filesystemIsolation||e.filesystem.enforcement!=="os")&&t.push("Contained mode requires OS filesystem isolation"),(!e.adapter.capabilities.networkIsolation||e.network.enforcement!=="os")&&t.push("Contained mode requires OS network isolation"),e.network.default!=="deny"&&t.push("Contained networking must default deny")),e.network.enforcement==="none"&&!e.network.acknowledgedUnrestricted&&t.push("Unrestricted networking must be explicitly acknowledged"),e.filesystem.writeRoots.length>0&&e.profile.permissionProfile==="read-only"&&t.push("Read-only profiles cannot receive write roots"),(!Array.isArray(e.browser.readAllowedDomains)||!Array.isArray(e.browser.actAllowedDomains))&&t.push("Browser read/action domain policies are required"),(!Array.isArray(e.browser.allowedSchemes)||e.browser.allowedSchemes.some(r=>r!=="http"&&r!=="https"))&&t.push("Browser allowed schemes are invalid"),(!Array.isArray(e.browser.allowedPorts)||e.browser.allowedPorts.some(r=>!Number.isInteger(r)||r<1||r>65535))&&t.push("Browser allowed ports are invalid"),e.secrets.some(r=>!r.secretId.trim())&&t.push("Secret projections require non-empty secret IDs"),new Set(e.secrets.map(r=>r.secretId)).size!==e.secrets.length&&t.push("Secret IDs must be unique"),new Set(e.capabilityLeaseIds).size!==e.capabilityLeaseIds.length&&t.push("Capability lease IDs must be unique"),/^[a-f0-9]{64}$/.test(e.profile.fingerprint)||t.push("Profile fingerprint is invalid"),!/^[a-f0-9]{64}$/.test(e.fingerprint))t.push("Contract fingerprint is invalid");else{let r={...e};delete r.fingerprint,je(r)!==e.fingerprint&&t.push("Contract fingerprint does not match content")}return t}function pe(e){let t=He(e);if(t.length>0){let r=t.includes("Contract fingerprint does not match content");throw new j(r?"SECURITY_CONTRACT_FINGERPRINT_MISMATCH":"SECURITY_CONTRACT_INVALID",t.join("; "))}}function je(e){return(0,ue.createHash)("sha256").update(JSON.stringify(G(e))).digest("hex")}function G(e){return Array.isArray(e)?e.map(G):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,G(r)]))}function le(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}var Ge=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,fe=1048576;function z(e){(!e||typeof e!="object")&&h("Automation request must be an object"),e.protocolVersion!==1&&h("Unsupported automation protocol version"),w(e.operationId,"operationId"),w(e.idempotencyKey,"idempotencyKey"),w(e.capabilityLeaseId,"capabilityLeaseId"),w(e.governingToolName,"governingToolName"),(!Number.isSafeInteger(e.expectedLeaseVersion)||e.expectedLeaseVersion<1)&&h("expectedLeaseVersion must be a positive safe integer"),ge(e.requestedAt)||h("requestedAt must be an ISO 8601 timestamp"),R(e.operation)||h(`Unsupported automation operation: ${e.operation}`),(!e.parameters||typeof e.parameters!="object"||Array.isArray(e.parameters))&&h("parameters must be a JSON object");let t;try{t=Buffer.byteLength(JSON.stringify(e.parameters),"utf8")}catch(r){throw new i("AUTOMATION_REQUEST_INVALID","parameters must be serializable JSON",void 0,{cause:r})}if(t>fe&&h(`parameters exceed ${fe} bytes`),w(e.identity?.runId,"identity.runId"),w(e.identity?.agentId,"identity.agentId"),pe(e.executionContract),We(e),!e.executionContract.capabilityLeaseIds.includes(e.capabilityLeaseId))throw new i("AUTOMATION_CONTRACT_INVALID",`Capability lease ${e.capabilityLeaseId} is not bound to the execution contract`);if(e.executionContract.expiresAt&&Date.parse(e.executionContract.expiresAt)<=Date.now())throw new i("AUTOMATION_CONTRACT_EXPIRED","Execution contract has expired")}function T(e){(!e||typeof e!="object")&&f("Adapter manifest must be an object"),e.protocolVersion!==1&&f("Adapter protocol version is unsupported"),N(e.adapterId,"adapterId"),N(e.adapterVersion,"adapterVersion"),N(e.platform,"platform"),N(e.architecture,"architecture"),e.targetBinding!=="atomic-preflight"&&f("Adapter must implement atomic preflight target binding"),(!Array.isArray(e.operations)||e.operations.length===0)&&f("Adapter must declare operations");let t=new Set;for(let r of e.operations)R(r)||f(`Adapter declares unknown operation ${r}`),t.has(r)&&f(`Adapter declares duplicate operation ${r}`),t.add(r);e.certified&&!e.certificationArtifactId&&f("A certified automation adapter requires a certification artifact"),Array.isArray(e.limitations)||f("Adapter limitations must be an array"),e.operations.some(r=>r.startsWith("browser."))&&(!e.policyEnforcement.domain||!e.policyEnforcement.scheme||!e.policyEnforcement.port)&&f("Browser adapters must enforce domain, scheme, and port policy"),e.operations.some(r=>r.startsWith("computer."))&&!e.supports.immediateStop&&f("Computer-use adapters must support immediate stop")}function O(e,t,r){let n=I(e.operation);if(!t.operations.includes(e.operation))throw new i("AUTOMATION_OPERATION_UNSUPPORTED",`Adapter ${t.adapterId} does not support ${e.operation}`);if(n.surface==="browser"){let o=e.executionContract.browser.mode;if(o==="none"||n.effect==="act"&&o!=="act")throw new i("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(ze(e,r,n.effect==="act"),e.operation==="browser.download"&&e.executionContract.browser.downloads==="deny")throw new i("AUTOMATION_POLICY_DENIED","Execution contract denies browser downloads");if(e.operation==="browser.upload"&&e.executionContract.browser.uploads==="deny")throw new i("AUTOMATION_POLICY_DENIED","Execution contract denies browser uploads");if(e.operation.startsWith("browser.record.")&&e.executionContract.browser.recording!=="bounded")throw new i("AUTOMATION_POLICY_DENIED","Execution contract denies browser recording")}else{let o=e.executionContract.computer.mode;if(o==="none"||n.effect==="act"&&o!=="act")throw new i("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);let a=e.executionContract.computer.allowedApplications,c=e.operation==="computer.launch"?qe(e):r.applicationId??e.declaredTarget?.applicationId;if((e.operation==="computer.launch"||a.length>0)&&(!c||!a.includes(c)))throw new i("AUTOMATION_POLICY_DENIED",`Application ${c??"<unknown>"} is not allowed`)}}function J(e,t){let r=I(e.operation),n=r.surface==="browser"?r.effect==="act"?"browser-act":"browser-read":r.effect==="act"?"computer-act":"computer-observe";return{subject:{runId:e.identity.runId,agentId:e.identity.agentId,...e.identity.turnId?{turnId:e.identity.turnId}:{},toolName:e.governingToolName,operationId:e.operationId},kind:n,operation:e.operation,...me(e,t)?{resource:me(e,t)}:{},...Ae(t)?{destination:Ae(t)}:{}}}function me(e,t){return e.declaredTarget?.resource??Je(t)}function q(e){let t=I(e.operation).evidence,r=e.evidencePolicy??{},n=W(t.before,r.before),o=W(t.after,r.after),a=W(t.recording,r.recording),c=r.retainUntil;return c&&!ge(c)&&h("evidencePolicy.retainUntil must be an ISO 8601 timestamp"),{before:n,after:o,recording:a,sensitivity:r.sensitivity??"confidential",...c?{retainUntil:c}:{},...r.legalHold!==void 0?{legalHold:r.legalHold}:{}}}function We(e){let t=e.executionContract.identity,r=["runId","agentId","sessionId","turnId","taskId","workspaceId"];for(let n of r){let o=t[n],a=e.identity[n];if(o!==void 0&&o!==a)throw new i("AUTOMATION_IDENTITY_MISMATCH",`Automation identity ${n} does not match the execution contract`)}}function ze(e,t,r){let n=t.url??t.origin??e.declaredTarget?.url??e.declaredTarget?.origin;if(!n){if(["browser.tabs.list","browser.wait"].includes(e.operation))return;throw new i("AUTOMATION_PREFLIGHT_INVALID","Browser preflight did not bind an effective URL")}let o;try{o=new URL(n)}catch{throw new i("AUTOMATION_POLICY_DENIED","Browser target URL is invalid")}if(o.username||o.password)throw new i("AUTOMATION_POLICY_DENIED","Browser target URLs cannot contain credentials");let a=o.protocol.replace(/:$/,"");a!=="http"&&a!=="https"&&E(`Browser scheme ${o.protocol} is not supported`);let c=a,s=o.hostname.toLowerCase().replace(/\.$/,""),l=o.port?Number(o.port):c==="https"?443:80,d=e.executionContract.browser,p=Ke(s);if(he(s,d.deniedDomains)&&E(`Browser domain ${s} is denied`),Ie(o,e.executionContract.network.denyDestinations)&&E(`Network policy explicitly denies ${c}://${s}:${l}`),p&&d.allowLoopbackDevelopment)return;d.allowedSchemes.includes(c)||E(`Browser scheme ${o.protocol} is not allowed`),d.allowedPorts.includes(l)||E(`Browser port ${l} is not allowed`);let m=r?d.actAllowedDomains:d.readAllowedDomains;he(s,m)||E(`Browser domain ${s} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&(Ie(o,e.executionContract.network.allowDestinations)||E(`Network policy does not allow ${c}://${s}:${l}`))}function Ie(e,t){let r=e.protocol.replace(/:$/,""),n=e.hostname.toLowerCase().replace(/\.$/,""),o=e.port?Number(e.port):r==="https"?443:80;return t.some(a=>{let c=a.scheme?.replace(/^custom:/,"");return a.host===n&&(a.port===void 0||a.port===o)&&(c===void 0||c===r)})}function Je(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function Ae(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function qe(e){let t=e.parameters.target,r=t&&typeof t=="object"&&!Array.isArray(t)?t.app_id:void 0,n=e.parameters.applicationId??r??e.declaredTarget?.applicationId;return typeof n=="string"&&n.length>0?n:void 0}function he(e,t){return t.some(r=>{let n=r.toLowerCase();if(n.startsWith(".")){let o=n.slice(1);return e===o||e.endsWith(`.${o}`)}return e===n})}function Ke(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function W(e,t){let r={disabled:0,optional:1,required:2};return!t||r[t]<=r[e]?e:t}function w(e,t){(typeof e!="string"||!Ge.test(e))&&h(`${t} is invalid`)}function N(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&f(`${t} is invalid`)}function ge(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}function E(e){throw new i("AUTOMATION_POLICY_DENIED",e)}function h(e){throw new i("AUTOMATION_REQUEST_INVALID",e)}function f(e){throw new i("AUTOMATION_OPERATION_UNSUPPORTED",e)}var _e=require("node:crypto");var be=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation"],Ee=["draft","pending_review","approved","rejected","superseded","archived"],we=["public","internal","confidential","restricted"],ye=["agent","tool","user","system","integration"],ve=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],Te=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var Se=require("node:crypto");function P(e){return{algorithm:"sha256",value:(0,Se.createHash)("sha256").update(e).digest("hex")}}var Ye="[\\u0000-\\u001f\\u007f]",jr=new RegExp(Ye);var Gr=new Set(Ee),Wr=new Set(we),zr=new Set(ye),Jr=new Set(be),qr=new Set(ve),Kr=new Set(Te);var x=class extends Error{constructor(r,n,o,a){super(n,a);this.code=r;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail};var Y=32*1024*1024,Ze=1024*1024*1024,Qe=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function X(e){let r=(e.now??(()=>new Date().toISOString()))(),n=new Set;return e.evidence.map((o,a)=>{if(tt(o),n.has(o.evidenceId))throw new i("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${o.evidenceId}`);n.add(o.evidenceId);let c=et(o),s=(0,_e.createHash)("sha256").update(`${e.request.operationId}\0${o.evidenceId}\0${c.hash.value}`).digest("hex").slice(0,32);return{schemaVersion:1,artifactId:`automation_${s}`,revision:1,kind:o.kind,title:o.title,...o.description?{description:o.description}:{},state:"draft",createdAt:r,mediaType:o.mediaType,sensitivity:o.sensitivity??e.policy.sensitivity,identity:{...e.request.identity},content:c,provenance:{producer:{kind:"tool",id:e.request.governingToolName,displayName:e.manifest.adapterId,profileFingerprint:e.request.executionContract.profile.fingerprint},operationId:e.request.operationId,executionContractFingerprint:e.request.executionContract.fingerprint,capabilityLeaseIds:[e.request.capabilityLeaseId],attributes:{automationProtocolVersion:e.request.protocolVersion,automationOperation:e.request.operation,automationEvidenceId:o.evidenceId,automationEvidencePhase:o.phase,adapterId:e.manifest.adapterId,adapterVersion:e.manifest.adapterVersion,evidenceIndex:a}},...o.anchors?{anchors:structuredClone(o.anchors)}:{},...e.policy.retainUntil||e.policy.legalHold!==void 0?{retention:{...e.policy.retainUntil?{retainUntil:e.policy.retainUntil}:{},...e.policy.legalHold!==void 0?{legalHold:e.policy.legalHold}:{}}}:{},extensions:{...o.extensions??{},xenoAutomation:{phase:o.phase,adapter:e.manifest.adapterId,certifiedAdapter:e.manifest.certified}}}})}async function k(e,t){if(!e)return t.map(n=>structuredClone(n));let r=[];for(let n of t)try{let o=await e.create(n);r.push(o.artifact)}catch(o){if(o instanceof x&&o.code==="ARTIFACT_ALREADY_EXISTS"){let a=await e.require(n.artifactId,n.revision);if(a.artifact.content.hash.value===n.content.hash.value){r.push(a.artifact);continue}}throw new i("AUTOMATION_EVIDENCE_PERSISTENCE_FAILED",`Failed to persist automation evidence ${n.artifactId}`,{artifactId:n.artifactId},{cause:o})}return r}function S(e,t,r){if(t[r]==="required"&&!e.some(n=>n.phase===r))throw new i("AUTOMATION_EVIDENCE_REQUIRED",`Automation operation requires ${r} evidence before it can be trusted`)}function et(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return Ce(t),{hash:P(e.content.text),sizeBytes:t,storage:{type:"inline",text:e.content.text},encoding:"utf8",...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}if(e.content.type==="base64"){let t=rt(e.content.base64);return Ce(t.byteLength),{hash:P(t),sizeBytes:t.byteLength,storage:{type:"inline",base64:e.content.base64},encoding:"base64",...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}if(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0||e.content.sizeBytes>Ze)throw new i("AUTOMATION_EVIDENCE_INVALID","Referenced evidence size is invalid");if(!e.content.hash?.algorithm||!e.content.hash.value)throw new i("AUTOMATION_EVIDENCE_INVALID","Referenced evidence requires a content hash");if(e.content.hash.algorithm==="sha256"&&!/^[a-f0-9]{64}$/.test(e.content.hash.value))throw new i("AUTOMATION_EVIDENCE_INVALID","Referenced evidence SHA-256 is invalid");return{hash:{...e.content.hash},sizeBytes:e.content.sizeBytes,storage:structuredClone(e.content.storage),...e.content.encoding?{encoding:e.content.encoding}:{},...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}function tt(e){(!e||typeof e!="object")&&g("Evidence must be an object"),Qe.test(e.evidenceId)||g("Evidence ID is invalid"),["before","action","after","recording","diagnostic"].includes(e.phase)||g("Evidence phase is invalid"),(!e.kind||!e.title?.trim()||e.title.length>512)&&g("Evidence kind and title are required"),/^[\w!#$&^_.+-]+\/[\w!#$&^_.+-]+(?:;.*)?$/.test(e.mediaType)||g("Evidence media type is invalid")}function rt(e){(e.length===0||e.length>Math.ceil(Y/3)*4+4)&&g("Inline base64 evidence is empty or too large"),(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)&&g("Inline evidence is not canonical base64");let t=Buffer.from(e,"base64");return t.toString("base64")!==e&&g("Inline evidence is not canonical base64"),t}function Ce(e){e>Y&&g(`Inline evidence exceeds ${Y} bytes`)}function g(e){throw new i("AUTOMATION_EVIDENCE_INVALID",e)}var Ne=require("node:crypto");var Re=3e4,nt=1e3,ee=class{adapter;leaseAuthority;artifactRepository;now;executions=new Map;active=new Map;constructor(t){this.adapter=t.adapter,this.leaseAuthority=t.leaseAuthority,this.artifactRepository=t.artifactRepository,this.now=t.now??(()=>new Date().toISOString())}execute(t,r){let n=ct(t),o=this.executions.get(t.operationId);if(o){if(o.fingerprint!==n)throw new i("AUTOMATION_OPERATION_CONFLICT",`Operation ${t.operationId} was already submitted with different authority or parameters`);return o.promise}let a=new AbortController,c=dt(r,a);this.active.set(t.operationId,a);let s=this.executeFresh(t,a.signal).finally(()=>{c(),this.active.delete(t.operationId)});return this.executions.set(t.operationId,{fingerprint:n,promise:s}),this.trimIdempotencyRecords(),s}async stop(t,r="human-stop"){let n=this.active.get(t);return n?(n.abort(new Error(r)),await this.adapter.stop?.(t,r),!0):!1}async executeFresh(t,r){z(t),Q(r);let n=await this.adapter.manifest();T(n);let o=I(t.operation),a=q(t),c=this.now(),s=await this.adapter.preflight(t,r);ot(s,this.now()),O(t,n,s.observedTarget),Q(r);let l=s.evidence??[];S(l,a,"before");let d=await k(this.artifactRepository,X({request:t,manifest:n,policy:a,evidence:l,now:this.now}));if(Q(r),Date.parse(s.expiresAt)<=Date.parse(this.now()))throw new i("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let p=J(t,s.observedTarget),m=await this.leaseAuthority.consume(t.capabilityLeaseId,t.expectedLeaseVersion,p),ae={contractFingerprint:t.executionContract.fingerprint,lease:m,capabilityUse:p},u;try{u=await this.adapter.execute(t,s,ae,r)}catch(A){return Z({request:t,manifest:n,descriptorEffect:o.effect,target:s.observedTarget,lease:m,artifacts:d,startedAt:c,completedAt:this.now(),status:r.aborted?"cancelled":"error",code:r.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_ADAPTER_ERROR",message:r.aborted?"Automation operation was stopped":lt(A)})}it(u);let se=at(s.observedTarget,u.observedTarget),D;try{O(t,n,u.observedTarget)}catch(A){D=A instanceof Error?A:new Error(String(A))}let C=u.evidence??[];st(l,C);let ce=[],U;try{S(C,a,"after"),S([...l,...C],a,"recording"),ce=await k(this.artifactRepository,X({request:t,manifest:n,policy:a,evidence:C,now:this.now}))}catch(A){U=A instanceof Error?A:new Error(String(A))}let M=[...d,...ce];return se||D?Z({request:t,manifest:n,descriptorEffect:o.effect,target:u.observedTarget,lease:m,artifacts:M,startedAt:u.startedAt,completedAt:u.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:se??D.message}):U?Z({request:t,manifest:n,descriptorEffect:o.effect,target:u.observedTarget,lease:m,artifacts:M,startedAt:u.startedAt,completedAt:u.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:U.message}):{operationId:t.operationId,status:u.status,effect:o.effect,startedAt:u.startedAt,completedAt:u.completedAt,adapter:Oe(n),target:structuredClone(u.observedTarget),...u.data!==void 0?{data:structuredClone(u.data)}:{},artifacts:M,lease:Pe(m),...u.error?{error:{...u.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>nt;){let t=this.executions.keys().next().value;if(!t||this.active.has(t))break;this.executions.delete(t)}}};function ot(e,t){if(!e||typeof e!="object"||!e.token?.trim())throw new i("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an invalid preflight token");let r=Date.parse(e.preparedAt),n=Date.parse(e.expiresAt),o=Date.parse(t);if(!Number.isFinite(r)||!Number.isFinite(n)||n<=r||n<=o)throw new i("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an expired or invalid preflight window");if(n-r>Re)throw new i("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${Re} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new i("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function it(e){if(!e||typeof e!="object")throw new i("AUTOMATION_REQUEST_INVALID","Adapter returned no result");if(!["ok","denied","cancelled","error"].includes(e.status))throw new i("AUTOMATION_REQUEST_INVALID","Adapter returned an invalid status");if(!Number.isFinite(Date.parse(e.startedAt))||!Number.isFinite(Date.parse(e.completedAt)))throw new i("AUTOMATION_REQUEST_INVALID","Adapter result timestamps are invalid");if(Date.parse(e.completedAt)<Date.parse(e.startedAt))throw new i("AUTOMATION_REQUEST_INVALID","Adapter completion precedes its start");if(!e.observedTarget||typeof e.observedTarget!="object")throw new i("AUTOMATION_REQUEST_INVALID","Adapter result has no observed target")}function at(e,t){let r=["tabId","deviceId","displayId"];for(let n of r)if(e[n]!==void 0&&e[n]!==t[n])return`Adapter changed bound ${n} between preflight and execution`}function st(e,t){let r=new Set(e.map(n=>n.evidenceId));for(let n of t){if(r.has(n.evidenceId))throw new i("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${n.evidenceId}`);r.add(n.evidenceId)}}function Z(e){return{operationId:e.request.operationId,status:e.status,effect:e.descriptorEffect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:Oe(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:Pe(e.lease),error:{code:e.code,message:e.message}}}function Oe(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function Pe(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function ct(e){return(0,Ne.createHash)("sha256").update(JSON.stringify(te(e))).digest("hex")}function te(e){return Array.isArray(e)?e.map(te):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,te(r)]))}function dt(e,t){if(!e)return()=>{};let r=()=>t.abort(e.reason);return e.aborted?r():e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)}function Q(e){if(e.aborted)throw new i("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function lt(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}function xe(e,t=()=>new Date().toISOString()){let r=[];pt(r,"manifest.valid",()=>T(e));let n=new Set(e.operations);return y(r,n,e.supports.consoleInspection,"browser.console.read","console inspection"),y(r,n,e.supports.networkInspection,"browser.network.read","network inspection"),y(r,n,e.supports.storageInspection,"browser.storage.read","storage inspection"),y(r,n,e.supports.pageErrorInspection,"browser.page-errors.read","page-error inspection"),y(r,n,e.supports.recordings,"browser.record.start","recording start"),y(r,n,e.supports.recordings,"browser.record.stop","recording stop"),n.has("browser.upload")&&b(r,"policy.upload",e.policyEnforcement.upload,"Upload policy is enforced"),n.has("browser.download")&&b(r,"policy.download",e.policyEnforcement.download,"Download policy is enforced"),[...n].some(o=>o.startsWith("browser."))&&(b(r,"policy.redirect",e.policyEnforcement.redirect,"Redirect policy is enforced"),b(r,"control.handback",e.supports.deterministicHandback,"Deterministic hand-back is supported")),[...n].some(o=>o.startsWith("computer."))&&(b(r,"control.stop",e.supports.immediateStop,"Immediate human stop is supported"),b(r,"privacy.redaction",e.supports.sensitiveRegionRedaction,"Sensitive-region redaction is supported")),b(r,"certification.binding",!e.certified||!!e.certificationArtifactId,e.certified?"Certification artifact is bound":"Adapter does not claim certification"),{protocolVersion:1,adapter:{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture},generatedAt:t(),passed:r.every(o=>o.status==="pass"),checks:r}}function ut(e){let r=xe(e).checks.filter(n=>n.status==="fail");if(r.length>0)throw new i("AUTOMATION_OPERATION_UNSUPPORTED",r.map(n=>`${n.id}: ${n.message}`).join("; "))}function y(e,t,r,n,o){let a=t.has(n);b(e,`capability.${n}`,r===a,r===a?`${o} declaration matches the operation catalog`:`${o} declaration does not match ${n}`)}function pt(e,t,r){try{r(),e.push({id:t,status:"pass",message:"Manifest satisfies the protocol contract"})}catch(n){e.push({id:t,status:"fail",message:n instanceof Error?n.message:String(n)})}}function b(e,t,r,n){e.push({id:t,status:r?"pass":"fail",message:n})}var ft=6e4,mt=48*1024*1024,re=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(t){if(this.endpoint=It(t.baseUrl),this.token=At(t.token),this.timeoutMs=Xe(t.timeoutMs??ft,1e3,3e5,"timeoutMs"),this.maxResponseBytes=Xe(t.maxResponseBytes??mt,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=t.fetch??globalThis.fetch,typeof this.fetchImpl!="function")throw new i("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}preflight(t,r){return this.request("preflight","POST",t,r)}execute(t,r,n,o){return this.request("execute","POST",{request:t,preflight:r,grant:n},o)}async stop(t,r){await this.request("stop","POST",{operationId:t,reason:r.slice(0,512)})}async request(t,r,n,o){let a=new AbortController,c=bt(o,a),s=setTimeout(()=>a.abort(new Error("automation transport timeout")),this.timeoutMs);s.unref?.();try{let l=new URL(t,this.endpoint),d=await this.fetchImpl(l,{method:r,redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.token}`,accept:"application/json",...r==="POST"?{"content-type":"application/json"}:{}},...r==="POST"?{body:JSON.stringify(n??{})}:{},signal:a.signal}),p=await ht(d,this.maxResponseBytes);if(!d.ok){let m=gt(p);throw new i("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${t}: ${m.message}`,{status:d.status,route:t,adapterCode:m.code})}if(!ne(p)||p.ok!==!0||!("result"in p))throw new i("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${t} envelope`);return p.result}catch(l){if(l instanceof i)throw l;let d=o?.aborted;throw new i(d?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",d?"Automation transport was stopped":`XENO Browser ${t} transport failed`,{route:t},{cause:l})}finally{clearTimeout(s),c()}}};function It(e){let t;try{t=new URL(e)}catch(n){throw new i("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL is invalid",void 0,{cause:n})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new i("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires HTTP(S)");if(t.username||t.password||t.search||t.hash)throw new i("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL cannot contain credentials, query, or fragment");let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="::1")throw new i("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport must use a loopback host");if(!t.port)throw new i("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires an explicit port");return t.pathname="/v1/automation/",t}function At(e){if(typeof e!="string"||e.length<32||e.length>512||/\s/.test(e))throw new i("AUTOMATION_TRANSPORT_ERROR","XENO Browser session token is invalid");return e}async function ht(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new i("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);if(e.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new i("AUTOMATION_RESPONSE_INVALID","XENO Browser response is not application/json");if(!e.body)throw new i("AUTOMATION_RESPONSE_INVALID","XENO Browser response body is missing");let o=e.body.getReader(),a=[],c=0;for(;;){let{done:d,value:p}=await o.read();if(d)break;if(c+=p.byteLength,c>t)throw await o.cancel("response too large"),new i("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);a.push(p)}let s=new Uint8Array(c),l=0;for(let d of a)s.set(d,l),l+=d.byteLength;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch(d){throw new i("AUTOMATION_RESPONSE_INVALID","XENO Browser response contains invalid JSON",void 0,{cause:d})}}function gt(e){return ne(e)&&ne(e.error)?{code:typeof e.error.code=="string"?e.error.code.slice(0,128):"UNKNOWN",message:typeof e.error.message=="string"?e.error.message.slice(0,1024):"request failed"}:{code:"UNKNOWN",message:"request failed"}}function bt(e,t){if(!e)return()=>{};let r=()=>t.abort(e.reason);return e.aborted?r():e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)}function Xe(e,t,r,n){if(!Number.isSafeInteger(e)||e<t||e>r)throw new i("AUTOMATION_TRANSPORT_ERROR",`${n} must be an integer from ${t} to ${r}`);return e}function ne(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var L=require("node:crypto");var Et=8*1024*1024,wt=4;function yt(e){return Lt(e.operations??_).map(r=>vt(r,e.runtime))}function vt(e,t){return{definition:{name:e,description:Rt(e),input_schema:Tt(e)},projectPolicyInput(r){let n=Pt(e,r),o=Ot(e,r);return{observabilityInput:n,permissionInput:o,permissionPreview:xt(e,r),approvalKey:`xeno-automation:${e}:${Dt(r)}`,riskLevel:Nt(e)}},async execute(r,n){let o=n?.authorization;if(!o||o.toolName!==e)return{success:!1,output:"",error:"Governed automation requires a host-issued authorization receipt",errorCode:"AUTOMATION_AUTHORIZATION_RECEIPT_REQUIRED",retryable:!1};let a=n.operationId??`automation_${(0,L.randomUUID)()}`,c=ie(e,r);n.reportProgress?.({activity:"state",message:`Authorizing ${e}`});try{let s=await t.execute({operation:e,governingToolName:e,operationId:a,idempotencyKey:a,parameters:structuredClone(r),...c?{declaredTarget:c}:{},authorization:o,...n.signal?{signal:n.signal}:{},...n.reportProgress?{reportProgress:n.reportProgress}:{}}),l=s.status==="ok";return{success:l,output:JSON.stringify(Xt(s)),...l?{}:{error:s.error?.message??`Governed automation ended with ${s.status}`,errorCode:s.error?.code??`AUTOMATION_${s.status.toUpperCase().replaceAll("-","_")}`},assistantContent:kt(s),evidence:s.artifacts.map(d=>({id:d.artifactId,kind:"artifact",status:s.status==="evidence-incomplete"?"failed":"verified",observedAt:d.updatedAt??d.createdAt,operationId:a,detail:{artifact_kind:d.kind,revision:d.revision,sensitivity:d.sensitivity}})),retryable:s.error?.retryable??!1}}catch(s){let l=n.signal?.aborted===!0;return{success:!1,output:"",error:l?"Governed automation was stopped":Ut(s),errorCode:l?"AUTOMATION_CANCELLED":Mt(s),retryable:!l}}}}}function Tt(e){let t=St(e),r=Ct(e);return{type:"object",properties:t,...r.length>0?{required:r}:{},...e==="browser.locate"?{oneOf:[{required:["selector"]},{required:["text"]}]}:{},additionalProperties:!1}}function St(e){let t=(c,s=8192)=>({type:"string",minLength:1,maxLength:s,description:c}),r={type:"number"},n={type:"boolean"},o={type:"object",properties:{x:r,y:r},required:["x","y"],additionalProperties:!1},a={deviceId:t("Target xeno-use device ID.",256),applicationId:t("Expected or launch-target application ID.",512),displayId:t("Target display ID.",256)};switch(e){case"browser.navigate":return{url:t("Destination URL."),waitUntil:{enum:["load","none"]},tabId:t("Expected active tab ID. Hosts with multiple visible tabs should require this.",256)};case"browser.wait":return{until:{enum:["load","ms"]},value:{type:"integer",minimum:0,maximum:6e4}};case"browser.snapshot":return{mode:{enum:["text","html","markdown","a11y"]},tabId:t("Expected active tab ID.",256)};case"browser.screenshot":return{tabId:t("Expected active tab ID.",256)};case"browser.locate":return{selector:t("CSS selector."),text:t("Visible text to locate.")};case"browser.click":return{selector:t("CSS selector returned by browser.snapshot or browser.locate."),tabId:t("Expected active tab ID.",256)};case"browser.type":return{selector:t("CSS selector."),text:{type:"string",maxLength:65536},clear:n,submit:n,tabId:t("Expected active tab ID.",256)};case"browser.key":return{combo:t("Key combo such as Control+a or Enter.",256),tabId:t("Expected active tab ID.",256)};case"browser.select":return{selector:t("CSS selector."),value:t("Option value."),tabId:t("Expected active tab ID.",256)};case"browser.scroll":return{selector:t("Optional CSS selector."),dx:r,dy:r,tabId:t("Expected active tab ID.",256)};case"browser.tabs.open":return{url:t("URL to open in an isolated browser tab.")};case"browser.tabs.close":return{tabId:t("Tab ID to close.",256)};case"browser.console.read":case"browser.network.read":case"browser.page-errors.read":return{limit:{type:"integer",minimum:1,maximum:1e3},clear:n,tabId:t("Expected active tab ID.",256)};case"browser.storage.read":return{tabId:t("Expected active tab ID.",256)};case"browser.upload":return{selector:t("File input or drop-target selector."),backendNodeId:{type:"integer",minimum:1},hostPaths:{type:"array",items:t("Host file path.",32768),minItems:1,maxItems:64},drop:n,tabId:t("Expected active tab ID.",256)};case"browser.download":return{toPath:t("Approved destination path.",32768),trigger:{type:"object",properties:{url:t("Download URL."),selector:t("Download trigger selector.")},oneOf:[{required:["url"]},{required:["selector"]}],additionalProperties:!1},tabId:t("Expected active tab ID.",256)};case"browser.record.start":return{maxDurationMs:{type:"integer",minimum:1e3,maximum:6e4},intervalMs:{type:"integer",minimum:100,maximum:5e3},tabId:t("Expected active tab ID.",256)};case"browser.record.stop":return{tabId:t("Expected active tab ID.",256)};case"computer.observe":case"computer.screenshot":case"computer.window-state":return a;case"computer.point":return{...a,point:o,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.click":return{...a,point:o,button:{enum:["left","right","middle"]},modifiers:_t()};case"computer.double-click":case"computer.right-click":return{...a,point:o};case"computer.drag":return{...a,from:o,to:o,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.type":return{...a,text:{type:"string",maxLength:65536}};case"computer.key":return{...a,combo:t("Key combo such as Control+a or Enter.",256)};case"computer.scroll":return{...a,at:o,delta:o};case"computer.wait":return{...a,milliseconds:{type:"integer",minimum:0,maximum:3e5}};case"computer.launch":return{...a,applicationId:t("Explicitly allowlisted application ID.",512)};case"browser.back":case"browser.forward":case"browser.reload":return{tabId:t("Expected active tab ID.",256)};case"browser.tabs.list":return{}}}function Ct(e){switch(e){case"browser.navigate":case"browser.tabs.open":return["url"];case"browser.click":return["selector"];case"browser.type":return["selector","text"];case"browser.key":return["combo"];case"browser.select":return["selector","value"];case"browser.upload":return["hostPaths"];case"browser.download":return["toPath","trigger"];case"computer.point":case"computer.click":case"computer.double-click":case"computer.right-click":return["point"];case"computer.drag":return["from","to"];case"computer.type":return["text"];case"computer.key":return["combo"];case"computer.scroll":return["at","delta"];case"computer.launch":return["applicationId"];default:return[]}}function _t(){return{type:"object",properties:{shift:{type:"boolean"},ctrl:{type:"boolean"},alt:{type:"boolean"},meta:{type:"boolean"}},additionalProperties:!1}}function Rt(e){let t=I(e),r=e.split(".").slice(1).join(" ");return`${t.effect==="act"?"Act on":"Inspect"} the ${t.surface} using governed ${r} automation. The host requires policy approval, an exact capability lease, target-bound preflight, and durable evidence.`}function Nt(e){return I(e).effect==="observe"?e==="browser.navigate"||e==="browser.tabs.open"?"medium":"low":["browser.type","browser.upload","browser.download","computer.type","computer.key","computer.launch"].includes(e)?"high":"medium"}function Ot(e,t){let r=ie(e,t),n={operation:e};r&&(n.target=r);for(let o of["selector","clear","submit","combo","value","dx","dy","point","from","to","at","delta","milliseconds"])t[o]!==void 0&&(n[o]=structuredClone(t[o]));return typeof t.text=="string"&&(n.text=`[redacted ${t.text.length} characters]`),Array.isArray(t.hostPaths)&&(n.hostPaths=t.hostPaths.map(()=>"[redacted host path]")),typeof t.toPath=="string"&&(n.toPath="[redacted destination path]"),n}function Pt(e,t){let r=structuredClone(t);return typeof r.text=="string"&&(r.text=`[redacted ${r.text.length} characters]`),Array.isArray(r.hostPaths)&&(r.hostPaths=r.hostPaths.map(()=>"[redacted host path]")),typeof r.toPath=="string"&&(r.toPath="[redacted destination path]"),Le(r.trigger)&&typeof r.trigger.url=="string"&&(r.trigger={...r.trigger,url:ke(r.trigger.url)}),typeof r.url=="string"&&(r.url=ke(r.url)),{operation:e,...r}}function xt(e,t){let r=ie(e,t),n=r?.url??r?.applicationId??r?.deviceId??r?.tabId??r?.resource??"current target";return`${e} on ${n}`}function ie(e,t){let r={};return typeof t.url=="string"&&(r.url=t.url),typeof t.tabId=="string"&&(r.tabId=t.tabId),typeof t.deviceId=="string"&&(r.deviceId=t.deviceId),typeof t.applicationId=="string"&&(r.applicationId=t.applicationId),typeof t.displayId=="string"&&(r.displayId=t.displayId),(e==="browser.navigate"||e==="browser.tabs.list"||e==="browser.tabs.open")&&(r.resource="browser-tabs"),Object.keys(r).length>0?r:void 0}function Xt(e){return{operationId:e.operationId,status:e.status,effect:e.effect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:e.adapter,target:e.target,...e.data!==void 0?{data:e.data}:{},artifacts:e.artifacts.map(t=>({artifactId:t.artifactId,revision:t.revision,kind:t.kind,title:t.title,state:t.state,mediaType:t.mediaType,sensitivity:t.sensitivity,hash:t.content.hash,sizeBytes:t.content.sizeBytes})),lease:e.lease,...e.error?{error:e.error}:{}}}function kt(e){let t=[];for(let r of e.artifacts){if(t.length>=wt||!r.mediaType.startsWith("image/"))continue;let n=r.content.storage;if(n.type!=="inline"||typeof n.base64!="string")continue;let o=Math.floor(n.base64.length*.75);o<=0||o>Et||t.push({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${n.base64}`,detail:"high"}})}return t}function Lt(e){let t=new Set(_),r=new Set;for(let n of e){if(!t.has(n))throw new TypeError(`Unsupported XENO automation operation: ${String(n)}`);r.add(n)}return Array.from(r)}function Dt(e){return(0,L.createHash)("sha256").update(oe(e)).digest("hex")}function oe(e){return Array.isArray(e)?`[${e.map(oe).join(",")}]`:Le(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${oe(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function ke(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid URL]"}}function Ut(e){return e instanceof Error?e.message:String(e)}function Mt(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:"AUTOMATION_EXECUTION_FAILED"}function Le(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}0&&(module.exports={XENO_AUTOMATION_OPERATIONS,XENO_AUTOMATION_PROTOCOL_VERSION,XenoAutomationError,XenoGovernedAutomationExecutor,XenoLoopbackAutomationAdapter,assertRequiredXenoAutomationEvidence,assertValidXenoAutomationAdapterManifest,assertValidXenoAutomationRequest,assertXenoAutomationAdapterConformant,assertXenoAutomationAuthority,buildXenoAutomationCapabilityUse,createXenoAutomationConformanceReport,createXenoGovernedAutomationTools,describeXenoAutomationOperation,isXenoAutomationOperation,materializeXenoAutomationEvidence,persistXenoAutomationEvidence,resolveXenoAutomationEvidencePolicy});