@xenosystem/agent-sdk 0.9.24 → 0.9.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/artifacts/index.cjs +1 -1
  2. package/dist/artifacts/index.js +1 -1
  3. package/dist/automation/index.cjs +1 -1
  4. package/dist/automation/index.d.cts +3 -0
  5. package/dist/automation/index.d.ts +3 -0
  6. package/dist/automation/index.js +1 -1
  7. package/dist/control-plane/index.cjs +1 -1
  8. package/dist/control-plane/index.js +1 -1
  9. package/dist/electron/index.cjs +124 -124
  10. package/dist/electron/index.d.cts +3 -0
  11. package/dist/electron/index.d.ts +3 -0
  12. package/dist/electron/index.js +123 -123
  13. package/dist/electron/metafile-cjs.json +1 -1
  14. package/dist/electron/metafile-esm.json +1 -1
  15. package/dist/governance/index.d.cts +2 -0
  16. package/dist/governance/index.d.ts +2 -0
  17. package/dist/hosted/index.cjs +1 -1
  18. package/dist/hosted/index.js +1 -1
  19. package/dist/hosted/metafile-cjs.json +1 -1
  20. package/dist/hosted/metafile-esm.json +1 -1
  21. package/dist/index.cjs +263 -263
  22. package/dist/index.d.cts +16 -7
  23. package/dist/index.d.ts +16 -7
  24. package/dist/index.js +273 -273
  25. package/dist/mcp/index.d.cts +3 -0
  26. package/dist/mcp/index.d.ts +3 -0
  27. package/dist/metafile-cjs.json +1 -1
  28. package/dist/metafile-esm.json +1 -1
  29. package/dist/session/index.cjs +1 -1
  30. package/dist/session/index.d.cts +2 -0
  31. package/dist/session/index.d.ts +2 -0
  32. package/dist/session/index.js +1 -1
  33. package/dist/session/metafile-cjs.json +1 -1
  34. package/dist/session/metafile-esm.json +1 -1
  35. package/dist/skills/index.d.cts +3 -0
  36. package/dist/skills/index.d.ts +3 -0
  37. package/dist/ui/index.d.cts +2 -0
  38. package/dist/ui/index.d.ts +2 -0
  39. package/dist/utils/index.d.cts +2 -0
  40. package/dist/utils/index.d.ts +2 -0
  41. package/package.json +10 -1
@@ -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.24";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.25";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.24";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.25";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,`
@@ -923,7 +923,7 @@ public static class Program
923
923
  }
924
924
  }
925
925
  `;function Kt(){let e=process.env.SystemRoot??process.env.WINDIR;if(e){let t=(0,at.join)(e,"Microsoft.NET","Framework64","v4.0.30319","csc.exe");if((0,ee.existsSync)(t))return t;let r=(0,at.join)(e,"Microsoft.NET","Framework","v4.0.30319","csc.exe");if((0,ee.existsSync)(r))return r}return null}var ct=require("node:child_process"),V=require("node:fs"),K=require("node:path"),Qt="XENO_BWRAP_PROFILE_OK",Yt=5e3,st;function Zt(e){try{return!(0,V.existsSync)(e)||!(0,V.statSync)(e).isFile()?null:((0,V.accessSync)(e,V.constants.X_OK),(0,V.realpathSync)(e))}catch{return null}}function Nn(){let e=process.env.XENO_BWRAP_PATH?.trim();if(e)return Zt((0,K.isAbsolute)(e)?e:(0,K.resolve)(e));let t=["/usr/bin/bwrap","/bin/bwrap",...(process.env.PATH??"").split(K.delimiter).filter(Boolean).map(r=>(0,K.join)(r,"bwrap"))];for(let r of new Set(t)){let n=Zt(r);if(n)return n}return null}function kn(){return["--die-with-parent","--new-session","--unshare-user","--unshare-pid","--unshare-uts","--unshare-ipc","--ro-bind","/","/","--proc","/proc","--dev","/dev","--chdir","/","--","/bin/sh","-c",`test -r /proc/self/status && printf ${Qt}`]}function er(){let e=[process.platform,process.env.XENO_BWRAP_PATH??"",process.env.PATH??""].join("\0");if(st?.key===e)return{...st.capability};let t;if(process.platform!=="linux")t={available:!1,reason:"The bubblewrap process-hardening profile can only be probed on a Linux host."};else{let r=Nn();if(!r)t={available:!1,reason:"bubblewrap is not installed or is not executable."};else{let n=(0,ct.spawnSync)(r,["--version"],{encoding:"utf8",timeout:Yt}),o=(0,ct.spawnSync)(r,kn(),{encoding:"utf8",timeout:Yt,env:process.env}),i=n.status===0?n.stdout.trim():void 0;if(o.status===0&&o.stdout===Qt)t={available:!0,executable:r,...i?{version:i}:{},reason:`An active ${i??"bubblewrap"} namespace profile passed its mount, PID, user, IPC, UTS, /proc, and /dev probe.`};else{let a=[o.error?.message,o.stderr.trim(),o.signal?`signal ${o.signal}`:void 0,o.status!==null?`exit ${o.status}`:void 0].filter(Boolean).join("; ");t={available:!1,executable:r,...i?{version:i}:{},reason:`bubblewrap was found but its active namespace profile failed${a?`: ${a}`:"."}`}}}}return st={key:e,capability:t},{...t}}var le=require("node:crypto"),Me=require("node:fs"),rr=require("node:path"),dt="xeno.containment-certification.v1",tr=512*1024,Xn=744*60*60*1e3,nr=Object.freeze(["allowedFilesystemRead","allowedFilesystemWrite","outsideFilesystemReadDenied","outsideFilesystemWriteDenied","unlistedFilesystemReadDenied","unlistedFilesystemWriteDenied","symlinkEscapeDenied","networkDefaultDeny","environmentSecretsExcluded","childProcessPolicyInherited","standardCommandLaunch","processTreeCleanup","timeoutEnforced","hostPolicyRecoveryClean","uiRestrictionsEnforced"]),I=class extends Error{constructor(t){super(`CONTAINMENT_CERTIFICATION_INVALID: ${t}`),this.name="ContainmentCertificationError"}};function Dn(e){let t={...e};return delete t.signature,Buffer.from(JSON.stringify(ut(t)),"utf8")}function or(e,t,r=new Date){if(!(0,rr.isAbsolute)(e.manifestPath))throw new I("manifestPath must be absolute");Ee(e.candidateSha256,"candidateSha256");let n=(0,Me.statSync)(e.manifestPath);if(!n.isFile())throw new I("manifestPath must reference a regular file");if(n.size<=0||n.size>tr)throw new I(`manifest size must be between 1 and ${tr} bytes`);let o=(0,Me.readFileSync)(e.manifestPath),i;try{i=JSON.parse(o.toString("utf8"))}catch{throw new I("manifest is not valid JSON")}let a=Ln(i);if(e.expectedCertificationId&&a.certificationId!==e.expectedCertificationId)throw new I("certificationId does not match the host binding");if(a.candidate.sha256.toLowerCase()!==e.candidateSha256.toLowerCase())throw new I("candidate digest does not match the running candidate binding");if(a.platform.os!==t.platform||a.platform.arch!==t.arch)throw new I("certification platform or architecture does not match this host");if(a.adapter.name!==t.name||a.adapter.version!==t.version||a.adapter.backend!==t.backend||a.adapter.isolationTier!==t.isolationTier||a.adapter.nativeBinarySha256.toLowerCase()!==t.nativeBinarySha256.toLowerCase())throw new I("certified adapter identity does not match the installed native adapter");let s=lt(a.issuedAt,"issuedAt"),c=lt(a.expiresAt,"expiresAt");if(c<=s)throw new I("expiresAt must be later than issuedAt");if(c-s>Xn)throw new I("certification lifetime exceeds 31 days");if(r.getTime()<s-5*6e4)throw new I("certification is not active yet");if(r.getTime()>=c)throw new I("certification has expired");for(let A of nr)if(a.conformance.checks[A]!==!0)throw new I(`required conformance check did not pass: ${A}`);if(!a.approvals.some(A=>A.role==="security-reviewer"&&A.subject!==a.issuedBy))throw new I("an independent security-reviewer approval is required");let d=e.trustedPublicKeys[a.signature.keyId];if(!d)throw new I("signature key is not trusted by this host");let y;try{y=Buffer.from(a.signature.value,"base64")}catch{throw new I("signature is not valid base64")}if(y.length!==64)throw new I("Ed25519 signature must be 64 bytes");let g=!1;try{g=(0,le.verify)(null,Dn(a),(0,le.createPublicKey)(d),y)}catch{throw new I("signature key or value is invalid")}if(!g)throw new I("signature verification failed");return{manifest:a,manifestSha256:(0,le.createHash)("sha256").update(o).digest("hex")}}function Ln(e){let t=Y(e,"manifest");if(t.schemaVersion!==dt)throw new I(`schemaVersion must be ${dt}`);let r=b(t.certificationId,"certificationId"),n=Y(t.candidate,"candidate"),o=Y(t.adapter,"adapter"),i=Y(t.platform,"platform"),a=Y(t.conformance,"conformance"),s=Y(a.checks,"conformance.checks"),c=Y(t.signature,"signature"),d=t.approvals;if(!Array.isArray(d)||d.length===0)throw new I("approvals must contain at least one approval");let y=d.map((k,w)=>{let j=Y(k,`approvals[${w}]`),ye=b(j.role,`approvals[${w}].role`);if(ye!=="security-reviewer"&&ye!=="release-reviewer")throw new I(`approvals[${w}].role is invalid`);let De=ye;lt(b(j.approvedAt,`approvals[${w}].approvedAt`),`approvals[${w}].approvedAt`);let be=b(j.approvalSha256,`approvals[${w}].approvalSha256`);return Ee(be,`approvals[${w}].approvalSha256`),{subject:b(j.subject,`approvals[${w}].subject`),role:De,approvedAt:j.approvedAt,approvalArtifactId:b(j.approvalArtifactId,`approvals[${w}].approvalArtifactId`),approvalSha256:be}}),g=b(o.backend,"adapter.backend");if(g!=="processcontainer"&&g!=="bubblewrap"&&g!=="seatbelt")throw new I("adapter.backend is invalid");let A=b(i.os,"platform.os"),m=b(i.arch,"platform.arch");if(b(c.algorithm,"signature.algorithm")!=="ed25519")throw new I("signature.algorithm must be ed25519");let v={};for(let k of nr){if(s[k]!==!0)throw new I(`conformance.checks.${k} must be true`);v[k]=!0}let T=b(o.nativeBinarySha256,"adapter.nativeBinarySha256"),U=b(n.sha256,"candidate.sha256"),L=b(a.reportSha256,"conformance.reportSha256");if(Ee(T,"adapter.nativeBinarySha256"),Ee(U,"candidate.sha256"),Ee(L,"conformance.reportSha256"),a.passed!==!0)throw new I("conformance.passed must be true");return{schemaVersion:dt,certificationId:r,candidate:{product:b(n.product,"candidate.product"),version:b(n.version,"candidate.version"),sha256:U},adapter:{name:o.name==="microsoft-mxc"?"microsoft-mxc":Mn(),version:b(o.version,"adapter.version"),backend:g,isolationTier:b(o.isolationTier,"adapter.isolationTier"),nativeBinarySha256:T},platform:{os:A,arch:m},conformance:{reportArtifactId:b(a.reportArtifactId,"conformance.reportArtifactId"),reportSha256:L,passed:!0,checks:v},issuedAt:b(t.issuedAt,"issuedAt"),expiresAt:b(t.expiresAt,"expiresAt"),issuedBy:b(t.issuedBy,"issuedBy"),approvals:y,signature:{algorithm:"ed25519",keyId:b(c.keyId,"signature.keyId"),value:b(c.value,"signature.value")}}}function Mn(){throw new I("adapter.name must be microsoft-mxc")}function Y(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new I(`${t} must be an object`);return e}function b(e,t){if(typeof e!="string"||e.trim().length===0)throw new I(`${t} must be a non-empty string`);return e}function Ee(e,t){if(!/^[a-f0-9]{64}$/i.test(e))throw new I(`${t} must be a SHA-256 hex digest`)}function lt(e,t){let r=Date.parse(e);if(!Number.isFinite(r))throw new I(`${t} must be an ISO timestamp`);return r}function ut(e){return Array.isArray(e)?e.map(ut):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ut(r)])):e}var te=require("node:crypto"),h=require("node:fs"),sr=require("node:os"),P=require("node:path"),mt=require("node:child_process"),cr=require("node:url");var ir="microsoft-mxc",ve="0.7.0";var Un="@microsoft/mxc-sdk",$n="sha512-EWhz2pKkcPluZHAOI1yneV+JK0NO/3hdh7nABBb0x4PjyUWMeSWPTBAjtIu+BhtMYOqlaijSPZMZ0Hs/J4ZL4A==",Ua=10*6e4,Vn=Object.freeze({"win32-x64-wxc-exec.exe":"db0a3422be9e1b396cc1b2547c70ff16b27412438a31c10a45abf370cac86ae2","win32-arm64-wxc-exec.exe":"e430d0e4f44f616e91db684f8d825a6dc93e06a1262b8d00bcaac7522a317aab","linux-x64-lxc-exec":"1efe3f817f5ae9ba9f9f2fd59142e79b2dde7a4dd024576b0ddb635fc87edeb5","linux-arm64-lxc-exec":"fdc00ccecf362ae3ddd8ccad93fd7c8b5b1f03c68897ab05ef1c9f1d327ea3fe","darwin-arm64-mxc-exec-mac":"77c07a86f483ed91dd5be290cd77878ac0c56fe113cdb8c764e7e5201c744ad2"}),$a=Object.freeze({"win32-x64-wxc-host-prep.exe":"531fb3cdb4b0c964908fd71b71d40961417afb399cbab72f92a25e95309a6416","win32-arm64-wxc-host-prep.exe":"3ef702332286a39153fc259310b5021e3de3c191751d7522684f6475f73af5ef"});function Bn(e){return e.some(t=>t.includes("wxc-host-prep prepare-system-drive")||t.includes("wxc-host-prep prepare-null-device"))}function Fn(e,t){if(e!=="win32"&&e!=="linux"&&e!=="darwin"||t!=="x64"&&t!=="arm64"||e==="darwin"&&t!=="arm64")return;let r=e==="win32"?"wxc-exec.exe":e==="darwin"?"mxc-exec-mac":"lxc-exec",n=Vn[`${e}-${t}-${r}`];return n?{platform:e,arch:t,binaryName:r,sha256:n}:void 0}var pt;function dr(e={}){if(pt&&!e.refresh)return ar(pt);let t=jn();return pt=t,ar(t)}function jn(){let e=process.platform,t=process.arch,r=Fn(e,t),n=!!r,o=Hn();if(!o)return n?x(`reviewed MXC ${ve} native assets are not installed`,!1,!0):x(ft(e,t),!1,!1);let i=(0,P.dirname)(o);if(!n)return x(ft(e,t),!0,!1,{packageRoot:i});let a="";try{let A=JSON.parse((0,h.readFileSync)(o,"utf8"));if(a=String(A.version??""),A.sourcePackage?.name!==Un||A.sourcePackage.version!==ve||A.sourcePackage.integrity!==$n)return x("MXC native asset provenance metadata is invalid",!0,!0,{packageRoot:i})}catch{return x("MXC package metadata is unreadable",!0,!0,{packageRoot:i})}if(a!==ve)return x(`MXC version ${a||"unknown"} is installed; XENO requires exactly ${ve}`,!0,!0,{packageRoot:i});if(!r)return x(ft(e,t),!0,!1,{packageRoot:i});let s=(0,P.join)(i,"bin",t,r.binaryName);if(!(0,h.existsSync)(s)||!(0,h.statSync)(s).isFile())return x(`MXC native binary is missing: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a});let c=s;try{c=Gn(s,r)}catch(A){return x(`MXC packaged native binary could not be materialized: ${A instanceof Error?A.message:String(A)}`,!0,!0,{packageRoot:i,version:a})}if(e!=="win32")try{(0,h.accessSync)(c,h.constants.X_OK)}catch{return x(`MXC native binary is not executable: ${r.binaryName}`,!0,!0,{packageRoot:i,version:a})}let d=(0,te.createHash)("sha256").update((0,h.readFileSync)(c)).digest("hex"),y=r.sha256;if(!y||d!==y)return x(`MXC native binary digest is not trusted for ${e}/${t}`,!0,!0,{packageRoot:i,version:a});if(e==="win32"){let A=(0,mt.spawnSync)(c,["--probe"],{encoding:"utf8",timeout:5e3,windowsHide:!0});if(A.error||A.status!==0)return x(`MXC native probe failed: ${A.error?.message??(A.stderr.trim()||`exit ${A.status}`)}`,!0,!0,{packageRoot:i,version:a});let m;try{m=JSON.parse(A.stdout)}catch{return x("MXC native probe returned invalid JSON",!0,!0,{packageRoot:i,version:a})}let N=typeof m.tier=="string"?m.tier:"unknown",v=Array.isArray(m.warnings)?m.warnings.filter(L=>typeof L=="string"):[],T=m.probes&&typeof m.probes=="object"?m.probes:void 0,U=T?.uiCapabilities&&typeof T.uiCapabilities=="object"?Object.fromEntries(Object.entries(T.uiCapabilities).filter(L=>typeof L[1]=="boolean")):void 0;return{installed:!0,supported:!0,available:!0,name:ir,version:a,packageRoot:i,nativeBinaryPath:c,nativeBinarySha256:d,backend:"processcontainer",isolationTier:N,platform:e,arch:t,warnings:v,needsHostPreparation:Bn(v),reason:`MXC ${a} processcontainer is installed (${N}).`,...U?{uiCapabilities:U}:{}}}if(e==="linux"){let A=(0,mt.spawnSync)("bwrap",["--version"],{encoding:"utf8",timeout:5e3});if(A.error||A.status!==0)return x("MXC requires bubblewrap on PATH for the stable Linux process adapter",!0,!0,{packageRoot:i,version:a})}let g=e==="darwin"?"seatbelt":"bubblewrap";return{installed:!0,supported:!0,available:!0,name:ir,version:a,packageRoot:i,nativeBinaryPath:c,nativeBinarySha256:d,backend:g,isolationTier:g,platform:e,arch:t,warnings:[],needsHostPreparation:!1,reason:`MXC ${a} ${g} adapter is installed.`}}function Hn(){let e=process.resourcesPath,t=process.env.XENO_MXC_ASSET_ROOT?.trim(),r=typeof __dirname=="string"?__dirname:(0,P.dirname)((0,cr.fileURLToPath)(void 0)),n=[...e&&(0,P.isAbsolute)(e)?[(0,P.join)(e,"mxc","package.json")]:[],...t&&(0,P.isAbsolute)(t)?[(0,P.join)(t,"package.json")]:[],(0,P.join)(r,"..","native","mxc","package.json"),(0,P.join)(r,"..","..","native","mxc","package.json")];for(let o of n){if(!(0,h.existsSync)(o))continue;let i=(0,h.lstatSync)(o);if(!(!i.isFile()||i.isSymbolicLink()))return(0,h.realpathSync)(o)}}function Gn(e,t){if(!!!process.pkg)return e;let n=(0,P.join)((0,sr.tmpdir)(),"xeno-mxc",ve,t.sha256);(0,h.mkdirSync)(n,{recursive:!0,mode:448});let o=(0,P.join)(n,t.binaryName);if((0,h.existsSync)(o)){let c=(0,h.lstatSync)(o);if(!c.isFile()||c.isSymbolicLink())throw new Error("materialized MXC path is not a regular file");if((0,te.createHash)("sha256").update((0,h.readFileSync)(o)).digest("hex")!==t.sha256)throw new Error("materialized MXC binary digest is invalid");return process.platform!=="win32"&&(0,h.chmodSync)(o,448),o}let i=(0,h.readFileSync)(e);if((0,te.createHash)("sha256").update(i).digest("hex")!==t.sha256)throw new Error("embedded MXC binary digest is invalid");let s=`${o}.${process.pid}.${(0,te.randomUUID)()}.tmp`;(0,h.writeFileSync)(s,i,{flag:"wx",mode:448});try{(0,h.renameSync)(s,o)}catch(c){try{(0,h.unlinkSync)(s)}catch{}if(!(0,h.existsSync)(o))throw c;let d=(0,h.lstatSync)(o);if((d.isFile()&&!d.isSymbolicLink()?(0,te.createHash)("sha256").update((0,h.readFileSync)(o)).digest("hex"):"")!==t.sha256)throw c}return process.platform!=="win32"&&(0,h.chmodSync)(o,448),o}function ft(e,t){return e!=="win32"&&e!=="linux"&&e!=="darwin"?`MXC has no stable process adapter for ${e}/${t}`:t!=="x64"&&t!=="arm64"?`MXC does not ship a ${e}/${t} native adapter`:"MXC Seatbelt currently ships for macOS ARM64 only"}function x(e,t=!1,r=!1,n={}){return{...n,installed:t,supported:r,available:!1,warnings:[],needsHostPreparation:!1,reason:e}}function ar(e){return{...e,warnings:[...e.warnings],...e.uiCapabilities?{uiCapabilities:{...e.uiCapabilities}}:{}}}var re=class extends Error{code;constructor(t,r){super(`${t}: ${r}`),this.name="ExecutionSecurityError",this.code=t}},Wn=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),qn=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!0,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!0,environmentSanitization:!0}),zn=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0}),Jn=Object.freeze({policyEnforcement:!0,restrictedIdentity:!0,lowIntegrity:!1,processTreeControl:!0,filesystemIsolation:!0,networkIsolation:!0,inheritedHandleAllowlist:!0,environmentSanitization:!0}),gt=Object.freeze({policyEnforcement:!0,restrictedIdentity:!1,lowIntegrity:!1,processTreeControl:!1,filesystemIsolation:!1,networkIsolation:!1,inheritedHandleAllowlist:!1,environmentSanitization:!0});function Kn(e){let t=e?.executionLevel;if(e?.requireOsContainment&&t&&t!=="contained")throw new re("SECURITY_POLICY_INVALID","requireOsContainment is a strict contained-mode compatibility flag and conflicts with the requested executionLevel.");return t??(e?.requireOsContainment?"contained":"policy-only")}function Yn(e){return e?.trustMode??"trusted-workspace"}function lr(e,t=process.platform,r){if(e==="policy-only")return{available:!0,requestedLevel:e,effectiveLevel:"policy-only",adapter:"policy-enforcer",isolation:"policy-only",certified:!0,capabilities:{...Wn},limitations:["No restricted process identity.","No filesystem isolation.","No network isolation."],reason:"Policy and permission checks are active without operating-system process isolation."};if(e==="process-hardened"){if(t==="win32"&&Kt())return{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"windows-restricted-token-job",isolation:"process-hardening",certified:!0,capabilities:{...qn},limitations:["Filesystem reads are not isolated.","Network access is not isolated.","This mode is not suitable for untrusted code."],reason:"Windows restricted-token, low-integrity, explicit-handle, and kill-on-close Job Object process hardening is available."};if(t==="linux"){let o=er();return o.available?{available:!0,requestedLevel:e,effectiveLevel:"process-hardened",adapter:"linux-bubblewrap",isolation:"process-hardening",certified:!0,capabilities:{...zn},limitations:["Filesystem reads are not isolated; the host root is mounted read-only.","Network access is not isolated.","Inherited file descriptors are limited by the host launcher rather than an adapter-owned allowlist.","This mode is not suitable for untrusted code."],reason:`linux-bubblewrap is available: ${o.reason}`}:{available:!1,requestedLevel:e,effectiveLevel:"unavailable",adapter:"unavailable",isolation:"none",certified:!1,capabilities:{...gt},limitations:["No certified process-hardening adapter is available for this platform."],reason:`Linux bubblewrap process hardening is unavailable: ${o.reason}`}}return{available:!1,requestedLevel:e,effectiveLevel:"unavailable",adapter:"unavailable",isolation:"none",certified:!1,capabilities:{...gt},limitations:["No certified process-hardening adapter is available for this platform."],reason:t==="win32"?"The Windows .NET Framework C# compiler is unavailable, so the restricted-token launcher cannot start.":`No certified process-hardened adapter is implemented for ${t}.`}}if(t!==process.platform)return Ue(t,`Native containment for ${t} cannot be certified from a ${process.platform} host.`);let n=dr();if(!n.available||!n.name||!n.version||!n.backend||!n.isolationTier||!n.nativeBinarySha256||!n.platform||!n.arch)return Ue(t,n.reason,n);if(!r)return Ue(t,`${n.reason} A signed candidate-bound XENO containment certification was not supplied.`,n);try{let o={name:n.name,version:n.version,backend:n.backend,isolationTier:n.isolationTier,nativeBinarySha256:n.nativeBinarySha256,platform:n.platform,arch:n.arch},i=or(r,o);return{available:!0,requestedLevel:e,effectiveLevel:"contained",adapter:"microsoft-mxc",isolation:"filesystem-network",certified:!0,capabilities:{...Jn},limitations:[...n.warnings],reason:`${n.reason} Signed XENO certification ${i.manifest.certificationId} is valid for this candidate.`,adapterVersion:n.version,backend:n.backend,isolationTier:n.isolationTier,nativeBinarySha256:n.nativeBinarySha256,certificationArtifactId:i.manifest.certificationId,certificationManifestSha256:i.manifestSha256,needsHostPreparation:n.needsHostPreparation}}catch(o){return Ue(t,o instanceof Error?o.message:"Containment certification validation failed.",n)}}function Zn(e,t){if(Yn(e)==="untrusted"&&t!=="contained")throw new re("UNTRUSTED_EXECUTION_DISABLED","Untrusted execution requires certified contained mode; policy-only and process-hardened modes are trusted-workspace features.")}function Qn(e){let t=e.requestedLevel==="contained"?"CONTAINMENT_UNAVAILABLE":"PROCESS_HARDENING_UNAVAILABLE";return new re(t,e.reason)}function ur(e,t=process.platform){let r=Kn(e);Zn(e,r);let n=lr(r,t,e.containmentCertification);if(!n.available)throw Qn(n);if(r==="process-hardened"&&e.allowNetwork!==!0)throw new re("NETWORK_ISOLATION_UNAVAILABLE","Process-hardened execution cannot enforce network denial. Set allowNetwork=true explicitly for a trusted workspace or request certified contained mode.");if(r!=="policy-only"){let o=Q(e.workingDirectory??process.cwd()).canonicalPath,i=[...e.allowedDirectories,...e.temporaryDirectories??[]];if(!Jt(o,i))throw new re("SECURITY_POLICY_INVALID",`Secured process working directory is outside the canonical allowed directories: ${o}`)}return n}function Ue(e,t,r){let n=r?.available===!0;return{available:!1,requestedLevel:"contained",effectiveLevel:"unavailable",adapter:n?"microsoft-mxc":"unavailable",isolation:n?"filesystem-network":"none",certified:!1,capabilities:{...gt},limitations:["Contained mode remains fail-closed until a signed, candidate-bound XENO certification is valid.",...r?.warnings??[],...e==="win32"&&!n?["Windows restricted-token execution is process hardening only."]:[]],reason:t,...r?.version?{adapterVersion:r.version}:{},...r?.backend?{backend:r.backend}:{},...r?.isolationTier?{isolationTier:r.isolationTier}:{},...r?.nativeBinarySha256?{nativeBinarySha256:r.nativeBinarySha256}:{},...r?{needsHostPreparation:r.needsHostPreparation}:{}}}var Ar=1,S=class extends Error{constructor(r,n){super(n);this.code=r;this.name="XenoSecureExecutionContractError"}code};function hr(e){let t=e.platform??process.platform,r=e.policy.executionLevel??(e.policy.requireOsContainment?"contained":"policy-only"),n=e.adapterStatus??ur(e.policy,t);if(!n.available||n.effectiveLevel==="unavailable")throw new S("SECURITY_CONTRACT_UNAVAILABLE",n.reason);if(n.requestedLevel!==r||n.effectiveLevel!==r)throw new S("SECURITY_CONTRACT_INVALID","Execution adapter status does not match the requested security level");let i=(e.now??(()=>new Date().toISOString()))(),a=Se([...e.policy.allowedDirectories,...e.policy.temporaryDirectories??[],e.policy.workingDirectory??process.cwd()],e.policy.workingDirectory,t),s=Se(e.filesystem?.readRoots??a,e.policy.workingDirectory,t),c=e.profile.capabilities.permissionProfile==="read-only",d=c?[]:Se(e.filesystem?.writeRoots??a,e.policy.workingDirectory,t),y=c?[]:Se(e.filesystem?.executeRoots??a,e.policy.workingDirectory,t),g=Se(e.filesystem?.deniedRoots??e.policy.deniedDirectories??[],e.policy.workingDirectory,t),A=n.capabilities.filesystemIsolation?"os":"policy",m=n.capabilities.networkIsolation?"os":r==="process-hardened"?"none":"policy",N=r==="contained"?"deny":e.network?.default??(e.policy.allowNetwork?"allow":"deny"),v=m==="none";if(v&&(!e.policy.allowNetwork||N!=="allow"))throw new S("SECURITY_CONTRACT_INVALID","An adapter without network isolation requires explicit unrestricted-network acknowledgement");if(c&&(e.browser?.mode==="act"||e.computer?.mode==="act"||(e.secrets?.length??0)>0))throw new S("SECURITY_CONTRACT_INVALID","Read-only Agent Profiles cannot receive browser action, computer action, or secret projection authority");let T=e.certificationArtifactId??n.certificationArtifactId;if(e.certificationArtifactId&&n.certificationArtifactId&&e.certificationArtifactId!==n.certificationArtifactId)throw new S("SECURITY_CONTRACT_INVALID","Requested certification artifact does not match the adapter certification");if(r==="contained"&&!T)throw new S("SECURITY_CONTRACT_INVALID","Contained execution requires a candidate-bound certification artifact");let U=ue(e.environment?.deniedKeys??[]),L=new Set(U),k=Te(e.browser?.allowedDomains??[]),w=Te(e.browser?.readAllowedDomains??k),j=Te(e.browser?.actAllowedDomains??k),ye=Te([...k,...w,...j]),De={schemaVersion:Ar,contractId:e.contractId,createdAt:i,...e.expiresAt?{expiresAt:e.expiresAt}:{},identity:{...e.identity},requestedLevel:r,effectiveLevel:n.effectiveLevel,trustMode:e.policy.trustMode??"trusted-workspace",profile:{id:e.profile.profile.id,version:e.profile.profile.version,fingerprint:e.profile.fingerprint,permissionProfile:e.profile.capabilities.permissionProfile},filesystem:{enforcement:A,readRoots:s,writeRoots:d,executeRoots:y,deniedRoots:g},network:{enforcement:m,default:N,allowDestinations:pr(e.network?.allowDestinations??[]),denyDestinations:pr(e.network?.denyDestinations??[]),dns:e.network?.dns??((e.network?.allowDestinations?.length??0)>0||N==="allow"?"system":"disabled"),...e.network?.proxyUrl?{proxyUrl:e.network.proxyUrl}:{},downloads:e.network?.downloads??"deny",acknowledgedUnrestricted:v},process:{processTreeControl:n.capabilities.processTreeControl,cleanup:n.capabilities.processTreeControl?"kill-tree":"best-effort",inheritedHandleAllowlist:n.capabilities.inheritedHandleAllowlist,...oo(e.process)},environment:{inheritance:e.environment?.inheritance??"allowlist",allowedKeys:ue(e.environment?.allowedKeys??e.policy.containedEnvironmentAllowlist??[]).filter(bn=>!L.has(bn)),deniedKeys:U},secrets:no(e.secrets??[]),externalActions:{default:e.profile.capabilities.externalActions.default,overrides:{...e.profile.capabilities.externalActions.overrides},requireCurrentTurnApproval:ue(e.profile.capabilities.externalActions.requireCurrentTurnApproval),requireCapabilityLease:!0},browser:{mode:e.browser?.mode??"none",profile:e.browser?.profile??"ephemeral",allowedDomains:ye,readAllowedDomains:w,actAllowedDomains:j,deniedDomains:Te(e.browser?.deniedDomains??[]),allowedSchemes:to(e.browser?.allowedSchemes??["https"]),allowedPorts:ro(e.browser?.allowedPorts??[443]),redirectPolicy:e.browser?.redirectPolicy??"policy",allowLoopbackDevelopment:e.browser?.allowLoopbackDevelopment??!1,downloads:e.browser?.downloads??"deny",uploads:e.browser?.uploads??"deny",recording:e.browser?.recording??"disabled"},computer:{mode:e.computer?.mode??"none",allowedApplications:ue(e.computer?.allowedApplications??[]),sensitiveRegionRedaction:e.computer?.sensitiveRegionRedaction??!0,humanStopRequired:e.computer?.humanStopRequired??!0},capabilityLeaseIds:ue(e.capabilityLeaseIds??[]),adapter:{id:n.adapter,version:e.adapterVersion??n.adapterVersion??"1",platform:t,architecture:e.architecture??(0,gr.arch)(),certified:n.certified,...T?{certificationArtifactId:T}:{},capabilities:{...n.capabilities},limitations:[...n.limitations]},...e.auditEventIds?{auditEventIds:ue(e.auditEventIds)}:{}},be={...De,fingerprint:Ir(De)};return ht(be),be}function eo(e){let t=[];if(!e||typeof e!="object")return["Contract must be an object"];if(e.schemaVersion!==Ar&&t.push("Unsupported schemaVersion"),e.contractId?.trim()||t.push("contractId is required"),(!e.identity?.runId?.trim()||!e.identity?.agentId?.trim())&&t.push("runId and agentId are required"),fr(e.createdAt)||t.push("createdAt must be an ISO 8601 timestamp"),e.expiresAt&&(!fr(e.expiresAt)||Date.parse(e.expiresAt)<=Date.parse(e.createdAt))&&t.push("expiresAt must be later than createdAt"),e.requestedLevel!==e.effectiveLevel&&t.push("requestedLevel and effectiveLevel must match"),e.trustMode==="untrusted"&&e.effectiveLevel!=="contained"&&t.push("Untrusted execution requires contained mode"),e.effectiveLevel==="contained"&&(e.adapter.certified||t.push("Contained mode requires a certified adapter"),e.adapter.certificationArtifactId||t.push("Contained mode requires a certification artifact"),(!e.adapter.capabilities.filesystemIsolation||e.filesystem.enforcement!=="os")&&t.push("Contained mode requires OS filesystem isolation"),(!e.adapter.capabilities.networkIsolation||e.network.enforcement!=="os")&&t.push("Contained mode requires OS network isolation"),e.network.default!=="deny"&&t.push("Contained networking must default deny")),e.network.enforcement==="none"&&!e.network.acknowledgedUnrestricted&&t.push("Unrestricted networking must be explicitly acknowledged"),e.filesystem.writeRoots.length>0&&e.profile.permissionProfile==="read-only"&&t.push("Read-only profiles cannot receive write roots"),(!Array.isArray(e.browser.readAllowedDomains)||!Array.isArray(e.browser.actAllowedDomains))&&t.push("Browser read/action domain policies are required"),(!Array.isArray(e.browser.allowedSchemes)||e.browser.allowedSchemes.some(r=>r!=="http"&&r!=="https"))&&t.push("Browser allowed schemes are invalid"),(!Array.isArray(e.browser.allowedPorts)||e.browser.allowedPorts.some(r=>!Number.isInteger(r)||r<1||r>65535))&&t.push("Browser allowed ports are invalid"),e.secrets.some(r=>!r.secretId.trim())&&t.push("Secret projections require non-empty secret IDs"),new Set(e.secrets.map(r=>r.secretId)).size!==e.secrets.length&&t.push("Secret IDs must be unique"),new Set(e.capabilityLeaseIds).size!==e.capabilityLeaseIds.length&&t.push("Capability lease IDs must be unique"),/^[a-f0-9]{64}$/.test(e.profile.fingerprint)||t.push("Profile fingerprint is invalid"),!/^[a-f0-9]{64}$/.test(e.fingerprint))t.push("Contract fingerprint is invalid");else{let r={...e};delete r.fingerprint,Ir(r)!==e.fingerprint&&t.push("Contract fingerprint does not match content")}return t}function ht(e){let t=eo(e);if(t.length>0){let r=t.includes("Contract fingerprint does not match content");throw new S(r?"SECURITY_CONTRACT_FINGERPRINT_MISMATCH":"SECURITY_CONTRACT_INVALID",t.join("; "))}}function Ir(e){return(0,mr.createHash)("sha256").update(JSON.stringify(At(e))).digest("hex")}function ue(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort().map(t=>t)}function Se(e,t,r){return[...new Set(e.map(n=>Q(n,{baseDirectory:t,platform:r}).canonicalPath))].sort((n,o)=>n.localeCompare(o))}function pr(e){let t=new Map;for(let r of e){if(!r.host?.trim())throw new S("SECURITY_CONTRACT_INVALID","Network destinations require a host");if(r.host.includes("*"))throw new S("SECURITY_CONTRACT_INVALID","Network destinations cannot contain wildcards");if(r.port!==void 0&&(!Number.isInteger(r.port)||r.port<1||r.port>65535))throw new S("SECURITY_CONTRACT_INVALID","Network destination port is invalid");let n={...r,host:r.host.trim().toLowerCase().replace(/\.$/,"")};t.set(`${n.scheme??""}:${n.host}:${n.port??""}`,n)}return[...t.values()].sort((r,n)=>r.host.localeCompare(n.host)||(r.port??0)-(n.port??0))}function Te(e){let t=new Set;for(let r of e){let n=r.trim().toLowerCase().replace(/\.$/,"");if(!n)continue;if(n.includes("*")||n.includes("://")||n.includes("/")||n.includes(":"))throw new S("SECURITY_CONTRACT_INVALID",`Browser domain rule is invalid: ${r}`);let o=n.startsWith(".")?n.slice(1):n;if(!/^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/.test(o)&&o!=="localhost")throw new S("SECURITY_CONTRACT_INVALID",`Browser domain rule is invalid: ${r}`);t.add(n)}return[...t].sort((r,n)=>r.localeCompare(n))}function to(e){for(let t of e)if(t!=="http"&&t!=="https")throw new S("SECURITY_CONTRACT_INVALID",`Browser scheme is invalid: ${t}`);return[...new Set(e)].sort()}function ro(e){for(let t of e)if(!Number.isInteger(t)||t<1||t>65535)throw new S("SECURITY_CONTRACT_INVALID",`Browser port is invalid: ${t}`);return[...new Set(e)].sort((t,r)=>t-r)}function no(e){let t=new Map;for(let r of e){if(!r.secretId?.trim())throw new S("SECURITY_CONTRACT_INVALID","Secret projections require an ID");if(t.has(r.secretId))throw new S("SECURITY_CONTRACT_INVALID",`Secret ${r.secretId} is projected more than once`);t.set(r.secretId,{...r})}return[...t.values()].sort((r,n)=>r.secretId.localeCompare(n.secretId))}function oo(e){let t={};for(let[r,n]of Object.entries(e??{})){if(!Number.isSafeInteger(n)||Number(n)<1)throw new S("SECURITY_CONTRACT_INVALID",`${r} must be a positive safe integer`);Object.assign(t,{[r]:n})}return t}function At(e){return Array.isArray(e)?e.map(At):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,At(r)]))}function fr(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}var io=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,yr=1048576;function yt(e){(!e||typeof e!="object")&&H("Automation request must be an object"),e.protocolVersion!==1&&H("Unsupported automation protocol version"),pe(e.operationId,"operationId"),pe(e.idempotencyKey,"idempotencyKey"),pe(e.capabilityLeaseId,"capabilityLeaseId"),pe(e.governingToolName,"governingToolName"),(!Number.isSafeInteger(e.expectedLeaseVersion)||e.expectedLeaseVersion<1)&&H("expectedLeaseVersion must be a positive safe integer"),Sr(e.requestedAt)||H("requestedAt must be an ISO 8601 timestamp"),Le(e.operation)||H(`Unsupported automation operation: ${e.operation}`),(!e.parameters||typeof e.parameters!="object"||Array.isArray(e.parameters))&&H("parameters must be a JSON object");let t;try{t=Buffer.byteLength(JSON.stringify(e.parameters),"utf8")}catch(r){throw new l("AUTOMATION_REQUEST_INVALID","parameters must be serializable JSON",void 0,{cause:r})}if(t>yr&&H(`parameters exceed ${yr} bytes`),pe(e.identity?.runId,"identity.runId"),pe(e.identity?.agentId,"identity.agentId"),ht(e.executionContract),ao(e),!e.executionContract.capabilityLeaseIds.includes(e.capabilityLeaseId))throw new l("AUTOMATION_CONTRACT_INVALID",`Capability lease ${e.capabilityLeaseId} is not bound to the execution contract`);if(e.executionContract.expiresAt&&Date.parse(e.executionContract.expiresAt)<=Date.now())throw new l("AUTOMATION_CONTRACT_EXPIRED","Execution contract has expired")}function Ce(e){(!e||typeof e!="object")&&$("Adapter manifest must be an object"),e.protocolVersion!==1&&$("Adapter protocol version is unsupported"),$e(e.adapterId,"adapterId"),$e(e.adapterVersion,"adapterVersion"),$e(e.platform,"platform"),$e(e.architecture,"architecture"),e.targetBinding!=="atomic-preflight"&&$("Adapter must implement atomic preflight target binding"),(!Array.isArray(e.operations)||e.operations.length===0)&&$("Adapter must declare operations");let t=new Set;for(let r of e.operations)Le(r)||$(`Adapter declares unknown operation ${r}`),t.has(r)&&$(`Adapter declares duplicate operation ${r}`),t.add(r);e.certified&&!e.certificationArtifactId&&$("A certified automation adapter requires a certification artifact"),Array.isArray(e.limitations)||$("Adapter limitations must be an array"),e.operations.some(r=>r.startsWith("browser."))&&(!e.policyEnforcement.domain||!e.policyEnforcement.scheme||!e.policyEnforcement.port)&&$("Browser adapters must enforce domain, scheme, and port policy"),e.operations.some(r=>r.startsWith("computer."))&&!e.supports.immediateStop&&$("Computer-use adapters must support immediate stop")}function Ve(e,t,r){let n=X(e.operation);if(!t.operations.includes(e.operation))throw new l("AUTOMATION_OPERATION_UNSUPPORTED",`Adapter ${t.adapterId} does not support ${e.operation}`);if(n.surface==="browser"){let o=e.executionContract.browser.mode;if(o==="none"||n.effect==="act"&&o!=="act")throw new l("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(so(e,r,n.effect==="act"),e.operation==="browser.download"&&e.executionContract.browser.downloads==="deny")throw new l("AUTOMATION_POLICY_DENIED","Execution contract denies browser downloads");if(e.operation==="browser.upload"&&e.executionContract.browser.uploads==="deny")throw new l("AUTOMATION_POLICY_DENIED","Execution contract denies browser uploads");if(e.operation.startsWith("browser.record.")&&e.executionContract.browser.recording!=="bounded")throw new l("AUTOMATION_POLICY_DENIED","Execution contract denies browser recording")}else{let o=e.executionContract.computer.mode;if(o==="none"||n.effect==="act"&&o!=="act")throw new l("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);let i=e.executionContract.computer.allowedApplications,a=e.operation==="computer.launch"?lo(e):r.applicationId??e.declaredTarget?.applicationId;if((e.operation==="computer.launch"||i.length>0)&&(!a||!i.includes(a)))throw new l("AUTOMATION_POLICY_DENIED",`Application ${a??"<unknown>"} is not allowed`)}}function bt(e,t){let r=X(e.operation),n=r.surface==="browser"?r.effect==="act"?"browser-act":"browser-read":r.effect==="act"?"computer-act":"computer-observe";return{subject:{runId:e.identity.runId,agentId:e.identity.agentId,...e.identity.turnId?{turnId:e.identity.turnId}:{},toolName:e.governingToolName,operationId:e.operationId},kind:n,operation:e.operation,...br(e,t)?{resource:br(e,t)}:{},...Er(t)?{destination:Er(t)}:{}}}function br(e,t){return e.declaredTarget?.resource??co(t)}function wt(e){let t=X(e.operation).evidence,r=e.evidencePolicy??{},n=It(t.before,r.before),o=It(t.after,r.after),i=It(t.recording,r.recording),a=r.retainUntil;return a&&!Sr(a)&&H("evidencePolicy.retainUntil must be an ISO 8601 timestamp"),{before:n,after:o,recording:i,sensitivity:r.sensitivity??"confidential",...a?{retainUntil:a}:{},...r.legalHold!==void 0?{legalHold:r.legalHold}:{}}}function ao(e){let t=e.executionContract.identity,r=["runId","agentId","sessionId","turnId","taskId","workspaceId"];for(let n of r){let o=t[n],i=e.identity[n];if(o!==void 0&&o!==i)throw new l("AUTOMATION_IDENTITY_MISMATCH",`Automation identity ${n} does not match the execution contract`)}}function so(e,t,r){let n=t.url??t.origin??e.declaredTarget?.url??e.declaredTarget?.origin;if(!n){if(["browser.tabs.list","browser.wait"].includes(e.operation))return;throw new l("AUTOMATION_PREFLIGHT_INVALID","Browser preflight did not bind an effective URL")}let o;try{o=new URL(n)}catch{throw new l("AUTOMATION_POLICY_DENIED","Browser target URL is invalid")}if(o.username||o.password)throw new l("AUTOMATION_POLICY_DENIED","Browser target URLs cannot contain credentials");let i=o.protocol.replace(/:$/,"");i!=="http"&&i!=="https"&&ne(`Browser scheme ${o.protocol} is not supported`);let a=i,s=o.hostname.toLowerCase().replace(/\.$/,""),c=o.port?Number(o.port):a==="https"?443:80,d=e.executionContract.browser,y=uo(s);if(vr(s,d.deniedDomains)&&ne(`Browser domain ${s} is denied`),wr(o,e.executionContract.network.denyDestinations)&&ne(`Network policy explicitly denies ${a}://${s}:${c}`),y&&d.allowLoopbackDevelopment)return;d.allowedSchemes.includes(a)||ne(`Browser scheme ${o.protocol} is not allowed`),d.allowedPorts.includes(c)||ne(`Browser port ${c} is not allowed`);let g=r?d.actAllowedDomains:d.readAllowedDomains;vr(s,g)||ne(`Browser domain ${s} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&(wr(o,e.executionContract.network.allowDestinations)||ne(`Network policy does not allow ${a}://${s}:${c}`))}function wr(e,t){let r=e.protocol.replace(/:$/,""),n=e.hostname.toLowerCase().replace(/\.$/,""),o=e.port?Number(e.port):r==="https"?443:80;return t.some(i=>{let a=i.scheme?.replace(/^custom:/,"");return i.host===n&&(i.port===void 0||i.port===o)&&(a===void 0||a===r)})}function co(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function Er(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function lo(e){let t=e.parameters.target,r=t&&typeof t=="object"&&!Array.isArray(t)?t.app_id:void 0,n=e.parameters.applicationId??r??e.declaredTarget?.applicationId;return typeof n=="string"&&n.length>0?n:void 0}function vr(e,t){return t.some(r=>{let n=r.toLowerCase();if(n.startsWith(".")){let o=n.slice(1);return e===o||e.endsWith(`.${o}`)}return e===n})}function uo(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function It(e,t){let r={disabled:0,optional:1,required:2};return!t||r[t]<=r[e]?e:t}function pe(e,t){(typeof e!="string"||!io.test(e))&&H(`${t} is invalid`)}function $e(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&$(`${t} is invalid`)}function Sr(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}function ne(e){throw new l("AUTOMATION_POLICY_DENIED",e)}function H(e){throw new l("AUTOMATION_REQUEST_INVALID",e)}function $(e){throw new l("AUTOMATION_OPERATION_UNSUPPORTED",e)}var Lr=require("node:crypto");var Tr=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation"],Cr=["draft","pending_review","approved","rejected","superseded","archived"],Pr=["public","internal","confidential","restricted"],Rr=["agent","tool","user","system","integration"],_r=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],xr=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var Et=require("node:buffer");var Or=require("node:crypto");function oe(e){return{algorithm:"sha256",value:(0,Or.createHash)("sha256").update(e).digest("hex")}}var po=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Be="custom:";function Pe(e,t=Be){return e.startsWith(t)?po.test(e.slice(t.length)):!1}var fe=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,r){super(t),this.name="XenoArtifactValidationError",this.issues=r.map(n=>({...n}))}},vt=class extends Error{constructor(r,n){super(`Artifact state cannot transition from ${r} to ${n}`);this.fromState=r;this.toState=n;this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},fo={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},mo="[\\u0000-\\u001f\\u007f]",go=new RegExp(mo),Nr=/^[a-f0-9]{64}$/,Ao=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ho=new Set(Cr),Io=new Set(Pr),yo=new Set(Rr),bo=new Set(Tr),wo=new Set(_r),Eo=new Set(xr);function u(e,t,r,n){e.push({path:t,code:r,message:n})}function f(e,t,r,n=1024){return typeof e!="string"||e.trim().length===0?(u(r,t,"required_string","Value must be a non-empty string"),!1):(e.length>n&&u(r,t,"string_too_long",`Value must not exceed ${n} characters`),go.test(e)&&u(r,t,"control_character","Value must not contain control characters"),!0)}function Re(e,t,r){e!==void 0&&(!Number.isFinite(Date.parse(e))||!e.includes("T"))&&u(r,t,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function ie(e,t,r,n){typeof e=="string"&&e.startsWith(t)&&(Pe(e,t)||u(n,r,"invalid_custom_name",`Custom name after ${t} is invalid`))}function kr(e,t,r){if(!e||typeof e!="object"){u(r,t,"missing_actor","Actor is required");return}f(e.kind,`${t}.kind`,r,64),yo.has(e.kind)||u(r,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),f(e.id,`${t}.id`,r,512),e?.displayName!==void 0&&f(e.displayName,`${t}.displayName`,r,512),e?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.profileFingerprint)&&u(r,`${t}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function St(e,t,r){if(!e||typeof e!="object"){u(r,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":f(e.path,`${t}.path`,r,4096);break;case"source-line":f(e.path,`${t}.path`,r,4096),(!Number.isInteger(e.startLine)||e.startLine<1)&&u(r,`${t}.startLine`,"invalid_line","startLine must be a positive integer"),e.endLine!==void 0&&(!Number.isInteger(e.endLine)||e.endLine<e.startLine)&&u(r,`${t}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":f(e.path,`${t}.path`,r,4096),f(e.hunkId,`${t}.hunkId`,r,512);break;case"symbol":f(e.path,`${t}.path`,r,4096),f(e.symbol,`${t}.symbol`,r,1024);break;case"dom-node":f(e.pageId,`${t}.pageId`,r,512),!e.selector&&!e.accessibilityId&&!e.snapshotArtifactId&&u(r,t,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":f(e.recordingArtifactId,`${t}.recordingArtifactId`,r,512),(!Number.isFinite(e.startMs)||e.startMs<0)&&u(r,`${t}.startMs`,"invalid_time","startMs must be a non-negative finite number"),e.endMs!==void 0&&(!Number.isFinite(e.endMs)||e.endMs<e.startMs)&&u(r,`${t}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":f(e.mediaArtifactId,`${t}.mediaArtifactId`,r,512),[e.x,e.y,e.width,e.height].every(Number.isFinite)?(e.width<=0||e.height<=0)&&u(r,t,"invalid_region_size","Region width and height must be positive"):u(r,t,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":f(e.artifactId,`${t}.artifactId`,r,512);break;default:typeof e.kind!="string"||!e.kind.startsWith("custom:")?u(r,`${t}.kind`,"unknown_anchor","Anchor kind is not supported"):ie(e.kind,"custom:",`${t}.kind`,r)}}function _e(e,t,r,n){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||u(r,t,"non_finite_number","JSON numbers must be finite");return}if(typeof e!="object"){u(r,t,"non_json_value","Value must be JSON-serializable");return}if(n.has(e)){u(r,t,"cyclic_value","Value must not contain cycles");return}if(n.add(e),Array.isArray(e))e.forEach((o,i)=>_e(o,`${t}[${i}]`,r,n));else for(let[o,i]of Object.entries(e))i===void 0?u(r,`${t}.${o}`,"undefined_value","Undefined is not valid JSON"):_e(i,`${t}.${o}`,r,n);n.delete(e)}}function vo(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_artifact",message:"Artifact must be an object"}];if(e.schemaVersion!==1&&u(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),f(e.artifactId,"artifactId",t,512),(!Number.isInteger(e.revision)||e.revision<1)&&u(t,"revision","invalid_revision","revision must be a positive integer"),f(e.kind,"kind",t,160),typeof e.kind=="string"&&!bo.has(e.kind)&&!e.kind.startsWith("custom:")&&u(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),ie(e.kind,"custom:","kind",t),f(e.title,"title",t,1024),e.description!==void 0&&f(e.description,"description",t,32768),f(e.state,"state",t,64),ho.has(e.state)||u(t,"state","unknown_state","Artifact state is not supported"),f(e.createdAt,"createdAt",t,128),Re(e.createdAt,"createdAt",t),Re(e.updatedAt,"updatedAt",t),e.updatedAt&&Number.isFinite(Date.parse(e.createdAt))&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&u(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt"),f(e.mediaType,"mediaType",t,255),f(e.sensitivity,"sensitivity",t,64),Io.has(e.sensitivity)||u(t,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),e.identity)for(let[n,o]of Object.entries(e.identity))o!==void 0&&f(o,`identity.${n}`,t,512);if(!e.content||typeof e.content!="object")u(t,"content","missing_content","content descriptor is required");else{!e.content.hash||typeof e.content.hash!="object"?u(t,"content.hash","missing_hash","content hash is required"):(f(e.content.hash.algorithm,"content.hash.algorithm",t,128),ie(e.content.hash.algorithm,"custom:","content.hash.algorithm",t),typeof e.content.hash.algorithm=="string"&&e.content.hash.algorithm!=="sha256"&&!e.content.hash.algorithm.startsWith("custom:")&&u(t,"content.hash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported"),f(e.content.hash.value,"content.hash.value",t,512),e.content.hash.algorithm==="sha256"&&!Nr.test(e.content.hash.value)&&u(t,"content.hash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters")),(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0)&&u(t,"content.sizeBytes","invalid_size","sizeBytes must be a non-negative safe integer");let n=e.content.storage;if(!n||typeof n!="object")u(t,"content.storage","missing_storage","storage reference is required");else if(n.type==="inline")if(n.text===void 0==(n.base64===void 0))u(t,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;n.text!==void 0?o=Et.Buffer.from(n.text,"utf8"):n.base64!==void 0&&(Ao.test(n.base64)?o=Et.Buffer.from(n.base64,"base64"):u(t,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),o&&e.content.sizeBytes!==o.byteLength&&u(t,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),o&&e.content.hash.algorithm==="sha256"&&oe(o).value!==e.content.hash.value&&u(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else n.type==="file"?f(n.path,"content.storage.path",t,4096):n.type==="blob"?f(n.uri,"content.storage.uri",t,8192):n.type==="git"?(f(n.commit,"content.storage.commit",t,512),f(n.path,"content.storage.path",t,4096)):n.type==="url"?(f(n.url,"content.storage.url",t,8192),Re(n.expiresAt,"content.storage.expiresAt",t)):n.type==="external"?(f(n.provider,"content.storage.provider",t,255),f(n.locator,"content.storage.locator",t,8192)):u(t,"content.storage.type","unknown_storage","Storage type is not supported");e.content.encoding!==void 0&&(typeof e.content.encoding!="string"||e.content.encoding!=="utf8"&&e.content.encoding!=="base64"&&e.content.encoding!=="binary"&&!e.content.encoding.startsWith("custom:"))&&u(t,"content.encoding","unknown_encoding","Content encoding is not supported"),ie(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?u(t,"provenance","missing_provenance","provenance is required"):(kr(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((n,o)=>f(n,`provenance.capabilityLeaseIds[${o}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((n,o)=>f(n,`provenance.sourceArtifactIds[${o}]`,t,512)),e.provenance.attributes&&_e(e.provenance.attributes,"provenance.attributes",t,new Set));let r=new Set;return e.relationships?.forEach((n,o)=>{let i=`relationships[${o}]`;f(n.relation,`${i}.relation`,t,160),typeof n.relation=="string"&&!Eo.has(n.relation)&&!n.relation.startsWith("custom:")&&u(t,`${i}.relation`,"unknown_relationship","Relationship type is not supported"),ie(n.relation,"custom:",`${i}.relation`,t),f(n.target?.type,`${i}.target.type`,t,160),typeof n.target?.type=="string"&&!wo.has(n.target.type)&&!n.target.type.startsWith("custom:")&&u(t,`${i}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),ie(n.target?.type,"custom:",`${i}.target.type`,t),f(n.target?.id,`${i}.target.id`,t,512);let a=`${n.relation}:${n.target?.type}:${n.target?.id}:${n.target?.revision??""}`;r.has(a)&&u(t,i,"duplicate_relationship","Duplicate relationship"),r.add(a),n.attributes&&_e(n.attributes,`${i}.attributes`,t,new Set)}),e.anchors?.forEach((n,o)=>St(n,`anchors[${o}]`,t)),e.revision===1&&e.predecessorRevision!==void 0&&u(t,"predecessorRevision","unexpected_predecessor","First revision cannot have a predecessor"),e.revision>1&&(!Number.isInteger(e.predecessorRevision)||(e.predecessorRevision??0)>=e.revision)&&u(t,"predecessorRevision","invalid_predecessor","Later revisions require an earlier predecessor revision"),Re(e.retention?.retainUntil,"retention.retainUntil",t),e.retention?.legalHold!==void 0&&typeof e.retention.legalHold!="boolean"&&u(t,"retention.legalHold","invalid_boolean","legalHold must be a boolean"),e.extensions&&_e(e.extensions,"extensions",t,new Set),t}function Fe(e){let t=vo(e);if(t.length>0)throw new fe("XENO artifact validation failed",t)}function So(e,t){return fo[e].includes(t)}function je(e,t){if(!So(e,t))throw new vt(e,t)}function Tt(e,t){let r=[];return e.schemaVersion!==1&&u(r,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),f(e.eventId,"eventId",r,512),f(e.artifactId,"artifactId",r,512),(!Number.isInteger(e.artifactRevision)||e.artifactRevision<1)&&u(r,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(e.sequence)||e.sequence<1)&&u(r,"sequence","invalid_sequence","sequence must be a positive integer"),f(e.recordedAt,"recordedAt",r,128),Re(e.recordedAt,"recordedAt",r),kr(e.actor,"actor",r),!e.artifactHash||typeof e.artifactHash!="object"?u(r,"artifactHash","missing_hash","Artifact hash is required"):(f(e.artifactHash.algorithm,"artifactHash.algorithm",r,128),ie(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",r),f(e.artifactHash.value,"artifactHash.value",r,512),e.artifactHash.algorithm==="sha256"&&!Nr.test(e.artifactHash.value)&&u(r,"artifactHash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters"),typeof e.artifactHash.algorithm=="string"&&e.artifactHash.algorithm!=="sha256"&&!e.artifactHash.algorithm.startsWith("custom:")&&u(r,"artifactHash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported")),["review-requested","comment-added","comment-resolved","comment-reopened","decision-recorded","review-withdrawn"].includes(e.type)||u(r,"type","unknown_review_event","Review event type is not supported"),e.type==="comment-added"?(f(e.commentId,"commentId",r,512),f(e.body,"body",r,65536),e.anchor&&St(e.anchor,"anchor",r)):e.type==="comment-resolved"||e.type==="comment-reopened"?f(e.commentId,"commentId",r,512):e.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(e.decision)||u(r,"decision","unknown_review_decision","Review decision is not supported"),e.scope&&St(e.scope,"scope",r)),t&&(e.artifactId!==t.artifactId&&u(r,"artifactId","artifact_mismatch","Review event targets a different artifact"),e.artifactRevision!==t.revision&&u(r,"artifactRevision","revision_mismatch","Review event targets a different revision"),e.artifactHash&&(e.artifactHash.algorithm!==t.content.hash.algorithm||e.artifactHash.value!==t.content.hash.value)&&u(r,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),r}function Ct(e){let t="not_requested",r,n,o,i=0,a=new Set,s=new Set;for(let c of[...e].sort((d,y)=>d.sequence-y.sequence))o=c.recordedAt,c.type==="review-requested"?t="pending":c.type==="review-withdrawn"?t="withdrawn":c.type==="comment-added"?(a.add(c.commentId),s.delete(c.commentId),t==="not_requested"&&(t="pending")):c.type==="comment-resolved"?s.add(c.commentId):c.type==="comment-reopened"?s.delete(c.commentId):c.type==="decision-recorded"&&(c.scope?i+=1:(r=c.decision,n=c.eventId,t=c.decision));return{status:t,totalComments:a.size,unresolvedComments:[...a].filter(c=>!s.has(c)).length,...r?{latestDecision:r}:{},...n?{latestDecisionEventId:n}:{},...i>0?{scopedDecisionCount:i}:{},...o?{lastReviewedAt:o}:{}}}var p=class extends Error{constructor(r,n,o,i){super(n,i);this.code=r;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},Oe=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(t={}){this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(r=>(this.idCounter+=1,`${r}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),t.initialState&&this.hydrate(t.initialState)}exportState(){let t=[...this.records.values()].flatMap(r=>[...r.values()]).sort(Xr).map(r=>({artifact:xe(r.artifact),recordVersion:r.recordVersion,lifecycleEvents:structuredClone(r.lifecycleEvents),reviewEvents:structuredClone(r.reviewEvents)}));return{schemaVersion:1,records:t}}async create(t){if(Fe(t),this.assertInitialState(t),t.revision!==1)throw new p("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:t.artifactId,revision:t.revision});if(this.records.has(t.artifactId))throw new p("ARTIFACT_ALREADY_EXISTS",`Artifact ${t.artifactId} already exists`,{artifactId:t.artifactId});let r=xe(t),n=this.createLifecycleEvent({artifact:r,sequence:1,actor:r.provenance.producer,fromState:null,toState:r.state,reason:"artifact-created"}),o={artifact:r,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(r.artifactId,new Map([[r.revision,o]])),this.currentRevisions.set(r.artifactId,r.revision),ae(o)}async createRevision(t,r={}){Fe(t),this.assertInitialState(t);let n=this.getMutable(t.artifactId);this.assertVersion(n,r.expectedRecordVersion);let o=n.artifact.revision+1;if(t.revision!==o||t.predecessorRevision!==n.artifact.revision)throw new p("ARTIFACT_REVISION_INVALID",`Revision ${t.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:t.artifactId,currentRevision:n.artifact.revision,requestedRevision:t.revision});if(Co(t,n.artifact))throw new p("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:t.artifactId,revision:t.revision});if(n.artifact.state==="archived")throw new p("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:t.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){je(n.artifact.state,"superseded");let c=this.now(),d=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:r.actor??t.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:r.reason??`superseded-by-revision-${t.revision}`,recordedAt:c});n.artifact.state="superseded",n.artifact.updatedAt=c,n.lifecycleEvents.push(d),n.recordVersion+=1}let i=xe(t),a=this.createLifecycleEvent({artifact:i,sequence:1,actor:r.actor??i.provenance.producer,fromState:null,toState:i.state,reason:r.reason??`revision-created-from-${n.artifact.revision}`}),s={artifact:i,recordVersion:1,lifecycleEvents:[a],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,s),this.currentRevisions.set(i.artifactId,i.revision),ae(s)}async get(t,r){let n=this.records.get(t);if(!n)return;let o=r??this.currentRevisions.get(t);if(o===void 0)return;let i=n.get(o);return i?ae(i):void 0}async require(t,r){let n=await this.get(t,r);if(!n)throw new p("ARTIFACT_NOT_FOUND",`Artifact ${t}${r===void 0?"":` revision ${r}`} was not found`,{artifactId:t,...r===void 0?{}:{revision:r}});return n}async list(t={}){let r=[];for(let[n,o]of this.records)if(!(t.artifactIds&&!t.artifactIds.includes(n)))if(t.includeSuperseded)r.push(...o.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let a=o.get(i);a&&r.push(a)}}return r.filter(n=>Po(n.artifact,t)).sort(Xr).map(ae)}async listRevisions(t){let r=this.records.get(t);return r?[...r.values()].sort((n,o)=>n.artifact.revision-o.artifact.revision).map(ae):[]}async transition(t){let r=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(r,t.expectedRecordVersion),je(r.artifact.state,t.toState),t.toState==="approved"||t.toState==="rejected"){let a=t.reviewEventId?r.reviewEvents.find(c=>c.eventId===t.reviewEventId&&c.type==="decision-recorded"):void 0,s=Ct(r.reviewEvents);if(!a||a.decision!==t.toState||s.latestDecisionEventId!==a.eventId)throw new p("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${t.toState} requires a matching decision event`,{artifactId:t.artifactId,revision:r.artifact.revision});if(t.toState==="approved"&&s.unresolvedComments>0)throw new p("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:t.artifactId,revision:r.artifact.revision,unresolvedComments:s.unresolvedComments})}let n=this.now(),o=r.artifact.state,i=this.createLifecycleEvent({artifact:r.artifact,sequence:r.lifecycleEvents.length+1,actor:t.actor,fromState:o,toState:t.toState,reason:t.reason,reviewEventId:t.reviewEventId,recordedAt:n});return r.artifact.state=t.toState,r.artifact.updatedAt=n,r.lifecycleEvents.push(i),r.recordVersion+=1,ae(r)}async appendReviewEvent(t){let r=t.event,n=this.getMutable(r.artifactId,r.artifactRevision);if(this.assertVersion(n,t.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new p("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:r.artifactId,revision:r.artifactRevision});if(this.assertReviewCommentState(n,r),(r.type==="review-requested"||r.type==="review-withdrawn"||r.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new p("ARTIFACT_REVIEW_INVALID",`${r.type} requires an artifact in pending_review state`,{artifactId:r.artifactId,revision:r.artifactRevision});let o={...structuredClone(r),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=Tt(o,n.artifact);if(i.length>0)throw new fe("XENO artifact review event validation failed",i);return n.reviewEvents.push(o),n.recordVersion+=1,ae(n)}getMutable(t,r){let n=this.records.get(t),o=r??this.currentRevisions.get(t),i=o===void 0?void 0:n?.get(o);if(!i)throw new p("ARTIFACT_NOT_FOUND",`Artifact ${t}${r===void 0?"":` revision ${r}`} was not found`,{artifactId:t,...r===void 0?{}:{revision:r}});return i}assertVersion(t,r){if(r!==void 0&&r!==t.recordVersion)throw new p("ARTIFACT_CONFLICT",`Expected record version ${r}, found ${t.recordVersion}`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision,expectedRecordVersion:r,actualRecordVersion:t.recordVersion})}assertInitialState(t){if(t.state!=="draft"&&t.state!=="pending_review")throw new p("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:t.artifactId,revision:t.revision})}assertReviewCommentState(t,r){if(r.type==="comment-added"){if(t.reviewEvents.some(i=>i.type==="comment-added"&&i.commentId===r.commentId))throw new p("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} already exists`);if(r.parentCommentId&&!t.reviewEvents.some(i=>i.type==="comment-added"&&i.commentId===r.parentCommentId))throw new p("ARTIFACT_REVIEW_INVALID",`Parent comment ${r.parentCommentId} does not exist`);return}if(r.type!=="comment-resolved"&&r.type!=="comment-reopened")return;if(!t.reviewEvents.some(i=>i.type==="comment-added"&&i.commentId===r.commentId))throw new p("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} does not exist`);let o=Ro(t.reviewEvents,r.commentId);if(r.type==="comment-resolved"&&o.resolved)throw new p("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} is already resolved`);if(r.type==="comment-reopened"&&!o.resolved)throw new p("ARTIFACT_REVIEW_INVALID",`Comment ${r.commentId} is not resolved`)}createLifecycleEvent(t){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:t.artifact.artifactId,revision:t.artifact.revision,sequence:t.sequence,recordedAt:t.recordedAt??this.now(),actor:{...t.actor},fromState:t.fromState,toState:t.toState,...t.reason?{reason:t.reason}:{},...t.reviewEventId?{reviewEventId:t.reviewEventId}:{}}}nextEventId(t){let r=this.idFactory(t);if(typeof r!="string"||r.trim().length===0||this.eventIds.has(r))throw new p("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${t} ID`);return this.eventIds.add(r),r}hydrate(t){if(t.schemaVersion!==1||!Array.isArray(t.records))throw new p("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let r=[...t.records].sort((n,o)=>n.artifact.artifactId.localeCompare(o.artifact.artifactId)||n.artifact.revision-o.artifact.revision);for(let n of r){let o=To(n,this.eventIds),i=this.records.get(o.artifact.artifactId);if(i||(i=new Map,this.records.set(o.artifact.artifactId,i)),i.has(o.artifact.revision))throw new p("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${o.artifact.artifactId}:${o.artifact.revision}`);i.set(o.artifact.revision,o),this.currentRevisions.set(o.artifact.artifactId,o.artifact.revision)}for(let[n,o]of this.records){let i=[...o.values()].sort((a,s)=>a.artifact.revision-s.artifact.revision);for(let a=0;a<i.length;a+=1){let s=i[a],c=a+1;if(s.artifact.revision!==c)throw new p("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${c}`);if(a===0&&s.artifact.predecessorRevision!==void 0)throw new p("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(a>0&&s.artifact.predecessorRevision!==c-1)throw new p("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${c} has an invalid predecessor`);if(a<i.length-1&&s.artifact.state!=="superseded")throw new p("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${c} must be superseded`)}}}};function To(e,t){if(Fe(e.artifact),!Number.isInteger(e.recordVersion)||e.recordVersion<1)throw new p("ARTIFACT_REVISION_INVALID","Persisted artifact recordVersion must be a positive integer",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(!Array.isArray(e.lifecycleEvents)||e.lifecycleEvents.length===0||!Array.isArray(e.reviewEvents))throw new p("ARTIFACT_REVISION_INVALID","Persisted artifact records require lifecycle and review event arrays",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let r=e.lifecycleEvents.length+e.reviewEvents.length;if(e.recordVersion!==r)throw new p("ARTIFACT_REVISION_INVALID",`Persisted record version ${e.recordVersion} does not match ${r} mutations`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let n=null;for(let i=0;i<e.lifecycleEvents.length;i+=1){let a=e.lifecycleEvents[i];if(a.schemaVersion!==1||a.artifactId!==e.artifact.artifactId||a.revision!==e.artifact.revision||a.sequence!==i+1||a.fromState!==n||typeof a.eventId!="string"||a.eventId.length===0||t.has(a.eventId)||!Number.isFinite(Date.parse(a.recordedAt)))throw new p("ARTIFACT_REVISION_INVALID",`Persisted lifecycle event ${i+1} is invalid`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(n===null){if(a.toState!=="draft"&&a.toState!=="pending_review")throw new p("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:e.artifact.artifactId,revision:e.artifact.revision})}else je(n,a.toState);t.add(a.eventId),n=a.toState}if(n!==e.artifact.state)throw new p("ARTIFACT_REVISION_INVALID","Persisted artifact state does not match its lifecycle tail",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let o=new Map;for(let i=0;i<e.reviewEvents.length;i+=1){let a=e.reviewEvents[i];if(a.sequence!==i+1||t.has(a.eventId))throw new p("ARTIFACT_REVIEW_INVALID",`Persisted review event ${i+1} has an invalid sequence or duplicate ID`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let s=Tt(a,e.artifact);if(s.length>0)throw new fe("Persisted XENO artifact review event validation failed",s);if(a.type==="comment-added"){if(o.has(a.commentId)||a.parentCommentId!==void 0&&!o.has(a.parentCommentId))throw new p("ARTIFACT_REVIEW_INVALID",`Persisted comment ${a.commentId} has an invalid identity or parent`);o.set(a.commentId,!1)}else if(a.type==="comment-resolved"||a.type==="comment-reopened"){let c=o.get(a.commentId);if(c===void 0||a.type==="comment-resolved"&&c||a.type==="comment-reopened"&&!c)throw new p("ARTIFACT_REVIEW_INVALID",`Persisted comment transition for ${a.commentId} is invalid`);o.set(a.commentId,a.type==="comment-resolved")}t.add(a.eventId)}return{artifact:xe(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function Co(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function Po(e,t){return!(t.kinds&&!t.kinds.includes(e.kind)||t.states&&!t.states.includes(e.state)||t.runId&&e.identity?.runId!==t.runId||t.sessionId&&e.identity?.sessionId!==t.sessionId||t.turnId&&e.identity?.turnId!==t.turnId||t.taskId&&e.identity?.taskId!==t.taskId||t.workspaceId&&e.identity?.workspaceId!==t.workspaceId||t.repositoryId&&e.identity?.repositoryId!==t.repositoryId||t.producerId&&e.provenance.producer.id!==t.producerId||t.sensitivity&&!t.sensitivity.includes(e.sensitivity))}function Xr(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function Ro(e,t){let r=!1;for(let n of e)(n.type==="comment-resolved"||n.type==="comment-reopened")&&n.commentId===t&&(r=n.type==="comment-resolved");return{resolved:r}}function xe(e){return structuredClone(e)}function ae(e){return{artifact:xe(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:Ct(e.reviewEvents)}}var Pt=32*1024*1024,_o=1024*1024*1024,xo=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function He(e){let r=(e.now??(()=>new Date().toISOString()))(),n=new Set;return e.evidence.map((o,i)=>{if(No(o),n.has(o.evidenceId))throw new l("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${o.evidenceId}`);n.add(o.evidenceId);let a=Oo(o),s=(0,Lr.createHash)("sha256").update(`${e.request.operationId}\0${o.evidenceId}\0${a.hash.value}`).digest("hex").slice(0,32);return{schemaVersion:1,artifactId:`automation_${s}`,revision:1,kind:o.kind,title:o.title,...o.description?{description:o.description}:{},state:"draft",createdAt:r,mediaType:o.mediaType,sensitivity:o.sensitivity??e.policy.sensitivity,identity:{...e.request.identity},content:a,provenance:{producer:{kind:"tool",id:e.request.governingToolName,displayName:e.manifest.adapterId,profileFingerprint:e.request.executionContract.profile.fingerprint},operationId:e.request.operationId,executionContractFingerprint:e.request.executionContract.fingerprint,capabilityLeaseIds:[e.request.capabilityLeaseId],attributes:{automationProtocolVersion:e.request.protocolVersion,automationOperation:e.request.operation,automationEvidenceId:o.evidenceId,automationEvidencePhase:o.phase,adapterId:e.manifest.adapterId,adapterVersion:e.manifest.adapterVersion,evidenceIndex:i}},...o.anchors?{anchors:structuredClone(o.anchors)}:{},...e.policy.retainUntil||e.policy.legalHold!==void 0?{retention:{...e.policy.retainUntil?{retainUntil:e.policy.retainUntil}:{},...e.policy.legalHold!==void 0?{legalHold:e.policy.legalHold}:{}}}:{},extensions:{...o.extensions??{},xenoAutomation:{phase:o.phase,adapter:e.manifest.adapterId,certifiedAdapter:e.manifest.certified}}}})}async function Ge(e,t){if(!e)return t.map(n=>structuredClone(n));let r=[];for(let n of t)try{let o=await e.create(n);r.push(o.artifact)}catch(o){if(o instanceof p&&o.code==="ARTIFACT_ALREADY_EXISTS"){let i=await e.require(n.artifactId,n.revision);if(i.artifact.content.hash.value===n.content.hash.value){r.push(i.artifact);continue}}throw new l("AUTOMATION_EVIDENCE_PERSISTENCE_FAILED",`Failed to persist automation evidence ${n.artifactId}`,{artifactId:n.artifactId},{cause:o})}return r}function Ne(e,t,r){if(t[r]==="required"&&!e.some(n=>n.phase===r))throw new l("AUTOMATION_EVIDENCE_REQUIRED",`Automation operation requires ${r} evidence before it can be trusted`)}function Oo(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return Dr(t),{hash:oe(e.content.text),sizeBytes:t,storage:{type:"inline",text:e.content.text},encoding:"utf8",...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}if(e.content.type==="base64"){let t=ko(e.content.base64);return Dr(t.byteLength),{hash:oe(t),sizeBytes:t.byteLength,storage:{type:"inline",base64:e.content.base64},encoding:"base64",...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}if(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0||e.content.sizeBytes>_o)throw new l("AUTOMATION_EVIDENCE_INVALID","Referenced evidence size is invalid");if(!e.content.hash?.algorithm||!e.content.hash.value)throw new l("AUTOMATION_EVIDENCE_INVALID","Referenced evidence requires a content hash");if(e.content.hash.algorithm==="sha256"&&!/^[a-f0-9]{64}$/.test(e.content.hash.value))throw new l("AUTOMATION_EVIDENCE_INVALID","Referenced evidence SHA-256 is invalid");return{hash:{...e.content.hash},sizeBytes:e.content.sizeBytes,storage:structuredClone(e.content.storage),...e.content.encoding?{encoding:e.content.encoding}:{},...e.redactedPreview?{redactedPreview:e.redactedPreview}:{}}}function No(e){(!e||typeof e!="object")&&G("Evidence must be an object"),xo.test(e.evidenceId)||G("Evidence ID is invalid"),["before","action","after","recording","diagnostic"].includes(e.phase)||G("Evidence phase is invalid"),(!e.kind||!e.title?.trim()||e.title.length>512)&&G("Evidence kind and title are required"),/^[\w!#$&^_.+-]+\/[\w!#$&^_.+-]+(?:;.*)?$/.test(e.mediaType)||G("Evidence media type is invalid")}function ko(e){(e.length===0||e.length>Math.ceil(Pt/3)*4+4)&&G("Inline base64 evidence is empty or too large"),(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)&&G("Inline evidence is not canonical base64");let t=Buffer.from(e,"base64");return t.toString("base64")!==e&&G("Inline evidence is not canonical base64"),t}function Dr(e){e>Pt&&G(`Inline evidence exceeds ${Pt} bytes`)}function G(e){throw new l("AUTOMATION_EVIDENCE_INVALID",e)}var Ur=require("node:crypto");var Mr=3e4,Xo=1e3,ke=class{adapter;leaseAuthority;artifactRepository;now;executions=new Map;active=new Map;constructor(t){this.adapter=t.adapter,this.leaseAuthority=t.leaseAuthority,this.artifactRepository=t.artifactRepository,this.now=t.now??(()=>new Date().toISOString())}execute(t,r){let n=$o(t),o=this.executions.get(t.operationId);if(o){if(o.fingerprint!==n)throw new l("AUTOMATION_OPERATION_CONFLICT",`Operation ${t.operationId} was already submitted with different authority or parameters`);return o.promise}let i=new AbortController,a=Vo(r,i);this.active.set(t.operationId,i);let s=this.executeFresh(t,i.signal).finally(()=>{a(),this.active.delete(t.operationId)});return this.executions.set(t.operationId,{fingerprint:n,promise:s}),this.trimIdempotencyRecords(),s}async stop(t,r="human-stop"){let n=this.active.get(t);return n?(n.abort(new Error(r)),await this.adapter.stop?.(t,r),!0):!1}async executeFresh(t,r){yt(t),_t(r);let n=await this.adapter.manifest();Ce(n);let o=X(t.operation),i=wt(t),a=this.now(),s=await this.adapter.preflight(t,r);Do(s,this.now()),Ve(t,n,s.observedTarget),_t(r);let c=s.evidence??[];Ne(c,i,"before");let d=await Ge(this.artifactRepository,He({request:t,manifest:n,policy:i,evidence:c,now:this.now}));if(_t(r),Date.parse(s.expiresAt)<=Date.parse(this.now()))throw new l("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let y=bt(t,s.observedTarget),g=await this.leaseAuthority.consume(t.capabilityLeaseId,t.expectedLeaseVersion,y),A={contractFingerprint:t.executionContract.fingerprint,lease:g,capabilityUse:y},m;try{m=await this.adapter.execute(t,s,A,r)}catch(w){return Rt({request:t,manifest:n,descriptorEffect:o.effect,target:s.observedTarget,lease:g,artifacts:d,startedAt:a,completedAt:this.now(),status:r.aborted?"cancelled":"error",code:r.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_ADAPTER_ERROR",message:r.aborted?"Automation operation was stopped":Bo(w)})}Lo(m);let N=Mo(s.observedTarget,m.observedTarget),v;try{Ve(t,n,m.observedTarget)}catch(w){v=w instanceof Error?w:new Error(String(w))}let T=m.evidence??[];Uo(c,T);let U=[],L;try{Ne(T,i,"after"),Ne([...c,...T],i,"recording"),U=await Ge(this.artifactRepository,He({request:t,manifest:n,policy:i,evidence:T,now:this.now}))}catch(w){L=w instanceof Error?w:new Error(String(w))}let k=[...d,...U];return N||v?Rt({request:t,manifest:n,descriptorEffect:o.effect,target:m.observedTarget,lease:g,artifacts:k,startedAt:m.startedAt,completedAt:m.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:N??v.message}):L?Rt({request:t,manifest:n,descriptorEffect:o.effect,target:m.observedTarget,lease:g,artifacts:k,startedAt:m.startedAt,completedAt:m.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:L.message}):{operationId:t.operationId,status:m.status,effect:o.effect,startedAt:m.startedAt,completedAt:m.completedAt,adapter:$r(n),target:structuredClone(m.observedTarget),...m.data!==void 0?{data:structuredClone(m.data)}:{},artifacts:k,lease:Vr(g),...m.error?{error:{...m.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>Xo;){let t=this.executions.keys().next().value;if(!t||this.active.has(t))break;this.executions.delete(t)}}};function Do(e,t){if(!e||typeof e!="object"||!e.token?.trim())throw new l("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an invalid preflight token");let r=Date.parse(e.preparedAt),n=Date.parse(e.expiresAt),o=Date.parse(t);if(!Number.isFinite(r)||!Number.isFinite(n)||n<=r||n<=o)throw new l("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an expired or invalid preflight window");if(n-r>Mr)throw new l("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${Mr} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new l("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function Lo(e){if(!e||typeof e!="object")throw new l("AUTOMATION_REQUEST_INVALID","Adapter returned no result");if(!["ok","denied","cancelled","error"].includes(e.status))throw new l("AUTOMATION_REQUEST_INVALID","Adapter returned an invalid status");if(!Number.isFinite(Date.parse(e.startedAt))||!Number.isFinite(Date.parse(e.completedAt)))throw new l("AUTOMATION_REQUEST_INVALID","Adapter result timestamps are invalid");if(Date.parse(e.completedAt)<Date.parse(e.startedAt))throw new l("AUTOMATION_REQUEST_INVALID","Adapter completion precedes its start");if(!e.observedTarget||typeof e.observedTarget!="object")throw new l("AUTOMATION_REQUEST_INVALID","Adapter result has no observed target")}function Mo(e,t){let r=["tabId","deviceId","displayId"];for(let n of r)if(e[n]!==void 0&&e[n]!==t[n])return`Adapter changed bound ${n} between preflight and execution`}function Uo(e,t){let r=new Set(e.map(n=>n.evidenceId));for(let n of t){if(r.has(n.evidenceId))throw new l("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${n.evidenceId}`);r.add(n.evidenceId)}}function Rt(e){return{operationId:e.request.operationId,status:e.status,effect:e.descriptorEffect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:$r(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:Vr(e.lease),error:{code:e.code,message:e.message}}}function $r(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function Vr(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function $o(e){return(0,Ur.createHash)("sha256").update(JSON.stringify(xt(e))).digest("hex")}function xt(e){return Array.isArray(e)?e.map(xt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,xt(r)]))}function Vo(e,t){if(!e)return()=>{};let r=()=>t.abort(e.reason);return e.aborted?r():e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)}function _t(e){if(e.aborted)throw new l("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function Bo(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}function Br(e,t=()=>new Date().toISOString()){let r=[];jo(r,"manifest.valid",()=>Ce(e));let n=new Set(e.operations);return me(r,n,e.supports.consoleInspection,"browser.console.read","console inspection"),me(r,n,e.supports.networkInspection,"browser.network.read","network inspection"),me(r,n,e.supports.storageInspection,"browser.storage.read","storage inspection"),me(r,n,e.supports.pageErrorInspection,"browser.page-errors.read","page-error inspection"),me(r,n,e.supports.recordings,"browser.record.start","recording start"),me(r,n,e.supports.recordings,"browser.record.stop","recording stop"),n.has("browser.upload")&&Z(r,"policy.upload",e.policyEnforcement.upload,"Upload policy is enforced"),n.has("browser.download")&&Z(r,"policy.download",e.policyEnforcement.download,"Download policy is enforced"),[...n].some(o=>o.startsWith("browser."))&&(Z(r,"policy.redirect",e.policyEnforcement.redirect,"Redirect policy is enforced"),Z(r,"control.handback",e.supports.deterministicHandback,"Deterministic hand-back is supported")),[...n].some(o=>o.startsWith("computer."))&&(Z(r,"control.stop",e.supports.immediateStop,"Immediate human stop is supported"),Z(r,"privacy.redaction",e.supports.sensitiveRegionRedaction,"Sensitive-region redaction is supported")),Z(r,"certification.binding",!e.certified||!!e.certificationArtifactId,e.certified?"Certification artifact is bound":"Adapter does not claim certification"),{protocolVersion:1,adapter:{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture},generatedAt:t(),passed:r.every(o=>o.status==="pass"),checks:r}}function Fo(e){let r=Br(e).checks.filter(n=>n.status==="fail");if(r.length>0)throw new l("AUTOMATION_OPERATION_UNSUPPORTED",r.map(n=>`${n.id}: ${n.message}`).join("; "))}function me(e,t,r,n,o){let i=t.has(n);Z(e,`capability.${n}`,r===i,r===i?`${o} declaration matches the operation catalog`:`${o} declaration does not match ${n}`)}function jo(e,t,r){try{r(),e.push({id:t,status:"pass",message:"Manifest satisfies the protocol contract"})}catch(n){e.push({id:t,status:"fail",message:n instanceof Error?n.message:String(n)})}}function Z(e,t,r,n){e.push({id:t,status:r?"pass":"fail",message:n})}var Ho=6e4,Go=48*1024*1024,Ot=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(t){if(this.endpoint=Wo(t.baseUrl),this.token=qo(t.token),this.timeoutMs=Fr(t.timeoutMs??Ho,1e3,3e5,"timeoutMs"),this.maxResponseBytes=Fr(t.maxResponseBytes??Go,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=t.fetch??globalThis.fetch,typeof this.fetchImpl!="function")throw new l("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}preflight(t,r){return this.request("preflight","POST",t,r)}execute(t,r,n,o){return this.request("execute","POST",{request:t,preflight:r,grant:n},o)}async stop(t,r){await this.request("stop","POST",{operationId:t,reason:r.slice(0,512)})}async request(t,r,n,o){let i=new AbortController,a=Ko(o,i),s=setTimeout(()=>i.abort(new Error("automation transport timeout")),this.timeoutMs);s.unref?.();try{let c=new URL(t,this.endpoint),d=await this.fetchImpl(c,{method:r,redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.token}`,accept:"application/json",...r==="POST"?{"content-type":"application/json"}:{}},...r==="POST"?{body:JSON.stringify(n??{})}:{},signal:i.signal}),y=await zo(d,this.maxResponseBytes);if(!d.ok){let g=Jo(y);throw new l("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${t}: ${g.message}`,{status:d.status,route:t,adapterCode:g.code})}if(!Nt(y)||y.ok!==!0||!("result"in y))throw new l("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${t} envelope`);return y.result}catch(c){if(c instanceof l)throw c;let d=o?.aborted;throw new l(d?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",d?"Automation transport was stopped":`XENO Browser ${t} transport failed`,{route:t},{cause:c})}finally{clearTimeout(s),a()}}};function Wo(e){let t;try{t=new URL(e)}catch(n){throw new l("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL is invalid",void 0,{cause:n})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new l("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires HTTP(S)");if(t.username||t.password||t.search||t.hash)throw new l("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL cannot contain credentials, query, or fragment");let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="::1")throw new l("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport must use a loopback host");if(!t.port)throw new l("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires an explicit port");return t.pathname="/v1/automation/",t}function qo(e){if(typeof e!="string"||e.length<32||e.length>512||/\s/.test(e))throw new l("AUTOMATION_TRANSPORT_ERROR","XENO Browser session token is invalid");return e}async function zo(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new l("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);if(e.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new l("AUTOMATION_RESPONSE_INVALID","XENO Browser response is not application/json");if(!e.body)throw new l("AUTOMATION_RESPONSE_INVALID","XENO Browser response body is missing");let o=e.body.getReader(),i=[],a=0;for(;;){let{done:d,value:y}=await o.read();if(d)break;if(a+=y.byteLength,a>t)throw await o.cancel("response too large"),new l("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);i.push(y)}let s=new Uint8Array(a),c=0;for(let d of i)s.set(d,c),c+=d.byteLength;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch(d){throw new l("AUTOMATION_RESPONSE_INVALID","XENO Browser response contains invalid JSON",void 0,{cause:d})}}function Jo(e){return Nt(e)&&Nt(e.error)?{code:typeof e.error.code=="string"?e.error.code.slice(0,128):"UNKNOWN",message:typeof e.error.message=="string"?e.error.message.slice(0,1024):"request failed"}:{code:"UNKNOWN",message:"request failed"}}function Ko(e,t){if(!e)return()=>{};let r=()=>t.abort(e.reason);return e.aborted?r():e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)}function Fr(e,t,r,n){if(!Number.isSafeInteger(e)||e<t||e>r)throw new l("AUTOMATION_TRANSPORT_ERROR",`${n} must be an integer from ${t} to ${r}`);return e}function Nt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var zr=require("node:crypto"),Xe=["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read","browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download"],Ae=class{constructor(t){this.options=t;if(this.base=Qo(t.baseUrl),this.fetchImpl=t.fetch??globalThis.fetch,this.timeoutMs=t.timeoutMs??6e4,!ei(t.token))throw new Error("XENO browser control-plane token is invalid")}options;base;fetchImpl;timeoutMs;async manifest(){let t=await this.call("health",void 0),r=Xe.filter(n=>t.verbs?.includes(jr(n))??!1);return{protocolVersion:1,adapterId:this.options.driver==="extension"?"xeno-extension-native":"xeno-browser-native",adapterVersion:t.version??"unknown",platform:process.platform,architecture:process.arch,operations:r,targetBinding:"atomic-preflight",profileIsolation:this.options.driver==="browser"?"both":"none",supports:{accessibilitySnapshots:!0,screenshots:!0,recordings:!1,consoleInspection:!0,networkInspection:!0,storageInspection:r.includes("browser.storage.read"),pageErrorInspection:!0,visibleCoControl:!0,deterministicHandback:!0,immediateStop:!0,sensitiveRegionRedaction:!1},policyEnforcement:{domain:!0,scheme:!0,port:!0,redirect:!0,upload:r.includes("browser.upload"),download:r.includes("browser.download")},certified:!1,limitations:[`${this.options.driver==="extension"?"Extension":"Browser"} transport is policy-enforced but not release-certified`,"sensitive-region screenshot redaction is not available"]}}async preflight(t,r){Zo(t.operation);let n=await this.call("health",void 0,r);if(!n.verbs?.includes(jr(t.operation)))throw new Error(`${this.options.driver} driver does not support ${t.operation}`);let o=qr(n.activeTab),i=ge(t.parameters.tabId)??t.declaredTarget?.tabId;if(i&&o&&i!==o)throw new Error(`Requested tab ${i} is not the active browser tab ${o}`);let a=Hr(t,o);Gr(t,a);let s=new Date;return{token:`${t.operationId}:${o??"unbound"}:${(0,zr.randomUUID)()}`,preparedAt:s.toISOString(),expiresAt:new Date(s.getTime()+2e4).toISOString(),observedTarget:a,...Kr(t.operation)?{evidence:[await this.snapshotEvidence(t,"before",r)]}:{},adapterState:{activeTab:o??null,driver:this.options.driver}}}async execute(t,r,n,o){let i=new Date().toISOString(),a=await this.call("health",void 0,o),s=qr(a.activeTab);if(r.observedTarget.tabId&&s!==r.observedTarget.tabId)throw new Error("Active browser tab changed after atomic preflight");Gr(t,r.observedTarget);try{let c=Jr(t.operation,t.parameters),d=await this.call(c.verb,c.params,o),y=Hr(t,s),g=t.operation==="browser.wait"||t.operation==="browser.tabs.list"?[]:[await this.resultEvidence(t,d,o)];return{status:"ok",startedAt:i,completedAt:new Date().toISOString(),observedTarget:y,data:ri(d),...g.length?{evidence:g}:{}}}catch(c){let d={code:oi(c),message:ni(c),retryable:!1};return{status:ii(c),startedAt:i,completedAt:new Date().toISOString(),observedTarget:r.observedTarget,error:d,evidence:[{evidenceId:`${t.operationId}-after-failure`,phase:"after",kind:"browser-snapshot",title:`${t.operation} failed attempt`,mediaType:"application/json",content:{type:"text",text:JSON.stringify({error:d})},sensitivity:"restricted"}]}}}async stop(t,r){await this.call("stop",{})}async resultEvidence(t,r,n){return t.operation==="browser.screenshot"?Yo(t,"after",r):this.snapshotEvidence(t,"after",n)}async snapshotEvidence(t,r,n){let o=await this.call("observe",{limit:1e3},n);return{evidenceId:`${t.operationId}-${r}`,phase:r,kind:"browser-snapshot",title:`${t.operation} ${r} state`,mediaType:"application/json",content:{type:"text",text:JSON.stringify(o)},sensitivity:"restricted"}}async call(t,r,n){let o=new AbortController,i=()=>o.abort(n?.reason);n?.aborted?i():n?.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>o.abort(new Error("browser control-plane timeout")),this.timeoutMs);a.unref?.();try{let s=await this.fetchImpl(new URL(`/v1/browser/${t}`,this.base),{method:t==="health"?"GET":"POST",redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.options.token}`,accept:"application/json",...t==="health"?{}:{"content-type":"application/json"}},...t==="health"?{}:{body:JSON.stringify(r??{})},signal:o.signal}),c=await s.json();if(!s.ok||c.ok!==!0)throw Object.assign(new Error(c.error?.message??`Browser ${t} failed with HTTP ${s.status}`),{code:c.error?.code??`HTTP_${s.status}`,status:s.status});return c.result}finally{clearTimeout(a),n?.removeEventListener("abort",i)}}};function jr(e){return Jr(e,{}).verb}function Jr(e,t){let r=Object.fromEntries(Object.entries(t).filter(([n])=>n!=="tabId"));switch(e){case"browser.navigate":return{verb:"navigate",params:r};case"browser.back":return{verb:"back",params:{}};case"browser.forward":return{verb:"forward",params:{}};case"browser.reload":return{verb:"reload",params:{}};case"browser.wait":return{verb:"wait",params:t.until==="ms"?{milliseconds:t.value??0}:{until:"load",timeout_ms:t.value??3e4}};case"browser.snapshot":return{verb:"observe",params:{limit:t.limit??1e3}};case"browser.screenshot":return{verb:"screenshot",params:{}};case"browser.locate":return{verb:"find",params:r};case"browser.tabs.list":return{verb:"tabs_list",params:{}};case"browser.tabs.open":return{verb:"tabs_new",params:r};case"browser.tabs.close":return{verb:"tabs_close",params:{id:t.tabId}};case"browser.console.read":return{verb:"console_log",params:r};case"browser.network.read":return{verb:"network_log",params:r};case"browser.page-errors.read":return{verb:"console_log",params:{...r,level:"error"}};case"browser.storage.read":return{verb:"storage",params:{}};case"browser.click":return{verb:"click",params:r};case"browser.type":return{verb:"type",params:{selector:t.selector,text:t.text,clear_first:t.clear,press_enter:t.submit}};case"browser.key":return{verb:"key",params:{combo:t.combo}};case"browser.select":return{verb:"select",params:r};case"browser.scroll":return{verb:"scroll",params:r};case"browser.upload":return{verb:"attach_file",params:{selector:t.selector,backendNodeId:t.backendNodeId,host_paths:t.hostPaths,drop:t.drop}};case"browser.download":return{verb:"download",params:{to_path:t.toPath,trigger:t.trigger}};default:throw new Error(`Unsupported browser operation ${e}`)}}function Yo(e,t,r){let n=We(r)?r:{},o=ge(n.base64)??ti(ge(n.screenshot));if(!o)throw new Error("Browser screenshot did not return image bytes");let i=ge(n.format)??(ge(n.screenshot)?.startsWith("data:image/jpeg")?"jpeg":"png");return{evidenceId:`${e.operationId}-${t}`,phase:t,kind:"screenshot",title:`${e.operation} result`,mediaType:i==="jpeg"?"image/jpeg":"image/png",content:{type:"base64",base64:o},sensitivity:"restricted"}}function Hr(e,t){let r=ge(e.parameters.url)??e.declaredTarget?.url;return{...e.declaredTarget??{},...r?{url:r}:{},...t?{tabId:t}:{}}}function Gr(e,t){if(e.operation==="browser.upload"&&e.executionContract.browser.uploads==="deny")throw Object.assign(new Error("Browser uploads are denied by the execution contract"),{code:"POLICY_DENIED"});if(e.operation==="browser.download"&&e.executionContract.browser.downloads==="deny")throw Object.assign(new Error("Browser downloads are denied by the execution contract"),{code:"POLICY_DENIED"});let r=t.url??t.origin;if(!r)return;let n=new URL(r),o=e.executionContract.browser,i=n.protocol.replace(/:$/,"");if(!o.allowedSchemes?.includes(i))throw Object.assign(new Error(`Browser scheme ${i} is denied`),{code:"POLICY_DENIED"});let a=n.port?Number(n.port):i==="http"?80:443;if(!o.allowedPorts?.includes(a))throw Object.assign(new Error(`Browser port ${a} is denied`),{code:"POLICY_DENIED"});let s=n.hostname.toLowerCase();if(o.deniedDomains?.some(d=>Wr(s,d)))throw Object.assign(new Error(`Browser domain ${s} is denied`),{code:"POLICY_DENIED"});let c=e.operation.startsWith("browser.")&&Kr(e.operation)?o.actAllowedDomains:o.readAllowedDomains;if(c&&c.length>0&&!c.some(d=>Wr(s,d)))throw Object.assign(new Error(`Browser domain ${s} is outside the allowed scope`),{code:"POLICY_DENIED"})}function Wr(e,t){let r=t.toLowerCase().replace(/^\*\./,".");return r.startsWith(".")?e.endsWith(r)||e===r.slice(1):e===r}function Kr(e){return["browser.navigate","browser.back","browser.forward","browser.reload","browser.tabs.open","browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download"].includes(e)}function Zo(e){if(!Xe.includes(e))throw new Error(`Unsupported browser operation ${e}`)}function Qo(e){let t=new URL(e),r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(t.protocol!=="http:"||!["localhost","127.0.0.1","::1"].includes(r)||!t.port)throw new Error("Browser control plane must be an explicit HTTP loopback URL");return t}function ei(e){return typeof e=="string"&&e.length>=32&&e.length<=512&&!/\s/.test(e)}function qr(e){return typeof e=="string"||typeof e=="number"?String(e):void 0}function ge(e){return typeof e=="string"&&e.length>0?e:void 0}function ti(e){return e?.match(/^data:image\/(?:png|jpeg);base64,(.+)$/)?.[1]}function ri(e){return JSON.parse(JSON.stringify(e??null))}function We(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ni(e){return e instanceof Error?e.message.slice(0,1024):String(e).slice(0,1024)}function oi(e){return We(e)&&typeof e.code=="string"?e.code:"BROWSER_OPERATION_FAILED"}function ii(e){return We(e)&&(e.status===403||e.status===409||e.code==="POLICY_DENIED")?"denied":We(e)&&e.name==="AbortError"?"cancelled":"error"}var Ie=require("node:fs"),pn=require("node:os"),z=require("node:path");var Ut=require("node:crypto"),_=require("node:fs/promises"),B=require("node:path");var W=require("node:fs"),kt=require("node:os"),Zr=require("node:path");function ai(){return new Date().toISOString()}function si(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function Qr(e){try{return JSON.parse((0,W.readFileSync)(e,"utf8"))}catch{return null}}function ci(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function di(e){return e.hostname!==(0,kt.hostname)()?!0:ci(e.pid)}function Yr(e,t){(0,W.mkdirSync)((0,Zr.dirname)(e),{recursive:!0}),(0,W.writeFileSync)(e,JSON.stringify(t,null,2)+`
926
- `,{encoding:"utf8",flag:"wx"})}function li(e,t){let r=Qr(e);r?.pid!==t.pid||r.hostname!==t.hostname||(0,W.rmSync)(e,{force:!0})}function en(e,t,r){let n=ai(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,kt.hostname)(),processStartedAt:si(),version:r,acquiredAt:n,updatedAt:n};try{Yr(e,o)}catch(i){if(i.code!=="EEXIST")throw i;let s=Qr(e);if(s&&di(s))throw new Error(`${t} is already locked by PID ${s.pid} on ${s.hostname}.`);(0,W.rmSync)(e,{force:!0}),Yr(e,o)}return{record:o,release:()=>{li(e,o)}}}var tn="0.9.24";var nn=1,ui="repository.v1.json",pi=5e3,fi=20,mi=64*1024*1024,qe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(t){if(!t||typeof t.directory!="string"||t.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let r=t.snapshotFileName??ui;if((0,B.basename)(r)!==r||!/^[A-Za-z0-9_.-]+$/.test(r))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,B.resolve)(t.directory),this.snapshotPath=(0,B.join)(this.directory,r),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Xt(t.lockTimeoutMs,pi,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Xt(t.lockRetryMs,fi,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Xt(t.maxSnapshotBytes,mi,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(r=>r.create(t))}async createRevision(t,r){return this.mutate(n=>n.createRevision(t,r))}async get(t,r){return(await this.load()).repository.get(t,r)}async require(t,r){return(await this.load()).repository.require(t,r)}async list(t){return(await this.load()).repository.list(t)}async listRevisions(t){return(await this.load()).repository.listRevisions(t)}async transition(t){return this.mutate(r=>r.transition(t))}async appendReviewEvent(t){return this.mutate(r=>r.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let r=await this.acquireLock();try{let n=await this.load(),o=await t(n.repository);return await this.persist(n),o}finally{r.release()}})}async enqueueMutation(t){let r=this.mutationTail.then(t,t);return this.mutationTail=r.then(()=>{},()=>{}),r}async acquireLock(){let t=Date.now(),r;for(;Date.now()-t<=this.lockTimeoutMs;)try{return en(this.lockPath,`artifact-repository:${(0,B.basename)(this.snapshotPath)}`,tn)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;r=n,await yi(this.lockRetryMs)}throw new p("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:r})}async load(){let t,r,n=!1;try{r=await this.readSnapshot(this.snapshotPath,!1)}catch(i){t=ze(i)}if(!r&&(t||await Ii(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:t?.message??"primary snapshot missing"}),r=i,n=!0)}catch(i){throw t?new p("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,ze(i)])}):i}if(!r&&t)throw t;let o=r?.state??{schemaVersion:1,records:[]};return{repository:new Oe({now:this.now,idFactory:i=>`${i}_${(0,Ut.randomUUID)()}`,initialState:o}),generation:r?.generation??0,createdAt:r?.createdAt??this.now(),hasSnapshot:r!==void 0,recoveredFromBackup:n,...r?{sourceSnapshot:r}:{}}}async persist(t){let r=this.now(),o={...{schemaVersion:nn,generation:t.generation,createdAt:t.createdAt,updatedAt:r,state:t.repository.exportState()},generation:t.generation+1},i=Ai(o),a=`${JSON.stringify(i,null,2)}
926
+ `,{encoding:"utf8",flag:"wx"})}function li(e,t){let r=Qr(e);r?.pid!==t.pid||r.hostname!==t.hostname||(0,W.rmSync)(e,{force:!0})}function en(e,t,r){let n=ai(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,kt.hostname)(),processStartedAt:si(),version:r,acquiredAt:n,updatedAt:n};try{Yr(e,o)}catch(i){if(i.code!=="EEXIST")throw i;let s=Qr(e);if(s&&di(s))throw new Error(`${t} is already locked by PID ${s.pid} on ${s.hostname}.`);(0,W.rmSync)(e,{force:!0}),Yr(e,o)}return{record:o,release:()=>{li(e,o)}}}var tn="0.9.25";var nn=1,ui="repository.v1.json",pi=5e3,fi=20,mi=64*1024*1024,qe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(t){if(!t||typeof t.directory!="string"||t.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let r=t.snapshotFileName??ui;if((0,B.basename)(r)!==r||!/^[A-Za-z0-9_.-]+$/.test(r))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,B.resolve)(t.directory),this.snapshotPath=(0,B.join)(this.directory,r),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Xt(t.lockTimeoutMs,pi,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Xt(t.lockRetryMs,fi,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Xt(t.maxSnapshotBytes,mi,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(r=>r.create(t))}async createRevision(t,r){return this.mutate(n=>n.createRevision(t,r))}async get(t,r){return(await this.load()).repository.get(t,r)}async require(t,r){return(await this.load()).repository.require(t,r)}async list(t){return(await this.load()).repository.list(t)}async listRevisions(t){return(await this.load()).repository.listRevisions(t)}async transition(t){return this.mutate(r=>r.transition(t))}async appendReviewEvent(t){return this.mutate(r=>r.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let r=await this.acquireLock();try{let n=await this.load(),o=await t(n.repository);return await this.persist(n),o}finally{r.release()}})}async enqueueMutation(t){let r=this.mutationTail.then(t,t);return this.mutationTail=r.then(()=>{},()=>{}),r}async acquireLock(){let t=Date.now(),r;for(;Date.now()-t<=this.lockTimeoutMs;)try{return en(this.lockPath,`artifact-repository:${(0,B.basename)(this.snapshotPath)}`,tn)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;r=n,await yi(this.lockRetryMs)}throw new p("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:r})}async load(){let t,r,n=!1;try{r=await this.readSnapshot(this.snapshotPath,!1)}catch(i){t=ze(i)}if(!r&&(t||await Ii(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:t?.message??"primary snapshot missing"}),r=i,n=!0)}catch(i){throw t?new p("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,ze(i)])}):i}if(!r&&t)throw t;let o=r?.state??{schemaVersion:1,records:[]};return{repository:new Oe({now:this.now,idFactory:i=>`${i}_${(0,Ut.randomUUID)()}`,initialState:o}),generation:r?.generation??0,createdAt:r?.createdAt??this.now(),hasSnapshot:r!==void 0,recoveredFromBackup:n,...r?{sourceSnapshot:r}:{}}}async persist(t){let r=this.now(),o={...{schemaVersion:nn,generation:t.generation,createdAt:t.createdAt,updatedAt:r,state:t.repository.exportState()},generation:t.generation+1},i=Ai(o),a=`${JSON.stringify(i,null,2)}
927
927
  `;if(Buffer.byteLength(a,"utf8")>this.maxSnapshotBytes)throw new p("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await(0,_.mkdir)(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await rn(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
928
928
  `),await rn(this.snapshotPath,a)}async readSnapshot(t,r){let n;try{n=await(0,_.stat)(t)}catch(o){if(!r&&Lt(o,"ENOENT")||r&&Lt(o,"ENOENT"))return;throw Mt("Unable to inspect artifact repository snapshot",t,o)}if(!n.isFile()||n.size>this.maxSnapshotBytes)throw new p("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:t,sizeBytes:n.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await(0,_.readFile)(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return gi(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof p?o:Mt("Unable to parse artifact repository snapshot",t,o,!0)}}};function gi(e,t){if(!Dt(e)||e.schemaVersion!==nn||!Number.isInteger(e.generation)||e.generation<0||typeof e.createdAt!="string"||!Number.isFinite(Date.parse(e.createdAt))||typeof e.updatedAt!="string"||!Number.isFinite(Date.parse(e.updatedAt))||!Dt(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!Dt(e.checksum)||e.checksum.algorithm!=="sha256"||typeof e.checksum.value!="string")throw new p("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:t});let r=e,n=hi(r),o=on(n);if(r.checksum.value!==o)throw new p("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new Oe({initialState:r.state}),structuredClone(r)}function Ai(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:on(e)}}}function hi(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function on(e){return oe(JSON.stringify(e)).value}async function rn(e,t){await(0,_.mkdir)((0,B.dirname)(e),{recursive:!0,mode:448});let r=`${e}.tmp.${process.pid}.${(0,Ut.randomUUID)()}`,n;try{n=await(0,_.open)(r,"wx",384),await n.writeFile(t,{encoding:"utf8"}),await n.sync(),await n.close(),n=void 0,await(0,_.rename)(r,e);try{let o=await(0,_.open)((0,B.dirname)(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{n&&await n.close().catch(()=>{}),await(0,_.unlink)(r).catch(()=>{})}}function Xt(e,t,r,n,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<r||e>n)throw new TypeError(`${o} must be an integer between ${r} and ${n}`);return e}function Dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lt(e,t){return e instanceof Error&&e.code===t}async function Ii(e){try{return(await(0,_.stat)(e)).isFile()}catch(t){if(Lt(t,"ENOENT"))return!1;throw Mt("Unable to inspect artifact repository backup",e,t)}}function ze(e){return e instanceof Error?e:new Error(String(e))}function Mt(e,t,r,n=!1){return new p(n?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${ze(r).message}`,{snapshotPath:t},{cause:ze(r)})}function yi(e){return new Promise(t=>setTimeout(t,e))}var he=require("node:os");var Bs=(0,he.platform)();var Fs=(0,he.release)(),js=(0,he.homedir)();var bi=2,$t=["publish","deploy","push","send","purchase","sign","file-legal","change-infrastructure"];function wi(e){return Array.from(new Set((e??[]).map(t=>t.trim()).filter(Boolean)))}function q(e){return{schemaVersion:bi,id:e.id,version:"1.0.0",displayName:e.displayName,description:e.description,kind:e.kind??"primary",prompt:e.prompt,capabilities:{tools:e.toolPolicy??{mode:"inherit"},skills:{preload:e.skills??[],...e.skillAllow?{allow:e.skillAllow}:{},deny:[]},hooks:[],permissionProfile:e.permissionProfile??"default",externalActions:{default:e.externalDefault??"ask",...e.externalOverrides?{overrides:e.externalOverrides}:{},requireCurrentTurnApproval:e.currentTurnApproval??[]}},memory:{scope:e.memoryScope??"project",role:e.id,soul:e.soul??"read"},execution:{defaultMode:e.defaultMode??"chat",allowedModes:e.allowedModes??["chat","plan","execute","review"],isolation:e.isolation??"none",allowBackground:e.allowBackground??!0,planForComplexTasks:e.planForComplexTasks??!0,defaultDryRun:e.defaultDryRun??!1},completion:{evidence:e.evidence??[],requirePrimarySources:e.primarySources??!1,requireCurrentInformation:e.currentInformation??!1,requireHumanReview:e.humanReview??!1,stopConditions:e.stopConditions??["The requested outcome is complete and required evidence has been reported.","A real authorization, information, or external-state blocker prevents safe progress."]},presentation:{label:e.displayName,color:e.color,glyph:e.glyph},tags:wi(e.tags)}}var Zs=[q({id:"assistant",displayName:"Assistant",description:"General-purpose XENO collaborator for mixed research, planning, and implementation work.",prompt:["Work as a thoughtful generalist. Establish the user's actual outcome, inspect relevant context, and take scoped action.","Escalate into a narrower specialist profile when domain risk or task depth warrants it."].join(`
929
929
  `),toolPolicy:{mode:"inherit"},skills:[],memoryScope:"user",evidence:["file-references"],currentTurnApproval:[...$t],color:"cyan",glyph:"\u25A0",tags:["general","primary"]}),q({id:"swe",displayName:"Software Engineer",description:"Repository-aware software engineer for careful implementation, debugging, refactoring, and verification.",prompt:["Inspect the repository before editing. Follow project instructions and preserve unrelated work.","Trace the smallest root cause, implement the narrowest coherent change, and verify from focused checks outward.","Do not claim completion without concrete test, typecheck, build, or runtime evidence appropriate to the risk."].join(`
@@ -1,3 +1,4 @@
1
+ import { WebJobProgress } from "@xenosystem/web-context-client/progress";
1
2
  declare const XENO_ARTIFACT_SCHEMA_VERSION: 1;
2
3
  type XenoJsonPrimitive = string | number | boolean | null;
3
4
  type XenoJsonValue = XenoJsonPrimitive | XenoJsonObject | XenoJsonValue[];
@@ -532,6 +533,7 @@ interface WebContextToolResult {
532
533
  mediaType: string;
533
534
  bytes: number;
534
535
  };
536
+ jobProgress?: WebJobProgress;
535
537
  }
536
538
  interface ToolDefinition {
537
539
  name: string;
@@ -613,6 +615,7 @@ interface ToolProgressUpdate {
613
615
  bytes?: number;
614
616
  outputBytes?: number;
615
617
  nextOffset?: number;
618
+ webContextProgress?: WebJobProgress;
616
619
  }
617
620
  interface ToolAuthorizationReceipt {
618
621
  turnId: string;