@xenosystem/agent-cli 0.5.173 → 0.5.174
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/index.js +12 -12
- package/dist/metafile-esm.json +1 -1
- package/dist/sdk-build-identity.json +11 -11
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -783,7 +783,7 @@ ${_}`:null}}]:[]],...e.promptSectionsTokenBudget!==void 0?{promptSectionsTokenBu
|
|
|
783
783
|
`)}function vde(e){let t=[`## Audit Replay ${e.traceId}`,"",`- Started: \`${e.startedAt}\``,`- Ended: \`${e.endedAt}\``,`- Duration: \`${e.durationMs}\` ms`,""];for(let r of e.steps){let n=[r.actor,r.riskLevel,r.status].filter(Boolean).join(" | ");t.push(`- **#${r.sequence} ${r.title}**${n?` _(${n})_`:""}`),r.detail&&t.push(` - ${r.detail}`)}return t.join(`
|
|
784
784
|
`)}function M5(e){let t=[`Audit replay ${e.traceId}`,`Started: ${e.startedAt}`,`Ended: ${e.endedAt}`,`Duration: ${e.durationMs} ms`,""];for(let r of e.steps){let n=[r.actor,r.riskLevel,r.status].filter(i=>typeof i=="string"&&i.length>0).join(" | ");t.push(`#${r.sequence} ${r.timestamp}`),t.push(` ${r.title}${n?` [${n}]`:""}`),r.detail&&t.push(` ${r.detail}`)}return t.join(`
|
|
785
785
|
`)}function kh(e){if(TQe.has(e))return{operation:e,surface:"browser",effect:"observe",evidence:{before:"disabled",after:e==="browser.wait"||e==="browser.tabs.list"?"optional":"required",recording:"optional"}};if(RQe.has(e)){let t=e==="browser.record.start"||e==="browser.record.stop";return{operation:e,surface:"browser",effect:"act",evidence:{before:"required",after:"required",recording:e==="browser.record.stop"?"required":"optional"}}}if(PQe.has(e))return{operation:e,surface:"computer",effect:"observe",evidence:{before:"disabled",after:e==="computer.wait"?"optional":"required",recording:"optional"}};if(_Qe.has(e))return{operation:e,surface:"computer",effect:"act",evidence:{before:"required",after:"required",recording:"optional"}};throw new TypeError(`Unsupported XENO automation operation: ${e}`)}function Ide(e){return TQe.has(e)||RQe.has(e)||PQe.has(e)||_Qe.has(e)}function oxn(e){return e??"inherit"}function JH(e){return ar(e.trim())}function sxn(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`)}function axn(e){let t=e.trim();if(!t)return null;let r=t.indexOf("(");if(r<0)return{kind:"exact",raw:t,toolName:JH(t)};if(!t.endsWith(")"))return null;let n=t.slice(0,r).trim(),i=t.slice(r+1,-1),o=i.indexOf(":");if(!n||o<0)return null;let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();return s?{kind:"parameterized",raw:t,toolName:JH(n),field:s,pattern:a,regex:sxn(a)}:null}function sNe(e){return!e||e.length===0?[]:e.map(t=>axn(t)).filter(t=>t!==null)}function BQe(e){let t=sNe(e.allow),r=sNe(e.deny),n=new Set,i=[],o=new Set,s=[];for(let a of t)a.kind==="exact"?n.add(a.toolName):i.push(a);for(let a of r)a.kind==="exact"?o.add(a.toolName):s.push(a);return{mode:oxn(e.mode),allowExact:n,allowParameterized:i,denyExact:o,denyParameterized:s,hasAllowRules:t.length>0}}function lxn(e,t){return e?new Set([...e].filter(r=>t.has(r))):new Set(t)}function FLt(e){let t=e.hasAllowRules?new Set([...e.allowExact,...e.allowParameterized.map(r=>r.toolName)]):void 0;return e.mode==="none"?new Set:(e.mode==="readOnly"&&(t=lxn(t,LLt)),t)}function cxn(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):null}function ESt(e,t){if(!Object.prototype.hasOwnProperty.call(t,e.field))return!1;let r=cxn(t[e.field]);return r===null?!1:e.regex.test(r)}function C3(e){return{success:!1,output:"",error:`Tool call blocked by custom agent tool policy: ${e}`}}function yq(e,t){let r=o=>(o??"").split(",").map(s=>s.trim()).filter(Boolean),n=r(e),i=r(t);if(e!==void 0&&n.length===0)throw new Error("--allowed-tools needs at least one tool name.");if(!(n.length===0&&i.length===0))return{...n.length?{allow:n}:{},...i.length?{deny:i}:{}}}function bq(e){if(!e)return[];let t=(r,n)=>sNe(r).filter(i=>i.kind==="parameterized"&&i.toolName==="Bash"&&i.field==="command").map(i=>{if(i.pattern.length===0)throw new Error(`${i.raw} names no command.`);if(n==="allow"&&i.pattern.replace(/\*/g,"").trim().length===0)throw new Error(`${i.raw} would approve every command. Use --bypass-permissions for full access.`);return{tool:"Bash",pattern:i.pattern,decision:n}});return[...t(e.deny,"deny"),...t(e.allow,"allow")]}function ui(e,t){if(!t)return{removed:[]};let r=BQe(t),n=FLt(r),i=[];for(let o of e.listNames()){let s=JH(o),a=n?!n.has(s):!1,l=r.denyExact.has(s);(a||l)&&e.unregister(o)&&i.push(o)}return ULt(r,n,i)}function ULt(e,t,r){return{removed:r,...t?{allowed:[...t].sort()}:{},...e.denyExact.size>0||e.denyParameterized.length>0?{denied:[...e.denyExact,...e.denyParameterized.map(n=>n.toolName)].sort()}:{}}}function Ea(e){if(!e)return;let t=BQe(e);return async(r,n)=>{let i=JH(r.toolName);if(t.mode==="none")return C3(`${r.toolName} is disabled for this custom agent.`);if(t.mode==="readOnly"&&!LLt.has(i))return C3(`${r.toolName} is not read-only.`);if(t.denyExact.has(i))return C3(`${r.toolName} is denied.`);let o=t.denyParameterized.find(s=>s.toolName===i&&ESt(s,r.input));if(o)return C3(`${o.raw} denied this input.`);if(t.hasAllowRules){let s=t.allowExact.has(i),a=t.allowParameterized.some(l=>l.toolName===i&&ESt(l,r.input));if(!s&&!a)return C3(`${r.toolName} input does not match the custom agent allow-list.`)}return n()}}function w0(e){(!e||typeof e!="object")&&c0("Automation request must be an object"),e.protocolVersion!==1&&c0("Unsupported automation protocol version"),fO(e.operationId,"operationId"),fO(e.idempotencyKey,"idempotencyKey"),fO(e.capabilityLeaseId,"capabilityLeaseId"),fO(e.governingToolName,"governingToolName"),(!Number.isSafeInteger(e.expectedLeaseVersion)||e.expectedLeaseVersion<1)&&c0("expectedLeaseVersion must be a positive safe integer"),GLt(e.requestedAt)||c0("requestedAt must be an ISO 8601 timestamp"),Ide(e.operation)||c0(`Unsupported automation operation: ${e.operation}`),(!e.parameters||typeof e.parameters!="object"||Array.isArray(e.parameters))&&c0("parameters must be a JSON object");let t;try{t=Buffer.byteLength(JSON.stringify(e.parameters),"utf8")}catch(r){throw new ve("AUTOMATION_REQUEST_INVALID","parameters must be serializable JSON",void 0,{cause:r})}if(t>kSt&&c0(`parameters exceed ${kSt} bytes`),fO(e.identity?.runId,"identity.runId"),fO(e.identity?.agentId,"identity.agentId"),oae(e.executionContract),uxn(e),!e.executionContract.capabilityLeaseIds.includes(e.capabilityLeaseId))throw new ve("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 ve("AUTOMATION_CONTRACT_EXPIRED","Execution contract has expired")}function $y(e){(!e||typeof e!="object")&&Xg("Adapter manifest must be an object"),e.protocolVersion!==1&&Xg("Adapter protocol version is unsupported"),Bre(e.adapterId,"adapterId"),Bre(e.adapterVersion,"adapterVersion"),Bre(e.platform,"platform"),Bre(e.architecture,"architecture"),e.targetBinding!=="atomic-preflight"&&Xg("Adapter must implement atomic preflight target binding"),(!Array.isArray(e.operations)||e.operations.length===0)&&Xg("Adapter must declare operations");let t=new Set;for(let r of e.operations)Ide(r)||Xg(`Adapter declares unknown operation ${r}`),t.has(r)&&Xg(`Adapter declares duplicate operation ${r}`),t.add(r);e.certified&&!e.certificationArtifactId&&Xg("A certified automation adapter requires a certification artifact"),Array.isArray(e.limitations)||Xg("Adapter limitations must be an array"),e.operations.some(r=>r.startsWith("browser."))&&(!e.policyEnforcement.domain||!e.policyEnforcement.scheme||!e.policyEnforcement.port)&&Xg("Browser adapters must enforce domain, scheme, and port policy"),e.operations.some(r=>r.startsWith("computer."))&&!e.supports.immediateStop&&Xg("Computer-use adapters must support immediate stop")}function Ede(e,t){let r=kh(e.operation);if(!t.operations.includes(e.operation))throw new ve("AUTOMATION_OPERATION_UNSUPPORTED",`Adapter ${t.adapterId} does not support ${e.operation}`);if(r.surface==="browser"){let n=e.executionContract.browser.mode;if(n==="none"||r.effect==="act"&&n!=="act")throw new ve("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(e.operation==="browser.download"&&e.executionContract.browser.downloads==="deny")throw new ve("AUTOMATION_POLICY_DENIED","Execution contract denies browser downloads");if(e.operation==="browser.upload"&&e.executionContract.browser.uploads==="deny")throw new ve("AUTOMATION_POLICY_DENIED","Execution contract denies browser uploads");if(e.operation.startsWith("browser.record.")&&e.executionContract.browser.recording!=="bounded")throw new ve("AUTOMATION_POLICY_DENIED","Execution contract denies browser recording")}else{let n=e.executionContract.computer.mode;if(n==="none"||r.effect==="act"&&n!=="act")throw new ve("AUTOMATION_POLICY_DENIED",`Execution contract denies ${e.operation}`);if(e.executionContract.computer.sensitiveRegionRedaction&&t.supports.sensitiveRegionRedaction!==!0)throw new ve("AUTOMATION_POLICY_DENIED","Owning adapter cannot satisfy required sensitive-region redaction; preflight capture refused.")}}function D2(e,t,r){Ede(e,t);let n=kh(e.operation);if(n.surface==="browser")pxn(e,r,n.effect==="act");else{let i=e.executionContract.computer.allowedApplications,o=e.operation==="computer.launch"?hxn(e):r.applicationId??e.declaredTarget?.applicationId;if((e.operation==="computer.launch"||i.length>0)&&(!o||!i.includes(o)))throw new ve("AUTOMATION_POLICY_DENIED",`Application ${o??"<unknown>"} is not allowed`)}}function kde(e,t){let r=kh(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,...SSt(e,t)?{resource:SSt(e,t)}:{},...CSt(t)?{destination:CSt(t)}:{}}}function SSt(e,t){return fxn(t)??e.declaredTarget?.resource}function zH(e){let t=kh(e.operation).evidence,r=e.evidencePolicy??{},n=TBe(t.before,r.before),i=TBe(t.after,r.after),o=TBe(t.recording,r.recording),s=r.retainUntil;return s&&!GLt(s)&&c0("evidencePolicy.retainUntil must be an ISO 8601 timestamp"),{before:n,after:i,recording:o,sensitivity:r.sensitivity??"confidential",...s?{retainUntil:s}:{},...r.legalHold!==void 0?{legalHold:r.legalHold}:{}}}function uxn(e){let t=e.executionContract.identity,r=["runId","agentId","sessionId","turnId","taskId","workspaceId"];for(let n of r){let i=t[n],o=e.identity[n];if(i!==void 0&&i!==o)throw new ve("AUTOMATION_IDENTITY_MISMATCH",`Automation identity ${n} does not match the execution contract`)}}function pxn(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 ve("AUTOMATION_PREFLIGHT_INVALID","Browser preflight did not bind an effective URL")}let i;try{i=new URL(n)}catch{throw new ve("AUTOMATION_POLICY_DENIED","Browser target URL is invalid")}if(i.username||i.password)throw new ve("AUTOMATION_POLICY_DENIED","Browser target URLs cannot contain credentials");let o=i.protocol.replace(/:$/,"");o!=="http"&&o!=="https"&&zT(`Browser scheme ${i.protocol} is not supported`);let s=o,a=i.hostname.toLowerCase().replace(/\.$/,""),l=i.port?Number(i.port):s==="https"?443:80,c=e.executionContract.browser,d=mxn(a);if(TSt(a,c.deniedDomains)&&zT(`Browser domain ${a} is denied`),xSt(i,e.executionContract.network.denyDestinations)&&zT(`Network policy explicitly denies ${s}://${a}:${l}`),d&&c.allowLoopbackDevelopment)return;c.allowedSchemes.includes(s)||zT(`Browser scheme ${i.protocol} is not allowed`),c.allowedPorts.includes(l)||zT(`Browser port ${l} is not allowed`);let u=r?c.actAllowedDomains:c.readAllowedDomains;TSt(a,u)||zT(`Browser domain ${a} is outside the ${r?"action":"read"} allowlist`),e.executionContract.network.default==="deny"&&(xSt(i,e.executionContract.network.allowDestinations)||zT(`Network policy does not allow ${s}://${a}:${l}`))}function xSt(e,t){let r=e.protocol.replace(/:$/,""),n=e.hostname.toLowerCase().replace(/\.$/,""),i=e.port?Number(e.port):r==="https"?443:80;return t.some(o=>{let s=o.scheme?.replace(/^custom:/,"");return o.host===n&&(o.port===void 0||o.port===i)&&(s===void 0||s===r)})}function fxn(e){return e.resource??e.tabId??e.pageId??e.deviceId??e.applicationId}function CSt(e){let t=e.origin??e.url;if(!t)return e.domain;try{return new URL(t).origin}catch{return t}}function hxn(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 TSt(e,t){return t.some(r=>{let n=r.toLowerCase();if(n.startsWith(".")){let i=n.slice(1);return e===i||e.endsWith(`.${i}`)}return e===n})}function mxn(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function TBe(e,t){let r={disabled:0,optional:1,required:2};return!t||r[t]<=r[e]?e:t}function fO(e,t){(typeof e!="string"||!dxn.test(e))&&c0(`${t} is invalid`)}function Bre(e,t){(typeof e!="string"||e.trim().length===0||e.length>256)&&Xg(`${t} is invalid`)}function GLt(e){return typeof e=="string"&&e.includes("T")&&Number.isFinite(Date.parse(e))}function zT(e){throw new ve("AUTOMATION_POLICY_DENIED",e)}function c0(e){throw new ve("AUTOMATION_REQUEST_INVALID",e)}function Xg(e){throw new ve("AUTOMATION_OPERATION_UNSUPPORTED",e)}function Ws(e){return{algorithm:"sha256",value:Axn("sha256").update(e).digest("hex")}}function ji(e){return JSON.stringify(aNe(e,new Set))}function qd(e){return Ws(ji(e))}function aNe(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 n=e.map(i=>aNe(i,t));return t.delete(e),n}let r={};for(let n of Object.keys(e).sort((i,o)=>i.localeCompare(o))){let i=e[n];if(i===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);r[n]=aNe(i,t)}return t.delete(e),r}function vt(e,t,r,n){e.push({path:t,code:r,message:n})}function fr(e,t,r,n=1024){return typeof e!="string"||e.trim().length===0?(vt(r,t,"required_string","Value must be a non-empty string"),!1):(e.length>n&&vt(r,t,"string_too_long",`Value must not exceed ${n} characters`),bxn.test(e)&&vt(r,t,"control_character","Value must not contain control characters"),!0)}function A8(e,t,r){e!==void 0&&(!Number.isFinite(Date.parse(e))||!e.includes("T"))&&vt(r,t,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function h2(e,t,r,n){typeof e=="string"&&e.startsWith(t)&&(n5(e,t)||vt(n,r,"invalid_custom_name",`Custom name after ${t} is invalid`))}function qLt(e,t,r){if(!e||typeof e!="object"){vt(r,t,"missing_actor","Actor is required");return}fr(e.kind,`${t}.kind`,r,64),kxn.has(e.kind)||vt(r,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),fr(e.id,`${t}.id`,r,512),e?.displayName!==void 0&&fr(e.displayName,`${t}.displayName`,r,512),e?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.profileFingerprint)&&vt(r,`${t}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function lNe(e,t,r){if(!e||typeof e!="object"){vt(r,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":fr(e.path,`${t}.path`,r,4096);break;case"source-line":fr(e.path,`${t}.path`,r,4096),(!Number.isInteger(e.startLine)||e.startLine<1)&&vt(r,`${t}.startLine`,"invalid_line","startLine must be a positive integer"),e.endLine!==void 0&&(!Number.isInteger(e.endLine)||e.endLine<e.startLine)&&vt(r,`${t}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":fr(e.path,`${t}.path`,r,4096),fr(e.hunkId,`${t}.hunkId`,r,512);break;case"symbol":fr(e.path,`${t}.path`,r,4096),fr(e.symbol,`${t}.symbol`,r,1024);break;case"dom-node":fr(e.pageId,`${t}.pageId`,r,512),!e.selector&&!e.accessibilityId&&!e.snapshotArtifactId&&vt(r,t,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":fr(e.recordingArtifactId,`${t}.recordingArtifactId`,r,512),(!Number.isFinite(e.startMs)||e.startMs<0)&&vt(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)&&vt(r,`${t}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":fr(e.mediaArtifactId,`${t}.mediaArtifactId`,r,512),[e.x,e.y,e.width,e.height].every(Number.isFinite)?(e.width<=0||e.height<=0)&&vt(r,t,"invalid_region_size","Region width and height must be positive"):vt(r,t,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":fr(e.artifactId,`${t}.artifactId`,r,512);break;default:typeof e.kind!="string"||!e.kind.startsWith("custom:")?vt(r,`${t}.kind`,"unknown_anchor","Anchor kind is not supported"):h2(e.kind,"custom:",`${t}.kind`,r)}}function W8(e,t,r,n){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||vt(r,t,"non_finite_number","JSON numbers must be finite");return}if(typeof e!="object"){vt(r,t,"non_json_value","Value must be JSON-serializable");return}if(n.has(e)){vt(r,t,"cyclic_value","Value must not contain cycles");return}if(n.add(e),Array.isArray(e))e.forEach((i,o)=>W8(i,`${t}[${o}]`,r,n));else for(let[i,o]of Object.entries(e))o===void 0?vt(r,`${t}.${i}`,"undefined_value","Undefined is not valid JSON"):W8(o,`${t}.${i}`,r,n);n.delete(e)}}function LQe(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_artifact",message:"Artifact must be an object"}];if(e.schemaVersion!==1&&vt(t,"schemaVersion","unsupported_schema","schemaVersion must be 1"),fr(e.artifactId,"artifactId",t,512),(!Number.isInteger(e.revision)||e.revision<1)&&vt(t,"revision","invalid_revision","revision must be a positive integer"),fr(e.kind,"kind",t,160),typeof e.kind=="string"&&!Sxn.has(e.kind)&&!e.kind.startsWith("custom:")&&vt(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),h2(e.kind,"custom:","kind",t),fr(e.title,"title",t,1024),e.description!==void 0&&fr(e.description,"description",t,32768),fr(e.state,"state",t,64),Ixn.has(e.state)||vt(t,"state","unknown_state","Artifact state is not supported"),fr(e.createdAt,"createdAt",t,128),A8(e.createdAt,"createdAt",t),A8(e.updatedAt,"updatedAt",t),e.updatedAt&&Number.isFinite(Date.parse(e.createdAt))&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&vt(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt"),fr(e.mediaType,"mediaType",t,255),fr(e.sensitivity,"sensitivity",t,64),Exn.has(e.sensitivity)||vt(t,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),e.identity)for(let[n,i]of Object.entries(e.identity))i!==void 0&&fr(i,`identity.${n}`,t,512);if(!e.content||typeof e.content!="object")vt(t,"content","missing_content","content descriptor is required");else{!e.content.hash||typeof e.content.hash!="object"?vt(t,"content.hash","missing_hash","content hash is required"):(fr(e.content.hash.algorithm,"content.hash.algorithm",t,128),h2(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:")&&vt(t,"content.hash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported"),fr(e.content.hash.value,"content.hash.value",t,512),e.content.hash.algorithm==="sha256"&&!VLt.test(e.content.hash.value)&&vt(t,"content.hash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters")),(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0)&&vt(t,"content.sizeBytes","invalid_size","sizeBytes must be a non-negative safe integer");let n=e.content.storage;if(!n||typeof n!="object")vt(t,"content.storage","missing_storage","storage reference is required");else if(n.type==="inline")if(n.text===void 0==(n.base64===void 0))vt(t,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let i;n.text!==void 0?i=RSt.from(n.text,"utf8"):n.base64!==void 0&&(vxn.test(n.base64)?i=RSt.from(n.base64,"base64"):vt(t,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),i&&e.content.sizeBytes!==i.byteLength&&vt(t,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),i&&e.content.hash.algorithm==="sha256"&&Ws(i).value!==e.content.hash.value&&vt(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else n.type==="file"?fr(n.path,"content.storage.path",t,4096):n.type==="blob"?fr(n.uri,"content.storage.uri",t,8192):n.type==="git"?(fr(n.commit,"content.storage.commit",t,512),fr(n.path,"content.storage.path",t,4096)):n.type==="url"?(fr(n.url,"content.storage.url",t,8192),A8(n.expiresAt,"content.storage.expiresAt",t)):n.type==="external"?(fr(n.provider,"content.storage.provider",t,255),fr(n.locator,"content.storage.locator",t,8192)):vt(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:"))&&vt(t,"content.encoding","unknown_encoding","Content encoding is not supported"),h2(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?vt(t,"provenance","missing_provenance","provenance is required"):(qLt(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((n,i)=>fr(n,`provenance.capabilityLeaseIds[${i}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((n,i)=>fr(n,`provenance.sourceArtifactIds[${i}]`,t,512)),e.provenance.attributes&&W8(e.provenance.attributes,"provenance.attributes",t,new Set));let r=new Set;return e.relationships?.forEach((n,i)=>{let o=`relationships[${i}]`;fr(n.relation,`${o}.relation`,t,160),typeof n.relation=="string"&&!Cxn.has(n.relation)&&!n.relation.startsWith("custom:")&&vt(t,`${o}.relation`,"unknown_relationship","Relationship type is not supported"),h2(n.relation,"custom:",`${o}.relation`,t),fr(n.target?.type,`${o}.target.type`,t,160),typeof n.target?.type=="string"&&!xxn.has(n.target.type)&&!n.target.type.startsWith("custom:")&&vt(t,`${o}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),h2(n.target?.type,"custom:",`${o}.target.type`,t),fr(n.target?.id,`${o}.target.id`,t,512);let s=`${n.relation}:${n.target?.type}:${n.target?.id}:${n.target?.revision??""}`;r.has(s)&&vt(t,o,"duplicate_relationship","Duplicate relationship"),r.add(s),n.attributes&&W8(n.attributes,`${o}.attributes`,t,new Set)}),e.anchors?.forEach((n,i)=>lNe(n,`anchors[${i}]`,t)),e.revision===1&&e.predecessorRevision!==void 0&&vt(t,"predecessorRevision","unexpected_predecessor","First revision cannot have a predecessor"),e.revision>1&&(!Number.isInteger(e.predecessorRevision)||(e.predecessorRevision??0)>=e.revision)&&vt(t,"predecessorRevision","invalid_predecessor","Later revisions require an earlier predecessor revision"),A8(e.retention?.retainUntil,"retention.retainUntil",t),e.retention?.legalHold!==void 0&&typeof e.retention.legalHold!="boolean"&&vt(t,"retention.legalHold","invalid_boolean","legalHold must be a boolean"),e.extensions&&W8(e.extensions,"extensions",t,new Set),t}function Vd(e){let t=LQe(e);if(t.length>0)throw new vq("XENO artifact validation failed",t)}function FQe(e,t){return wxn[e].includes(t)}function XH(e,t){if(!FQe(e,t))throw new DQe(e,t)}function Cde(e,t){let r=[];return e.schemaVersion!==1&&vt(r,"schemaVersion","unsupported_schema","schemaVersion must be 1"),fr(e.eventId,"eventId",r,512),fr(e.artifactId,"artifactId",r,512),(!Number.isInteger(e.artifactRevision)||e.artifactRevision<1)&&vt(r,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(e.sequence)||e.sequence<1)&&vt(r,"sequence","invalid_sequence","sequence must be a positive integer"),fr(e.recordedAt,"recordedAt",r,128),A8(e.recordedAt,"recordedAt",r),qLt(e.actor,"actor",r),!e.artifactHash||typeof e.artifactHash!="object"?vt(r,"artifactHash","missing_hash","Artifact hash is required"):(fr(e.artifactHash.algorithm,"artifactHash.algorithm",r,128),h2(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",r),fr(e.artifactHash.value,"artifactHash.value",r,512),e.artifactHash.algorithm==="sha256"&&!VLt.test(e.artifactHash.value)&&vt(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:")&&vt(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)||vt(r,"type","unknown_review_event","Review event type is not supported"),e.type==="comment-added"?(fr(e.commentId,"commentId",r,512),fr(e.body,"body",r,65536),e.anchor&&lNe(e.anchor,"anchor",r)):e.type==="comment-resolved"||e.type==="comment-reopened"?fr(e.commentId,"commentId",r,512):e.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(e.decision)||vt(r,"decision","unknown_review_decision","Review decision is not supported"),e.scope&&lNe(e.scope,"scope",r)),t&&(e.artifactId!==t.artifactId&&vt(r,"artifactId","artifact_mismatch","Review event targets a different artifact"),e.artifactRevision!==t.revision&&vt(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)&&vt(r,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),r}function Tde(e){let t="not_requested",r,n,i,o=0,s=new Set,a=new Set;for(let l of[...e].sort((c,d)=>c.sequence-d.sequence))i=l.recordedAt,l.type==="review-requested"?t="pending":l.type==="review-withdrawn"?t="withdrawn":l.type==="comment-added"?(s.add(l.commentId),a.delete(l.commentId),t==="not_requested"&&(t="pending")):l.type==="comment-resolved"?a.add(l.commentId):l.type==="comment-reopened"?a.delete(l.commentId):l.type==="decision-recorded"&&(l.scope?o+=1:(r=l.decision,n=l.eventId,t=l.decision));return{status:t,totalComments:s.size,unresolvedComments:[...s].filter(l=>!a.has(l)).length,...r?{latestDecision:r}:{},...n?{latestDecisionEventId:n}:{},...o>0?{scopedDecisionCount:o}:{},...i?{lastReviewedAt:i}:{}}}function Txn(e,t){if(Vd(e.artifact),!Number.isInteger(e.recordVersion)||e.recordVersion<1)throw new er("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 er("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 er("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 o=0;o<e.lifecycleEvents.length;o+=1){let s=e.lifecycleEvents[o];if(s.schemaVersion!==1||s.artifactId!==e.artifact.artifactId||s.revision!==e.artifact.revision||s.sequence!==o+1||s.fromState!==n||typeof s.eventId!="string"||s.eventId.length===0||t.has(s.eventId)||!Number.isFinite(Date.parse(s.recordedAt)))throw new er("ARTIFACT_REVISION_INVALID",`Persisted lifecycle event ${o+1} is invalid`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(n===null){if(s.toState!=="draft"&&s.toState!=="pending_review")throw new er("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:e.artifact.artifactId,revision:e.artifact.revision})}else XH(n,s.toState);t.add(s.eventId),n=s.toState}if(n!==e.artifact.state)throw new er("ARTIFACT_REVISION_INVALID","Persisted artifact state does not match its lifecycle tail",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let i=new Map;for(let o=0;o<e.reviewEvents.length;o+=1){let s=e.reviewEvents[o];if(s.sequence!==o+1||t.has(s.eventId))throw new er("ARTIFACT_REVIEW_INVALID",`Persisted review event ${o+1} has an invalid sequence or duplicate ID`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let a=Cde(s,e.artifact);if(a.length>0)throw new vq("Persisted XENO artifact review event validation failed",a);if(s.type==="comment-added"){if(i.has(s.commentId)||s.parentCommentId!==void 0&&!i.has(s.parentCommentId))throw new er("ARTIFACT_REVIEW_INVALID",`Persisted comment ${s.commentId} has an invalid identity or parent`);i.set(s.commentId,!1)}else if(s.type==="comment-resolved"||s.type==="comment-reopened"){let l=i.get(s.commentId);if(l===void 0||s.type==="comment-resolved"&&l||s.type==="comment-reopened"&&!l)throw new er("ARTIFACT_REVIEW_INVALID",`Persisted comment transition for ${s.commentId} is invalid`);i.set(s.commentId,s.type==="comment-resolved")}t.add(s.eventId)}return{artifact:J8(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function Rxn(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function Pxn(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 PSt(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function _xn(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 J8(e){return structuredClone(e)}function XT(e){return{artifact:J8(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:Tde(e.reviewEvents)}}function Noe(e){let t=(e.now??(()=>new Date().toISOString()))(),r=new Set;return e.evidence.map((n,i)=>{if(Oxn(n),r.has(n.evidenceId))throw new ve("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${n.evidenceId}`);r.add(n.evidenceId);let o=Mxn(n);return{schemaVersion:1,artifactId:`automation_${gxn("sha256").update(`${e.request.operationId}\0${n.evidenceId}\0${o.hash.value}`).digest("hex").slice(0,32)}`,revision:1,kind:n.kind,title:n.title,...n.description?{description:n.description}:{},state:"draft",createdAt:t,mediaType:n.mediaType,sensitivity:n.sensitivity??e.policy.sensitivity,identity:{...e.request.identity},content:o,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:n.evidenceId,automationEvidencePhase:n.phase,adapterId:e.manifest.adapterId,adapterVersion:e.manifest.adapterVersion,evidenceIndex:i}},...n.anchors?{anchors:structuredClone(n.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:{...n.extensions??{},xenoAutomation:{phase:n.phase,adapter:e.manifest.adapterId,certifiedAdapter:e.manifest.certified}}}})}async function YH(e,t){if(!e)return t.map(n=>structuredClone(n));let r=[];for(let n of t)try{let i=await e.create(n);r.push(i.artifact)}catch(i){if(i instanceof er&&i.code==="ARTIFACT_ALREADY_EXISTS"){let o=await e.require(n.artifactId,n.revision);if(o.artifact.content.hash.value===n.content.hash.value){r.push(o.artifact);continue}}throw new ve("AUTOMATION_EVIDENCE_PERSISTENCE_FAILED",`Failed to persist automation evidence ${n.artifactId}`,{artifactId:n.artifactId},{cause:i})}return r}function z8(e,t,r){if(t[r]==="required"&&!e.some(n=>n.phase===r))throw new ve("AUTOMATION_EVIDENCE_REQUIRED",`Automation operation requires ${r} evidence before it can be trusted`)}function Mxn(e){if(e.content.type==="text"){let t=Buffer.byteLength(e.content.text,"utf8");return _St(t),{hash:Ws(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=Nxn(e.content.base64);return _St(t.byteLength),{hash:Ws(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>Bxn)throw new ve("AUTOMATION_EVIDENCE_INVALID","Referenced evidence size is invalid");if(!e.content.hash?.algorithm||!e.content.hash.value)throw new ve("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 ve("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 Oxn(e){(!e||typeof e!="object")&&y0("Evidence must be an object"),$xn.test(e.evidenceId)||y0("Evidence ID is invalid"),["before","action","after","recording","diagnostic"].includes(e.phase)||y0("Evidence phase is invalid"),(!e.kind||!e.title?.trim()||e.title.length>512)&&y0("Evidence kind and title are required"),/^[\w!#$&^_.+-]+\/[\w!#$&^_.+-]+(?:;.*)?$/.test(e.mediaType)||y0("Evidence media type is invalid")}function Nxn(e){(e.length===0||e.length>Math.ceil(cNe/3)*4+4)&&y0("Inline base64 evidence is empty or too large"),(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)&&y0("Inline evidence is not canonical base64");let t=Buffer.from(e,"base64");return t.toString("base64")!==e&&y0("Inline evidence is not canonical base64"),t}function _St(e){e>cNe&&y0(`Inline evidence exceeds ${cNe} bytes`)}function y0(e){throw new ve("AUTOMATION_EVIDENCE_INVALID",e)}async function UQe(e,t,r,n){await e.assertCurrent(t);let i={operationId:t.operationId,fingerprint:r,ownerToken:Fxn()},o=await e.journal.begin(i);if(await e.assertCurrent(t),!o.claimed){if(o.record.outcome.kind!=="result")throw P0();let p=await e.artifactRepository.require(o.record.outcome.artifactId,1),f=p.artifact;if(f.content.storage.type!=="inline"||f.content.encoding!=="utf8"||f.provenance.operationId!==t.operationId||f.extensions?.automationRequestFingerprint!==r)throw P0();let h=f.content.storage.text;if(typeof h!="string"||Buffer.byteLength(h)>BSt||$re(h)!==o.record.outcome.sha256||f.content.hash.value!==o.record.outcome.sha256)throw P0();let m=JSON.parse(h);return $St(m,t),await e.assertCurrent(t),{...m,replayed:!0}}let s="automation-consume:"+$re(t.operationId+"\0"+r),a=await n(s);$St(a,t);let l=JSON.stringify(a),c=Buffer.byteLength(l);if(c>BSt)throw P0();let d=$re(l),u={schemaVersion:1,artifactId:"automation_result_"+$re(t.operationId+"\0"+r),revision:1,kind:"custom:automation-result",title:"Governed automation outcome",state:"draft",createdAt:a.completedAt,mediaType:"application/json",sensitivity:"restricted",identity:{...t.identity},content:{hash:{algorithm:"sha256",value:d},sizeBytes:c,encoding:"utf8",storage:{type:"inline",text:l}},provenance:{producer:{kind:"system",id:"xeno-governed-automation"},operationId:t.operationId,executionContractFingerprint:t.executionContract.fingerprint,capabilityLeaseIds:[t.capabilityLeaseId]},extensions:{automationRequestFingerprint:r}};return await e.assertCurrent(t),await YH(e.artifactRepository,[u]),await e.journal.finish(i,{kind:"result",artifactId:u.artifactId,sha256:d}),await e.assertCurrent(t),{...a,replayed:!1}}function $St(e,t){if(!e||typeof e!="object")throw P0();let r=e;if(r.operationId!==t.operationId||!["ok","error","cancelled","denied","evidence-incomplete"].includes(r.status)||!r.target||!Array.isArray(r.artifacts)||!r.lease||!r.adapter)throw P0()}function $re(e){return Lxn("sha256").update(e).digest("hex")}function P0(){return new ve("AUTOMATION_OUTCOME_PENDING","Automation outcome is pending or unknown; recover the same operation rather than dispatching it again")}function Uxn(e,t){if(!e||typeof e!="object"||!e.token?.trim())throw new ve("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an invalid preflight token");let r=Date.parse(e.preparedAt),n=Date.parse(e.expiresAt),i=Date.parse(t);if(!Number.isFinite(r)||!Number.isFinite(n)||n<=r||n<=i)throw new ve("AUTOMATION_PREFLIGHT_INVALID","Adapter returned an expired or invalid preflight window");if(n-r>MSt)throw new ve("AUTOMATION_PREFLIGHT_INVALID",`Preflight TTL exceeds ${MSt} ms`);if(!e.observedTarget||typeof e.observedTarget!="object")throw new ve("AUTOMATION_PREFLIGHT_INVALID","Adapter did not bind an observed target")}function Qxn(e){if(!e||typeof e!="object")throw new ve("AUTOMATION_REQUEST_INVALID","Adapter returned no result");if(!["ok","denied","cancelled","error"].includes(e.status))throw new ve("AUTOMATION_REQUEST_INVALID","Adapter returned an invalid status");if(!Number.isFinite(Date.parse(e.startedAt))||!Number.isFinite(Date.parse(e.completedAt)))throw new ve("AUTOMATION_REQUEST_INVALID","Adapter result timestamps are invalid");if(Date.parse(e.completedAt)<Date.parse(e.startedAt))throw new ve("AUTOMATION_REQUEST_INVALID","Adapter completion precedes its start");if(!e.observedTarget||typeof e.observedTarget!="object")throw new ve("AUTOMATION_REQUEST_INVALID","Adapter result has no observed target")}function Gxn(e,t){let r=["tabId","pageId","deviceId","applicationId","displayId"];for(let n of r)if(e[n]!==void 0&&e[n]!==t[n])return`Adapter changed bound ${n} between preflight and execution`}function jxn(e,t){let r=new Set(e.map(n=>n.evidenceId));for(let n of t){if(r.has(n.evidenceId))throw new ve("AUTOMATION_EVIDENCE_INVALID",`Duplicate evidence ID ${n.evidenceId}`);r.add(n.evidenceId)}}function RBe(e){return{operationId:e.request.operationId,status:e.status,effect:e.descriptorEffect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:dNe(e.manifest),target:structuredClone(e.target),artifacts:e.artifacts,lease:uNe(e.lease),error:{code:e.code,message:e.message}}}function dNe(e){return{adapterId:e.adapterId,adapterVersion:e.adapterVersion,platform:e.platform,architecture:e.architecture}}function uNe(e){return{leaseId:e.leaseId,version:e.version,state:e.state,useCount:e.useCount}}function Hxn(e){return Dxn("sha256").update(JSON.stringify(pNe(e))).digest("hex")}function pNe(e){return Array.isArray(e)?e.map(pNe):!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,pNe(r)]))}function Vxn(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 ay(e){if(e.aborted)throw new ve("AUTOMATION_CANCELLED","Automation operation was stopped before dispatch")}function qxn(e){return e instanceof Error&&e.message.slice(0,1024)||"Automation adapter failed"}async function WLt(e){if(!Wxn(e))throw Error("Automation journal requires an absolute host-owned path");let{DatabaseSync:t}=await import("node:sqlite");return new GQe(new t(e))}function fNe(e){for(let t of[e.operationId,e.ownerToken])if(typeof t!="string"||!t.trim()||t.length>1024)throw Error("Invalid automation journal identity");if(!/^[a-f0-9]{64}$/.test(e.fingerprint))throw Error("Invalid automation journal fingerprint")}function hNe(e){if(!e||typeof e!="object")throw Error("Invalid automation journal record");let t=e;if(fNe(t),NO(t,["schemaVersion","operationId","fingerprint","ownerToken","outcome"]),t.schemaVersion!==1||!t.outcome)throw Error("Invalid automation journal schema");let r=t.outcome;if(r.kind==="result"){if(NO(r,["kind","artifactId","sha256"]),typeof r.artifactId!="string"||!r.artifactId||r.artifactId.length>256||!/^[a-f0-9]{64}$/.test(r.sha256))throw Error("Invalid automation result reference")}else if(r.kind==="failed"){if(NO(r,["kind","code"]),typeof r.code!="string"||!/^AUTOMATION_[A-Z_]{1,100}$/.test(r.code))throw Error("Invalid automation failure code")}else if(r.kind==="pending")NO(r,["kind"]);else throw Error("Invalid automation journal outcome")}function NO(e,t){if(Array.isArray(e)||Object.keys(e).some(r=>!t.includes(r)))throw Error("Unexpected automation journal fields")}function NSt(e){hNe(e);let t=JSON.stringify(e);if(t.length>16384)throw Error("Automation journal record too large");return t}function Mre(){return new ve("AUTOMATION_OPERATION_CONFLICT","Automation operation identity or owner conflicts with durable state")}function jQe(e,t=()=>new Date().toISOString()){let r=[];Jxn(r,"manifest.valid",()=>$y(e));let n=new Set(e.operations);return hO(r,n,e.supports.consoleInspection,"browser.console.read","console inspection"),hO(r,n,e.supports.networkInspection,"browser.network.read","network inspection"),hO(r,n,e.supports.storageInspection,"browser.storage.read","storage inspection"),hO(r,n,e.supports.pageErrorInspection,"browser.page-errors.read","page-error inspection"),hO(r,n,e.supports.recordings,"browser.record.start","recording start"),hO(r,n,e.supports.recordings,"browser.record.stop","recording stop"),n.has("browser.upload")&&T1(r,"policy.upload",e.policyEnforcement.upload,"Upload policy is enforced"),n.has("browser.download")&&T1(r,"policy.download",e.policyEnforcement.download,"Download policy is enforced"),[...n].some(i=>i.startsWith("browser."))&&(T1(r,"policy.redirect",e.policyEnforcement.redirect,"Redirect policy is enforced"),T1(r,"control.handback",e.supports.deterministicHandback,"Deterministic hand-back is supported")),[...n].some(i=>i.startsWith("computer."))&&(T1(r,"control.stop",e.supports.immediateStop,"Immediate human stop is supported"),T1(r,"privacy.redaction",e.supports.sensitiveRegionRedaction,"Sensitive-region redaction is supported")),T1(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(i=>i.status==="pass"),checks:r}}function JLt(e){let t=jQe(e).checks.filter(r=>r.status==="fail");if(t.length>0)throw new ve("AUTOMATION_OPERATION_UNSUPPORTED",t.map(r=>`${r.id}: ${r.message}`).join("; "))}function hO(e,t,r,n,i){let o=t.has(n);T1(e,`capability.${n}`,r===o,r===o?`${i} declaration matches the operation catalog`:`${i} declaration does not match ${n}`)}function Jxn(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 T1(e,t,r,n){e.push({id:t,status:r?"pass":"fail",message:n})}function Yxn(e){let t;try{t=new URL(e)}catch(n){throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Browser base URL is invalid",void 0,{cause:n})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires HTTP(S)");if(t.username||t.password||t.search||t.hash)throw new ve("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 ve("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport must use a loopback host");if(!t.port)throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Browser transport requires an explicit port");return t.pathname="/v1/automation/",t}function Kxn(e){if(typeof e!="string"||e.length<32||e.length>512||/\s/.test(e))throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Browser session token is invalid");return e}async function VQe(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw new ve("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);if(e.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new ve("AUTOMATION_RESPONSE_INVALID","XENO Browser response is not application/json");if(!e.body)throw new ve("AUTOMATION_RESPONSE_INVALID","XENO Browser response body is missing");let i=e.body.getReader(),o=[],s=0;try{for(;;){let{done:c,value:d}=await L2(i.read(),r);if(c)break;if(s+=d.byteLength,s>t)throw await i.cancel("response too large"),new ve("AUTOMATION_RESPONSE_INVALID",`XENO Browser response exceeds ${t} bytes`);o.push(d)}}finally{i.cancel().catch(()=>{}),i.releaseLock()}let a=new Uint8Array(s),l=0;for(let c of o)a.set(c,l),l+=c.byteLength;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch(c){throw new ve("AUTOMATION_RESPONSE_INVALID","XENO Browser response contains invalid JSON",void 0,{cause:c})}}async function L2(e,t){let r,n=new Promise((i,o)=>{r=()=>o(t.reason??new Error("Automation operation cancelled")),t.addEventListener("abort",r,{once:!0}),t.aborted&&r()});try{return await Promise.race([e,n])}finally{t.removeEventListener("abort",r)}}function Zxn(e){return mNe(e)&&mNe(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 qQe(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 DSt(e,t,r,n){if(!Number.isSafeInteger(e)||e<t||e>r)throw new ve("AUTOMATION_TRANSPORT_ERROR",`${n} must be an integer from ${t} to ${r}`);return e}function mNe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function LSt(e){return typeof e=="string"&&e.length>=32&&e.length<=16384&&!/\s/.test(e)}function ph(e){throw new ve("AUTOMATION_POLICY_DENIED",e)}function Ore(e){throw new ve("AUTOMATION_OPERATION_CONFLICT",e)}function PBe(e,t,r,n){return e===void 0?t:Number.isSafeInteger(e)&&e>=r&&e<=n?e:ph("Invalid browser owner bound")}function gNe(e){return Array.isArray(e)?e.map(gNe):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>[t,gNe(r)])):e}function Wg(e){return eCn("sha256").update(JSON.stringify(gNe(e))).digest("hex")}function xm(e){let t;try{t=JSON.stringify(e)}catch{return ph("Browser owner input must be JSON")}(!t||Buffer.byteLength(t)>2*1024*1024)&&ph("Browser owner JSON exceeds 2 MiB");let r=JSON.parse(t),n=i=>{if(i&&typeof i=="object"){Object.freeze(i);for(let o of Object.values(i))n(o)}};return n(r),r}function Loe(e){return ANe(e)}function ANe(e){try{let t=JSON.stringify(e);if(!t||Buffer.byteLength(t)>Doe)throw tn();return rCn("sha256").update(JSON.stringify(wNe(JSON.parse(t)))).digest("hex")}catch{throw tn()}}function wNe(e){return Array.isArray(e)?e.map(wNe):lie(e)?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>[t,wNe(r)])):e}function BBe(){return nCn(32).toString("hex")}function tn(){return Object.assign(new Error("Private computer host authority unavailable or refused"),{code:"AUTOMATION_POLICY_DENIED"})}function USt(e){let t;try{t=JSON.stringify(e)}catch{throw tn()}if(!t||Buffer.byteLength(t)>Doe)throw tn();return Buffer.from(`${t}
|
|
786
|
-
`)}function lie(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function Pde(e){e=Object.freeze({...e});let t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol)||!["127.0.0.1","localhost","[::1]"].includes(t.hostname)||!t.port||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw new ve("AUTOMATION_TRANSPORT_ERROR","Extension native host requires an explicit loopback origin.");if(typeof e.token!="string"||e.token.length<32||e.token.length>512||/\s/.test(e.token)||typeof e.assertCurrent!="function"||typeof e.authorizeGrant!="function")throw new ve("AUTOMATION_TRANSPORT_ERROR","Extension native host credentials or authority ports are unavailable.");let r=new Map;async function n(w,y,b,I,v=QSt(),E){let S=new AbortController,x=qQe(I,S),k=setTimeout(()=>S.abort(),6e4);try{S.signal.throwIfAborted();let C=b?{params:y,target:b,operationId:v,...E?{navigationPolicy:E}:{}}:y,P=(e.fetch??globalThis.fetch)(new URL(`/v1/browser/${w}`,t),{method:w==="health"?"GET":"POST",redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},...w==="health"?{}:{body:JSON.stringify(C)},signal:S.signal});P.then($=>{S.signal.aborted&&$.body?.cancel().catch(()=>{})},()=>{});let _=await L2(P,S.signal),R=await VQe(_,8*1024*1024,S.signal);if(!_.ok||!R||R.ok!==!0||!("result"in R))throw new ve("AUTOMATION_TRANSPORT_ERROR",`Extension refused ${w}.`);let B=R.result;if(B&&typeof B=="object"&&("error"in B||"success"in B&&B.success===!1))throw new ve("AUTOMATION_POLICY_DENIED",`Extension ${w} failed or was denied.`);return B}catch(C){throw C instanceof ve?C:new ve(I?.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",`Extension ${w} transport stopped or failed.`)}finally{clearTimeout(k),x()}}function i(w){let y=w?.integrations?.xenoUse,b=y?.scopedTargets;if(y?.contract!=="xeno-use/browser-driver/1"||b?.version!==1||b.bridgeEpoch!==!0||b.documentEpoch!==!0||b.postApprovalRecheck!==!0||b.stopDrain!==!0||b.operationCancellation!==!0||!Array.isArray(w.verbs))throw new ve("AUTOMATION_OPERATION_UNSUPPORTED","Update Extension and its native host: scoped targets and acknowledged cancellation are required.")}let o=await n("health",{});i(o);let s=o.integrations.xenoUse.navigationPolicy,a=s?.version===1&&s.documentRequestInterception===!0&&s.explicitFinish===!0&&s.maxTtlMs===3e4,l=o.integrations.xenoUse,c=a&&s.popupInterception===!0&&l.profileIsolation==="isolated-persistent"&&typeof l.ownerInstanceId=="string"&&/^[a-f0-9-]{36}$/i.test(l.ownerInstanceId),d=new Set(["browser.navigate","browser.back","browser.forward","browser.reload"]),u=Object.keys($Be).filter(w=>o.verbs.includes($Be[w])&&(!d.has(w)||c)),p={protocolVersion:1,adapterId:"xeno-extension-native",adapterVersion:String(o.version??"unknown"),platform:process.platform,architecture:process.arch,operations:u,targetBinding:"atomic-preflight",profileIsolation:c?"isolated-persistent":"shared-user",certified:!1,limitations:[c?"Uses a dedicated owner-launched browser profile.":"Uses the existing signed-in browser profile; no profile isolation.",...c?[]:["Navigation tools require the managed browser owner."],"Native platform qualification is required before release certification."],supports:{accessibilitySnapshots:!0,screenshots:!0,recordings:!1,consoleInspection:!0,networkInspection:!0,storageInspection:!1,pageErrorInspection:!1,visibleCoControl:!0,deterministicHandback:!1,immediateStop:!0,sensitiveRegionRedaction:!1},policyEnforcement:{domain:!0,scheme:!0,port:!0,redirect:c,upload:!1,download:!1}};function f(w,y){let b=y??w.declaredTarget?.tabId;if(!b||!/^[1-9][0-9]*$/.test(b)||!Number.isSafeInteger(Number(b)))throw new ve("AUTOMATION_TARGET_CHANGED","Extension tools require an explicit tabId.");return{tabId:b,runId:w.identity.runId,conversationId:w.identity.sessionId??w.identity.runId}}async function h(w,y,b){let I=f(w,b?.tabId),v=await n("target",{},I,y);if(v?.tabId!==I.tabId||v.runId!==I.runId||v.conversationId!==I.conversationId||typeof v.bridgeEpoch!="string"||!v.bridgeEpoch||!Number.isSafeInteger(v.documentEpoch)||v.documentEpoch<1||typeof v.url!="string")throw new ve("AUTOMATION_TARGET_CHANGED","Extension returned an invalid target binding.");let E=new URL(v.url);if(v.origin!==E.origin)throw new ve("AUTOMATION_TARGET_CHANGED","Extension target origin changed.");if(c&&(typeof v.browserTargetId!="string"||!/^[A-Za-z0-9._-]{1,128}$/.test(v.browserTargetId)))throw new ve("AUTOMATION_TARGET_CHANGED","Managed browser requires its native target identity.");return{target:{tabId:v.tabId,url:v.url,origin:E.origin,domain:E.hostname,port:Number(E.port||(E.protocol==="https:"?443:80))},ownerId:v.bridgeEpoch,documentEpoch:v.documentEpoch,profile:c?"isolated-persistent":"shared-user",...c?{nativeTargetId:v.browserTargetId}:{}}}function m(w,y){return{...f(w,y.target.tabId),bridgeEpoch:y.ownerId,documentEpoch:Number(y.documentEpoch),...y.nativeTargetId?{browserTargetId:y.nativeTargetId}:{}}}async function g(w,y,b,I,v,E=!1){let S=m(w,y),x=QSt(),k=w.executionContract.browser,C=E&&a?{allowedSchemes:k.allowedSchemes,allowedPorts:k.allowedPorts,allowedDomains:kh(w.operation).effect==="act"?k.actAllowedDomains:k.readAllowedDomains,deniedDomains:k.deniedDomains,redirectPolicy:k.redirectPolicy,allowLoopbackDevelopment:k.allowLoopbackDevelopment,initialUrl:y.target.url,ttlMs:3e4,network:w.executionContract.network}:void 0,P=n(b,I,S,v,x,C);r.set(x,{target:S,nativeId:w.operationId,pending:P});try{return await P}finally{!v.aborted&&!C&&r.delete(x)}}let A=new JQe({manifest:p,ports:{assertCurrent:e.assertCurrent,authorizeGrant:e.authorizeGrant,resolveTarget:h,assertTargetUnchanged:async(w,y)=>{let b=[...r.values()].find(v=>v.target.tabId===w.target.tabId)?.target??{tabId:w.target.tabId,runId:"target-check",conversationId:"target-check"},I=await n("target",{},b,y);if(I.bridgeEpoch!==w.ownerId||I.documentEpoch!==w.documentEpoch||I.url!==w.target.url||c&&I.browserTargetId!==w.nativeTargetId)throw new ve("AUTOMATION_TARGET_CHANGED","Extension tab or document changed.")},captureEvidence:async(w,y)=>{await w.assertDispatchAllowed();let b=await g(w.request,w.binding,"screenshot",{},w.signal);if(b?.format!=="png"||typeof b.base64!="string"||b.base64.length>1e6||!/^[A-Za-z0-9+/]+={0,2}$/.test(b.base64))throw new ve("AUTOMATION_EVIDENCE_INVALID","Extension screenshot is invalid or exceeds the inline evidence bound.");return[{evidenceId:`${w.request.operationId}.${y}`,phase:y,kind:"screenshot",title:`Extension ${y}`,mediaType:"image/png",content:{type:"base64",base64:b.base64},sensitivity:"restricted"}]},dispatch:async w=>{let y=$Be[w.request.operation];if(!y)throw new ve("AUTOMATION_OPERATION_UNSUPPORTED","Extension operation is not mapped.");await w.assertDispatchAllowed();let b=await g(w.request,w.binding,y,w.request.parameters,w.signal,!0),I=await h(w.request,w.signal,w.binding.target);return{data:b,observedTarget:I.target}},finish:async w=>{for(let[y,b]of r)if(b.nativeId===w){let I=await n("operation_finish",{},b.target,void 0,y);if(I?.finished!==!0||I.drained!==!0||I.operationId!==y)throw new ve("AUTOMATION_TRANSPORT_ERROR","Extension did not confirm guard completion and drain.");r.delete(y)}},stop:async w=>{for(let[y,b]of r)if(b.nativeId===w){let I=await n("stop",{},b.target,void 0,y);if(I?.stopped!==!0||I.drained!==!0||I.operationId!==y)throw new ve("AUTOMATION_TRANSPORT_ERROR","Extension did not confirm cancellation and drain.");await b.pending.catch(()=>{}),r.delete(y)}}}});return{manifest:async()=>{let w=await n("health",{});if(i(w),w.version!==o.version||JSON.stringify(w.verbs)!==JSON.stringify(o.verbs)||JSON.stringify(w.integrations.xenoUse.navigationPolicy)!==JSON.stringify(s))throw new ve("AUTOMATION_OPERATION_UNSUPPORTED","Extension capabilities changed; reconnect the host session.");if(w.integrations.xenoUse.ownerInstanceId!==l.ownerInstanceId||w.integrations.xenoUse.profileIsolation!==l.profileIsolation)throw new ve("AUTOMATION_TARGET_CHANGED","Extension browser owner changed; reconnect the host session.");return A.manifest()},assertCurrent:w=>A.assertCurrent(w),preflight:(w,y)=>A.preflight(w,y),execute:(w,y,b,I)=>A.execute(w,y,b,I),stop:(w,y)=>A.stop(w,y)}}function mCn(e,t){if(!OBe(e)||e.schemaVersion!==Bde||!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))||!OBe(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!OBe(e.checksum)||e.checksum.algorithm!=="sha256"||typeof e.checksum.value!="string")throw new er("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:t});let r=e,n=ACn(r),i=rFt(n);if(r.checksum.value!==i)throw new er("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new Rde({initialState:r.state}),structuredClone(r)}function gCn(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:rFt(e)}}}function ACn(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function rFt(e){return Ws(JSON.stringify(e)).value}async function VSt(e,t){await eFt(HSt(e),{recursive:!0,mode:448});let r=`${e}.tmp.${process.pid}.${ZLt()}`,n;try{n=await GSt(r,"wx",384),await n.writeFile(t,{encoding:"utf8"}),await n.sync(),await n.close(),n=void 0,await qN(r,e);try{let i=await GSt(HSt(e),"r");try{await i.sync()}finally{await i.close()}}catch{}}finally{n&&await n.close().catch(()=>{}),await lCn(r).catch(()=>{})}}function MBe(e,t,r,n,i){if(e===void 0)return t;if(!Number.isInteger(e)||e<r||e>n)throw new TypeError(`${i} must be an integer between ${r} and ${n}`);return e}function OBe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bNe(e,t){return e instanceof Error&&e.code===t}async function wCn(e){try{return(await tFt(e)).isFile()}catch(t){if(bNe(t,"ENOENT"))return!1;throw vNe("Unable to inspect artifact repository backup",e,t)}}function Foe(e){return e instanceof Error?e:new Error(String(e))}function vNe(e,t,r,n=!1){return new er(n?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${Foe(r).message}`,{snapshotPath:t},{cause:Foe(r)})}function yCn(e){return new Promise(t=>setTimeout(t,e))}function XQe(e){return NCn(e.operations??CR).map(t=>kCn(t,e.runtime))}function kCn(e,t){return{definition:{name:e,description:RCn(e),input_schema:SCn(e)},projectPolicyInput(r){let n=BCn(e,r),i=_Cn(e,r);return{observabilityInput:n,permissionInput:i,permissionPreview:$Cn(e,r),approvalKey:`xeno-automation:${e}:${DCn(r)}`,riskLevel:PCn(e)}},async execute(r,n){if(e==="browser.screenshot"&&(typeof r.tabId!="string"||!r.tabId.trim()))return{success:!1,output:"",error:"Screen capture requires an explicit authorized tabId.",errorCode:"AUTOMATION_CAPTURE_TARGET_REQUIRED",retryable:!1};let i=n?.authorization;if(!i||i.toolName!==e)return{success:!1,output:"",error:"Governed automation requires a host-issued authorization receipt",errorCode:"AUTOMATION_AUTHORIZATION_RECEIPT_REQUIRED",retryable:!1};let o=n.operationId??`automation_${vCn()}`,s=YQe(e,r);n.reportProgress?.({activity:"state",message:`Authorizing ${e}`});try{let a=await t.execute({operation:e,governingToolName:e,operationId:o,idempotencyKey:o,parameters:structuredClone(r),...s?{declaredTarget:s}:{},authorization:i,...n.signal?{signal:n.signal}:{},...n.reportProgress?{reportProgress:n.reportProgress}:{}}),l=a.status==="ok";return{success:l,output:JSON.stringify(MCn(a)),...l?{}:{error:a.error?.message??`Governed automation ended with ${a.status}`,errorCode:a.error?.code??`AUTOMATION_${a.status.toUpperCase().replaceAll("-","_")}`},assistantContent:OCn(a),evidence:a.artifacts.map(c=>({id:c.artifactId,kind:"artifact",status:a.status==="evidence-incomplete"?"failed":"verified",observedAt:c.updatedAt??c.createdAt,operationId:o,detail:{artifact_kind:c.kind,revision:c.revision,sensitivity:c.sensitivity}})),retryable:a.error?.retryable??!1}}catch(a){let l=n.signal?.aborted===!0;return{success:!1,output:"",error:l?"Governed automation was stopped":LCn(a),errorCode:l?"AUTOMATION_CANCELLED":FCn(a),retryable:!1}}}}}function SCn(e){let t=xCn(e),r=CCn(e);return{type:"object",properties:t,...r.length>0?{required:r}:{},...e==="browser.locate"?{oneOf:[{required:["selector"]},{required:["text"]}]}:{},additionalProperties:!1}}function xCn(e){let t=(s,a=8192)=>({type:"string",minLength:1,maxLength:a,description:s}),r={type:"number"},n={type:"boolean"},i={type:"object",properties:{x:r,y:r},required:["x","y"],additionalProperties:!1},o={deviceId:t("Target xeno-use device ID.",256),applicationId:t("Expected or launch-target application ID.",512),displayId:t("Target display ID.",256)};switch(e){case"browser.navigate":return{url:t("Destination URL."),waitUntil:{enum:["load","none"]},tabId:t("Expected active tab ID. Hosts with multiple visible tabs should require this.",256)};case"browser.wait":return{until:{enum:["load","ms"]},value:{type:"integer",minimum:0,maximum:6e4}};case"browser.snapshot":return{mode:{enum:["text","html","markdown","a11y"]},tabId:t("Expected active tab ID.",256)};case"browser.screenshot":return{tabId:t("Expected active tab ID.",256)};case"browser.locate":return{selector:t("CSS selector."),text:t("Visible text to locate.")};case"browser.click":return{selector:t("CSS selector returned by browser.snapshot or browser.locate."),tabId:t("Expected active tab ID.",256)};case"browser.type":return{selector:t("CSS selector."),text:{type:"string",maxLength:65536},clear:n,submit:n,tabId:t("Expected active tab ID.",256)};case"browser.key":return{combo:t("Key combo such as Control+a or Enter.",256),tabId:t("Expected active tab ID.",256)};case"browser.select":return{selector:t("CSS selector."),value:t("Option value."),tabId:t("Expected active tab ID.",256)};case"browser.scroll":return{selector:t("Optional CSS selector."),dx:r,dy:r,tabId:t("Expected active tab ID.",256)};case"browser.tabs.open":return{url:t("URL to open in an isolated browser tab.")};case"browser.tabs.close":return{tabId:t("Tab ID to close.",256)};case"browser.console.read":case"browser.network.read":case"browser.page-errors.read":return{limit:{type:"integer",minimum:1,maximum:1e3},clear:n,tabId:t("Expected active tab ID.",256)};case"browser.storage.read":return{tabId:t("Expected active tab ID.",256)};case"browser.upload":return{selector:t("File input or drop-target selector."),backendNodeId:{type:"integer",minimum:1},hostPaths:{type:"array",items:t("Host file path.",32768),minItems:1,maxItems:64},drop:n,tabId:t("Expected active tab ID.",256)};case"browser.download":return{toPath:t("Approved destination path.",32768),trigger:{type:"object",properties:{url:t("Download URL."),selector:t("Download trigger selector.")},oneOf:[{required:["url"]},{required:["selector"]}],additionalProperties:!1},tabId:t("Expected active tab ID.",256)};case"browser.record.start":return{maxDurationMs:{type:"integer",minimum:1e3,maximum:6e4},intervalMs:{type:"integer",minimum:100,maximum:5e3},tabId:t("Expected active tab ID.",256)};case"browser.record.stop":return{tabId:t("Expected active tab ID.",256)};case"computer.observe":case"computer.screenshot":case"computer.window-state":return o;case"computer.point":return{...o,point:i,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.click":return{...o,point:i,button:{enum:["left","right","middle"]},modifiers:TCn()};case"computer.double-click":case"computer.right-click":return{...o,point:i};case"computer.drag":return{...o,from:i,to:i,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.type":return{...o,text:{type:"string",maxLength:65536}};case"computer.key":return{...o,combo:t("Key combo such as Control+a or Enter.",256)};case"computer.scroll":return{...o,at:i,delta:i};case"computer.wait":return{...o,milliseconds:{type:"integer",minimum:0,maximum:3e5}};case"computer.launch":return{...o,applicationId:t("Explicitly allowlisted application ID.",512)};case"browser.back":case"browser.forward":case"browser.reload":return{tabId:t("Expected active tab ID.",256)};case"browser.tabs.list":return{}}}function CCn(e){switch(e){case"browser.navigate":case"browser.tabs.open":return["url"];case"browser.click":return["selector"];case"browser.type":return["selector","text"];case"browser.key":return["combo"];case"browser.select":return["selector","value"];case"browser.upload":return["hostPaths"];case"browser.download":return["toPath","trigger"];case"browser.screenshot":return["tabId"];case"computer.point":case"computer.click":case"computer.double-click":case"computer.right-click":return["point"];case"computer.drag":return["from","to"];case"computer.type":return["text"];case"computer.key":return["combo"];case"computer.scroll":return["at","delta"];case"computer.launch":return["applicationId"];default:return[]}}function TCn(){return{type:"object",properties:{shift:{type:"boolean"},ctrl:{type:"boolean"},alt:{type:"boolean"},meta:{type:"boolean"}},additionalProperties:!1}}function RCn(e){let t=kh(e),r=e.split(".").slice(1).join(" ");return`${t.effect==="act"?"Act on":"Inspect"} the ${t.surface} using governed ${r} automation. The host requires policy approval, an exact capability lease, target-bound preflight, and durable evidence.`}function PCn(e){return kh(e).effect==="observe"?e==="browser.navigate"||e==="browser.tabs.open"?"medium":"low":["browser.type","browser.upload","browser.download","computer.type","computer.key","computer.launch"].includes(e)?"high":"medium"}function _Cn(e,t){let r=YQe(e,t),n={operation:e};r&&(n.target=r);for(let i of["selector","clear","submit","combo","value","dx","dy","point","from","to","at","delta","milliseconds"])t[i]!==void 0&&(n[i]=structuredClone(t[i]));return typeof t.text=="string"&&(n.text=`[redacted ${t.text.length} characters]`),Array.isArray(t.hostPaths)&&(n.hostPaths=t.hostPaths.map(()=>"[redacted host path]")),typeof t.toPath=="string"&&(n.toPath="[redacted destination path]"),n}function BCn(e,t){let r=structuredClone(t);return typeof r.text=="string"&&(r.text=`[redacted ${r.text.length} characters]`),Array.isArray(r.hostPaths)&&(r.hostPaths=r.hostPaths.map(()=>"[redacted host path]")),typeof r.toPath=="string"&&(r.toPath="[redacted destination path]"),nFt(r.trigger)&&typeof r.trigger.url=="string"&&(r.trigger={...r.trigger,url:qSt(r.trigger.url)}),typeof r.url=="string"&&(r.url=qSt(r.url)),{operation:e,...r}}function $Cn(e,t){let r=YQe(e,t),n=r?.url??r?.applicationId??r?.deviceId??r?.tabId??r?.resource??"current target";return`${e} on ${n}`}function YQe(e,t){let r={};return typeof t.url=="string"&&(r.url=t.url),typeof t.tabId=="string"&&(r.tabId=t.tabId),typeof t.deviceId=="string"&&(r.deviceId=t.deviceId),typeof t.applicationId=="string"&&(r.applicationId=t.applicationId),typeof t.displayId=="string"&&(r.displayId=t.displayId),(e==="browser.navigate"||e==="browser.tabs.list"||e==="browser.tabs.open")&&(r.resource="browser-tabs"),Object.keys(r).length>0?r:void 0}function MCn(e){return{operationId:e.operationId,status:e.status,effect:e.effect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:e.adapter,target:e.target,...e.data!==void 0?{data:e.data}:{},artifacts:e.artifacts.map(t=>({artifactId:t.artifactId,revision:t.revision,kind:t.kind,title:t.title,state:t.state,mediaType:t.mediaType,sensitivity:t.sensitivity,hash:t.content.hash,sizeBytes:t.content.sizeBytes})),lease:e.lease,...e.error?{error:e.error}:{}}}function OCn(e){let t=[];for(let r of e.artifacts){if(t.length>=ECn||!r.mediaType.startsWith("image/"))continue;let n=r.content.storage;if(n.type!=="inline"||typeof n.base64!="string")continue;let i=Math.floor(n.base64.length*.75);i<=0||i>ICn||t.push({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${n.base64}`,detail:"high"}})}return t}function NCn(e){let t=new Set(CR),r=new Set;for(let n of e){if(!t.has(n))throw new TypeError(`Unsupported XENO automation operation: ${String(n)}`);r.add(n)}return Array.from(r)}function DCn(e){return bCn("sha256").update(INe(e)).digest("hex")}function INe(e){return Array.isArray(e)?`[${e.map(INe).join(",")}]`:nFt(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${INe(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function qSt(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid URL]"}}function LCn(e){return e instanceof Error?e.message:String(e)}function FCn(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:"AUTOMATION_EXECUTION_FAILED"}function nFt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ode(e){return new Mde(e)}function gS(e){if(e)return async t=>{let r=kh(t.operation).effect;await e.append({trace_id:t.traceId,event_type:t.eventType,actor:"system",risk_level:r==="act"?"high":"low",...t.eventType==="automation_lease_approved"?{decision:"allow"}:{},status:t.eventType==="automation_failed"?"error":"ok",...t.eventType==="automation_failed"&&t.status?{reason:t.status}:{},metadata:{operation:t.operation,operation_id:t.operationId,lease_id:t.leaseId,contract_fingerprint:t.contractFingerprint,result_status:t.status,artifact_ids:t.artifactIds,permission_reason:t.permissionReason}})}}async function Iq(e=nI()){let t=await Promise.all([WSt("browser",e),WSt("computer",e)]);return{schemaVersion:1,protocolVersion:1,enabled:t.some(r=>r.configured),surfaces:t,docs:"docs/GOVERNED_AUTOMATION.md"}}function nI(e=process.env){let t=iA(e.XENO_EXTENSION_SESSION_FILE)??yNe(KLt(),".xeno","use-drivers","xeno-extension.json"),r=e.XENO_BROWSER_DRIVER==="extension"||!e.XENO_BROWSER_DRIVER&&!e.XENO_BROWSER_AUTOMATION_URL&&!e.XENO_BROWSER_SESSION_FILE&&zQe(t)?"extension":"browser",n=jCn(e,r),i=iA(e.XENO_BROWSER_AUTOMATION_URL)??n?.baseUrl,o=iA(e.XENO_BROWSER_AUTOMATION_TOKEN)??n?.token,s=iA(e.XENO_USE_BASE_URL),a=iA(e.XENO_USE_TOKEN)??GCn(e.XENO_USE_TOKEN_FILE),l=iA(e.XENO_USE_DEVICE_ID);return{browser:{driver:r,...i?{baseUrl:i}:{},...o?{token:o}:{},readDomains:Dre(e.XENO_BROWSER_READ_DOMAINS),actDomains:Dre(e.XENO_BROWSER_ACT_DOMAINS),deniedDomains:Dre(e.XENO_BROWSER_DENIED_DOMAINS),ports:XCn(e.XENO_BROWSER_ALLOWED_PORTS,[443]),allowLoopbackDevelopment:e.XENO_BROWSER_ALLOW_LOOPBACK_DEVELOPMENT==="1",uploads:JSt(e.XENO_BROWSER_UPLOADS,"prompt"),downloads:JSt(e.XENO_BROWSER_DOWNLOADS,"prompt"),recording:e.XENO_BROWSER_RECORDING==="bounded"?"bounded":"disabled"},computer:{...s?{baseUrl:s}:{},...a?{token:a}:{},...l?{deviceId:l}:{},allowedApplications:Dre(e.XENO_USE_ALLOWED_APPLICATIONS)}}}function GCn(e){let t=iA(e);if(!(!t||!zQe(t)))try{return iA(YLt(t,"utf8"))}catch{return}}function jCn(e,t){let r=iA(e.XENO_BROWSER_SESSION_FILE)??(t==="extension"?iA(e.XENO_EXTENSION_SESSION_FILE)??yNe(KLt(),".xeno","use-drivers","xeno-extension.json"):iA(e.XENO_SESSION_FILE)??(e.APPDATA?yNe(e.APPDATA,"xeno-browser","session.json"):void 0));if(!(!r||!zQe(r)))try{let n=JSON.parse(YLt(r,"utf8")),i=Number(n.port),o=typeof n.token=="string"?n.token:"",s=typeof n.driver=="string"?n.driver:void 0;return!Number.isSafeInteger(i)||i<=0||i>65535||!HCn(o)||s&&s!==(t==="extension"?"xeno-extension-native":"xeno-browser-loopback")?void 0:{baseUrl:`http://127.0.0.1:${i}`,token:o}}catch{return}}function HCn(e){return e.length>=32&&e.length<=512&&!/\s/.test(e)}async function WSt(e,t){let r=e==="browser"?t.browser:t.computer,n=e==="browser"?ENe(t.browser):Uoe(t.computer),i=!!r&&Object.values(r).some(o=>typeof o=="string"&&o.length>0);if(!n)return{surface:e,configured:!1,available:!1,certified:!1,operations:[],limitations:["Adapter credentials are not completely configured."],...i?{error:e==="browser"?oFt(t.browser):KQe(t.computer)}:{}};try{let o=await(e==="browser"?t.browser.driver==="extension"?await Pde({baseUrl:t.browser.baseUrl,token:t.browser.token,assertCurrent:async()=>{throw new Error("Status inspection cannot authorize browser effects.")},authorizeGrant:async()=>{throw new Error("Status inspection cannot issue browser grants.")}}):new _de({baseUrl:t.browser.baseUrl,token:t.browser.token,driver:t.browser.driver,...t.browser.ownedView?{ownedView:t.browser.ownedView}:{}}):await iFt(t.computer)).manifest();if($y(o),e==="computer"&&cie("observe",t).sensitiveRegionRedaction&&o.supports.sensitiveRegionRedaction!==!0)throw new Error("Owning computer adapter cannot satisfy this host's required sensitive-region redaction.");return VCn(e,o)}catch(o){return{surface:e,configured:!0,available:!1,certified:!1,operations:[],limitations:["Configured adapter is unavailable."],error:uFt(o)}}}async function iFt(e){if(e={...e},!Uoe(e))throw new Error(KQe(e));return new WQe({baseUrl:e.baseUrl,...e.authorize?{authorize:e.authorize}:{token:e.token}})}function VCn(e,t){return{surface:e,configured:!0,available:!0,certified:t.certified,adapterId:t.adapterId,adapterVersion:t.adapterVersion,operations:[...t.operations],limitations:[...t.limitations]}}function qCn(e,t,r,n){let i=r.browser,o=aFt(t),s=o&&!cFt(o.hostname)?o.hostname:void 0,a=Qoe([...i.readDomains,...s?[s]:[]]),l=Qoe([...i.actDomains,...e==="act"&&s?[s]:[]]),c=dFt([...i.ports,...o?[lFt(o)]:[]]);return{mode:e==="act"?"act":"read",profile:i.driver==="extension"?n==="isolated-persistent"?"isolated-persistent":"shared-user":"ephemeral",readAllowedDomains:a,actAllowedDomains:l,deniedDomains:i.deniedDomains,allowedSchemes:i.allowLoopbackDevelopment?["https","http"]:["https"],allowedPorts:c,redirectPolicy:"policy",allowLoopbackDevelopment:i.allowLoopbackDevelopment,uploads:i.uploads,downloads:i.downloads,recording:i.recording}}function cie(e,t){return{mode:e==="act"?"act":"observe",allowedApplications:t.computer?.allowedApplications??[],sensitiveRegionRedaction:!0,humanStopRequired:!0}}function WCn(e,t){let r=[],n=aFt(e);n&&r.push({scheme:n.protocol.replace(/:$/,""),host:n.hostname.toLowerCase(),port:lFt(n)});for(let i of Qoe([...t.browser?.readDomains??[],...t.browser?.actDomains??[]]))if(!(i.startsWith(".")||i.includes("*")))for(let o of t.browser?.ports??[443])r.push({scheme:o===80?"http":"https",host:i,port:o});return{default:"deny",allowDestinations:YCn(r)}}function JCn(e,t,r){if(!e.startsWith("computer."))return t;let n=t?.deviceId??r.computer?.deviceId,i=t?.applicationId;if(!(!n&&!i&&!t))return{...t??{},...n?{deviceId:n}:{}}}function R3(e){let t=e.authorization;if(!t||t.toolName!==e.governingToolName||!t.permission.allowed||!t.policy.allowed)throw new Error("Automation authorization receipt does not match the governing tool");rDe(t,e.governingToolName,e.parameters)}function zCn(e){try{return JSON.parse(JSON.stringify(e))}catch(t){throw new Error(`Automation parameters are not JSON serializable: ${uFt(t)}`)}}function ENe(e){return!!e?.baseUrl&&!!e.token}function Uoe(e,t=!1){return sFt(e,t)===void 0}function oFt(e){return`Browser automation configuration is incomplete; missing ${[e?.baseUrl?"":"XENO_BROWSER_AUTOMATION_URL",e?.token?"":"XENO_BROWSER_AUTOMATION_TOKEN"].filter(Boolean).join(", ")}`}function KQe(e,t=!1){return sFt(e,t)??"Computer automation configuration is unavailable."}function sFt(e,t){let r=e?.token!==void 0,n=e?.authorize!==void 0;if(r&&n)return"Computer automation requires exactly one bootstrap token or canonical request authorizer.";if(n&&typeof e?.authorize!="function")return"Computer automation requires a callable canonical request authorizer.";if(r&&(typeof e?.token!="string"||!e.token.trim()))return"Computer automation bootstrap token is invalid.";if(e?.baseUrl!==void 0)try{let o=new URL(e.baseUrl);if(o.username||o.password||o.search||o.hash||o.pathname!=="/"||o.protocol!=="https:"&&!(o.protocol==="http:"&&cFt(o.hostname)&&!n))return"Computer automation requires an HTTPS origin; explicit bootstrap compatibility may use loopback HTTP only."}catch{return"Computer automation endpoint must be a valid origin."}let i=[!t&&!e?.baseUrl?"XENO_USE_BASE_URL":"",!t&&!r&&!n?"XENO_USE_TOKEN or canonical request authorizer":"",e?.deviceId?.trim()?"":"XENO_USE_DEVICE_ID"].filter(Boolean);return i.length?`Computer automation configuration is incomplete; missing ${i.join(", ")}`:void 0}function aFt(e){let t=e?.url??e?.origin;if(t)try{return new URL(t)}catch{return}}function lFt(e){return e.port?Number(e.port):e.protocol==="http:"?80:443}function cFt(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"}function Dre(e){return Qoe((e??"").split(",").map(t=>t.trim().toLowerCase()).filter(Boolean))}function XCn(e,t){let r=(e??"").split(",").map(n=>Number(n.trim())).filter(n=>Number.isSafeInteger(n)&&n>0&&n<=65535);return r.length>0?dFt(r):t}function JSt(e,t){return e==="deny"||e==="prompt"||e==="allow"?e:t}function iA(e){return e?.trim()||void 0}function Qoe(e){return[...new Set(e)]}function dFt(e){return[...new Set(e)].sort((t,r)=>t-r)}function YCn(e){let t=new Set;return e.filter(r=>{let n=`${r.scheme??""}:${r.host}:${r.port??""}`;return t.has(n)?!1:(t.add(n),!0)})}function uFt(e){return e instanceof Error?e.message:String(e)}function Eq(e){let t=["XENO governed automation",""];for(let r of e.surfaces){let n=r.configured?r.available?"available":"unavailable":"not configured",i=r.certified?"certified":"not release-certified";t.push(`${r.surface}: ${n}; ${i}`),r.adapterId&&t.push(` adapter: ${r.adapterId}@${r.adapterVersion??"unknown"}`),r.operations.length>0&&t.push(` operations: ${r.operations.length}`);for(let o of r.limitations)t.push(` limitation: ${o}`);r.error&&t.push(` error: ${r.error}`)}return t.push("",`Docs: ${e.docs}`),t.join(`
|
|
786
|
+
`)}function lie(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function Pde(e){e=Object.freeze({...e});let t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol)||!["127.0.0.1","localhost","[::1]"].includes(t.hostname)||!t.port||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw new ve("AUTOMATION_TRANSPORT_ERROR","Extension native host requires an explicit loopback origin.");if(typeof e.token!="string"||e.token.length<32||e.token.length>512||/\s/.test(e.token)||typeof e.assertCurrent!="function"||typeof e.authorizeGrant!="function")throw new ve("AUTOMATION_TRANSPORT_ERROR","Extension native host credentials or authority ports are unavailable.");let r=new Map;async function n(y,b,I,v,E=QSt(),S){let x=new AbortController,k=qQe(v,x),C=setTimeout(()=>x.abort(),6e4);try{x.signal.throwIfAborted();let P=I?{params:b,target:I,operationId:E,...S?{navigationPolicy:S}:{}}:b,_=(e.fetch??globalThis.fetch)(new URL(`/v1/browser/${y}`,t),{method:y==="health"?"GET":"POST",redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},...y==="health"?{}:{body:JSON.stringify(P)},signal:x.signal});_.then(O=>{x.signal.aborted&&O.body?.cancel().catch(()=>{})},()=>{});let R=await L2(_,x.signal),B=await VQe(R,8*1024*1024,x.signal);if(!R.ok||!B||B.ok!==!0||!("result"in B))throw new ve("AUTOMATION_TRANSPORT_ERROR",`Extension refused ${y}.`);let $=B.result;if($&&typeof $=="object"&&("error"in $||"success"in $&&$.success===!1))throw new ve("AUTOMATION_POLICY_DENIED",`Extension ${y} failed or was denied.`);return $}catch(P){throw P instanceof ve?P:new ve(v?.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",`Extension ${y} transport stopped or failed.`)}finally{clearTimeout(C),k()}}function i(y){let b=y?.integrations?.xenoUse,I=b?.scopedTargets;if(b?.contract!=="xeno-use/browser-driver/1"||I?.version!==1||I.bridgeEpoch!==!0||I.documentEpoch!==!0||I.postApprovalRecheck!==!0||I.stopDrain!==!0||I.operationCancellation!==!0||!Array.isArray(y.verbs))throw new ve("AUTOMATION_OPERATION_UNSUPPORTED","Update Extension and its native host: scoped targets and acknowledged cancellation are required.")}let o=await n("health",{});i(o);let s=o.integrations.xenoUse.navigationPolicy,a=s?.version===1&&s.documentRequestInterception===!0&&s.explicitFinish===!0&&s.maxTtlMs===3e4,l=o.integrations.xenoUse,c=a&&s.popupInterception===!0&&l.profileIsolation==="isolated-persistent"&&typeof l.ownerInstanceId=="string"&&/^[a-f0-9-]{36}$/i.test(l.ownerInstanceId),d=new Set(["browser.navigate","browser.back","browser.forward","browser.reload"]),u=Object.keys($Be).filter(y=>o.verbs.includes($Be[y])&&(!d.has(y)||a)),p={protocolVersion:1,adapterId:"xeno-extension-native",adapterVersion:String(o.version??"unknown"),platform:process.platform,architecture:process.arch,operations:u,targetBinding:"atomic-preflight",profileIsolation:c?"isolated-persistent":"shared-user",certified:!1,limitations:[c?"Uses a dedicated owner-launched browser profile.":"Uses the existing signed-in browser profile; no profile isolation.",...c?[]:a?["Popups a page opens itself are not contained on the signed-in profile."]:["Navigation tools need the extension navigation guard."],"Native platform qualification is required before release certification."],supports:{accessibilitySnapshots:!0,screenshots:!0,recordings:!1,consoleInspection:!0,networkInspection:!0,storageInspection:!1,pageErrorInspection:!1,visibleCoControl:!0,deterministicHandback:!1,immediateStop:!0,sensitiveRegionRedaction:!1},policyEnforcement:{domain:!0,scheme:!0,port:!0,redirect:a,upload:!1,download:!1}};function f(y,b){let I=b??y.declaredTarget?.tabId;if(!I||!/^[1-9][0-9]*$/.test(I)||!Number.isSafeInteger(Number(I)))throw new ve("AUTOMATION_TARGET_CHANGED","Extension tools require an explicit tabId.");return{tabId:I,runId:y.identity.runId,conversationId:y.identity.sessionId??y.identity.runId}}async function h(y){let b=await n("tabs_list",{},void 0,y),I=Array.isArray(b)?b:b?.tabs??[],v=I.find(E=>E.active===!0)??I[0];if(v?.id===void 0)throw new ve("AUTOMATION_TARGET_CHANGED","The browser has no open tab.");return String(v.id)}async function m(y,b,I){let v=I?.tabId??y.declaredTarget?.tabId,E=f(y,v??(y.operation==="browser.tabs.list"?await h(b):void 0)),S=await n("target",{},E,b);if(S?.tabId!==E.tabId||S.runId!==E.runId||S.conversationId!==E.conversationId||typeof S.bridgeEpoch!="string"||!S.bridgeEpoch||!Number.isSafeInteger(S.documentEpoch)||S.documentEpoch<1||typeof S.url!="string")throw new ve("AUTOMATION_TARGET_CHANGED","Extension returned an invalid target binding.");let x=new URL(S.url);if(S.origin!==x.origin)throw new ve("AUTOMATION_TARGET_CHANGED","Extension target origin changed.");if(c&&(typeof S.browserTargetId!="string"||!/^[A-Za-z0-9._-]{1,128}$/.test(S.browserTargetId)))throw new ve("AUTOMATION_TARGET_CHANGED","Managed browser requires its native target identity.");return{target:{tabId:S.tabId,url:S.url,origin:x.origin,domain:x.hostname,port:Number(x.port||(x.protocol==="https:"?443:80))},ownerId:S.bridgeEpoch,documentEpoch:S.documentEpoch,profile:c?"isolated-persistent":"shared-user",...c?{nativeTargetId:S.browserTargetId}:{}}}function g(y,b){return{...f(y,b.target.tabId),bridgeEpoch:b.ownerId,documentEpoch:Number(b.documentEpoch),...b.nativeTargetId?{browserTargetId:b.nativeTargetId}:{}}}async function A(y,b,I,v,E,S=!1){let x=g(y,b),k=QSt(),C=y.executionContract.browser,P=S&&a?{allowedSchemes:C.allowedSchemes,allowedPorts:C.allowedPorts,allowedDomains:kh(y.operation).effect==="act"?C.actAllowedDomains:C.readAllowedDomains,deniedDomains:C.deniedDomains,redirectPolicy:C.redirectPolicy,allowLoopbackDevelopment:C.allowLoopbackDevelopment,initialUrl:b.target.url,ttlMs:3e4,network:y.executionContract.network}:void 0,_=n(I,v,x,E,k,P);r.set(k,{target:x,nativeId:y.operationId,pending:_});try{return await _}finally{!E.aborted&&!P&&r.delete(k)}}let w=new JQe({manifest:p,ports:{assertCurrent:e.assertCurrent,authorizeGrant:e.authorizeGrant,resolveTarget:m,assertTargetUnchanged:async(y,b)=>{let I=[...r.values()].find(E=>E.target.tabId===y.target.tabId)?.target??{tabId:y.target.tabId,runId:"target-check",conversationId:"target-check"},v=await n("target",{},I,b);if(v.bridgeEpoch!==y.ownerId||v.documentEpoch!==y.documentEpoch||v.url!==y.target.url||c&&v.browserTargetId!==y.nativeTargetId)throw new ve("AUTOMATION_TARGET_CHANGED","Extension tab or document changed.")},captureEvidence:async(y,b)=>{await y.assertDispatchAllowed();let I=await A(y.request,y.binding,"screenshot",{},y.signal);if(I?.format!=="png"||typeof I.base64!="string"||I.base64.length>1e6||!/^[A-Za-z0-9+/]+={0,2}$/.test(I.base64))throw new ve("AUTOMATION_EVIDENCE_INVALID","Extension screenshot is invalid or exceeds the inline evidence bound.");return[{evidenceId:`${y.request.operationId}.${b}`,phase:b,kind:"screenshot",title:`Extension ${b}`,mediaType:"image/png",content:{type:"base64",base64:I.base64},sensitivity:"restricted"}]},dispatch:async y=>{let b=$Be[y.request.operation];if(!b)throw new ve("AUTOMATION_OPERATION_UNSUPPORTED","Extension operation is not mapped.");await y.assertDispatchAllowed();let I=await A(y.request,y.binding,b,y.request.parameters,y.signal,!0),v=await m(y.request,y.signal,y.binding.target);return{data:I,observedTarget:v.target}},finish:async y=>{for(let[b,I]of r)if(I.nativeId===y){let v=await n("operation_finish",{},I.target,void 0,b);if(v?.finished!==!0||v.drained!==!0||v.operationId!==b)throw new ve("AUTOMATION_TRANSPORT_ERROR","Extension did not confirm guard completion and drain.");r.delete(b)}},stop:async y=>{for(let[b,I]of r)if(I.nativeId===y){let v=await n("stop",{},I.target,void 0,b);if(v?.stopped!==!0||v.drained!==!0||v.operationId!==b)throw new ve("AUTOMATION_TRANSPORT_ERROR","Extension did not confirm cancellation and drain.");await I.pending.catch(()=>{}),r.delete(b)}}}});return{manifest:async()=>{let y=await n("health",{});if(i(y),y.version!==o.version||JSON.stringify(y.verbs)!==JSON.stringify(o.verbs)||JSON.stringify(y.integrations.xenoUse.navigationPolicy)!==JSON.stringify(s))throw new ve("AUTOMATION_OPERATION_UNSUPPORTED","Extension capabilities changed; reconnect the host session.");if(y.integrations.xenoUse.ownerInstanceId!==l.ownerInstanceId||y.integrations.xenoUse.profileIsolation!==l.profileIsolation)throw new ve("AUTOMATION_TARGET_CHANGED","Extension browser owner changed; reconnect the host session.");return w.manifest()},assertCurrent:y=>w.assertCurrent(y),preflight:(y,b)=>w.preflight(y,b),execute:(y,b,I,v)=>w.execute(y,b,I,v),stop:(y,b)=>w.stop(y,b)}}function mCn(e,t){if(!OBe(e)||e.schemaVersion!==Bde||!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))||!OBe(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!OBe(e.checksum)||e.checksum.algorithm!=="sha256"||typeof e.checksum.value!="string")throw new er("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:t});let r=e,n=ACn(r),i=rFt(n);if(r.checksum.value!==i)throw new er("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new Rde({initialState:r.state}),structuredClone(r)}function gCn(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:rFt(e)}}}function ACn(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function rFt(e){return Ws(JSON.stringify(e)).value}async function VSt(e,t){await eFt(HSt(e),{recursive:!0,mode:448});let r=`${e}.tmp.${process.pid}.${ZLt()}`,n;try{n=await GSt(r,"wx",384),await n.writeFile(t,{encoding:"utf8"}),await n.sync(),await n.close(),n=void 0,await qN(r,e);try{let i=await GSt(HSt(e),"r");try{await i.sync()}finally{await i.close()}}catch{}}finally{n&&await n.close().catch(()=>{}),await lCn(r).catch(()=>{})}}function MBe(e,t,r,n,i){if(e===void 0)return t;if(!Number.isInteger(e)||e<r||e>n)throw new TypeError(`${i} must be an integer between ${r} and ${n}`);return e}function OBe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bNe(e,t){return e instanceof Error&&e.code===t}async function wCn(e){try{return(await tFt(e)).isFile()}catch(t){if(bNe(t,"ENOENT"))return!1;throw vNe("Unable to inspect artifact repository backup",e,t)}}function Foe(e){return e instanceof Error?e:new Error(String(e))}function vNe(e,t,r,n=!1){return new er(n?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${Foe(r).message}`,{snapshotPath:t},{cause:Foe(r)})}function yCn(e){return new Promise(t=>setTimeout(t,e))}function XQe(e){return NCn(e.operations??CR).map(t=>kCn(t,e.runtime))}function kCn(e,t){return{definition:{name:e,description:RCn(e),input_schema:SCn(e)},projectPolicyInput(r){let n=BCn(e,r),i=_Cn(e,r);return{observabilityInput:n,permissionInput:i,permissionPreview:$Cn(e,r),approvalKey:`xeno-automation:${e}:${DCn(r)}`,riskLevel:PCn(e)}},async execute(r,n){if(e==="browser.screenshot"&&(typeof r.tabId!="string"||!r.tabId.trim()))return{success:!1,output:"",error:"Screen capture requires an explicit authorized tabId.",errorCode:"AUTOMATION_CAPTURE_TARGET_REQUIRED",retryable:!1};let i=n?.authorization;if(!i||i.toolName!==e)return{success:!1,output:"",error:"Governed automation requires a host-issued authorization receipt",errorCode:"AUTOMATION_AUTHORIZATION_RECEIPT_REQUIRED",retryable:!1};let o=n.operationId??`automation_${vCn()}`,s=YQe(e,r);n.reportProgress?.({activity:"state",message:`Authorizing ${e}`});try{let a=await t.execute({operation:e,governingToolName:e,operationId:o,idempotencyKey:o,parameters:structuredClone(r),...s?{declaredTarget:s}:{},authorization:i,...n.signal?{signal:n.signal}:{},...n.reportProgress?{reportProgress:n.reportProgress}:{}}),l=a.status==="ok";return{success:l,output:JSON.stringify(MCn(a)),...l?{}:{error:a.error?.message??`Governed automation ended with ${a.status}`,errorCode:a.error?.code??`AUTOMATION_${a.status.toUpperCase().replaceAll("-","_")}`},assistantContent:OCn(a),evidence:a.artifacts.map(c=>({id:c.artifactId,kind:"artifact",status:a.status==="evidence-incomplete"?"failed":"verified",observedAt:c.updatedAt??c.createdAt,operationId:o,detail:{artifact_kind:c.kind,revision:c.revision,sensitivity:c.sensitivity}})),retryable:a.error?.retryable??!1}}catch(a){let l=n.signal?.aborted===!0;return{success:!1,output:"",error:l?"Governed automation was stopped":LCn(a),errorCode:l?"AUTOMATION_CANCELLED":FCn(a),retryable:!1}}}}}function SCn(e){let t=xCn(e),r=CCn(e);return{type:"object",properties:t,...r.length>0?{required:r}:{},...e==="browser.locate"?{oneOf:[{required:["selector"]},{required:["text"]}]}:{},additionalProperties:!1}}function xCn(e){let t=(s,a=8192)=>({type:"string",minLength:1,maxLength:a,description:s}),r={type:"number"},n={type:"boolean"},i={type:"object",properties:{x:r,y:r},required:["x","y"],additionalProperties:!1},o={deviceId:t("Target xeno-use device ID.",256),applicationId:t("Expected or launch-target application ID.",512),displayId:t("Target display ID.",256)};switch(e){case"browser.navigate":return{url:t("Destination URL."),waitUntil:{enum:["load","none"]},tabId:t("Expected active tab ID. Hosts with multiple visible tabs should require this.",256)};case"browser.wait":return{until:{enum:["load","ms"]},value:{type:"integer",minimum:0,maximum:6e4}};case"browser.snapshot":return{mode:{enum:["text","html","markdown","a11y"]},tabId:t("Expected active tab ID.",256)};case"browser.screenshot":return{tabId:t("Expected active tab ID.",256)};case"browser.locate":return{selector:t("CSS selector."),text:t("Visible text to locate.")};case"browser.click":return{selector:t("CSS selector returned by browser.snapshot or browser.locate."),tabId:t("Expected active tab ID.",256)};case"browser.type":return{selector:t("CSS selector."),text:{type:"string",maxLength:65536},clear:n,submit:n,tabId:t("Expected active tab ID.",256)};case"browser.key":return{combo:t("Key combo such as Control+a or Enter.",256),tabId:t("Expected active tab ID.",256)};case"browser.select":return{selector:t("CSS selector."),value:t("Option value."),tabId:t("Expected active tab ID.",256)};case"browser.scroll":return{selector:t("Optional CSS selector."),dx:r,dy:r,tabId:t("Expected active tab ID.",256)};case"browser.tabs.open":return{url:t("URL to open in an isolated browser tab.")};case"browser.tabs.close":return{tabId:t("Tab ID to close.",256)};case"browser.console.read":case"browser.network.read":case"browser.page-errors.read":return{limit:{type:"integer",minimum:1,maximum:1e3},clear:n,tabId:t("Expected active tab ID.",256)};case"browser.storage.read":return{tabId:t("Expected active tab ID.",256)};case"browser.upload":return{selector:t("File input or drop-target selector."),backendNodeId:{type:"integer",minimum:1},hostPaths:{type:"array",items:t("Host file path.",32768),minItems:1,maxItems:64},drop:n,tabId:t("Expected active tab ID.",256)};case"browser.download":return{toPath:t("Approved destination path.",32768),trigger:{type:"object",properties:{url:t("Download URL."),selector:t("Download trigger selector.")},oneOf:[{required:["url"]},{required:["selector"]}],additionalProperties:!1},tabId:t("Expected active tab ID.",256)};case"browser.record.start":return{maxDurationMs:{type:"integer",minimum:1e3,maximum:6e4},intervalMs:{type:"integer",minimum:100,maximum:5e3},tabId:t("Expected active tab ID.",256)};case"browser.record.stop":return{tabId:t("Expected active tab ID.",256)};case"computer.observe":case"computer.screenshot":case"computer.window-state":return o;case"computer.point":return{...o,point:i,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.click":return{...o,point:i,button:{enum:["left","right","middle"]},modifiers:TCn()};case"computer.double-click":case"computer.right-click":return{...o,point:i};case"computer.drag":return{...o,from:i,to:i,durationMs:{type:"integer",minimum:0,maximum:6e4}};case"computer.type":return{...o,text:{type:"string",maxLength:65536}};case"computer.key":return{...o,combo:t("Key combo such as Control+a or Enter.",256)};case"computer.scroll":return{...o,at:i,delta:i};case"computer.wait":return{...o,milliseconds:{type:"integer",minimum:0,maximum:3e5}};case"computer.launch":return{...o,applicationId:t("Explicitly allowlisted application ID.",512)};case"browser.back":case"browser.forward":case"browser.reload":return{tabId:t("Expected active tab ID.",256)};case"browser.tabs.list":return{}}}function CCn(e){switch(e){case"browser.navigate":case"browser.tabs.open":return["url"];case"browser.click":return["selector"];case"browser.type":return["selector","text"];case"browser.key":return["combo"];case"browser.select":return["selector","value"];case"browser.upload":return["hostPaths"];case"browser.download":return["toPath","trigger"];case"browser.screenshot":return["tabId"];case"computer.point":case"computer.click":case"computer.double-click":case"computer.right-click":return["point"];case"computer.drag":return["from","to"];case"computer.type":return["text"];case"computer.key":return["combo"];case"computer.scroll":return["at","delta"];case"computer.launch":return["applicationId"];default:return[]}}function TCn(){return{type:"object",properties:{shift:{type:"boolean"},ctrl:{type:"boolean"},alt:{type:"boolean"},meta:{type:"boolean"}},additionalProperties:!1}}function RCn(e){let t=kh(e),r=e.split(".").slice(1).join(" ");return`${t.effect==="act"?"Act on":"Inspect"} the ${t.surface} using governed ${r} automation. The host requires policy approval, an exact capability lease, target-bound preflight, and durable evidence.`}function PCn(e){return kh(e).effect==="observe"?e==="browser.navigate"||e==="browser.tabs.open"?"medium":"low":["browser.type","browser.upload","browser.download","computer.type","computer.key","computer.launch"].includes(e)?"high":"medium"}function _Cn(e,t){let r=YQe(e,t),n={operation:e};r&&(n.target=r);for(let i of["selector","clear","submit","combo","value","dx","dy","point","from","to","at","delta","milliseconds"])t[i]!==void 0&&(n[i]=structuredClone(t[i]));return typeof t.text=="string"&&(n.text=`[redacted ${t.text.length} characters]`),Array.isArray(t.hostPaths)&&(n.hostPaths=t.hostPaths.map(()=>"[redacted host path]")),typeof t.toPath=="string"&&(n.toPath="[redacted destination path]"),n}function BCn(e,t){let r=structuredClone(t);return typeof r.text=="string"&&(r.text=`[redacted ${r.text.length} characters]`),Array.isArray(r.hostPaths)&&(r.hostPaths=r.hostPaths.map(()=>"[redacted host path]")),typeof r.toPath=="string"&&(r.toPath="[redacted destination path]"),nFt(r.trigger)&&typeof r.trigger.url=="string"&&(r.trigger={...r.trigger,url:qSt(r.trigger.url)}),typeof r.url=="string"&&(r.url=qSt(r.url)),{operation:e,...r}}function $Cn(e,t){let r=YQe(e,t),n=r?.url??r?.applicationId??r?.deviceId??r?.tabId??r?.resource??"current target";return`${e} on ${n}`}function YQe(e,t){let r={};return typeof t.url=="string"&&(r.url=t.url),typeof t.tabId=="string"&&(r.tabId=t.tabId),typeof t.deviceId=="string"&&(r.deviceId=t.deviceId),typeof t.applicationId=="string"&&(r.applicationId=t.applicationId),typeof t.displayId=="string"&&(r.displayId=t.displayId),(e==="browser.navigate"||e==="browser.tabs.list"||e==="browser.tabs.open")&&(r.resource="browser-tabs"),Object.keys(r).length>0?r:void 0}function MCn(e){return{operationId:e.operationId,status:e.status,effect:e.effect,startedAt:e.startedAt,completedAt:e.completedAt,adapter:e.adapter,target:e.target,...e.data!==void 0?{data:e.data}:{},artifacts:e.artifacts.map(t=>({artifactId:t.artifactId,revision:t.revision,kind:t.kind,title:t.title,state:t.state,mediaType:t.mediaType,sensitivity:t.sensitivity,hash:t.content.hash,sizeBytes:t.content.sizeBytes})),lease:e.lease,...e.error?{error:e.error}:{}}}function OCn(e){let t=[];for(let r of e.artifacts){if(t.length>=ECn||!r.mediaType.startsWith("image/"))continue;let n=r.content.storage;if(n.type!=="inline"||typeof n.base64!="string")continue;let i=Math.floor(n.base64.length*.75);i<=0||i>ICn||t.push({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${n.base64}`,detail:"high"}})}return t}function NCn(e){let t=new Set(CR),r=new Set;for(let n of e){if(!t.has(n))throw new TypeError(`Unsupported XENO automation operation: ${String(n)}`);r.add(n)}return Array.from(r)}function DCn(e){return bCn("sha256").update(INe(e)).digest("hex")}function INe(e){return Array.isArray(e)?`[${e.map(INe).join(",")}]`:nFt(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${INe(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}function qSt(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid URL]"}}function LCn(e){return e instanceof Error?e.message:String(e)}function FCn(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:"AUTOMATION_EXECUTION_FAILED"}function nFt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ode(e){return new Mde(e)}function gS(e){if(e)return async t=>{let r=kh(t.operation).effect;await e.append({trace_id:t.traceId,event_type:t.eventType,actor:"system",risk_level:r==="act"?"high":"low",...t.eventType==="automation_lease_approved"?{decision:"allow"}:{},status:t.eventType==="automation_failed"?"error":"ok",...t.eventType==="automation_failed"&&t.status?{reason:t.status}:{},metadata:{operation:t.operation,operation_id:t.operationId,lease_id:t.leaseId,contract_fingerprint:t.contractFingerprint,result_status:t.status,artifact_ids:t.artifactIds,permission_reason:t.permissionReason}})}}async function Iq(e=nI()){let t=await Promise.all([WSt("browser",e),WSt("computer",e)]);return{schemaVersion:1,protocolVersion:1,enabled:t.some(r=>r.configured),surfaces:t,docs:"docs/GOVERNED_AUTOMATION.md"}}function nI(e=process.env){let t=iA(e.XENO_EXTENSION_SESSION_FILE)??yNe(KLt(),".xeno","use-drivers","xeno-extension.json"),r=e.XENO_BROWSER_DRIVER==="extension"||!e.XENO_BROWSER_DRIVER&&!e.XENO_BROWSER_AUTOMATION_URL&&!e.XENO_BROWSER_SESSION_FILE&&zQe(t)?"extension":"browser",n=jCn(e,r),i=iA(e.XENO_BROWSER_AUTOMATION_URL)??n?.baseUrl,o=iA(e.XENO_BROWSER_AUTOMATION_TOKEN)??n?.token,s=iA(e.XENO_USE_BASE_URL),a=iA(e.XENO_USE_TOKEN)??GCn(e.XENO_USE_TOKEN_FILE),l=iA(e.XENO_USE_DEVICE_ID);return{browser:{driver:r,...i?{baseUrl:i}:{},...o?{token:o}:{},readDomains:Dre(e.XENO_BROWSER_READ_DOMAINS),actDomains:Dre(e.XENO_BROWSER_ACT_DOMAINS),deniedDomains:Dre(e.XENO_BROWSER_DENIED_DOMAINS),ports:XCn(e.XENO_BROWSER_ALLOWED_PORTS,[443]),allowLoopbackDevelopment:e.XENO_BROWSER_ALLOW_LOOPBACK_DEVELOPMENT==="1",uploads:JSt(e.XENO_BROWSER_UPLOADS,"prompt"),downloads:JSt(e.XENO_BROWSER_DOWNLOADS,"prompt"),recording:e.XENO_BROWSER_RECORDING==="bounded"?"bounded":"disabled"},computer:{...s?{baseUrl:s}:{},...a?{token:a}:{},...l?{deviceId:l}:{},allowedApplications:Dre(e.XENO_USE_ALLOWED_APPLICATIONS)}}}function GCn(e){let t=iA(e);if(!(!t||!zQe(t)))try{return iA(YLt(t,"utf8"))}catch{return}}function jCn(e,t){let r=iA(e.XENO_BROWSER_SESSION_FILE)??(t==="extension"?iA(e.XENO_EXTENSION_SESSION_FILE)??yNe(KLt(),".xeno","use-drivers","xeno-extension.json"):iA(e.XENO_SESSION_FILE)??(e.APPDATA?yNe(e.APPDATA,"xeno-browser","session.json"):void 0));if(!(!r||!zQe(r)))try{let n=JSON.parse(YLt(r,"utf8")),i=Number(n.port),o=typeof n.token=="string"?n.token:"",s=typeof n.driver=="string"?n.driver:void 0;return!Number.isSafeInteger(i)||i<=0||i>65535||!HCn(o)||s&&s!==(t==="extension"?"xeno-extension-native":"xeno-browser-loopback")?void 0:{baseUrl:`http://127.0.0.1:${i}`,token:o}}catch{return}}function HCn(e){return e.length>=32&&e.length<=512&&!/\s/.test(e)}async function WSt(e,t){let r=e==="browser"?t.browser:t.computer,n=e==="browser"?ENe(t.browser):Uoe(t.computer),i=!!r&&Object.values(r).some(o=>typeof o=="string"&&o.length>0);if(!n)return{surface:e,configured:!1,available:!1,certified:!1,operations:[],limitations:["Adapter credentials are not completely configured."],...i?{error:e==="browser"?oFt(t.browser):KQe(t.computer)}:{}};try{let o=await(e==="browser"?t.browser.driver==="extension"?await Pde({baseUrl:t.browser.baseUrl,token:t.browser.token,assertCurrent:async()=>{throw new Error("Status inspection cannot authorize browser effects.")},authorizeGrant:async()=>{throw new Error("Status inspection cannot issue browser grants.")}}):new _de({baseUrl:t.browser.baseUrl,token:t.browser.token,driver:t.browser.driver,...t.browser.ownedView?{ownedView:t.browser.ownedView}:{}}):await iFt(t.computer)).manifest();if($y(o),e==="computer"&&cie("observe",t).sensitiveRegionRedaction&&o.supports.sensitiveRegionRedaction!==!0)throw new Error("Owning computer adapter cannot satisfy this host's required sensitive-region redaction.");return VCn(e,o)}catch(o){return{surface:e,configured:!0,available:!1,certified:!1,operations:[],limitations:["Configured adapter is unavailable."],error:uFt(o)}}}async function iFt(e){if(e={...e},!Uoe(e))throw new Error(KQe(e));return new WQe({baseUrl:e.baseUrl,...e.authorize?{authorize:e.authorize}:{token:e.token}})}function VCn(e,t){return{surface:e,configured:!0,available:!0,certified:t.certified,adapterId:t.adapterId,adapterVersion:t.adapterVersion,operations:[...t.operations],limitations:[...t.limitations]}}function qCn(e,t,r,n){let i=r.browser,o=aFt(t),s=o&&!cFt(o.hostname)?o.hostname:void 0,a=Qoe([...i.readDomains,...s?[s]:[]]),l=Qoe([...i.actDomains,...e==="act"&&s?[s]:[]]),c=dFt([...i.ports,...o?[lFt(o)]:[]]);return{mode:e==="act"?"act":"read",profile:i.driver==="extension"?n==="isolated-persistent"?"isolated-persistent":"shared-user":"ephemeral",readAllowedDomains:a,actAllowedDomains:l,deniedDomains:i.deniedDomains,allowedSchemes:i.allowLoopbackDevelopment?["https","http"]:["https"],allowedPorts:c,redirectPolicy:"policy",allowLoopbackDevelopment:i.allowLoopbackDevelopment,uploads:i.uploads,downloads:i.downloads,recording:i.recording}}function cie(e,t){return{mode:e==="act"?"act":"observe",allowedApplications:t.computer?.allowedApplications??[],sensitiveRegionRedaction:!0,humanStopRequired:!0}}function WCn(e,t){let r=[],n=aFt(e);n&&r.push({scheme:n.protocol.replace(/:$/,""),host:n.hostname.toLowerCase(),port:lFt(n)});for(let i of Qoe([...t.browser?.readDomains??[],...t.browser?.actDomains??[]]))if(!(i.startsWith(".")||i.includes("*")))for(let o of t.browser?.ports??[443])r.push({scheme:o===80?"http":"https",host:i,port:o});return{default:"deny",allowDestinations:YCn(r)}}function JCn(e,t,r){if(!e.startsWith("computer."))return t;let n=t?.deviceId??r.computer?.deviceId,i=t?.applicationId;if(!(!n&&!i&&!t))return{...t??{},...n?{deviceId:n}:{}}}function R3(e){let t=e.authorization;if(!t||t.toolName!==e.governingToolName||!t.permission.allowed||!t.policy.allowed)throw new Error("Automation authorization receipt does not match the governing tool");rDe(t,e.governingToolName,e.parameters)}function zCn(e){try{return JSON.parse(JSON.stringify(e))}catch(t){throw new Error(`Automation parameters are not JSON serializable: ${uFt(t)}`)}}function ENe(e){return!!e?.baseUrl&&!!e.token}function Uoe(e,t=!1){return sFt(e,t)===void 0}function oFt(e){return`Browser automation configuration is incomplete; missing ${[e?.baseUrl?"":"XENO_BROWSER_AUTOMATION_URL",e?.token?"":"XENO_BROWSER_AUTOMATION_TOKEN"].filter(Boolean).join(", ")}`}function KQe(e,t=!1){return sFt(e,t)??"Computer automation configuration is unavailable."}function sFt(e,t){let r=e?.token!==void 0,n=e?.authorize!==void 0;if(r&&n)return"Computer automation requires exactly one bootstrap token or canonical request authorizer.";if(n&&typeof e?.authorize!="function")return"Computer automation requires a callable canonical request authorizer.";if(r&&(typeof e?.token!="string"||!e.token.trim()))return"Computer automation bootstrap token is invalid.";if(e?.baseUrl!==void 0)try{let o=new URL(e.baseUrl);if(o.username||o.password||o.search||o.hash||o.pathname!=="/"||o.protocol!=="https:"&&!(o.protocol==="http:"&&cFt(o.hostname)&&!n))return"Computer automation requires an HTTPS origin; explicit bootstrap compatibility may use loopback HTTP only."}catch{return"Computer automation endpoint must be a valid origin."}let i=[!t&&!e?.baseUrl?"XENO_USE_BASE_URL":"",!t&&!r&&!n?"XENO_USE_TOKEN or canonical request authorizer":"",e?.deviceId?.trim()?"":"XENO_USE_DEVICE_ID"].filter(Boolean);return i.length?`Computer automation configuration is incomplete; missing ${i.join(", ")}`:void 0}function aFt(e){let t=e?.url??e?.origin;if(t)try{return new URL(t)}catch{return}}function lFt(e){return e.port?Number(e.port):e.protocol==="http:"?80:443}function cFt(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"}function Dre(e){return Qoe((e??"").split(",").map(t=>t.trim().toLowerCase()).filter(Boolean))}function XCn(e,t){let r=(e??"").split(",").map(n=>Number(n.trim())).filter(n=>Number.isSafeInteger(n)&&n>0&&n<=65535);return r.length>0?dFt(r):t}function JSt(e,t){return e==="deny"||e==="prompt"||e==="allow"?e:t}function iA(e){return e?.trim()||void 0}function Qoe(e){return[...new Set(e)]}function dFt(e){return[...new Set(e)].sort((t,r)=>t-r)}function YCn(e){let t=new Set;return e.filter(r=>{let n=`${r.scheme??""}:${r.host}:${r.port??""}`;return t.has(n)?!1:(t.add(n),!0)})}function uFt(e){return e instanceof Error?e.message:String(e)}function Eq(e){let t=["XENO governed automation",""];for(let r of e.surfaces){let n=r.configured?r.available?"available":"unavailable":"not configured",i=r.certified?"certified":"not release-certified";t.push(`${r.surface}: ${n}; ${i}`),r.adapterId&&t.push(` adapter: ${r.adapterId}@${r.adapterVersion??"unknown"}`),r.operations.length>0&&t.push(` operations: ${r.operations.length}`);for(let o of r.limitations)t.push(` limitation: ${o}`);r.error&&t.push(` error: ${r.error}`)}return t.push("",`Docs: ${e.docs}`),t.join(`
|
|
787
787
|
`)}function Xa(e,t,r,n){e.push({path:t,code:r,message:n})}function P3(e){return e.includes("T")&&Number.isFinite(Date.parse(e))}function zSt(e,t){return e.startsWith(kV)?n5(e):t.has(e)}function eGe(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_graph",message:"Evidence graph must be an object"}];e.schemaVersion!==1&&Xa(t,"schemaVersion","unsupported_schema","schemaVersion must be 1"),(typeof e.graphId!="string"||e.graphId.trim().length===0)&&Xa(t,"graphId","required_string","graphId must be a non-empty string"),(!Number.isInteger(e.version)||e.version<1)&&Xa(t,"version","invalid_version","version must be a positive integer"),P3(e.createdAt)||Xa(t,"createdAt","invalid_timestamp","createdAt must be an ISO 8601 timestamp"),P3(e.updatedAt)||Xa(t,"updatedAt","invalid_timestamp","updatedAt must be an ISO 8601 timestamp"),P3(e.createdAt)&&P3(e.updatedAt)&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&Xa(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt");let r=new Map;Array.isArray(e.nodes)||Xa(t,"nodes","invalid_nodes","nodes must be an array"),(Array.isArray(e.nodes)?e.nodes:[]).forEach((d,u)=>{let p=`nodes[${u}]`;typeof d.id!="string"||d.id.trim().length===0?Xa(t,`${p}.id`,"required_string","Node ID must be a non-empty string"):r.has(d.id)?Xa(t,`${p}.id`,"duplicate_node",`Node ID ${d.id} is duplicated`):r.set(d.id,d),(typeof d.type!="string"||!zSt(d.type,ZCn))&&Xa(t,`${p}.type`,"invalid_node_type","Node type is invalid"),d.artifactRevision!==void 0&&(!Number.isInteger(d.artifactRevision)||d.artifactRevision<1)&&Xa(t,`${p}.artifactRevision`,"invalid_revision","artifactRevision must be a positive integer")});let n=new Set,i=new Set;Array.isArray(e.edges)||Xa(t,"edges","invalid_edges","edges must be an array"),(Array.isArray(e.edges)?e.edges:[]).forEach((d,u)=>{let p=`edges[${u}]`;typeof d.id!="string"||d.id.trim().length===0?Xa(t,`${p}.id`,"required_string","Edge ID must be a non-empty string"):n.has(d.id)&&Xa(t,`${p}.id`,"duplicate_edge",`Edge ID ${d.id} is duplicated`),n.add(d.id),(typeof d.type!="string"||!zSt(d.type,eTn))&&Xa(t,`${p}.type`,"invalid_edge_type","Edge type is invalid");let f=`${d.type}:${d.from}:${d.to}`;i.has(f)&&Xa(t,p,"duplicate_edge_identity","Equivalent evidence edge is duplicated"),i.add(f),r.has(d.from)||Xa(t,`${p}.from`,"dangling_reference",`Source node ${d.from} does not exist`),r.has(d.to)||Xa(t,`${p}.to`,"dangling_reference",`Target node ${d.to} does not exist`),d.from===d.to&&Xa(t,p,"self_edge","Evidence edges cannot point to the same node"),P3(d.createdAt)||Xa(t,`${p}.createdAt`,"invalid_timestamp","createdAt must be an ISO 8601 timestamp")});let o=(Array.isArray(e.edges)?e.edges:[]).filter(d=>KCn.has(d.type)),s=new Map;for(let d of o){let u=s.get(d.from)??[];u.push(d.to),s.set(d.from,u)}let a=new Set,l=new Set,c=d=>{if(a.has(d))return!0;if(l.has(d))return!1;a.add(d);for(let u of s.get(d)??[])if(c(u))return!0;return a.delete(d),l.add(d),!1};for(let d of r.keys())if(c(d)){Xa(t,"edges","cyclic_graph","Dependency, decomposition, and supersession edges must be acyclic");break}return t}function m2(e){let t=eGe(e);if(t.length>0)throw new ZQe(t)}function fFt(e){return{...e,...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function hFt(e){return{...e,...e.producer?{producer:{...e.producer}}:{},...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function Lre(e){return{...e,nodes:e.nodes.map(fFt),edges:e.edges.map(hFt)}}function Nde(e,t={}){if(typeof e!="string")throw new TypeError("Unified diff must be a string");let r=Fre(t.maxBytes,tTn,1024,256*1024*1024,"maxBytes"),n=Fre(t.maxFiles,rTn,1,1e5,"maxFiles"),i=Fre(t.maxHunks,nTn,1,1e6,"maxHunks"),o=Fre(t.maxLines,iTn,1,5e6,"maxLines");if(mFt.byteLength(e,"utf8")>r)throw new Ud(`Unified diff exceeds ${r} bytes`);let s=e.replace(/\r\n/g,`
|
|
788
788
|
`).replace(/\r/g,`
|
|
789
789
|
`),a=s.length===0?[]:s.split(`
|
|
@@ -2786,7 +2786,7 @@ public static class XenoProtectedWrite {
|
|
|
2786
2786
|
$request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
2787
2787
|
$result = [XenoProtectedWrite]::Run([string]$request.path, [Convert]::FromBase64String([string]$request.payload), [bool]$request.ifAbsent, [string]$request.operationId, [string]$request.operation, [int]$request.parentPid, [long]$request.parentBirth)
|
|
2788
2788
|
$result | ConvertTo-Json -Compress
|
|
2789
|
-
`});$Sn=X(()=>{"use strict";ls(),uSt(),uSt(),mq=dQe()?.isPlatformSupported===!0,pde="ai.xenostudio.xeno-agent.mcp",fde="xeno.host.state.encryption-key.v1",g8="aes-256-gcm",C1=32,sie=12,tNe=16,RO="b64:",$oe="dpapi:v1:"}),fQe=X(()=>{"use strict";ade(),G1n(),P5t(),R5t(),r5(),wRt(),tae(),lR(),SV(),nLt(),J1n(),Z1n(),Q5e(),ISn(),z5e(),eDe(),$Sn(),iDe(),$Pt()}),hde=X(()=>{"use strict";hQe=2});Ade=X(()=>{"use strict";Use(),hde(),Moe=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,CLt=2e3,yQe=2*1024*1024,bQe=2e3,vQe=64*1024*1024,TLt=new Set(["node_modules",".git",".hg",".svn"])});EQe=X(()=>{"use strict";Ade(),hde(),oNe=128*1024});BLt=X(()=>{"use strict"}),$Lt={};fun($Lt,{createDelegatedXenoAgent:()=>kR});SQe=X(()=>{"use strict";QUe(),JUe(),fQe(),P5(),MLt=[{tool:"Write",decision:"deny"},{tool:"Edit",decision:"deny"},{tool:"Patch",decision:"deny"},{tool:"MemoryWrite",decision:"deny"},{tool:"Bash",decision:"deny"},{tool:"dispatch_agent",decision:"deny"}]});P5=X(()=>{"use strict";EQe(),Ade(),Y0(),Q0(),DUe(),AUe(),vDt(),ls(),XUe(),BLt(),Kl(),Xae(),fQe(),wR(),BN=8192,WH=50});rR();J0="0.10.109";Lse();gn();Pc();SR=class{filePath;sessionId;labels;sequence=0;writeQueue=Promise.resolve();constructor(e){this.filePath=e.filePath,this.sessionId=e.sessionId,this.labels={run_id:e.runId,agent_id:e.agentId,parent_agent_id:e.parentAgentId,workspace:e.workspace,model:e.model,provider:e.provider}}get path(){return this.filePath}async append(e){let t=txn(),r={id:t,sequence:this.sequence++,timestamp:new Date().toISOString(),session_id:e.session_id??this.sessionId,...this.labels,...e};return this.writeQueue=this.writeQueue.then(async()=>{await yne(this.filePath,JSON.stringify(r))}),await this.writeQueue,t}async read(e){let t=await Sl(this.filePath);if(!t)return[];let r=W3(t);return e?.eventType&&(r=r.filter(n=>n.event_type===e.eventType)),e?.traceId&&(r=r.filter(n=>n.trace_id===e.traceId)),e?.limit!==void 0&&(r=r.slice(-Math.max(0,e.limit))),r}async tail(e=20){let t=Math.max(1,Math.min(e,500));return this.read({limit:t})}async exportJson(e){let t=await this.read();return await qs(e,JSON.stringify(t,null,2)),t.length}async flush(){await this.writeQueue}};T5e();Xse();TQe=new Set(["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read"]),RQe=new Set(["browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download","browser.record.start","browser.record.stop"]),PQe=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),_Qe=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),CR=[...TQe,...RQe,...PQe,..._Qe];cd();LLt=new Set(["Read","Glob","Grep","LS","GitStatus","GitDiff","GitLog","WebFetch","WebSearch","MemoryRead","NotebookRead","ReadImage","SqliteAnalyze","ElfAnalyze","GcodeAnalyze","HtmlSanitizerAudit","ArtifactCompare","Think","ToolSearch","Skill",...CR.filter(e=>kh(e).effect==="observe")]),O5=class{constructor(e){this.registry=e}registry;removedTools=new Map;restore(){for(let[e,t]of this.removedTools)this.registry.has(e)||this.registry.register(t);this.removedTools.clear()}apply(e){if(this.restore(),!e)return{removed:[]};let t=BQe(e),r=FLt(t),n=[];for(let i of this.registry.listNames()){let o=JH(i),s=r?!r.has(o):!1,a=t.denyExact.has(o);if(!s&&!a)continue;let l=this.registry.get(i);l&&this.registry.unregister(i)&&(this.removedTools.set(i,l),n.push(i))}return ULt(t,r,n)}};QLt=1,ve=class extends Error{constructor(e,t,r,n){super(t,n),this.code=e,this.detail=r,this.name="XenoAutomationError"}code;detail};eDe();dxn=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,kSt=1048576;jLt=1,HLt=1,$Qe=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation","page"],MQe=["draft","pending_review","approved","rejected","superseded","archived"],OQe=["public","internal","confidential","restricted"],NQe=["agent","tool","user","system","integration"],Sde=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],xde=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];sae();vq=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(r=>({...r}))}},DQe=class extends Error{constructor(e,t){super(`Artifact state cannot transition from ${e} to ${t}`),this.fromState=e,this.toState=t,this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},wxn={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},yxn="[\\u0000-\\u001f\\u007f]",bxn=new RegExp(yxn),VLt=/^[a-f0-9]{64}$/,vxn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ixn=new Set(MQe),Exn=new Set(OQe),kxn=new Set(NQe),Sxn=new Set($Qe),xxn=new Set(Sde),Cxn=new Set(xde);er=class extends Error{constructor(e,t,r,n){super(t,n),this.code=e,this.detail=r,this.name="XenoArtifactRepositoryError"}code;detail},Rde=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(e={}){this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>(this.idCounter+=1,`${t}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),e.initialState&&this.hydrate(e.initialState)}exportState(){return{schemaVersion:1,records:[...this.records.values()].flatMap(t=>[...t.values()]).sort(PSt).map(t=>({artifact:J8(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(Vd(e),this.assertInitialState(e),e.revision!==1)throw new er("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:e.artifactId,revision:e.revision});if(this.records.has(e.artifactId))throw new er("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=J8(e),r=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),n={artifact:t,recordVersion:1,lifecycleEvents:[r],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,n]])),this.currentRevisions.set(t.artifactId,t.revision),XT(n)}async createRevision(e,t={}){Vd(e),this.assertInitialState(e);let r=this.getMutable(e.artifactId);this.assertVersion(r,t.expectedRecordVersion);let n=r.artifact.revision+1;if(e.revision!==n||e.predecessorRevision!==r.artifact.revision)throw new er("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${r.artifact.revision}`,{artifactId:e.artifactId,currentRevision:r.artifact.revision,requestedRevision:e.revision});if(Rxn(e,r.artifact))throw new er("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(r.artifact.state==="archived")throw new er("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:r.artifact.revision});if(r.artifact.state!=="superseded"){XH(r.artifact.state,"superseded");let a=this.now(),l=this.createLifecycleEvent({artifact:r.artifact,sequence:r.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:r.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});r.artifact.state="superseded",r.artifact.updatedAt=a,r.lifecycleEvents.push(l),r.recordVersion+=1}let i=J8(e),o=this.createLifecycleEvent({artifact:i,sequence:1,actor:t.actor??i.provenance.producer,fromState:null,toState:i.state,reason:t.reason??`revision-created-from-${r.artifact.revision}`}),s={artifact:i,recordVersion:1,lifecycleEvents:[o],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,s),this.currentRevisions.set(i.artifactId,i.revision),XT(s)}async get(e,t){let r=this.records.get(e);if(!r)return;let n=t??this.currentRevisions.get(e);if(n===void 0)return;let i=r.get(n);return i?XT(i):void 0}async require(e,t){let r=await this.get(e,t);if(!r)throw new er("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return r}async list(e={}){let t=[];for(let[r,n]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(r)))if(e.includeSuperseded)t.push(...n.values());else{let i=this.currentRevisions.get(r);if(i!==void 0){let o=n.get(i);o&&t.push(o)}}return t.filter(r=>Pxn(r.artifact,e)).sort(PSt).map(XT)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((r,n)=>r.artifact.revision-n.artifact.revision).map(XT):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),XH(t.artifact.state,e.toState),e.toState==="approved"||e.toState==="rejected"){let o=e.reviewEventId?t.reviewEvents.find(a=>a.eventId===e.reviewEventId&&a.type==="decision-recorded"):void 0,s=Tde(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new er("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${e.toState} requires a matching decision event`,{artifactId:e.artifactId,revision:t.artifact.revision});if(e.toState==="approved"&&s.unresolvedComments>0)throw new er("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let r=this.now(),n=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:n,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:r});return t.artifact.state=e.toState,t.artifact.updatedAt=r,t.lifecycleEvents.push(i),t.recordVersion+=1,XT(t)}async appendReviewEvent(e){let t=e.event,r=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(r,e.expectedRecordVersion),r.artifact.state==="archived"||r.artifact.state==="superseded")throw new er("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${r.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(r,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&r.artifact.state!=="pending_review")throw new er("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let n={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:r.reviewEvents.length+1,recordedAt:this.now()},i=Cde(n,r.artifact);if(i.length>0)throw new vq("XENO artifact review event validation failed",i);return r.reviewEvents.push(n),r.recordVersion+=1,XT(r)}getMutable(e,t){let r=this.records.get(e),n=t??this.currentRevisions.get(e),i=n===void 0?void 0:r?.get(n);if(!i)throw new er("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return i}assertVersion(e,t){if(t!==void 0&&t!==e.recordVersion)throw new er("ARTIFACT_CONFLICT",`Expected record version ${t}, found ${e.recordVersion}`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision,expectedRecordVersion:t,actualRecordVersion:e.recordVersion})}assertInitialState(e){if(e.state!=="draft"&&e.state!=="pending_review")throw new er("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:e.artifactId,revision:e.revision})}assertReviewCommentState(e,t){if(t.type==="comment-added"){if(e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.commentId))throw new er("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.parentCommentId))throw new er("ARTIFACT_REVIEW_INVALID",`Parent comment ${t.parentCommentId} does not exist`);return}if(t.type!=="comment-resolved"&&t.type!=="comment-reopened")return;if(!e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.commentId))throw new er("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let r=_xn(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&r.resolved)throw new er("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!r.resolved)throw new er("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is not resolved`)}createLifecycleEvent(e){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:e.artifact.artifactId,revision:e.artifact.revision,sequence:e.sequence,recordedAt:e.recordedAt??this.now(),actor:{...e.actor},fromState:e.fromState,toState:e.toState,...e.reason?{reason:e.reason}:{},...e.reviewEventId?{reviewEventId:e.reviewEventId}:{}}}nextEventId(e){let t=this.idFactory(e);if(typeof t!="string"||t.trim().length===0||this.eventIds.has(t))throw new er("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${e} ID`);return this.eventIds.add(t),t}hydrate(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new er("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((r,n)=>r.artifact.artifactId.localeCompare(n.artifact.artifactId)||r.artifact.revision-n.artifact.revision);for(let r of t){let n=Txn(r,this.eventIds),i=this.records.get(n.artifact.artifactId);if(i||(i=new Map,this.records.set(n.artifact.artifactId,i)),i.has(n.artifact.revision))throw new er("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${n.artifact.artifactId}:${n.artifact.revision}`);i.set(n.artifact.revision,n),this.currentRevisions.set(n.artifact.artifactId,n.artifact.revision)}for(let[r,n]of this.records){let i=[...n.values()].sort((o,s)=>o.artifact.revision-s.artifact.revision);for(let o=0;o<i.length;o+=1){let s=i[o],a=o+1;if(s.artifact.revision!==a)throw new er("ARTIFACT_REVISION_INVALID",`Persisted artifact ${r} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new er("ARTIFACT_REVISION_INVALID",`Initial revision for ${r} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new er("ARTIFACT_REVISION_INVALID",`Persisted revision ${r}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new er("ARTIFACT_REVISION_INVALID",`Non-current revision ${r}:${a} must be superseded`)}}}};cNe=32*1024*1024,Bxn=1024*1024*1024,$xn=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;BSt=16*1024*1024;MSt=3e4,OSt=1e3,QQe=class{adapter;leaseAuthority;durable;artifactRepository;now;assertCurrent;executions=new Map;active=new Map;constructor(e){if(this.adapter=e.adapter,this.leaseAuthority=e.leaseAuthority,!!e.leaseAuthority==!!e.durable)throw new Error("Choose exactly one legacy or durable automation authority");this.durable=e.durable,this.artifactRepository=e.durable?.artifactRepository??e.artifactRepository,this.now=e.now??(()=>new Date().toISOString()),this.assertCurrent=e.assertCurrent||e.adapter.assertCurrent?async t=>{await e.assertCurrent?.(t),await e.adapter.assertCurrent?.(t)}:void 0,this.onPreflight=e.onPreflight,this.onGrant=e.onGrant}onPreflight;onGrant;execute(e,t){e=structuredClone(e);let r=Hxn(e),n=this.executions.get(e.operationId);if(n){if(n.fingerprint!==r)throw new ve("AUTOMATION_OPERATION_CONFLICT",`Operation ${e.operationId} was already submitted with different authority or parameters`);if(this.durable){let l=this.durable;return l.assertCurrent(e).then(()=>this.assertCurrent?.(e)).then(()=>n.promise).then(async c=>(await l.assertCurrent(e),await this.assertCurrent?.(e),structuredClone(c)))}return this.assertCurrent?Promise.resolve(this.assertCurrent(e)).then(()=>n.promise).then(async l=>(await this.assertCurrent?.(e),structuredClone(l))):n.promise}if(this.active.size>=OSt)throw new ve("AUTOMATION_OPERATION_CONFLICT","Automation active-operation capacity reached");let i=new AbortController,o=Vxn(t,i);this.active.set(e.operationId,i);let s=this.durable,a=(s?UQe({...s,assertCurrent:async l=>{await s.assertCurrent(l),await this.assertCurrent?.(l)}},e,r,l=>this.executeFresh(e,i.signal,l)):this.executeFresh(e,i.signal)).finally(()=>{o(),this.active.delete(e.operationId)});return this.executions.set(e.operationId,{fingerprint:r,promise:a}),this.durable&&a.then(()=>this.executions.delete(e.operationId),()=>this.executions.delete(e.operationId)),this.trimIdempotencyRecords(),a}async stop(e,t="human-stop"){let r=this.active.get(e);return r?(r.abort(new Error(t)),await this.adapter.stop?.(e,t),!0):!1}async executeFresh(e,t,r){w0(e),await this.assertCurrent?.(e),ay(t);let n=await this.adapter.manifest();$y(n),Ede(e,n);let i=kh(e.operation),o=zH(e),s=this.now(),a=await this.adapter.preflight(e,t);Uxn(a,this.now()),D2(e,n,a.observedTarget),ay(t),await this.onPreflight?.(structuredClone(e),structuredClone(a),t),ay(t);let l=a.evidence??[];w0(e),await this.assertCurrent?.(e),ay(t),z8(l,o,"before");let c=await YH(this.artifactRepository,Noe({request:e,manifest:n,policy:o,evidence:l,now:this.now}));if(ay(t),Date.parse(a.expiresAt)<=Date.parse(this.now()))throw new ve("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let d=kde(e,a.observedTarget);await this.assertCurrent?.(e);let u;if(this.durable){await this.durable.assertCurrent(e);let b=await this.durable.consume(r,e.capabilityLeaseId,e.expectedLeaseVersion,d);if(b.executionDisposition!=="dispatch-once"||b.replayed)throw P0();u=b.lease,await this.durable.assertCurrent(e)}else u=await this.leaseAuthority.consume(e.capabilityLeaseId,e.expectedLeaseVersion,d);let p={contractFingerprint:e.executionContract.fingerprint,lease:u,capabilityUse:d};await this.onGrant?.(structuredClone(e),structuredClone(a),structuredClone(p),t),ay(t);let f;try{ay(t),w0(e),await this.assertCurrent?.(e),ay(t),f=await this.adapter.execute(e,a,p,t)}catch(b){return RBe({request:e,manifest:n,descriptorEffect:i.effect,target:a.observedTarget,lease:u,artifacts:c,startedAt:s,completedAt:this.now(),status:t.aborted?"cancelled":"error",code:t.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_ADAPTER_ERROR",message:t.aborted?"Automation operation was stopped":qxn(b)})}if(Qxn(f),ay(t),w0(e),await this.assertCurrent?.(e),f.operationId!==void 0&&f.operationId!==e.operationId)throw new ve("AUTOMATION_RESPONSE_INVALID","Adapter returned another operation identity");let h=Gxn(a.observedTarget,f.observedTarget),m;try{D2(e,n,f.observedTarget)}catch(b){m=b instanceof Error?b:new Error(String(b))}if(h||m)return RBe({request:e,manifest:n,descriptorEffect:i.effect,target:a.observedTarget,lease:u,artifacts:c,startedAt:f.startedAt,completedAt:f.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:h??m.message});if(f.status!=="ok")return{operationId:e.operationId,status:f.status,effect:i.effect,startedAt:f.startedAt,completedAt:f.completedAt,adapter:dNe(n),target:structuredClone(f.observedTarget),artifacts:c,lease:uNe(u),error:f.error?{...f.error}:{code:"AUTOMATION_ADAPTER_ERROR",message:"Owning adapter refused the operation."}};let g=f.evidence??[];jxn(l,g);let A=[],w;try{z8(g,o,"after"),z8([...l,...g],o,"recording"),A=await YH(this.artifactRepository,Noe({request:e,manifest:n,policy:o,evidence:g,now:this.now}))}catch(b){w=b instanceof Error?b:new Error(String(b))}let y=[...c,...A];return ay(t),w0(e),await this.assertCurrent?.(e),w?RBe({request:e,manifest:n,descriptorEffect:i.effect,target:f.observedTarget,lease:u,artifacts:y,startedAt:f.startedAt,completedAt:f.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:w.message}):{operationId:e.operationId,status:f.status,effect:i.effect,startedAt:f.startedAt,completedAt:f.completedAt,adapter:dNe(n),target:structuredClone(f.observedTarget),...f.data!==void 0?{data:structuredClone(f.data)}:{},artifacts:y,lease:uNe(u),...f.error?{error:{...f.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>OSt;){let e=this.executions.keys().next().value;if(!e||this.active.has(e))break;this.executions.delete(e)}}};GQe=class{constructor(e){this.database=e;try{if(e.exec("PRAGMA busy_timeout=0; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS automation_execution_schema(id INTEGER PRIMARY KEY CHECK(id=1),version INTEGER NOT NULL); INSERT OR IGNORE INTO automation_execution_schema VALUES(1,1);"),e.prepare("SELECT version FROM automation_execution_schema WHERE id=1").get()?.version!==1)throw Error("Unsupported automation execution journal");e.exec("CREATE TABLE IF NOT EXISTS automation_executions(id TEXT PRIMARY KEY,body TEXT NOT NULL)")}catch(t){throw e.close(),this.closed=!0,t}}database;closed=!1;async begin(e){return e=structuredClone(e),fNe(e),NO(e,["operationId","fingerprint","ownerToken"]),this.transaction(()=>{let t=this.read(e.operationId);if(t){if(t.fingerprint!==e.fingerprint)throw Mre();return{claimed:!1,record:t}}let r=this.database.prepare("SELECT COUNT(*) AS count FROM automation_executions").get()?.count;if(typeof r!="number"||r>=1e5)throw Error("Automation journal capacity reached; explicit archival required");let n={schemaVersion:1,...e,outcome:{kind:"pending"}};return this.database.prepare("INSERT INTO automation_executions(id,body) VALUES(?,?)").run(e.operationId,NSt(n)),{claimed:!0,record:n}})}async get(e){if(typeof e!="string"||!e.trim()||e.length>1024)throw Error("Invalid automation journal identity");return this.transaction(()=>this.read(e))}async finish(e,t){e=structuredClone(e),t=structuredClone(t),fNe(e),NO(e,["operationId","fingerprint","ownerToken"]);let r={schemaVersion:1,...e,outcome:t};return hNe(r),this.transaction(()=>{let n=this.read(e.operationId);if(!n||n.fingerprint!==e.fingerprint||n.ownerToken!==e.ownerToken)throw Mre();if(n.outcome.kind!=="pending"){if(JSON.stringify(n.outcome)!==JSON.stringify(t))throw Mre();return}this.database.prepare("UPDATE automation_executions SET body=? WHERE id=?").run(NSt(r),e.operationId)})}close(){this.closed||(this.closed=!0,this.database.close())}read(e){let t=this.database.prepare("SELECT CASE WHEN length(body)<=16384 THEN body ELSE NULL END AS body FROM automation_executions WHERE id=?").get(e);if(!t)return;if(typeof t.body!="string")throw Error("Corrupt automation journal size");let r=JSON.parse(t.body);if(hNe(r),r.operationId!==e)throw Mre();return r}async transaction(e){let t=Date.now()+1e3;for(;;){if(this.closed)throw Error("Automation journal closed");let r=!1;try{this.database.exec("BEGIN IMMEDIATE"),r=!0;let n=e();return this.database.exec("COMMIT"),n}catch(n){if(r)try{this.database.exec("ROLLBACK")}catch{}if(Date.now()>=t||!/SQLITE_BUSY|database is locked/.test(String(n)))throw n;await new Promise(i=>setTimeout(i,10))}}}};zxn=6e4,Xxn=48*1024*1024,HQe=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;ownedView;constructor(e){if(this.endpoint=Yxn(e.baseUrl),this.token=Kxn(e.token),this.timeoutMs=DSt(e.timeoutMs??zxn,1e3,3e5,"timeoutMs"),this.maxResponseBytes=DSt(e.maxResponseBytes??Xxn,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=e.fetch??globalThis.fetch,e.ownedView&&(!/^[a-f0-9]{64}$/.test(e.ownedView.ownerId)||!e.ownedView.sessionId?.trim()))throw new ve("AUTOMATION_REQUEST_INVALID","Owned Browser frame binding is invalid.");if(this.ownedView=e.ownedView?Object.freeze({...e.ownedView}):void 0,typeof this.fetchImpl!="function")throw new ve("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}async preflight(e,t){let r=await this.request("preflight","POST",e,t);if(this.ownedView&&e.operation==="browser.screenshot"){let n=e.declaredTarget?.tabId;if(!n||r.observedTarget.tabId!==n||e.identity.sessionId!==this.ownedView.sessionId)throw new ve("AUTOMATION_IDENTITY_MISMATCH","Owned capture requires the exact host session and tab.");let i=await this.request(`target?tabId=${encodeURIComponent(n)}`,"GET",void 0,t);if(i.tabId!==n||!Number.isSafeInteger(i.documentEpoch)||i.documentEpoch<0)throw new ve("AUTOMATION_TARGET_CHANGED","Owned capture target metadata changed.");return{...r,adapterState:{...r.adapterState,ownedViewDocumentEpoch:i.documentEpoch}}}return r}async execute(e,t,r,n){if(this.ownedView&&e.operation==="browser.screenshot"){let i=e.declaredTarget?.tabId,o=t.adapterState?.ownedViewDocumentEpoch;if(!i||t.observedTarget.tabId!==i||e.identity.sessionId!==this.ownedView.sessionId||!Number.isSafeInteger(o))throw new ve("AUTOMATION_IDENTITY_MISMATCH","Owned frame does not bind this request.");let s=new Date().toISOString(),a=await this.request("view-frame","POST",{version:1,...this.ownedView,tabId:i,documentEpoch:o,request:e,preflight:t,grant:r},n);if(a.version!==1||a.ownerId!==this.ownedView.ownerId||a.sessionId!==this.ownedView.sessionId||a.tabId!==i||a.documentEpoch!==o||a.mediaType!=="image/png"||!Number.isFinite(Date.parse(a.capturedAt))||Date.parse(a.capturedAt)<Date.parse(s)||a.origin!==new URL(t.observedTarget.url??t.observedTarget.origin??"").origin||typeof a.base64!="string"||a.base64.length>5592408||!/^[A-Za-z0-9+/]+={0,2}$/.test(a.base64)||a.base64.length%4!==0)throw new ve("AUTOMATION_RESPONSE_INVALID","Owned Browser returned a changed or oversized frame.");n.throwIfAborted(),w0(e);let l=Buffer.from(a.base64,"base64");if(l.length<24||l.length>4*1024*1024||l.subarray(0,8).toString("hex")!=="89504e470d0a1a0a"||l.readUInt32BE(16)<1||l.readUInt32BE(20)<1||l.readUInt32BE(16)*l.readUInt32BE(20)>2073600)throw new ve("AUTOMATION_RESPONSE_INVALID","Owned Browser returned invalid bounded PNG bytes.");return{operationId:e.operationId,status:"ok",startedAt:s,completedAt:a.capturedAt,observedTarget:t.observedTarget,evidence:[{evidenceId:`${e.operationId}.after`,phase:"after",kind:"screenshot",title:"Owned Browser frame",mediaType:"image/png",content:{type:"base64",base64:a.base64},sensitivity:"restricted"}]}}return this.request("execute","POST",{request:e,preflight:t,grant:r},n)}async stop(e,t){await this.request("stop","POST",{operationId:e,reason:t.slice(0,512)})}async request(e,t,r,n){let i=new AbortController,o=qQe(n,i),s=setTimeout(()=>i.abort(new Error("automation transport timeout")),this.timeoutMs);try{if(i.signal.aborted)throw new Error("Automation was cancelled before dispatch");let a=new URL(e,this.endpoint),l=this.fetchImpl(a,{method:t,redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.token}`,accept:"application/json",...t==="POST"?{"content-type":"application/json"}:{}},...t==="POST"?{body:JSON.stringify(r??{})}:{},signal:i.signal});l.then(u=>{i.signal.aborted&&u.body?.cancel().catch(()=>{})},()=>{});let c=await L2(l,i.signal),d=await L2(VQe(c,this.maxResponseBytes,i.signal),i.signal);if(!c.ok){let u=Zxn(d);throw new ve("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${e}: ${u.message}`,{status:c.status,route:e,adapterCode:u.code})}if(!mNe(d)||d.ok!==!0||!("result"in d))throw new ve("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${e} envelope`);return d.result}catch(a){if(a instanceof ve)throw a;let l=n?.aborted;throw new ve(l?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",l?"Automation transport was stopped":`XENO Browser ${e} transport failed`,{route:e},{cause:a})}finally{clearTimeout(s),o()}}};WQe=class{endpoint;options;constructor(e){let t;try{t=new URL(e.baseUrl)}catch{throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Use origin is invalid.")}let r=["localhost","127.0.0.1","[::1]"].includes(t.hostname);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&r&&!e.authorize))throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Use requires HTTPS; bootstrap HTTP is loopback-only.");if(e.token!==void 0==(e.authorize!==void 0)||e.authorize!==void 0&&typeof e.authorize!="function"||e.token!==void 0&&(!r||!LSt(e.token)))throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Use requires exactly one canonical authorizer or loopback bootstrap token.");for(let[n,i,o,s]of[["timeoutMs",e.timeoutMs??6e4,1e3,3e5],["maxResponseBytes",e.maxResponseBytes??48*1024*1024,1024,128*1024*1024]])if(!Number.isSafeInteger(i)||i<o||i>s)throw new ve("AUTOMATION_TRANSPORT_ERROR",`Invalid XENO Use ${n}.`);this.endpoint=new URL("/v1/use/automation/",t),this.options=Object.freeze({...e,authorize:e.authorize?.bind(void 0),fetch:e.fetch??globalThis.fetch})}async manifest(){let e=await this.request("manifest","GET");if($y(e),e.adapterId!=="xeno-use"||e.operations.some(t=>!t.startsWith("computer.")))throw new ve("AUTOMATION_OPERATION_UNSUPPORTED","XENO Use returned a different owning adapter contract.");return e}preflight(e,t){return this.request("preflight","POST",e,t)}execute(e,t,r,n){return this.request("execute","POST",{request:e,preflight:t,grant:r},n)}async assertCurrent(e){if((await this.request("current","POST",{request:e})).current!==!0)throw new ve("AUTOMATION_IDENTITY_MISMATCH","XENO Use operation authority is no longer current.")}async stop(e,t){if((await this.request("stop","POST",{operationId:e,reason:t.slice(0,512)})).stopped!==!0)throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Use did not confirm operation stop.")}async request(e,t,r,n){let i=new AbortController,o=qQe(n,i),s=setTimeout(()=>i.abort(),this.options.timeoutMs??6e4);try{i.signal.throwIfAborted();let a=new URL(e,this.endpoint),l=new Headers({accept:"application/json"});if(t==="POST"&&l.set("content-type","application/json"),this.options.authorize){let p;try{p=await L2(this.options.authorize(t,a.href),i.signal)}catch{throw new ve("AUTOMATION_TRANSPORT_ERROR","Canonical XENO Use authorization is unavailable.")}let f=p?.headers&&new Headers(p.headers).get("dpop");if(p?.tokenType!=="DPoP"||!LSt(p.token)||!f||/\s/.test(f))throw new ve("AUTOMATION_TRANSPORT_ERROR","Canonical XENO Use DPoP authorization is unavailable.");l.set("authorization",`DPoP ${p.token}`),l.set("dpop",f)}else l.set("authorization",`Bearer ${this.options.token}`);i.signal.throwIfAborted();let c=this.options.fetch(a,{method:t,headers:l,redirect:"error",credentials:"omit",cache:"no-store",signal:i.signal,...t==="POST"?{body:JSON.stringify(r??{})}:{}});c.then(p=>{i.signal.aborted&&p.body?.cancel().catch(()=>{})},()=>{});let d=await L2(c,i.signal),u=await L2(VQe(d,this.options.maxResponseBytes??48*1024*1024,i.signal),i.signal);if(!d.ok)throw new ve("AUTOMATION_TRANSPORT_ERROR",`XENO Use rejected ${e}.`,{status:d.status,route:e});if(!u||typeof u!="object"||!("ok"in u)||u.ok!==!0||!("result"in u))throw new ve("AUTOMATION_RESPONSE_INVALID","XENO Use returned an invalid automation envelope.");return u.result}catch(a){throw n?.aborted?new ve("AUTOMATION_CANCELLED","XENO Use transport was stopped."):a instanceof ve?a:new ve("AUTOMATION_TRANSPORT_ERROR",`XENO Use ${e} transport failed.`)}finally{clearTimeout(s),o()}}};SV();JQe=class{ports;declaration;now;ttl;maxPreflights;maxExecutions;prepared=new Map;executions=new Map;pendingPreflights=0;resultBytes=0;disposed=!1;constructor(e){$y(e.manifest),e.manifest.operations.some(t=>!t.startsWith("browser."))&&ph("Browser owner cannot advertise computer operations"),this.declaration=xm(e.manifest),this.ports=Object.freeze({...e.ports}),this.now=e.now??Date.now,this.ttl=PBe(e.preflightTtlMs,15e3,1,3e4),this.maxPreflights=PBe(e.maximumPreflights,256,1,1e3),this.maxExecutions=PBe(e.maximumExecutions,256,1,1e3)}manifest(){return structuredClone(this.declaration)}async assertCurrent(e){await this.current(xm(e),new AbortController().signal)}async preflight(e,t){let r=xm(e);await this.current(r,t);for(let[n,i]of this.prepared)i.expires<=this.now()&&this.prepared.delete(n);this.prepared.size+this.pendingPreflights>=this.maxPreflights&&Ore("Preflight capacity reached"),this.pendingPreflights++;try{let n=xm(await this.ports.resolveTarget(r,t));this.checkBinding(r,n),await this.ports.assertTargetUnchanged(n,t);let i=await this.capture(r,n,t,"before");await this.current(r,t),await this.ports.assertTargetUnchanged(n,t);let o=this.now(),s=xm({token:tCn(32).toString("base64url"),preparedAt:new Date(o).toISOString(),expiresAt:new Date(o+this.ttl).toISOString(),observedTarget:n.target,evidence:i,adapterState:{ownerId:n.ownerId,documentEpoch:n.documentEpoch}});return this.prepared.set(s.token,{requestHash:Wg(r),preflight:s,binding:n,expires:o+this.ttl}),structuredClone(s)}finally{this.pendingPreflights--}}async execute(e,t,r,n){let i=xm(e),o=xm(t),s=xm(r);await this.current(i,n);let a=Wg(i),l=Wg(s),c=this.executions.get(i.operationId);if(c){(c.requestHash!==a||c.grantHash!==l||Wg(c.prepared.preflight)!==Wg(o))&&Ore("Operation ID reused with different request, grant or preflight"),await this.authorize(i,c.prepared,s,n);let h=await c.promise;return await this.authorize(i,c.prepared,s,n),structuredClone(h)}let d=this.prepared.get(o.token);if(!d||d.expires<=this.now()||d.requestHash!==a||Wg(d.preflight)!==Wg(o))throw new ve("AUTOMATION_PREFLIGHT_INVALID","Preflight is missing, expired or changed");(this.executions.size>=this.maxExecutions||this.resultBytes>=16*1024*1024)&&Ore("Execution ledger capacity reached; session cannot accept new work"),[...this.executions.values()].some(h=>h.active&&h.prepared.binding.target.tabId===d.binding.target.tabId)&&Ore("An operation already owns this tab"),this.prepared.delete(o.token);let u=new AbortController,p=()=>{this.stop(i.operationId,"caller-abort").catch(()=>{})},f={requestHash:a,grantHash:l,prepared:d,controller:u,active:!0,promise:Promise.resolve(void 0)};return this.executions.set(i.operationId,f),n.addEventListener("abort",p,{once:!0}),f.promise=this.run(i,d,s,u.signal).finally(()=>{f.active=!1,n.removeEventListener("abort",p)}),n.aborted&&p(),structuredClone(await f.promise)}async stop(e,t="human-stop"){let r=this.executions.get(e);if(r?.active){r.controller.abort(new ve("AUTOMATION_CANCELLED",t.slice(0,256))),r.nativeStop??=Promise.resolve().then(()=>this.ports.stop(e,t));try{await r.nativeStop}finally{await r.promise.catch(()=>{})}}}async dispose(){this.disposed=!0,this.prepared.clear(),await Promise.all([...this.executions.keys()].map(e=>this.stop(e,"owner-shutdown")))}async run(e,t,r,n){let i=new Date(this.now()).toISOString();try{if(await this.authorize(e,t,r,n),t.expires<=this.now())throw new ve("AUTOMATION_PREFLIGHT_INVALID","Preflight expired during authorization");let o=this.context(e,t.binding,n,()=>this.authorize(e,t,r,n)),s=xm(await this.ports.dispatch(o));await this.current(e,n),this.checkGrant(e,t.binding.target,r),await this.ports.authorizeGrant(e,t.preflight,r,n);let a=s.observedTarget??t.binding.target;D2(e,this.declaration,a);let l=e.operation==="browser.tabs.close",c=l?t.binding:xm(await this.ports.resolveTarget(e,n,a));if(c.profile!==t.binding.profile||Wg(c.target)!==Wg(a)||e.operation!=="browser.tabs.open"&&(c.ownerId!==t.binding.ownerId||c.target.tabId!==t.binding.target.tabId))throw new ve("AUTOMATION_TARGET_CHANGED","Result target was closed, replaced or changed");if(!["browser.navigate","browser.back","browser.forward","browser.reload","browser.click","browser.type","browser.key","browser.tabs.open"].includes(e.operation)&&c.documentEpoch!==t.binding.documentEpoch)throw new ve("AUTOMATION_TARGET_CHANGED","Result document changed unexpectedly");a.url&&this.destination(e,t.binding,a.url,["browser.navigate","browser.tabs.open"].includes(e.operation)&&a.url===e.parameters.url);let d=[...s.evidence??[],...l?[]:await this.capture(e,c,n,"after")];if(zH(e).after==="required"&&!d.some(f=>f.phase==="after"))throw new ve("AUTOMATION_EVIDENCE_REQUIRED","Owner requires after evidence");await this.current(e,n),this.checkGrant(e,t.binding.target,r),await this.ports.authorizeGrant(e,t.preflight,r,n),await this.ports.finish?.(e.operationId),await this.current(e,n),this.checkGrant(e,t.binding.target,r),await this.ports.authorizeGrant(e,t.preflight,r,n);let u=xm({...s,operationId:e.operationId,status:"ok",observedTarget:a,evidence:d,startedAt:i,completedAt:new Date(this.now()).toISOString()}),p=Buffer.byteLength(JSON.stringify(u));if(p>1048576||this.resultBytes+p>16*1024*1024)throw new ve("AUTOMATION_EVIDENCE_INVALID","Result exceeds session evidence bounds");return this.resultBytes+=p,u}catch(o){let s=o;n.aborted&&await this.executions.get(e.operationId)?.nativeStop;try{await this.ports.finish?.(e.operationId)}catch(l){s=l}let a=n.aborted?"AUTOMATION_CANCELLED":s instanceof ve?s.code:"AUTOMATION_POLICY_DENIED";return{operationId:e.operationId,status:n.aborted?"cancelled":"error",startedAt:i,completedAt:new Date(this.now()).toISOString(),observedTarget:structuredClone(t.binding.target),error:{code:a,message:s instanceof Error?s.message.slice(0,512):"Browser owner refused operation"}}}}async current(e,t){if(this.disposed||t.aborted)throw new ve("AUTOMATION_CANCELLED","Browser owner operation stopped");if(w0(e),e.operation.startsWith("browser.")||ph("Browser owner requires a browser operation"),this.ports.authorizeGrant||ph("Trusted grant issuer authorization is not installed"),await this.ports.assertCurrent(e,t),this.disposed||t.aborted)throw new ve("AUTOMATION_CANCELLED","Browser owner operation stopped")}checkBinding(e,t){(!t.ownerId||!t.target.tabId||!t.target.url||!(typeof t.documentEpoch=="number"&&Number.isSafeInteger(t.documentEpoch)&&t.documentEpoch>=0||typeof t.documentEpoch=="string"&&t.documentEpoch.length>0))&&ph("Owner did not bind an exact tab and document"),(t.profile!==e.executionContract.browser.profile||this.declaration.profileIsolation!==t.profile&&!(this.declaration.profileIsolation==="both"&&t.profile!=="shared-user"))&&ph("Browser security profile does not match owner isolation");let r=new URL(t.target.url);(t.target.origin!==void 0&&t.target.origin!==r.origin||t.target.domain!==void 0&&t.target.domain!==r.hostname||t.target.port!==void 0&&t.target.port!==Number(r.port||(r.protocol==="https:"?443:80)))&&ph("Owner target metadata does not match its exact URL");for(let n of["tabId","pageId","resource","url","origin"]){let i=e.operation==="browser.navigate"||e.operation==="browser.tabs.open";if(!(n==="resource"&&e.declaredTarget?.resource==="browser-tabs"&&(i||e.operation==="browser.tabs.list"))){if(n==="url"&&i){e.declaredTarget?.url!==void 0&&e.declaredTarget.url!==e.parameters.url&&ph("Declared navigation URL does not match destination");continue}if(e.declaredTarget?.[n]!==void 0&&e.declaredTarget[n]!==t.target[n])throw new ve("AUTOMATION_TARGET_CHANGED",`Exact declared ${n} changed`)}}D2(e,this.declaration,t.target),(e.operation==="browser.navigate"||e.operation==="browser.tabs.open")&&(typeof e.parameters.url!="string"&&ph("Navigation requires an explicit URL"),this.destination(e,t,e.parameters.url,!0))}checkGrant(e,t,r){pA(r.lease);let n=r.lease,i=kde(e,t);(r.contractFingerprint!==e.executionContract.fingerprint||Wg(r.capabilityUse)!==Wg(i)||n.leaseId!==e.capabilityLeaseId||n.version!==e.expectedLeaseVersion+1||n.useCount<1||!["active","exhausted"].includes(n.state)||!n.expiresAt||Date.parse(n.expiresAt)<=this.now()||n.profileFingerprint!==e.executionContract.profile.fingerprint||n.subject.runId!==e.identity.runId||n.subject.agentId!==e.identity.agentId||n.subject.turnId!==e.identity.turnId||n.subject.toolName!==e.governingToolName||n.subject.operationId!==void 0&&n.subject.operationId!==e.operationId||n.scope.kind!==i.kind||n.scope.governingToolName!==e.governingToolName||!n.scope.operations.includes(e.operation)||n.scope.resources!==void 0&&(!i.resource||!n.scope.resources.includes(i.resource))||n.scope.destinations!==void 0&&(!i.destination||!n.scope.destinations.includes(i.destination)))&&ph("Consumed grant does not match exact request and lease")}async authorize(e,t,r,n){await this.current(e,n),this.checkBinding(e,t.binding),this.checkGrant(e,t.binding.target,r),await this.ports.authorizeGrant(e,t.preflight,r,n),await this.ports.assertTargetUnchanged(t.binding,n),await this.current(e,n)}destination(e,t,r,n=!1){if(D2(e,this.declaration,{tabId:t.target.tabId,url:r}),!n&&r!==t.target.url){let i=e.executionContract.browser.redirectPolicy;(i==="deny"||i==="same-origin"&&new URL(r).origin!==new URL(t.target.url).origin)&&ph("Browser redirect policy refused destination")}}context(e,t,r,n){return{request:e,binding:t,signal:r,assertDispatchAllowed:async i=>{n?await n():(await this.current(e,r),await this.ports.assertTargetUnchanged(t,r)),i&&this.destination(e,t,i,["browser.navigate","browser.tabs.open"].includes(e.operation)&&i===e.parameters.url)}}}async capture(e,t,r,n){let i=zH(e)[n];if(i==="disabled")return[];await this.current(e,r),await this.ports.assertTargetUnchanged(t,r);let o=xm(await this.ports.captureEvidence(this.context(e,t,r),n));if(await this.ports.assertTargetUnchanged(t,r),await this.current(e,r),i==="required"&&!o.some(s=>s.phase===n))throw new ve("AUTOMATION_EVIDENCE_REQUIRED",`Owner requires ${n} evidence`);return o}};Doe=4*1024*1024,iCn=64,oCn=64,FSt=8192,_Be=/^[a-f0-9]{64}$/,zLt=class{channelEpoch;stream;timeoutMs;decisions=new Map;pending=new Map;nonces=new Set;retiredIds=new Set;frame=Buffer.alloc(0);writeTail=Promise.resolve();queuedWrites=0;dead=!1;constructor(e){if(this.stream=e.stream,this.channelEpoch=e.channelEpoch??BBe(),!_Be.test(this.channelEpoch)||(this.timeoutMs=e.timeoutMs??1e4,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>6e4))throw tn();this.stream.on("data",this.onData),this.stream.on("error",this.onDeath),this.stream.on("end",this.onDeath),this.stream.on("close",this.onDeath),(this.stream.destroyed||!this.stream.readable||!this.stream.writable)&&this.kill()}async begin(e,t,r){this.live();let n=Loe(e);if(this.decisions.has(e.operationId)||this.decisions.size>=oCn||r.aborted||t.profileFingerprint!==e.executionContract.profile.fingerprint)throw tn();try{if(t.assertCurrent()!==void 0)throw tn()}catch{throw tn()}let i={decisionId:BBe(),operationId:e.operationId,requestHash:n,decision:Object.freeze({...t,assertCurrent:t.assertCurrent}),signal:r,denied:!1,abort:()=>{this.cancel(i)}};this.decisions.set(e.operationId,i),r.addEventListener("abort",i.abort,{once:!0}),r.aborted&&i.abort();try{await this.rpc("begin",i,{request:e,decision:{authorization:t.authorization,profileFingerprint:t.profileFingerprint}}),this.check(i)}catch{throw this.cancel(i),tn()}}async recordPreflight(e,t,r){let n=this.row(e),i=ANe(t);if(n.preflightHash&&n.preflightHash!==i)throw tn();n.preflightHash=i,await this.record("recordPreflight",e,{preflight:t},r),this.check(n)}async recordGrant(e,t,r,n){await this.record("recordGrant",e,{preflight:t,grant:r},n)}async assertCurrent(e){let t=this.row(e);this.check(t);try{await this.rpc("assertCurrent",t),this.check(t)}catch{throw this.cancel(t),tn()}}async finish(e){this.live();let t=this.row(e,!0);t.denied=!0;let r=await this.rpc("finish",t);if(r.result?.withdrawn!==!0||r.result.decisionId!==t.decisionId)throw tn();t.signal.removeEventListener("abort",t.abort),this.decisions.delete(t.operationId)}async close(){if(this.stream.destroyed&&this.kill(),!this.dead&&this.decisions.size>0)throw tn();this.kill(),this.stream.destroy()}async record(e,t,r,n){let i=this.row(t);if(n.aborted)throw this.cancel(i),tn();this.check(i);let o=()=>this.cancel(i);n.addEventListener("abort",o,{once:!0});try{if(await this.rpc(e,i,r),this.check(i),n.aborted)throw tn()}catch{throw this.cancel(i),tn()}finally{n.removeEventListener("abort",o)}}row(e,t=!1){this.live();let r=this.decisions.get(e.operationId);if(!r||r.requestHash!==Loe(e)||!t&&r.denied)throw tn();return r}check(e){if(this.live(),e.denied||e.signal.aborted)throw tn();try{if(e.decision.assertCurrent()!==void 0)throw tn()}catch{throw e.denied=!0,tn()}if(e.signal.aborted||e.denied||this.dead)throw tn()}cancel(e){if(e.denied=!0,!this.dead)try{this.rpc("cancel",e).catch(()=>{})}catch{this.kill()}}rpc(e,t,r={}){if(this.live(),this.pending.size>=iCn||this.retiredIds.size>=FSt)throw tn();let n=BBe(),i={version:1,kind:"request",id:n,channelEpoch:this.channelEpoch,method:e,payload:{...r,decisionId:t.decisionId,operationId:t.operationId,requestHash:t.requestHash}},o=USt(i);return new Promise((s,a)=>{let l=setTimeout(()=>{this.pending.delete(n),this.retiredIds.add(n),a(tn())},this.timeoutMs);this.pending.set(n,{resolve:s,reject:a,timer:l}),this.write(o).catch(()=>{this.kill()})})}write(e){if(this.live(),this.queuedWrites>=128)return this.kill(),Promise.reject(tn());this.queuedWrites++;let t=this.writeTail.then(()=>new Promise((r,n)=>{if(this.dead){n(tn());return}this.stream.write(e,i=>i?n(tn()):r())}));return this.writeTail=t.catch(()=>{}).finally(()=>{this.queuedWrites--}),t}onData=e=>{if(this.dead)return;if(!Buffer.isBuffer(e)&&typeof e!="string"){this.kill();return}let t=Buffer.isBuffer(e)?e:Buffer.from(e),r=0;for(let n=0;n<t.length;n++){if(t[n]!==10)continue;if(this.frame.length+n-r>Doe){this.kill();return}let i=Buffer.concat([this.frame,t.subarray(r,n)]);this.frame=Buffer.alloc(0),r=n+1;try{this.receive(JSON.parse(i.toString("utf8")))}catch{this.kill();return}if(this.dead)return}if(this.frame.length+t.length-r>Doe){this.kill();return}this.frame=Buffer.concat([this.frame,t.subarray(r)])};receive(e){if(!lie(e)||e.version!==1||typeof e.id!="string"||!_Be.test(e.id))throw tn();if(e.kind==="decision.check"||e.kind==="decision.grant.check"){this.challenge(e);return}if(e.kind!=="response"||e.channelEpoch!==this.channelEpoch||typeof e.ok!="boolean")throw tn();let t=this.pending.get(e.id);if(!t){if(this.retiredIds.has(e.id))return;throw tn()}this.pending.delete(e.id),clearTimeout(t.timer),e.ok?t.resolve(e):t.reject(tn())}challenge(e){for(let s of["channelEpoch","decisionId","requestHash","nonce"])if(typeof e[s]!="string"||!_Be.test(e[s]))throw tn();if(typeof e.operationId!="string"||e.operationId.length<1||e.operationId.length>256)throw tn();let t=e,r=this.decisions.get(t.operationId),n=!this.nonces.has(t.nonce);if(this.nonces.size>=FSt)throw tn();this.nonces.add(t.nonce);let i=!1;if(n&&t.channelEpoch===this.channelEpoch&&r&&t.decisionId===r.decisionId&&t.requestHash===r.requestHash)try{if(this.check(r),e.kind==="decision.grant.check"){let s=e;if(!lie(s.preflight)||!lie(s.grant)||!r.decision.assertGrantCurrent||r.preflightHash!==ANe(s.preflight)||r.decision.assertGrantCurrent(s.preflight,s.grant)!==void 0)throw tn();this.check(r)}i=!0}catch{i=!1}let o={version:1,kind:e.kind==="decision.grant.check"?"decision.grant.result":"decision.result",id:t.id,channelEpoch:t.channelEpoch,decisionId:t.decisionId,operationId:t.operationId,requestHash:t.requestHash,nonce:t.nonce,current:i};this.write(USt(o)).catch(()=>{this.kill()})}live(){if(this.stream.destroyed&&this.kill(),this.dead)throw tn()}onDeath=()=>{this.kill()};kill(){if(!this.dead){this.dead=!0,this.frame=Buffer.alloc(0);for(let e of this.pending.values())clearTimeout(e.timer),e.reject(tn());this.pending.clear();for(let e of this.decisions.values())e.denied=!0,e.signal.removeEventListener("abort",e.abort);this.stream.off("data",this.onData),this.stream.destroy()}}};$Be={"browser.navigate":"navigate","browser.back":"back","browser.forward":"forward","browser.reload":"reload","browser.snapshot":"observe","browser.screenshot":"screenshot","browser.locate":"find","browser.click":"click","browser.type":"type","browser.key":"key","browser.select":"select","browser.scroll":"scroll","browser.wait":"wait","browser.tabs.list":"tabs_list","browser.console.read":"console_log","browser.network.read":"network_log"};XLt=["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"],_de=class extends HQe{driver;constructor(e){super(e),this.driver=e.driver}async manifest(){let e=await super.manifest();if($y(e),!(this.driver==="browser"?["xeno-browser","xeno-browser-native"]:["xeno-extension-native","xeno-extension"]).includes(e.adapterId)||e.operations.some(t=>!t.startsWith("browser.")))throw new ve("AUTOMATION_OPERATION_UNSUPPORTED","Configured Browser driver returned a different owning adapter contract.");return e}};gn();aR();Bde=1,uCn="repository.v1.json",pCn=5e3,fCn=20,hCn=64*1024*1024,$de=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let t=e.snapshotFileName??uCn;if(jSt(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=dCn(e.directory),this.snapshotPath=cCn(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=MBe(e.lockTimeoutMs,pCn,100,6e4,"lockTimeoutMs"),this.lockRetryMs=MBe(e.lockRetryMs,fCn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=MBe(e.maxSnapshotBytes,hCn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(t=>t.create(e))}async createRevision(e,t){return this.mutate(r=>r.createRevision(e,t))}async get(e,t){return(await this.load()).repository.get(e,t)}async require(e,t){return(await this.load()).repository.require(e,t)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(t=>t.transition(e))}async appendReviewEvent(e){return this.mutate(t=>t.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let t=await this.acquireLock();try{let r=await this.load(),n=await e(r.repository);return await this.persist(r),n}finally{t.release()}})}async enqueueMutation(e){let t=this.mutationTail.then(e,e);return this.mutationTail=t.then(()=>{},()=>{}),t}async acquireLock(){let e=Date.now(),t;for(;Date.now()-e<=this.lockTimeoutMs;)try{return nS(this.lockPath,`artifact-repository:${jSt(this.snapshotPath)}`,J0)}catch(r){if(!(r instanceof Error)||!/already locked by PID/.test(r.message))throw r;t=r,await yCn(this.lockRetryMs)}throw new er("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,r=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=Foe(i)}if(!t&&(e||await wCn(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),t=i,r=!0)}catch(i){throw e?new er("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,Foe(i)])}):i}if(!t&&e)throw e;let n=t?.state??{schemaVersion:1,records:[]};return{repository:new Rde({now:this.now,idFactory:i=>`${i}_${ZLt()}`,initialState:n}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:r,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),r={schemaVersion:Bde,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},n=gCn(r),i=`${JSON.stringify(n,null,2)}
|
|
2789
|
+
`});$Sn=X(()=>{"use strict";ls(),uSt(),uSt(),mq=dQe()?.isPlatformSupported===!0,pde="ai.xenostudio.xeno-agent.mcp",fde="xeno.host.state.encryption-key.v1",g8="aes-256-gcm",C1=32,sie=12,tNe=16,RO="b64:",$oe="dpapi:v1:"}),fQe=X(()=>{"use strict";ade(),G1n(),P5t(),R5t(),r5(),wRt(),tae(),lR(),SV(),nLt(),J1n(),Z1n(),Q5e(),ISn(),z5e(),eDe(),$Sn(),iDe(),$Pt()}),hde=X(()=>{"use strict";hQe=2});Ade=X(()=>{"use strict";Use(),hde(),Moe=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,CLt=2e3,yQe=2*1024*1024,bQe=2e3,vQe=64*1024*1024,TLt=new Set(["node_modules",".git",".hg",".svn"])});EQe=X(()=>{"use strict";Ade(),hde(),oNe=128*1024});BLt=X(()=>{"use strict"}),$Lt={};fun($Lt,{createDelegatedXenoAgent:()=>kR});SQe=X(()=>{"use strict";QUe(),JUe(),fQe(),P5(),MLt=[{tool:"Write",decision:"deny"},{tool:"Edit",decision:"deny"},{tool:"Patch",decision:"deny"},{tool:"MemoryWrite",decision:"deny"},{tool:"Bash",decision:"deny"},{tool:"dispatch_agent",decision:"deny"}]});P5=X(()=>{"use strict";EQe(),Ade(),Y0(),Q0(),DUe(),AUe(),vDt(),ls(),XUe(),BLt(),Kl(),Xae(),fQe(),wR(),BN=8192,WH=50});rR();J0="0.10.110";Lse();gn();Pc();SR=class{filePath;sessionId;labels;sequence=0;writeQueue=Promise.resolve();constructor(e){this.filePath=e.filePath,this.sessionId=e.sessionId,this.labels={run_id:e.runId,agent_id:e.agentId,parent_agent_id:e.parentAgentId,workspace:e.workspace,model:e.model,provider:e.provider}}get path(){return this.filePath}async append(e){let t=txn(),r={id:t,sequence:this.sequence++,timestamp:new Date().toISOString(),session_id:e.session_id??this.sessionId,...this.labels,...e};return this.writeQueue=this.writeQueue.then(async()=>{await yne(this.filePath,JSON.stringify(r))}),await this.writeQueue,t}async read(e){let t=await Sl(this.filePath);if(!t)return[];let r=W3(t);return e?.eventType&&(r=r.filter(n=>n.event_type===e.eventType)),e?.traceId&&(r=r.filter(n=>n.trace_id===e.traceId)),e?.limit!==void 0&&(r=r.slice(-Math.max(0,e.limit))),r}async tail(e=20){let t=Math.max(1,Math.min(e,500));return this.read({limit:t})}async exportJson(e){let t=await this.read();return await qs(e,JSON.stringify(t,null,2)),t.length}async flush(){await this.writeQueue}};T5e();Xse();TQe=new Set(["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read"]),RQe=new Set(["browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download","browser.record.start","browser.record.stop"]),PQe=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),_Qe=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),CR=[...TQe,...RQe,...PQe,..._Qe];cd();LLt=new Set(["Read","Glob","Grep","LS","GitStatus","GitDiff","GitLog","WebFetch","WebSearch","MemoryRead","NotebookRead","ReadImage","SqliteAnalyze","ElfAnalyze","GcodeAnalyze","HtmlSanitizerAudit","ArtifactCompare","Think","ToolSearch","Skill",...CR.filter(e=>kh(e).effect==="observe")]),O5=class{constructor(e){this.registry=e}registry;removedTools=new Map;restore(){for(let[e,t]of this.removedTools)this.registry.has(e)||this.registry.register(t);this.removedTools.clear()}apply(e){if(this.restore(),!e)return{removed:[]};let t=BQe(e),r=FLt(t),n=[];for(let i of this.registry.listNames()){let o=JH(i),s=r?!r.has(o):!1,a=t.denyExact.has(o);if(!s&&!a)continue;let l=this.registry.get(i);l&&this.registry.unregister(i)&&(this.removedTools.set(i,l),n.push(i))}return ULt(t,r,n)}};QLt=1,ve=class extends Error{constructor(e,t,r,n){super(t,n),this.code=e,this.detail=r,this.name="XenoAutomationError"}code;detail};eDe();dxn=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,kSt=1048576;jLt=1,HLt=1,$Qe=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation","page"],MQe=["draft","pending_review","approved","rejected","superseded","archived"],OQe=["public","internal","confidential","restricted"],NQe=["agent","tool","user","system","integration"],Sde=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],xde=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];sae();vq=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(r=>({...r}))}},DQe=class extends Error{constructor(e,t){super(`Artifact state cannot transition from ${e} to ${t}`),this.fromState=e,this.toState=t,this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},wxn={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},yxn="[\\u0000-\\u001f\\u007f]",bxn=new RegExp(yxn),VLt=/^[a-f0-9]{64}$/,vxn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ixn=new Set(MQe),Exn=new Set(OQe),kxn=new Set(NQe),Sxn=new Set($Qe),xxn=new Set(Sde),Cxn=new Set(xde);er=class extends Error{constructor(e,t,r,n){super(t,n),this.code=e,this.detail=r,this.name="XenoArtifactRepositoryError"}code;detail},Rde=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(e={}){this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>(this.idCounter+=1,`${t}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),e.initialState&&this.hydrate(e.initialState)}exportState(){return{schemaVersion:1,records:[...this.records.values()].flatMap(t=>[...t.values()]).sort(PSt).map(t=>({artifact:J8(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(Vd(e),this.assertInitialState(e),e.revision!==1)throw new er("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:e.artifactId,revision:e.revision});if(this.records.has(e.artifactId))throw new er("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=J8(e),r=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),n={artifact:t,recordVersion:1,lifecycleEvents:[r],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,n]])),this.currentRevisions.set(t.artifactId,t.revision),XT(n)}async createRevision(e,t={}){Vd(e),this.assertInitialState(e);let r=this.getMutable(e.artifactId);this.assertVersion(r,t.expectedRecordVersion);let n=r.artifact.revision+1;if(e.revision!==n||e.predecessorRevision!==r.artifact.revision)throw new er("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${r.artifact.revision}`,{artifactId:e.artifactId,currentRevision:r.artifact.revision,requestedRevision:e.revision});if(Rxn(e,r.artifact))throw new er("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(r.artifact.state==="archived")throw new er("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:r.artifact.revision});if(r.artifact.state!=="superseded"){XH(r.artifact.state,"superseded");let a=this.now(),l=this.createLifecycleEvent({artifact:r.artifact,sequence:r.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:r.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});r.artifact.state="superseded",r.artifact.updatedAt=a,r.lifecycleEvents.push(l),r.recordVersion+=1}let i=J8(e),o=this.createLifecycleEvent({artifact:i,sequence:1,actor:t.actor??i.provenance.producer,fromState:null,toState:i.state,reason:t.reason??`revision-created-from-${r.artifact.revision}`}),s={artifact:i,recordVersion:1,lifecycleEvents:[o],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,s),this.currentRevisions.set(i.artifactId,i.revision),XT(s)}async get(e,t){let r=this.records.get(e);if(!r)return;let n=t??this.currentRevisions.get(e);if(n===void 0)return;let i=r.get(n);return i?XT(i):void 0}async require(e,t){let r=await this.get(e,t);if(!r)throw new er("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return r}async list(e={}){let t=[];for(let[r,n]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(r)))if(e.includeSuperseded)t.push(...n.values());else{let i=this.currentRevisions.get(r);if(i!==void 0){let o=n.get(i);o&&t.push(o)}}return t.filter(r=>Pxn(r.artifact,e)).sort(PSt).map(XT)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((r,n)=>r.artifact.revision-n.artifact.revision).map(XT):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),XH(t.artifact.state,e.toState),e.toState==="approved"||e.toState==="rejected"){let o=e.reviewEventId?t.reviewEvents.find(a=>a.eventId===e.reviewEventId&&a.type==="decision-recorded"):void 0,s=Tde(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new er("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${e.toState} requires a matching decision event`,{artifactId:e.artifactId,revision:t.artifact.revision});if(e.toState==="approved"&&s.unresolvedComments>0)throw new er("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let r=this.now(),n=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:n,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:r});return t.artifact.state=e.toState,t.artifact.updatedAt=r,t.lifecycleEvents.push(i),t.recordVersion+=1,XT(t)}async appendReviewEvent(e){let t=e.event,r=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(r,e.expectedRecordVersion),r.artifact.state==="archived"||r.artifact.state==="superseded")throw new er("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${r.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(r,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&r.artifact.state!=="pending_review")throw new er("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let n={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:r.reviewEvents.length+1,recordedAt:this.now()},i=Cde(n,r.artifact);if(i.length>0)throw new vq("XENO artifact review event validation failed",i);return r.reviewEvents.push(n),r.recordVersion+=1,XT(r)}getMutable(e,t){let r=this.records.get(e),n=t??this.currentRevisions.get(e),i=n===void 0?void 0:r?.get(n);if(!i)throw new er("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return i}assertVersion(e,t){if(t!==void 0&&t!==e.recordVersion)throw new er("ARTIFACT_CONFLICT",`Expected record version ${t}, found ${e.recordVersion}`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision,expectedRecordVersion:t,actualRecordVersion:e.recordVersion})}assertInitialState(e){if(e.state!=="draft"&&e.state!=="pending_review")throw new er("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:e.artifactId,revision:e.revision})}assertReviewCommentState(e,t){if(t.type==="comment-added"){if(e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.commentId))throw new er("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.parentCommentId))throw new er("ARTIFACT_REVIEW_INVALID",`Parent comment ${t.parentCommentId} does not exist`);return}if(t.type!=="comment-resolved"&&t.type!=="comment-reopened")return;if(!e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.commentId))throw new er("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let r=_xn(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&r.resolved)throw new er("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!r.resolved)throw new er("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is not resolved`)}createLifecycleEvent(e){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:e.artifact.artifactId,revision:e.artifact.revision,sequence:e.sequence,recordedAt:e.recordedAt??this.now(),actor:{...e.actor},fromState:e.fromState,toState:e.toState,...e.reason?{reason:e.reason}:{},...e.reviewEventId?{reviewEventId:e.reviewEventId}:{}}}nextEventId(e){let t=this.idFactory(e);if(typeof t!="string"||t.trim().length===0||this.eventIds.has(t))throw new er("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${e} ID`);return this.eventIds.add(t),t}hydrate(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new er("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((r,n)=>r.artifact.artifactId.localeCompare(n.artifact.artifactId)||r.artifact.revision-n.artifact.revision);for(let r of t){let n=Txn(r,this.eventIds),i=this.records.get(n.artifact.artifactId);if(i||(i=new Map,this.records.set(n.artifact.artifactId,i)),i.has(n.artifact.revision))throw new er("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${n.artifact.artifactId}:${n.artifact.revision}`);i.set(n.artifact.revision,n),this.currentRevisions.set(n.artifact.artifactId,n.artifact.revision)}for(let[r,n]of this.records){let i=[...n.values()].sort((o,s)=>o.artifact.revision-s.artifact.revision);for(let o=0;o<i.length;o+=1){let s=i[o],a=o+1;if(s.artifact.revision!==a)throw new er("ARTIFACT_REVISION_INVALID",`Persisted artifact ${r} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new er("ARTIFACT_REVISION_INVALID",`Initial revision for ${r} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new er("ARTIFACT_REVISION_INVALID",`Persisted revision ${r}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new er("ARTIFACT_REVISION_INVALID",`Non-current revision ${r}:${a} must be superseded`)}}}};cNe=32*1024*1024,Bxn=1024*1024*1024,$xn=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;BSt=16*1024*1024;MSt=3e4,OSt=1e3,QQe=class{adapter;leaseAuthority;durable;artifactRepository;now;assertCurrent;executions=new Map;active=new Map;constructor(e){if(this.adapter=e.adapter,this.leaseAuthority=e.leaseAuthority,!!e.leaseAuthority==!!e.durable)throw new Error("Choose exactly one legacy or durable automation authority");this.durable=e.durable,this.artifactRepository=e.durable?.artifactRepository??e.artifactRepository,this.now=e.now??(()=>new Date().toISOString()),this.assertCurrent=e.assertCurrent||e.adapter.assertCurrent?async t=>{await e.assertCurrent?.(t),await e.adapter.assertCurrent?.(t)}:void 0,this.onPreflight=e.onPreflight,this.onGrant=e.onGrant}onPreflight;onGrant;execute(e,t){e=structuredClone(e);let r=Hxn(e),n=this.executions.get(e.operationId);if(n){if(n.fingerprint!==r)throw new ve("AUTOMATION_OPERATION_CONFLICT",`Operation ${e.operationId} was already submitted with different authority or parameters`);if(this.durable){let l=this.durable;return l.assertCurrent(e).then(()=>this.assertCurrent?.(e)).then(()=>n.promise).then(async c=>(await l.assertCurrent(e),await this.assertCurrent?.(e),structuredClone(c)))}return this.assertCurrent?Promise.resolve(this.assertCurrent(e)).then(()=>n.promise).then(async l=>(await this.assertCurrent?.(e),structuredClone(l))):n.promise}if(this.active.size>=OSt)throw new ve("AUTOMATION_OPERATION_CONFLICT","Automation active-operation capacity reached");let i=new AbortController,o=Vxn(t,i);this.active.set(e.operationId,i);let s=this.durable,a=(s?UQe({...s,assertCurrent:async l=>{await s.assertCurrent(l),await this.assertCurrent?.(l)}},e,r,l=>this.executeFresh(e,i.signal,l)):this.executeFresh(e,i.signal)).finally(()=>{o(),this.active.delete(e.operationId)});return this.executions.set(e.operationId,{fingerprint:r,promise:a}),this.durable&&a.then(()=>this.executions.delete(e.operationId),()=>this.executions.delete(e.operationId)),this.trimIdempotencyRecords(),a}async stop(e,t="human-stop"){let r=this.active.get(e);return r?(r.abort(new Error(t)),await this.adapter.stop?.(e,t),!0):!1}async executeFresh(e,t,r){w0(e),await this.assertCurrent?.(e),ay(t);let n=await this.adapter.manifest();$y(n),Ede(e,n);let i=kh(e.operation),o=zH(e),s=this.now(),a=await this.adapter.preflight(e,t);Uxn(a,this.now()),D2(e,n,a.observedTarget),ay(t),await this.onPreflight?.(structuredClone(e),structuredClone(a),t),ay(t);let l=a.evidence??[];w0(e),await this.assertCurrent?.(e),ay(t),z8(l,o,"before");let c=await YH(this.artifactRepository,Noe({request:e,manifest:n,policy:o,evidence:l,now:this.now}));if(ay(t),Date.parse(a.expiresAt)<=Date.parse(this.now()))throw new ve("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let d=kde(e,a.observedTarget);await this.assertCurrent?.(e);let u;if(this.durable){await this.durable.assertCurrent(e);let b=await this.durable.consume(r,e.capabilityLeaseId,e.expectedLeaseVersion,d);if(b.executionDisposition!=="dispatch-once"||b.replayed)throw P0();u=b.lease,await this.durable.assertCurrent(e)}else u=await this.leaseAuthority.consume(e.capabilityLeaseId,e.expectedLeaseVersion,d);let p={contractFingerprint:e.executionContract.fingerprint,lease:u,capabilityUse:d};await this.onGrant?.(structuredClone(e),structuredClone(a),structuredClone(p),t),ay(t);let f;try{ay(t),w0(e),await this.assertCurrent?.(e),ay(t),f=await this.adapter.execute(e,a,p,t)}catch(b){return RBe({request:e,manifest:n,descriptorEffect:i.effect,target:a.observedTarget,lease:u,artifacts:c,startedAt:s,completedAt:this.now(),status:t.aborted?"cancelled":"error",code:t.aborted?"AUTOMATION_CANCELLED":"AUTOMATION_ADAPTER_ERROR",message:t.aborted?"Automation operation was stopped":qxn(b)})}if(Qxn(f),ay(t),w0(e),await this.assertCurrent?.(e),f.operationId!==void 0&&f.operationId!==e.operationId)throw new ve("AUTOMATION_RESPONSE_INVALID","Adapter returned another operation identity");let h=Gxn(a.observedTarget,f.observedTarget),m;try{D2(e,n,f.observedTarget)}catch(b){m=b instanceof Error?b:new Error(String(b))}if(h||m)return RBe({request:e,manifest:n,descriptorEffect:i.effect,target:a.observedTarget,lease:u,artifacts:c,startedAt:f.startedAt,completedAt:f.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:h??m.message});if(f.status!=="ok")return{operationId:e.operationId,status:f.status,effect:i.effect,startedAt:f.startedAt,completedAt:f.completedAt,adapter:dNe(n),target:structuredClone(f.observedTarget),artifacts:c,lease:uNe(u),error:f.error?{...f.error}:{code:"AUTOMATION_ADAPTER_ERROR",message:"Owning adapter refused the operation."}};let g=f.evidence??[];jxn(l,g);let A=[],w;try{z8(g,o,"after"),z8([...l,...g],o,"recording"),A=await YH(this.artifactRepository,Noe({request:e,manifest:n,policy:o,evidence:g,now:this.now}))}catch(b){w=b instanceof Error?b:new Error(String(b))}let y=[...c,...A];return ay(t),w0(e),await this.assertCurrent?.(e),w?RBe({request:e,manifest:n,descriptorEffect:i.effect,target:f.observedTarget,lease:u,artifacts:y,startedAt:f.startedAt,completedAt:f.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:w.message}):{operationId:e.operationId,status:f.status,effect:i.effect,startedAt:f.startedAt,completedAt:f.completedAt,adapter:dNe(n),target:structuredClone(f.observedTarget),...f.data!==void 0?{data:structuredClone(f.data)}:{},artifacts:y,lease:uNe(u),...f.error?{error:{...f.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>OSt;){let e=this.executions.keys().next().value;if(!e||this.active.has(e))break;this.executions.delete(e)}}};GQe=class{constructor(e){this.database=e;try{if(e.exec("PRAGMA busy_timeout=0; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS automation_execution_schema(id INTEGER PRIMARY KEY CHECK(id=1),version INTEGER NOT NULL); INSERT OR IGNORE INTO automation_execution_schema VALUES(1,1);"),e.prepare("SELECT version FROM automation_execution_schema WHERE id=1").get()?.version!==1)throw Error("Unsupported automation execution journal");e.exec("CREATE TABLE IF NOT EXISTS automation_executions(id TEXT PRIMARY KEY,body TEXT NOT NULL)")}catch(t){throw e.close(),this.closed=!0,t}}database;closed=!1;async begin(e){return e=structuredClone(e),fNe(e),NO(e,["operationId","fingerprint","ownerToken"]),this.transaction(()=>{let t=this.read(e.operationId);if(t){if(t.fingerprint!==e.fingerprint)throw Mre();return{claimed:!1,record:t}}let r=this.database.prepare("SELECT COUNT(*) AS count FROM automation_executions").get()?.count;if(typeof r!="number"||r>=1e5)throw Error("Automation journal capacity reached; explicit archival required");let n={schemaVersion:1,...e,outcome:{kind:"pending"}};return this.database.prepare("INSERT INTO automation_executions(id,body) VALUES(?,?)").run(e.operationId,NSt(n)),{claimed:!0,record:n}})}async get(e){if(typeof e!="string"||!e.trim()||e.length>1024)throw Error("Invalid automation journal identity");return this.transaction(()=>this.read(e))}async finish(e,t){e=structuredClone(e),t=structuredClone(t),fNe(e),NO(e,["operationId","fingerprint","ownerToken"]);let r={schemaVersion:1,...e,outcome:t};return hNe(r),this.transaction(()=>{let n=this.read(e.operationId);if(!n||n.fingerprint!==e.fingerprint||n.ownerToken!==e.ownerToken)throw Mre();if(n.outcome.kind!=="pending"){if(JSON.stringify(n.outcome)!==JSON.stringify(t))throw Mre();return}this.database.prepare("UPDATE automation_executions SET body=? WHERE id=?").run(NSt(r),e.operationId)})}close(){this.closed||(this.closed=!0,this.database.close())}read(e){let t=this.database.prepare("SELECT CASE WHEN length(body)<=16384 THEN body ELSE NULL END AS body FROM automation_executions WHERE id=?").get(e);if(!t)return;if(typeof t.body!="string")throw Error("Corrupt automation journal size");let r=JSON.parse(t.body);if(hNe(r),r.operationId!==e)throw Mre();return r}async transaction(e){let t=Date.now()+1e3;for(;;){if(this.closed)throw Error("Automation journal closed");let r=!1;try{this.database.exec("BEGIN IMMEDIATE"),r=!0;let n=e();return this.database.exec("COMMIT"),n}catch(n){if(r)try{this.database.exec("ROLLBACK")}catch{}if(Date.now()>=t||!/SQLITE_BUSY|database is locked/.test(String(n)))throw n;await new Promise(i=>setTimeout(i,10))}}}};zxn=6e4,Xxn=48*1024*1024,HQe=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;ownedView;constructor(e){if(this.endpoint=Yxn(e.baseUrl),this.token=Kxn(e.token),this.timeoutMs=DSt(e.timeoutMs??zxn,1e3,3e5,"timeoutMs"),this.maxResponseBytes=DSt(e.maxResponseBytes??Xxn,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=e.fetch??globalThis.fetch,e.ownedView&&(!/^[a-f0-9]{64}$/.test(e.ownedView.ownerId)||!e.ownedView.sessionId?.trim()))throw new ve("AUTOMATION_REQUEST_INVALID","Owned Browser frame binding is invalid.");if(this.ownedView=e.ownedView?Object.freeze({...e.ownedView}):void 0,typeof this.fetchImpl!="function")throw new ve("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}async preflight(e,t){let r=await this.request("preflight","POST",e,t);if(this.ownedView&&e.operation==="browser.screenshot"){let n=e.declaredTarget?.tabId;if(!n||r.observedTarget.tabId!==n||e.identity.sessionId!==this.ownedView.sessionId)throw new ve("AUTOMATION_IDENTITY_MISMATCH","Owned capture requires the exact host session and tab.");let i=await this.request(`target?tabId=${encodeURIComponent(n)}`,"GET",void 0,t);if(i.tabId!==n||!Number.isSafeInteger(i.documentEpoch)||i.documentEpoch<0)throw new ve("AUTOMATION_TARGET_CHANGED","Owned capture target metadata changed.");return{...r,adapterState:{...r.adapterState,ownedViewDocumentEpoch:i.documentEpoch}}}return r}async execute(e,t,r,n){if(this.ownedView&&e.operation==="browser.screenshot"){let i=e.declaredTarget?.tabId,o=t.adapterState?.ownedViewDocumentEpoch;if(!i||t.observedTarget.tabId!==i||e.identity.sessionId!==this.ownedView.sessionId||!Number.isSafeInteger(o))throw new ve("AUTOMATION_IDENTITY_MISMATCH","Owned frame does not bind this request.");let s=new Date().toISOString(),a=await this.request("view-frame","POST",{version:1,...this.ownedView,tabId:i,documentEpoch:o,request:e,preflight:t,grant:r},n);if(a.version!==1||a.ownerId!==this.ownedView.ownerId||a.sessionId!==this.ownedView.sessionId||a.tabId!==i||a.documentEpoch!==o||a.mediaType!=="image/png"||!Number.isFinite(Date.parse(a.capturedAt))||Date.parse(a.capturedAt)<Date.parse(s)||a.origin!==new URL(t.observedTarget.url??t.observedTarget.origin??"").origin||typeof a.base64!="string"||a.base64.length>5592408||!/^[A-Za-z0-9+/]+={0,2}$/.test(a.base64)||a.base64.length%4!==0)throw new ve("AUTOMATION_RESPONSE_INVALID","Owned Browser returned a changed or oversized frame.");n.throwIfAborted(),w0(e);let l=Buffer.from(a.base64,"base64");if(l.length<24||l.length>4*1024*1024||l.subarray(0,8).toString("hex")!=="89504e470d0a1a0a"||l.readUInt32BE(16)<1||l.readUInt32BE(20)<1||l.readUInt32BE(16)*l.readUInt32BE(20)>2073600)throw new ve("AUTOMATION_RESPONSE_INVALID","Owned Browser returned invalid bounded PNG bytes.");return{operationId:e.operationId,status:"ok",startedAt:s,completedAt:a.capturedAt,observedTarget:t.observedTarget,evidence:[{evidenceId:`${e.operationId}.after`,phase:"after",kind:"screenshot",title:"Owned Browser frame",mediaType:"image/png",content:{type:"base64",base64:a.base64},sensitivity:"restricted"}]}}return this.request("execute","POST",{request:e,preflight:t,grant:r},n)}async stop(e,t){await this.request("stop","POST",{operationId:e,reason:t.slice(0,512)})}async request(e,t,r,n){let i=new AbortController,o=qQe(n,i),s=setTimeout(()=>i.abort(new Error("automation transport timeout")),this.timeoutMs);try{if(i.signal.aborted)throw new Error("Automation was cancelled before dispatch");let a=new URL(e,this.endpoint),l=this.fetchImpl(a,{method:t,redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.token}`,accept:"application/json",...t==="POST"?{"content-type":"application/json"}:{}},...t==="POST"?{body:JSON.stringify(r??{})}:{},signal:i.signal});l.then(u=>{i.signal.aborted&&u.body?.cancel().catch(()=>{})},()=>{});let c=await L2(l,i.signal),d=await L2(VQe(c,this.maxResponseBytes,i.signal),i.signal);if(!c.ok){let u=Zxn(d);throw new ve("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${e}: ${u.message}`,{status:c.status,route:e,adapterCode:u.code})}if(!mNe(d)||d.ok!==!0||!("result"in d))throw new ve("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${e} envelope`);return d.result}catch(a){if(a instanceof ve)throw a;let l=n?.aborted;throw new ve(l?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",l?"Automation transport was stopped":`XENO Browser ${e} transport failed`,{route:e},{cause:a})}finally{clearTimeout(s),o()}}};WQe=class{endpoint;options;constructor(e){let t;try{t=new URL(e.baseUrl)}catch{throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Use origin is invalid.")}let r=["localhost","127.0.0.1","[::1]"].includes(t.hostname);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&r&&!e.authorize))throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Use requires HTTPS; bootstrap HTTP is loopback-only.");if(e.token!==void 0==(e.authorize!==void 0)||e.authorize!==void 0&&typeof e.authorize!="function"||e.token!==void 0&&(!r||!LSt(e.token)))throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Use requires exactly one canonical authorizer or loopback bootstrap token.");for(let[n,i,o,s]of[["timeoutMs",e.timeoutMs??6e4,1e3,3e5],["maxResponseBytes",e.maxResponseBytes??48*1024*1024,1024,128*1024*1024]])if(!Number.isSafeInteger(i)||i<o||i>s)throw new ve("AUTOMATION_TRANSPORT_ERROR",`Invalid XENO Use ${n}.`);this.endpoint=new URL("/v1/use/automation/",t),this.options=Object.freeze({...e,authorize:e.authorize?.bind(void 0),fetch:e.fetch??globalThis.fetch})}async manifest(){let e=await this.request("manifest","GET");if($y(e),e.adapterId!=="xeno-use"||e.operations.some(t=>!t.startsWith("computer.")))throw new ve("AUTOMATION_OPERATION_UNSUPPORTED","XENO Use returned a different owning adapter contract.");return e}preflight(e,t){return this.request("preflight","POST",e,t)}execute(e,t,r,n){return this.request("execute","POST",{request:e,preflight:t,grant:r},n)}async assertCurrent(e){if((await this.request("current","POST",{request:e})).current!==!0)throw new ve("AUTOMATION_IDENTITY_MISMATCH","XENO Use operation authority is no longer current.")}async stop(e,t){if((await this.request("stop","POST",{operationId:e,reason:t.slice(0,512)})).stopped!==!0)throw new ve("AUTOMATION_TRANSPORT_ERROR","XENO Use did not confirm operation stop.")}async request(e,t,r,n){let i=new AbortController,o=qQe(n,i),s=setTimeout(()=>i.abort(),this.options.timeoutMs??6e4);try{i.signal.throwIfAborted();let a=new URL(e,this.endpoint),l=new Headers({accept:"application/json"});if(t==="POST"&&l.set("content-type","application/json"),this.options.authorize){let p;try{p=await L2(this.options.authorize(t,a.href),i.signal)}catch{throw new ve("AUTOMATION_TRANSPORT_ERROR","Canonical XENO Use authorization is unavailable.")}let f=p?.headers&&new Headers(p.headers).get("dpop");if(p?.tokenType!=="DPoP"||!LSt(p.token)||!f||/\s/.test(f))throw new ve("AUTOMATION_TRANSPORT_ERROR","Canonical XENO Use DPoP authorization is unavailable.");l.set("authorization",`DPoP ${p.token}`),l.set("dpop",f)}else l.set("authorization",`Bearer ${this.options.token}`);i.signal.throwIfAborted();let c=this.options.fetch(a,{method:t,headers:l,redirect:"error",credentials:"omit",cache:"no-store",signal:i.signal,...t==="POST"?{body:JSON.stringify(r??{})}:{}});c.then(p=>{i.signal.aborted&&p.body?.cancel().catch(()=>{})},()=>{});let d=await L2(c,i.signal),u=await L2(VQe(d,this.options.maxResponseBytes??48*1024*1024,i.signal),i.signal);if(!d.ok)throw new ve("AUTOMATION_TRANSPORT_ERROR",`XENO Use rejected ${e}.`,{status:d.status,route:e});if(!u||typeof u!="object"||!("ok"in u)||u.ok!==!0||!("result"in u))throw new ve("AUTOMATION_RESPONSE_INVALID","XENO Use returned an invalid automation envelope.");return u.result}catch(a){throw n?.aborted?new ve("AUTOMATION_CANCELLED","XENO Use transport was stopped."):a instanceof ve?a:new ve("AUTOMATION_TRANSPORT_ERROR",`XENO Use ${e} transport failed.`)}finally{clearTimeout(s),o()}}};SV();JQe=class{ports;declaration;now;ttl;maxPreflights;maxExecutions;prepared=new Map;executions=new Map;pendingPreflights=0;resultBytes=0;disposed=!1;constructor(e){$y(e.manifest),e.manifest.operations.some(t=>!t.startsWith("browser."))&&ph("Browser owner cannot advertise computer operations"),this.declaration=xm(e.manifest),this.ports=Object.freeze({...e.ports}),this.now=e.now??Date.now,this.ttl=PBe(e.preflightTtlMs,15e3,1,3e4),this.maxPreflights=PBe(e.maximumPreflights,256,1,1e3),this.maxExecutions=PBe(e.maximumExecutions,256,1,1e3)}manifest(){return structuredClone(this.declaration)}async assertCurrent(e){await this.current(xm(e),new AbortController().signal)}async preflight(e,t){let r=xm(e);await this.current(r,t);for(let[n,i]of this.prepared)i.expires<=this.now()&&this.prepared.delete(n);this.prepared.size+this.pendingPreflights>=this.maxPreflights&&Ore("Preflight capacity reached"),this.pendingPreflights++;try{let n=xm(await this.ports.resolveTarget(r,t));this.checkBinding(r,n),await this.ports.assertTargetUnchanged(n,t);let i=await this.capture(r,n,t,"before");await this.current(r,t),await this.ports.assertTargetUnchanged(n,t);let o=this.now(),s=xm({token:tCn(32).toString("base64url"),preparedAt:new Date(o).toISOString(),expiresAt:new Date(o+this.ttl).toISOString(),observedTarget:n.target,evidence:i,adapterState:{ownerId:n.ownerId,documentEpoch:n.documentEpoch}});return this.prepared.set(s.token,{requestHash:Wg(r),preflight:s,binding:n,expires:o+this.ttl}),structuredClone(s)}finally{this.pendingPreflights--}}async execute(e,t,r,n){let i=xm(e),o=xm(t),s=xm(r);await this.current(i,n);let a=Wg(i),l=Wg(s),c=this.executions.get(i.operationId);if(c){(c.requestHash!==a||c.grantHash!==l||Wg(c.prepared.preflight)!==Wg(o))&&Ore("Operation ID reused with different request, grant or preflight"),await this.authorize(i,c.prepared,s,n);let h=await c.promise;return await this.authorize(i,c.prepared,s,n),structuredClone(h)}let d=this.prepared.get(o.token);if(!d||d.expires<=this.now()||d.requestHash!==a||Wg(d.preflight)!==Wg(o))throw new ve("AUTOMATION_PREFLIGHT_INVALID","Preflight is missing, expired or changed");(this.executions.size>=this.maxExecutions||this.resultBytes>=16*1024*1024)&&Ore("Execution ledger capacity reached; session cannot accept new work"),[...this.executions.values()].some(h=>h.active&&h.prepared.binding.target.tabId===d.binding.target.tabId)&&Ore("An operation already owns this tab"),this.prepared.delete(o.token);let u=new AbortController,p=()=>{this.stop(i.operationId,"caller-abort").catch(()=>{})},f={requestHash:a,grantHash:l,prepared:d,controller:u,active:!0,promise:Promise.resolve(void 0)};return this.executions.set(i.operationId,f),n.addEventListener("abort",p,{once:!0}),f.promise=this.run(i,d,s,u.signal).finally(()=>{f.active=!1,n.removeEventListener("abort",p)}),n.aborted&&p(),structuredClone(await f.promise)}async stop(e,t="human-stop"){let r=this.executions.get(e);if(r?.active){r.controller.abort(new ve("AUTOMATION_CANCELLED",t.slice(0,256))),r.nativeStop??=Promise.resolve().then(()=>this.ports.stop(e,t));try{await r.nativeStop}finally{await r.promise.catch(()=>{})}}}async dispose(){this.disposed=!0,this.prepared.clear(),await Promise.all([...this.executions.keys()].map(e=>this.stop(e,"owner-shutdown")))}async run(e,t,r,n){let i=new Date(this.now()).toISOString();try{if(await this.authorize(e,t,r,n),t.expires<=this.now())throw new ve("AUTOMATION_PREFLIGHT_INVALID","Preflight expired during authorization");let o=this.context(e,t.binding,n,()=>this.authorize(e,t,r,n)),s=xm(await this.ports.dispatch(o));await this.current(e,n),this.checkGrant(e,t.binding.target,r),await this.ports.authorizeGrant(e,t.preflight,r,n);let a=s.observedTarget??t.binding.target;D2(e,this.declaration,a);let l=e.operation==="browser.tabs.close",c=l?t.binding:xm(await this.ports.resolveTarget(e,n,a));if(c.profile!==t.binding.profile||Wg(c.target)!==Wg(a)||e.operation!=="browser.tabs.open"&&(c.ownerId!==t.binding.ownerId||c.target.tabId!==t.binding.target.tabId))throw new ve("AUTOMATION_TARGET_CHANGED","Result target was closed, replaced or changed");if(!["browser.navigate","browser.back","browser.forward","browser.reload","browser.click","browser.type","browser.key","browser.tabs.open"].includes(e.operation)&&c.documentEpoch!==t.binding.documentEpoch)throw new ve("AUTOMATION_TARGET_CHANGED","Result document changed unexpectedly");a.url&&this.destination(e,t.binding,a.url,["browser.navigate","browser.tabs.open"].includes(e.operation)&&a.url===e.parameters.url);let d=[...s.evidence??[],...l?[]:await this.capture(e,c,n,"after")];if(zH(e).after==="required"&&!d.some(f=>f.phase==="after"))throw new ve("AUTOMATION_EVIDENCE_REQUIRED","Owner requires after evidence");await this.current(e,n),this.checkGrant(e,t.binding.target,r),await this.ports.authorizeGrant(e,t.preflight,r,n),await this.ports.finish?.(e.operationId),await this.current(e,n),this.checkGrant(e,t.binding.target,r),await this.ports.authorizeGrant(e,t.preflight,r,n);let u=xm({...s,operationId:e.operationId,status:"ok",observedTarget:a,evidence:d,startedAt:i,completedAt:new Date(this.now()).toISOString()}),p=Buffer.byteLength(JSON.stringify(u));if(p>1048576||this.resultBytes+p>16*1024*1024)throw new ve("AUTOMATION_EVIDENCE_INVALID","Result exceeds session evidence bounds");return this.resultBytes+=p,u}catch(o){let s=o;n.aborted&&await this.executions.get(e.operationId)?.nativeStop;try{await this.ports.finish?.(e.operationId)}catch(l){s=l}let a=n.aborted?"AUTOMATION_CANCELLED":s instanceof ve?s.code:"AUTOMATION_POLICY_DENIED";return{operationId:e.operationId,status:n.aborted?"cancelled":"error",startedAt:i,completedAt:new Date(this.now()).toISOString(),observedTarget:structuredClone(t.binding.target),error:{code:a,message:s instanceof Error?s.message.slice(0,512):"Browser owner refused operation"}}}}async current(e,t){if(this.disposed||t.aborted)throw new ve("AUTOMATION_CANCELLED","Browser owner operation stopped");if(w0(e),e.operation.startsWith("browser.")||ph("Browser owner requires a browser operation"),this.ports.authorizeGrant||ph("Trusted grant issuer authorization is not installed"),await this.ports.assertCurrent(e,t),this.disposed||t.aborted)throw new ve("AUTOMATION_CANCELLED","Browser owner operation stopped")}checkBinding(e,t){(!t.ownerId||!t.target.tabId||!t.target.url||!(typeof t.documentEpoch=="number"&&Number.isSafeInteger(t.documentEpoch)&&t.documentEpoch>=0||typeof t.documentEpoch=="string"&&t.documentEpoch.length>0))&&ph("Owner did not bind an exact tab and document"),(t.profile!==e.executionContract.browser.profile||this.declaration.profileIsolation!==t.profile&&!(this.declaration.profileIsolation==="both"&&t.profile!=="shared-user"))&&ph("Browser security profile does not match owner isolation");let r=new URL(t.target.url);(t.target.origin!==void 0&&t.target.origin!==r.origin||t.target.domain!==void 0&&t.target.domain!==r.hostname||t.target.port!==void 0&&t.target.port!==Number(r.port||(r.protocol==="https:"?443:80)))&&ph("Owner target metadata does not match its exact URL");for(let n of["tabId","pageId","resource","url","origin"]){let i=e.operation==="browser.navigate"||e.operation==="browser.tabs.open";if(!(n==="resource"&&e.declaredTarget?.resource==="browser-tabs"&&(i||e.operation==="browser.tabs.list"))){if(n==="url"&&i){e.declaredTarget?.url!==void 0&&e.declaredTarget.url!==e.parameters.url&&ph("Declared navigation URL does not match destination");continue}if(e.declaredTarget?.[n]!==void 0&&e.declaredTarget[n]!==t.target[n])throw new ve("AUTOMATION_TARGET_CHANGED",`Exact declared ${n} changed`)}}D2(e,this.declaration,t.target),(e.operation==="browser.navigate"||e.operation==="browser.tabs.open")&&(typeof e.parameters.url!="string"&&ph("Navigation requires an explicit URL"),this.destination(e,t,e.parameters.url,!0))}checkGrant(e,t,r){pA(r.lease);let n=r.lease,i=kde(e,t);(r.contractFingerprint!==e.executionContract.fingerprint||Wg(r.capabilityUse)!==Wg(i)||n.leaseId!==e.capabilityLeaseId||n.version!==e.expectedLeaseVersion+1||n.useCount<1||!["active","exhausted"].includes(n.state)||!n.expiresAt||Date.parse(n.expiresAt)<=this.now()||n.profileFingerprint!==e.executionContract.profile.fingerprint||n.subject.runId!==e.identity.runId||n.subject.agentId!==e.identity.agentId||n.subject.turnId!==e.identity.turnId||n.subject.toolName!==e.governingToolName||n.subject.operationId!==void 0&&n.subject.operationId!==e.operationId||n.scope.kind!==i.kind||n.scope.governingToolName!==e.governingToolName||!n.scope.operations.includes(e.operation)||n.scope.resources!==void 0&&(!i.resource||!n.scope.resources.includes(i.resource))||n.scope.destinations!==void 0&&(!i.destination||!n.scope.destinations.includes(i.destination)))&&ph("Consumed grant does not match exact request and lease")}async authorize(e,t,r,n){await this.current(e,n),this.checkBinding(e,t.binding),this.checkGrant(e,t.binding.target,r),await this.ports.authorizeGrant(e,t.preflight,r,n),await this.ports.assertTargetUnchanged(t.binding,n),await this.current(e,n)}destination(e,t,r,n=!1){if(D2(e,this.declaration,{tabId:t.target.tabId,url:r}),!n&&r!==t.target.url){let i=e.executionContract.browser.redirectPolicy;(i==="deny"||i==="same-origin"&&new URL(r).origin!==new URL(t.target.url).origin)&&ph("Browser redirect policy refused destination")}}context(e,t,r,n){return{request:e,binding:t,signal:r,assertDispatchAllowed:async i=>{n?await n():(await this.current(e,r),await this.ports.assertTargetUnchanged(t,r)),i&&this.destination(e,t,i,["browser.navigate","browser.tabs.open"].includes(e.operation)&&i===e.parameters.url)}}}async capture(e,t,r,n){let i=zH(e)[n];if(i==="disabled")return[];await this.current(e,r),await this.ports.assertTargetUnchanged(t,r);let o=xm(await this.ports.captureEvidence(this.context(e,t,r),n));if(await this.ports.assertTargetUnchanged(t,r),await this.current(e,r),i==="required"&&!o.some(s=>s.phase===n))throw new ve("AUTOMATION_EVIDENCE_REQUIRED",`Owner requires ${n} evidence`);return o}};Doe=4*1024*1024,iCn=64,oCn=64,FSt=8192,_Be=/^[a-f0-9]{64}$/,zLt=class{channelEpoch;stream;timeoutMs;decisions=new Map;pending=new Map;nonces=new Set;retiredIds=new Set;frame=Buffer.alloc(0);writeTail=Promise.resolve();queuedWrites=0;dead=!1;constructor(e){if(this.stream=e.stream,this.channelEpoch=e.channelEpoch??BBe(),!_Be.test(this.channelEpoch)||(this.timeoutMs=e.timeoutMs??1e4,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>6e4))throw tn();this.stream.on("data",this.onData),this.stream.on("error",this.onDeath),this.stream.on("end",this.onDeath),this.stream.on("close",this.onDeath),(this.stream.destroyed||!this.stream.readable||!this.stream.writable)&&this.kill()}async begin(e,t,r){this.live();let n=Loe(e);if(this.decisions.has(e.operationId)||this.decisions.size>=oCn||r.aborted||t.profileFingerprint!==e.executionContract.profile.fingerprint)throw tn();try{if(t.assertCurrent()!==void 0)throw tn()}catch{throw tn()}let i={decisionId:BBe(),operationId:e.operationId,requestHash:n,decision:Object.freeze({...t,assertCurrent:t.assertCurrent}),signal:r,denied:!1,abort:()=>{this.cancel(i)}};this.decisions.set(e.operationId,i),r.addEventListener("abort",i.abort,{once:!0}),r.aborted&&i.abort();try{await this.rpc("begin",i,{request:e,decision:{authorization:t.authorization,profileFingerprint:t.profileFingerprint}}),this.check(i)}catch{throw this.cancel(i),tn()}}async recordPreflight(e,t,r){let n=this.row(e),i=ANe(t);if(n.preflightHash&&n.preflightHash!==i)throw tn();n.preflightHash=i,await this.record("recordPreflight",e,{preflight:t},r),this.check(n)}async recordGrant(e,t,r,n){await this.record("recordGrant",e,{preflight:t,grant:r},n)}async assertCurrent(e){let t=this.row(e);this.check(t);try{await this.rpc("assertCurrent",t),this.check(t)}catch{throw this.cancel(t),tn()}}async finish(e){this.live();let t=this.row(e,!0);t.denied=!0;let r=await this.rpc("finish",t);if(r.result?.withdrawn!==!0||r.result.decisionId!==t.decisionId)throw tn();t.signal.removeEventListener("abort",t.abort),this.decisions.delete(t.operationId)}async close(){if(this.stream.destroyed&&this.kill(),!this.dead&&this.decisions.size>0)throw tn();this.kill(),this.stream.destroy()}async record(e,t,r,n){let i=this.row(t);if(n.aborted)throw this.cancel(i),tn();this.check(i);let o=()=>this.cancel(i);n.addEventListener("abort",o,{once:!0});try{if(await this.rpc(e,i,r),this.check(i),n.aborted)throw tn()}catch{throw this.cancel(i),tn()}finally{n.removeEventListener("abort",o)}}row(e,t=!1){this.live();let r=this.decisions.get(e.operationId);if(!r||r.requestHash!==Loe(e)||!t&&r.denied)throw tn();return r}check(e){if(this.live(),e.denied||e.signal.aborted)throw tn();try{if(e.decision.assertCurrent()!==void 0)throw tn()}catch{throw e.denied=!0,tn()}if(e.signal.aborted||e.denied||this.dead)throw tn()}cancel(e){if(e.denied=!0,!this.dead)try{this.rpc("cancel",e).catch(()=>{})}catch{this.kill()}}rpc(e,t,r={}){if(this.live(),this.pending.size>=iCn||this.retiredIds.size>=FSt)throw tn();let n=BBe(),i={version:1,kind:"request",id:n,channelEpoch:this.channelEpoch,method:e,payload:{...r,decisionId:t.decisionId,operationId:t.operationId,requestHash:t.requestHash}},o=USt(i);return new Promise((s,a)=>{let l=setTimeout(()=>{this.pending.delete(n),this.retiredIds.add(n),a(tn())},this.timeoutMs);this.pending.set(n,{resolve:s,reject:a,timer:l}),this.write(o).catch(()=>{this.kill()})})}write(e){if(this.live(),this.queuedWrites>=128)return this.kill(),Promise.reject(tn());this.queuedWrites++;let t=this.writeTail.then(()=>new Promise((r,n)=>{if(this.dead){n(tn());return}this.stream.write(e,i=>i?n(tn()):r())}));return this.writeTail=t.catch(()=>{}).finally(()=>{this.queuedWrites--}),t}onData=e=>{if(this.dead)return;if(!Buffer.isBuffer(e)&&typeof e!="string"){this.kill();return}let t=Buffer.isBuffer(e)?e:Buffer.from(e),r=0;for(let n=0;n<t.length;n++){if(t[n]!==10)continue;if(this.frame.length+n-r>Doe){this.kill();return}let i=Buffer.concat([this.frame,t.subarray(r,n)]);this.frame=Buffer.alloc(0),r=n+1;try{this.receive(JSON.parse(i.toString("utf8")))}catch{this.kill();return}if(this.dead)return}if(this.frame.length+t.length-r>Doe){this.kill();return}this.frame=Buffer.concat([this.frame,t.subarray(r)])};receive(e){if(!lie(e)||e.version!==1||typeof e.id!="string"||!_Be.test(e.id))throw tn();if(e.kind==="decision.check"||e.kind==="decision.grant.check"){this.challenge(e);return}if(e.kind!=="response"||e.channelEpoch!==this.channelEpoch||typeof e.ok!="boolean")throw tn();let t=this.pending.get(e.id);if(!t){if(this.retiredIds.has(e.id))return;throw tn()}this.pending.delete(e.id),clearTimeout(t.timer),e.ok?t.resolve(e):t.reject(tn())}challenge(e){for(let s of["channelEpoch","decisionId","requestHash","nonce"])if(typeof e[s]!="string"||!_Be.test(e[s]))throw tn();if(typeof e.operationId!="string"||e.operationId.length<1||e.operationId.length>256)throw tn();let t=e,r=this.decisions.get(t.operationId),n=!this.nonces.has(t.nonce);if(this.nonces.size>=FSt)throw tn();this.nonces.add(t.nonce);let i=!1;if(n&&t.channelEpoch===this.channelEpoch&&r&&t.decisionId===r.decisionId&&t.requestHash===r.requestHash)try{if(this.check(r),e.kind==="decision.grant.check"){let s=e;if(!lie(s.preflight)||!lie(s.grant)||!r.decision.assertGrantCurrent||r.preflightHash!==ANe(s.preflight)||r.decision.assertGrantCurrent(s.preflight,s.grant)!==void 0)throw tn();this.check(r)}i=!0}catch{i=!1}let o={version:1,kind:e.kind==="decision.grant.check"?"decision.grant.result":"decision.result",id:t.id,channelEpoch:t.channelEpoch,decisionId:t.decisionId,operationId:t.operationId,requestHash:t.requestHash,nonce:t.nonce,current:i};this.write(USt(o)).catch(()=>{this.kill()})}live(){if(this.stream.destroyed&&this.kill(),this.dead)throw tn()}onDeath=()=>{this.kill()};kill(){if(!this.dead){this.dead=!0,this.frame=Buffer.alloc(0);for(let e of this.pending.values())clearTimeout(e.timer),e.reject(tn());this.pending.clear();for(let e of this.decisions.values())e.denied=!0,e.signal.removeEventListener("abort",e.abort);this.stream.off("data",this.onData),this.stream.destroy()}}};$Be={"browser.navigate":"navigate","browser.back":"back","browser.forward":"forward","browser.reload":"reload","browser.snapshot":"observe","browser.screenshot":"screenshot","browser.locate":"find","browser.click":"click","browser.type":"type","browser.key":"key","browser.select":"select","browser.scroll":"scroll","browser.wait":"wait","browser.tabs.list":"tabs_list","browser.console.read":"console_log","browser.network.read":"network_log"};XLt=["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"],_de=class extends HQe{driver;constructor(e){super(e),this.driver=e.driver}async manifest(){let e=await super.manifest();if($y(e),!(this.driver==="browser"?["xeno-browser","xeno-browser-native"]:["xeno-extension-native","xeno-extension"]).includes(e.adapterId)||e.operations.some(t=>!t.startsWith("browser.")))throw new ve("AUTOMATION_OPERATION_UNSUPPORTED","Configured Browser driver returned a different owning adapter contract.");return e}};gn();aR();Bde=1,uCn="repository.v1.json",pCn=5e3,fCn=20,hCn=64*1024*1024,$de=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let t=e.snapshotFileName??uCn;if(jSt(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=dCn(e.directory),this.snapshotPath=cCn(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=MBe(e.lockTimeoutMs,pCn,100,6e4,"lockTimeoutMs"),this.lockRetryMs=MBe(e.lockRetryMs,fCn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=MBe(e.maxSnapshotBytes,hCn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(t=>t.create(e))}async createRevision(e,t){return this.mutate(r=>r.createRevision(e,t))}async get(e,t){return(await this.load()).repository.get(e,t)}async require(e,t){return(await this.load()).repository.require(e,t)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(t=>t.transition(e))}async appendReviewEvent(e){return this.mutate(t=>t.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let t=await this.acquireLock();try{let r=await this.load(),n=await e(r.repository);return await this.persist(r),n}finally{t.release()}})}async enqueueMutation(e){let t=this.mutationTail.then(e,e);return this.mutationTail=t.then(()=>{},()=>{}),t}async acquireLock(){let e=Date.now(),t;for(;Date.now()-e<=this.lockTimeoutMs;)try{return nS(this.lockPath,`artifact-repository:${jSt(this.snapshotPath)}`,J0)}catch(r){if(!(r instanceof Error)||!/already locked by PID/.test(r.message))throw r;t=r,await yCn(this.lockRetryMs)}throw new er("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,r=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=Foe(i)}if(!t&&(e||await wCn(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),t=i,r=!0)}catch(i){throw e?new er("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,Foe(i)])}):i}if(!t&&e)throw e;let n=t?.state??{schemaVersion:1,records:[]};return{repository:new Rde({now:this.now,idFactory:i=>`${i}_${ZLt()}`,initialState:n}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:r,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),r={schemaVersion:Bde,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},n=gCn(r),i=`${JSON.stringify(n,null,2)}
|
|
2790
2790
|
`;if(Buffer.byteLength(i,"utf8")>this.maxSnapshotBytes)throw new er("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await eFt(this.directory,{recursive:!0,mode:448}),e.hasSnapshot&&!e.recoveredFromBackup&&e.sourceSnapshot&&await VSt(this.backupPath,`${JSON.stringify(e.sourceSnapshot,null,2)}
|
|
2791
2791
|
`),await VSt(this.snapshotPath,i)}async readSnapshot(e,t){let r;try{r=await tFt(e)}catch(n){if(!t&&bNe(n,"ENOENT")||t&&bNe(n,"ENOENT"))return;throw vNe("Unable to inspect artifact repository snapshot",e,n)}if(!r.isFile()||r.size>this.maxSnapshotBytes)throw new er("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:e,sizeBytes:r.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let n=await aCn(e);if(n.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return mCn(JSON.parse(n.toString("utf8")),e)}catch(n){throw n instanceof er?n:vNe("Unable to parse artifact repository snapshot",e,n,!0)}}};SV();eDe();ICn=8*1024*1024,ECn=4;iDe();UCn=CR.filter(e=>e.startsWith("browser.")),QCn=CR.filter(e=>e.startsWith("computer.")),NBe=6e4,Mde=class{constructor(e){this.options=e,this.environment=e.environment??nI()}options;leases=new N1({maximumDurationMs:NBe,maximumUses:1});activeExecutors=new Map;environment;browserAdapter;browserDecisions=new Map;computerAdapter;verifiedOperations=[];registered=new Map;register(e){if(this.options.safeMode)return 0;let t=this.verifiedOperations;if(t.length===0)return 0;let r=XQe({runtime:this,operations:t});for(let n of r)if(e.has(n.definition.name)&&!this.registered.get(e)?.some(i=>i.definition.name===n.definition.name&&e.get(i.definition.name)===i))throw new Error("Automation capability registration conflicts with another tool owner.");return e.registerAll(r),this.registered.set(e,r),t.length}async registerVerified(e){for(let[r,n]of this.registered)for(let i of n)r.get(i.definition.name)===i&&r.unregister(i.definition.name);if(this.registered.clear(),this.verifiedOperations=[],this.options.safeMode)return 0;let t=[];for(let r of["browser","computer"])if(!(r==="computer"&&!this.options.computerHostAuthority)&&!(r==="browser"?!ENe(this.environment.browser):!Uoe(this.environment.computer,!!this.options.computerAdapter)))try{let n=await this.adapterFor(r),i=await n.manifest();if($y(i),r==="computer"&&cie("observe",this.environment).sensitiveRegionRedaction&&i.supports.sensitiveRegionRedaction!==!0)continue;let o=r==="browser"?UCn:QCn;t.push(...i.operations.filter(s=>o.includes(s)))}catch{}return this.verifiedOperations=[...new Set(t)],this.register(e)}async execute(e){if(this.options.safeMode)throw new Error("Governed automation is disabled in safe mode");if(R3(e),e.operation==="browser.screenshot"&&!e.declaredTarget?.tabId?.trim())throw new Error("Screen capture requires an explicit authorized tabId.");let t=kh(e.operation),r=t.surface==="computer"?this.options.computerHostAuthority:void 0;if(t.surface==="computer"&&!r)throw new Error("Computer automation requires independent host operation authority.");let n=await this.adapterFor(t.surface),i=await n.manifest();if($y(i),t.surface==="computer"&&cie(t.effect,this.environment).sensitiveRegionRedaction&&i.supports.sensitiveRegionRedaction!==!0)throw new Error("Owning computer adapter cannot satisfy this host's required sensitive-region redaction.");if(!i.operations.includes(e.operation))throw new Error("Owning adapter no longer supports this operation; refresh capability discovery.");let o=this.options.profile(),s={runId:this.options.runId,agentId:this.options.agentId??"agent-main",...this.options.sessionId?{sessionId:this.options.sessionId}:{},turnId:e.authorization.turnId,...this.options.workspaceId?{workspaceId:this.options.workspaceId}:{}},a=JCn(e.operation,e.declaredTarget,this.environment),l=t.surface==="browser"?t.effect==="act"?"browser-act":"browser-read":t.effect==="act"?"computer-act":"computer-observe",c=t.effect==="act"?"external":"read",d=`lease-${sCn()}`,u=(w,y,b)=>{if(e.signal?.throwIfAborted(),w!==d||y!==2||this.options.profile().fingerprint!==o.fingerprint)throw new Error("Automation lease authority changed during preflight; obtain fresh authorization.");let I=this.leases.request({leaseId:d,subject:{runId:s.runId,agentId:s.agentId,turnId:s.turnId,toolName:e.governingToolName,operationId:e.operationId},scope:{kind:l,effect:c,operations:[e.operation],...b.resource?{resources:[b.resource]}:{},...b.destination?{destinations:[b.destination]}:{},governingToolName:e.governingToolName},reason:`${e.operation} authorized by the CLI policy and permission layers`,requestedBy:{kind:"agent",id:s.agentId,profileFingerprint:o.fingerprint},durationMs:NBe,requestTtlMs:3e4,maxUses:1,childInheritance:"none",policyFingerprints:[o.fingerprint]},o),v=this.leases.approve({leaseId:I.leaseId,expectedVersion:I.version,approvedBy:{kind:"integration",id:`xeno-${this.options.surface}-permission-engine`,displayName:`XENO ${this.options.surface.toUpperCase()} permission engine`},approvalContext:{surface:this.options.surface,turnId:e.authorization.turnId,messageId:e.authorization.toolCallId}});return this.leases.consume(v.leaseId,v.version,b)},p=Y5e({contractId:`contract-${e.operationId}`,identity:s,policy:this.securityPolicy(),profile:o,...this.options.securityStatus?{adapterStatus:this.options.securityStatus}:{},filesystem:{readRoots:[T3(this.options.cwd())],writeRoots:[T3(this.options.cwd())],executeRoots:[T3(this.options.cwd())]},network:WCn(a,this.environment),browser:t.surface==="browser"?qCn(t.effect,a,this.environment,i.profileIsolation):{mode:"none"},computer:t.surface==="computer"?cie(t.effect,this.environment):{mode:"none"},capabilityLeaseIds:[d],expiresAt:new Date(Date.now()+NBe).toISOString()}),f={protocolVersion:1,operationId:e.operationId,idempotencyKey:e.idempotencyKey,requestedAt:new Date().toISOString(),identity:s,governingToolName:e.governingToolName,operation:e.operation,parameters:zCn(e.parameters),...a?{declaredTarget:a}:{},executionContract:p,capabilityLeaseId:d,expectedLeaseVersion:2},h=new AbortController,m=h.signal,g=()=>h.abort(e.signal?.reason);e.signal?.aborted?g():e.signal?.addEventListener("abort",g,{once:!0});let A=new QQe({adapter:n,assertCurrent:async w=>{if(m.throwIfAborted(),R3(e),this.options.profile().fingerprint!==o.fingerprint)throw new Error("Automation authority changed during execution; evidence release refused.");await r?.assertCurrent(structuredClone(w))},...r?{onPreflight:(w,y,b)=>r.recordPreflight(w,y,b),onGrant:(w,y,b,I)=>r.recordGrant(w,y,b,I)}:{},leaseAuthority:{consume:async(w,y,b)=>{let I=u(w,y,b);return await this.audit({eventType:"automation_lease_approved",traceId:e.authorization.turnId,operation:e.operation,operationId:e.operationId,leaseId:d,contractFingerprint:p.fingerprint,permissionReason:e.authorization.permission.reason}),I}},artifactRepository:new $de({directory:T3(this.options.cwd(),".xeno","artifacts")})});if(this.activeExecutors.has(e.operationId)||this.activeExecutors.size>=64)throw e.signal?.removeEventListener("abort",g),Object.assign(new Error("Host automation operation identity is already active or capacity is reached."),{code:"AUTOMATION_OPERATION_CONFLICT",retryable:!1});this.activeExecutors.set(e.operationId,{executor:A,controller:h}),t.surface==="browser"&&this.browserDecisions.set(e.operationId,{request:structuredClone(f),assertCurrent:()=>{if(m.throwIfAborted(),R3(e),this.options.profile().fingerprint!==o.fingerprint)throw new Error("Browser host profile authority changed.")}});try{e.reportProgress?.({activity:"state",message:`Executing governed ${e.operation}`}),await r?.begin(structuredClone(f),{authorization:e.authorization,profileFingerprint:o.fingerprint,assertCurrent:()=>{if(m.throwIfAborted(),R3(e),this.options.profile().fingerprint!==o.fingerprint)throw new Error("Computer host profile authority changed.")},assertGrantCurrent:(y,b)=>{m.throwIfAborted(),R3(e);let I=this.leases.get(f.capabilityLeaseId);if(this.options.profile().fingerprint!==o.fingerprint||!I||!Nre(I,b.lease))throw new Error("Computer consumed lease was not issued by this host.")}},m);let w=await A.execute(f,m);return await this.audit({eventType:w.status==="ok"?"automation_completed":"automation_failed",traceId:e.authorization.turnId,operation:e.operation,operationId:e.operationId,leaseId:d,contractFingerprint:p.fingerprint,status:w.status,artifactIds:w.artifacts.map(y=>y.artifactId)}),w}catch(w){throw await this.audit({eventType:"automation_failed",traceId:e.authorization.turnId,operation:e.operation,operationId:e.operationId,leaseId:d,contractFingerprint:p.fingerprint,status:w instanceof Error?w.name:"error"}),w}finally{e.signal?.removeEventListener("abort",g);try{await r?.finish(structuredClone(f))}finally{this.activeExecutors.delete(e.operationId),this.browserDecisions.delete(e.operationId)}}}async stop(e,t="human-stop"){let r=this.activeExecutors.get(e);return r?(r.controller.abort(new Error(t)),await r.executor.stop(e,t),!0):!1}securityPolicy(){let e=this.options.securityPolicy?.();if(e)return e;let t=T3(this.options.cwd());return{allowedDirectories:[t],workingDirectory:t,capabilities:{terminal:!0,fileRead:!0,fileWrite:!0,appLaunch:!0},executionLevel:"policy-only",trustMode:"trusted-workspace",allowNetwork:!1}}adapterFor(e){if(e==="browser"){let r=this.environment.browser;if(!ENe(r))throw new Error(oFt(r));return this.browserAdapter??=r.driver==="extension"?Pde({baseUrl:r.baseUrl,token:r.token,assertCurrent:async(n,i)=>{i.throwIfAborted();let o=this.browserDecisions.get(n.operationId);if(!o||!Nre(o.request,n))throw new Error("Independent browser operation authority is unavailable.");o.assertCurrent()},authorizeGrant:async(n,i,o,s)=>{s.throwIfAborted();let a=this.browserDecisions.get(n.operationId),l=this.leases.get(n.capabilityLeaseId);if(!a||!Nre(a.request,n)||!l||!Nre(l,o.lease))throw new Error("Browser consumed lease was not issued by this host.");a.assertCurrent()}}):Promise.resolve(new _de({baseUrl:r.baseUrl,token:r.token,driver:r.driver,...r.ownedView?{ownedView:r.ownedView}:{}})),this.browserAdapter}let t=this.environment.computer;if(!Uoe(t,!!this.options.computerAdapter))throw new Error(KQe(t,!!this.options.computerAdapter));return this.computerAdapter??=this.options.computerAdapter?Promise.resolve(this.options.computerAdapter):iFt(t),this.computerAdapter}async audit(e){try{await this.options.onAudit?.(e)}catch{}}};sae();ZQe=class extends Error{code="EVIDENCE_GRAPH_INVALID";issues;constructor(e){super("XENO evidence graph validation failed"),this.name="XenoEvidenceGraphValidationError",this.issues=e.map(t=>({...t}))}},KCn=new Set(["depends_on","decomposes","supersedes"]),ZCn=new Set(Sde),eTn=new Set(xde);pFt=class{now;graph;constructor(e){if("schemaVersion"in e)m2(e),this.now=()=>new Date().toISOString(),this.graph=Lre(e);else{this.now=e.now??(()=>new Date().toISOString());let t=this.now();this.graph={schemaVersion:1,graphId:e.graphId,version:1,createdAt:t,updatedAt:t,nodes:[],edges:[]},m2(this.graph)}}addNode(e){let t=Lre(this.graph);return t.nodes.push(fFt(e)),this.touch(t),m2(t),this.graph=t,this}addEdge(e){let t=Lre(this.graph);return t.edges.push(hFt(e)),this.touch(t),m2(t),this.graph=t,this}build(){return m2(this.graph),Lre(this.graph)}touch(e){e.version+=1,e.updatedAt=this.now()}};tTn=16*1024*1024,rTn=5e3,nTn=1e5,iTn=1e6,oTn=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,Ud=class extends Error{constructor(e,t){super(t===void 0?e:`${e} at diff line ${t}`),this.line=t,this.name="XenoDiffParseError"}line;code="XENO_DIFF_INVALID"};Goe=class{repository;actor;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");if(!e.actor?.kind||!e.actor.id?.trim())throw new TypeError("Review actor is required");this.repository=e.repository,this.actor=structuredClone(e.actor),this.idFactory=e.idFactory??(()=>`comment_${uTn()}`)}async addComment(e){let t=Dde(e.body,"Review comment body",65536),r=await this.repository.require(e.artifactId,e.revision),n=joe(r,e),i=Hoe(this.idFactory(),"Comment ID"),o=pTn(e.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:r.recordVersion,event:{type:"comment-added",artifactId:r.artifact.artifactId,artifactRevision:r.artifact.revision,artifactHash:r.artifact.content.hash,actor:this.actor,commentId:i,body:t,...n?{anchor:n}:{},...o?{parentCommentId:o}:{}}})}async setCommentResolution(e){let t=Hoe(e.commentId,"Review comment ID"),r=ZSt(e.reason,"Resolution reason",16*1024),n=await this.repository.require(e.artifactId,e.revision);return this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:e.resolved?"comment-resolved":"comment-reopened",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,commentId:t,...r?{reason:r}:{}}})}async decide(e){let t=await this.repository.require(e.artifactId,e.revision);if(t.artifact.state!=="pending_review")throw new er("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${t.artifact.state}`);let r=joe(t,e),n=ZSt(e.rationale,"Decision rationale",64*1024),i=await this.repository.appendReviewEvent({expectedRecordVersion:t.recordVersion,event:{type:"decision-recorded",artifactId:t.artifact.artifactId,artifactRevision:t.artifact.revision,artifactHash:t.artifact.content.hash,actor:this.actor,decision:e.decision,...n?{rationale:n}:{},...r?{scope:r}:{}}});if(r||e.decision==="changes_requested")return i;let o=i.reviewEvents.at(-1);if(!o||o.type!=="decision-recorded")throw new er("ARTIFACT_REVIEW_INVALID","Artifact decision event was not recorded");return this.repository.transition({artifactId:i.artifact.artifactId,revision:i.artifact.revision,expectedRecordVersion:i.recordVersion,toState:e.decision,actor:this.actor,reviewEventId:o.eventId,...n?{reason:n}:{}})}};F2="xeno.spec.v1",$N="xeno.spec-execution.v1",nd=class extends Error{constructor(e){super(`XENO spec is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},AFt=class{repository;now;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");this.repository=e.repository,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(()=>fTn())}async create(e,t){if(e.revision!==1||e.predecessorRevision!==void 0)throw new nd(["A new spec must begin at revision 1 without a predecessor"]);let r=Voe(e,t);return await this.repository.create(r.requirements),await this.repository.create(r.design),await this.repository.create(r.taskGraph),await this.repository.create(r.plan),r}async revise(e,t){let r=k2(e.specId),n=await this.repository.require(r.plan);if(e.revision!==n.artifact.revision+1||e.predecessorRevision!==n.artifact.revision)throw new nd([`Revision ${e.revision} must follow approved or reviewed revision ${n.artifact.revision}`]);let i=Voe(e,t);return await this.repository.createRevision(i.requirements,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.design,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.taskGraph,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.plan,{actor:t.producer,reason:"spec-revised"}),i}async approve(e,t,r){return new Goe({repository:this.repository,actor:t}).decide({artifactId:k2(e).plan,decision:"approved",...r?{rationale:r}:{}})}async reject(e,t,r){return new Goe({repository:this.repository,actor:t}).decide({artifactId:k2(e).plan,decision:"rejected",rationale:r})}async startExecution(e,t){let r=await this.repository.require(k2(e).plan);if(r.artifact.state!=="approved")throw new nd([`Spec ${e} must be approved before execution`]);let n=qoe(r.artifact),i=this.now(),o={schemaVersion:$N,executionId:`spec_execution_${this.idFactory()}`,specId:n.specId,specRevision:n.revision,planArtifactId:r.artifact.artifactId,planHash:{...r.artifact.content.hash},state:"ready",createdAt:i,updatedAt:i,observedPaths:[],tasks:n.tasks.map(s=>({taskId:s.id,status:"pending",evidence:[],acceptanceEvidence:Object.fromEntries(s.acceptanceCriterionIds.map(a=>[a,[]]))}))};return this.repository.create(Woe(o,{producer:t,identity:r.artifact.identity,sensitivity:r.artifact.sensitivity,accessPolicyId:r.artifact.accessPolicyId}))}async updateExecution(e,t,r){let n=await this.repository.require(e),i=iGe(n.artifact),o=await this.repository.require(i.planArtifactId,i.specRevision);if(o.artifact.state!=="approved"||!KH(o.artifact.content.hash,i.planHash))throw new nd(["Execution is no longer bound to the approved plan revision"]);let s=t(structuredClone(i));s.schemaVersion=$N,s.executionId=i.executionId,s.specId=i.specId,s.specRevision=i.specRevision,s.planArtifactId=i.planArtifactId,s.planHash={...i.planHash},s.createdAt=i.createdAt,s.updatedAt=this.now(),Lde(s,qoe(o.artifact));let a=Woe(s,{producer:r,identity:n.artifact.identity,sensitivity:n.artifact.sensitivity,accessPolicyId:n.artifact.accessPolicyId},n.artifact.revision+1,n.artifact.revision);return this.repository.createRevision(a,{actor:r,reason:"spec-execution-updated"})}};sae();Fde="xeno.review-report.v1",oGe=["correctness","security","performance","api","tests","documentation"],sGe=["source","test","trace","artifact","reproduction","benchmark"],id=class extends Error{constructor(e){super(`XENO review is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},vFt=class{reviewer;verifier;now;idFactory;constructor(e){if(typeof e?.reviewer!="function")throw new TypeError("Review agent executor is required");this.reviewer=e.reviewer,this.verifier=e.verifier,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${yTn()}`)}async run(e){Ude(e.pack),Qde(e.target),zoe(e.runId,"runId");let t=this.now(),r=await Promise.all(e.pack.dimensions.map(async(a,l)=>{let c=await this.reviewer({...e,dimension:a,reviewerSlot:l});return ITn(c,a,e.pack.maxFindings),structuredClone(c)})),n=r.flatMap(a=>a.findings.map(l=>({finding:l,reviewerAgentId:a.reviewerAgentId})));if(n.length>e.pack.maxFindings)throw new id([`Reviewers returned ${n.length} findings, exceeding maxFindings ${e.pack.maxFindings}`]);let i=bTn(n,this.idFactory);for(let a of i){let l=this.verifier?await Promise.all(Array.from({length:e.pack.verifierCount},async(f,h)=>{let m=await this.verifier({...e,finding:structuredClone(a),verifierSlot:h});return ETn(m),structuredClone(m)})):[];a.verifications=kTn(l),a.evidence=CFt([...a.evidence,...a.verifications.flatMap(f=>f.evidence)]);let c=new Set(a.verifications.filter(f=>f.outcome==="reproduced").map(f=>f.verifierAgentId)).size,d=a.verifications.length>0&&a.verifications.every(f=>f.outcome==="rejected"),u=new Set(a.evidence.map(f=>f.producerId)).size;c>=e.pack.minimumVerifierReproductions?(a.state="verified",a.verificationBasis="verifier"):e.pack.allowIndependentEvidenceVerification&&u>=e.pack.minimumIndependentEvidenceProducers?(a.state="verified",a.verificationBasis="independent-evidence"):d?(a.state="rejected",a.verificationBasis="verifier"):(a.state="unverified",a.verificationBasis="none");let p=a.verifications.map(f=>f.confidence).filter(f=>f!==void 0);p.length>0&&(a.confidence=$Ft(Math.min(a.confidence,...p)))}i.sort(STn);let o=this.now(),s={schemaVersion:Fde,reportId:zoe(this.idFactory("report"),"reportId"),runId:e.runId,pack:structuredClone(e.pack),target:structuredClone(e.target),startedAt:t,completedAt:o,reviewers:r.map(a=>({agentId:a.reviewerAgentId,dimension:a.dimension,findingCount:a.findings.length})),findings:i,summary:PFt(i)};return N5(s),s}};gn();Bm="index.html",cGe=16*1024*1024,Koe=255,FTn={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".md":"text/markdown; charset=utf-8",".txt":"text/plain; charset=utf-8",".csv":"text/csv; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".pdf":"application/pdf",".wasm":"application/wasm"};uGe=class{repository;directory;now;maxBytes;constructor(e){if(!e?.repository)throw new TypeError("XenoPageStore requires an artifact repository");if(typeof e.directory!="string"||!e.directory.trim())throw new TypeError("XenoPageStore requires a directory");this.repository=e.repository,this.directory=ext(e.directory),this.now=e.now??(()=>new Date().toISOString()),this.maxBytes=e.maxBytes??cGe}revisionDirectory(e,t){if(!/^[A-Za-z0-9_-]+$/u.test(e))throw new TypeError(`Unsafe artifact id: ${e}`);return ly(this.directory,e,`r${t}`)}async publish(e){let t=typeof e.html=="string"?e.html:"";if(!t.trim())throw new TypeError("A page needs HTML content.");let r=new Map;for(let I of e.files??[]){let v=Zoe(I.path);if("error"in v)throw new TypeError(v.error);if(r.has(v.path))throw new TypeError(`Duplicate file path: ${v.path}`);r.set(v.path,{bytes:LBe(I.bytes),contentType:I.contentType??Y8(v.path)})}if(r.size>Koe)throw new TypeError(`A page may carry at most ${Koe} files.`);let n=LBe(t),i=n.byteLength+[...r.values()].reduce((I,v)=>I+v.bytes.byteLength,0);if(i>this.maxBytes)throw new TypeError(`Page revision is ${i} bytes; the limit is ${this.maxBytes}.`);let o=QFt("sha256").update(n),s={};for(let[I,v]of[...r.entries()].sort(([E],[S])=>E.localeCompare(S)))s[I]={sha256:UTn(v.bytes),sizeBytes:v.bytes.byteLength,contentType:v.contentType},o.update(`\0${I}\0${s[I].sha256}`);let a=o.digest("hex"),l=e.artifactId?await this.repository.get(e.artifactId):void 0;if(e.artifactId&&!l)throw new TypeError(`Unknown page artifact ${e.artifactId}.`);if(l&&l.artifact.kind!=="page")throw new TypeError(`Artifact ${e.artifactId} is a ${l.artifact.kind}, not a page.`);if(l&&l.artifact.content.hash.value===a)return{...await this.toPublished(l),unchanged:!0};let c=l?.artifact.artifactId??`page_${kNe().replaceAll("-","").slice(0,20)}`,d=l?l.artifact.revision+1:1,u=this.revisionDirectory(c,d);DBe(u,{recursive:!0});let p=ly(u,Bm);FBe(p,n);for(let[I,v]of r){let E=ly(u,...I.split("/"));DBe(ly(E,".."),{recursive:!0}),FBe(E,v.bytes)}let f=l?UBe(l):{},h=e.title?.trim()||dGe(t)||(typeof f.title=="string"?f.title:void 0)||"Untitled page",m=e.icon?.trim()||(typeof f.icon=="string"?f.icon:void 0),g=e.description?.trim()||l?.artifact.description,A=Array.isArray(f.publications)?f.publications:[],w=this.now(),y={schemaVersion:1,artifactId:c,revision:d,kind:"page",title:h,...g?{description:g}:{},state:"draft",createdAt:l?.artifact.createdAt??w,updatedAt:w,mediaType:"text/html",sensitivity:l?.artifact.sensitivity??"internal",...e.identity??l?.artifact.identity?{identity:e.identity??l.artifact.identity}:{},content:{hash:{algorithm:"sha256",value:a},sizeBytes:i,storage:{type:"file",path:p},encoding:"utf8",redactedPreview:t.slice(0,200)},provenance:{producer:e.producer},...l?{predecessorRevision:l.artifact.revision}:{},extensions:{page:{entry:Bm,htmlSha256:Ws(n).value,files:s,...m?{icon:m}:{},title:h,publications:A,...e.home?{requestedHome:e.home}:{}}}},b=l?await this.repository.createRevision(y,{actor:e.producer,reason:"page republished"}):await this.repository.create(y);return this.toPublished(b)}async recordPublication(e,t){let r=await this.repository.require(e),n=UBe(r),i=(await this.toPublished(r)).publications.filter(s=>s.home!==t.home);i.push(t);let o={...r.artifact,revision:r.artifact.revision,extensions:{...r.artifact.extensions,page:{...n,publications:i}}};return this.writeSidecar(e,{publications:i}),this.toPublished({...r,artifact:o})}sidecarPath(e){return ly(this.directory,e,"publications.json")}writeSidecar(e,t){DBe(ly(this.directory,e),{recursive:!0}),FBe(this.sidecarPath(e),LBe(`${JSON.stringify(t,null,2)}
|
|
2792
2792
|
`))}readSidecar(e){try{let t=JSON.parse(Qre(this.sidecarPath(e),"utf8"));return Array.isArray(t.publications)?t.publications:[]}catch{return[]}}async get(e,t){let r=await this.repository.get(e,t);if(!(!r||r.artifact.kind!=="page"))return this.toPublished(r)}async list(){let e=await this.repository.list({kinds:["page"]});return(await Promise.all(e.map(t=>this.toPublished(t)))).sort((t,r)=>(r.updatedAt??r.createdAt).localeCompare(t.updatedAt??t.createdAt))}resolveFile(e,t,r){let n=r===Bm||r===""?{path:Bm}:Zoe(r);if("error"in n)return;let i=this.revisionDirectory(e,t),o=ext(i,...n.path.split("/"));if(!(o!==i&&!o.startsWith(i+LTn))&&!(!BTn(o)||!MTn(o).isFile()))return{path:o,contentType:Y8(o)}}readEntry(e,t){let r=this.resolveFile(e,t,Bm);return r?Qre(r.path,"utf8"):void 0}readRevision(e,t){let r=this.revisionDirectory(e,t),n=Qre(ly(r,Bm),"utf8"),i=[],o=(s,a)=>{for(let l of $Tn(s,{withFileTypes:!0})){let c=a?`${a}/${l.name}`:l.name;l.isDirectory()?o(ly(s,l.name),c):c!==Bm&&i.push({path:c,bytes:Qre(ly(s,l.name)),contentType:Y8(c)})}};return o(r,""),{html:n,files:i}}async addComment(e,t,r,n){let i=await this.repository.require(e);if(i.artifact.kind!=="page")throw new TypeError(`Artifact ${e} is a ${i.artifact.kind}, not a page.`);let o=t.trim();if(!o)throw new TypeError("A comment needs text.");let s=(await this.repository.appendReviewEvent({event:{type:"comment-added",artifactId:e,artifactRevision:i.artifact.revision,artifactHash:i.artifact.content.hash,actor:r,commentId:`cmt_${kNe().replaceAll("-","").slice(0,16)}`,body:o.slice(0,2e4),...n?{anchor:n}:{}}})).reviewEvents.at(-1);if(!s||s.type!=="comment-added")throw new Error("Comment was not recorded.");return s}async listComments(e){await this.repository.require(e);let t=await this.repository.listRevisions(e),r=new Set,n=[];for(let i of t)for(let o of i.reviewEvents)o.type!=="comment-added"||r.has(o.commentId)||(r.add(o.commentId),n.push(o));return n.sort((i,o)=>i.recordedAt.localeCompare(o.recordedAt)||i.sequence-o.sequence)}async toPublished(e){let t=UBe(e),r=t.files&&typeof t.files=="object"&&!Array.isArray(t.files)?t.files:{},n=this.readSidecar(e.artifact.artifactId),i=[...(Array.isArray(t.publications)?t.publications:[]).filter(o=>!n.some(s=>s.home===o.home)),...n];return{artifactId:e.artifact.artifactId,revision:e.artifact.revision,title:e.artifact.title,...e.artifact.description?{description:e.artifact.description}:{},...typeof t.icon=="string"?{icon:t.icon}:{},hash:e.artifact.content.hash.value,sizeBytes:e.artifact.content.sizeBytes,files:r,directory:this.revisionDirectory(e.artifact.artifactId,e.artifact.revision),entryPath:ly(this.revisionDirectory(e.artifact.artifactId,e.artifact.revision),Bm),publications:i,createdAt:e.artifact.createdAt,...e.artifact.updatedAt?{updatedAt:e.artifact.updatedAt}:{}}}},Z1=["generator","extractor","converter","ai","capture","utility"],pGe="https://tools.xenosystem.ai";Tc=class extends Error{constructor(e,t,r){super(e),this.status=t,this.code=r,this.name="ArtifactCloudError"}status;code;retryable=!1},oxt=1024*1024,HTn=new Set(["missing_html","not_found","invalid_parent","bad_input","denied","needs_approval","conflict","rate_limited"]);GFt=class{baseUrl;getToken;authorize;accountDisplay;fetchImpl;timeoutMs;userAgent;constructor(e){if(this.baseUrl=e.baseUrl.replace(/\/+$/u,""),e.getToken&&e.authorize)throw new Error("Artifact credentials and canonical authorizer are mutually exclusive.");if(e.authorize){let t=new URL(e.baseUrl);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw new Error("Canonical artifact transport requires an HTTPS origin.")}if(this.getToken=e.getToken??(()=>{}),this.authorize=e.authorize,this.accountDisplay=e.accountDisplay,this.fetchImpl=e.fetchImpl??fetch,this.timeoutMs=e.timeoutMs??6e4,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>3e5)throw new Error("Artifact request deadline must be between 1 and 300000 milliseconds.");this.userAgent=e.userAgent}get origin(){return this.baseUrl}signedIn(){return this.authorize?this.accountDisplay?.()===!0:!!this.getToken()}async request(e,t,r){let n=this.getToken(),i=`${this.baseUrl}${t}`,o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs),a=!1,l;try{let c;try{c=this.authorize?await SNe(this.authorize(e,i),o.signal):void 0}catch(h){throw h instanceof Tc?h:new Tc("Canonical artifact account authority is unavailable.",void 0,"unreachable")}if(this.authorize?!c:!n)throw new Tc("Not signed in to XENO. Run `xeno login`, then promote the page again.",401,"not_signed_in");if(this.authorize&&(typeof c?.authorization!="string"||!/^DPoP [\x21-\x7e]{1,16384}$/.test(c.authorization)||typeof c.dpop!="string"||!/^[\x21-\x7e]{1,16384}$/.test(c.dpop)))throw new Tc("Canonical artifact authorization refused.",401,"not_signed_in");let d=r!==void 0?JSON.stringify(r):void 0;o.signal.throwIfAborted(),a=!0;let u=await SNe(this.fetchImpl(i,{method:e,headers:{authorization:c?.authorization??`Bearer ${n}`,...c?.dpop?{dpop:c.dpop}:{},accept:"application/json",...r!==void 0?{"content-type":"application/json"}:{},...this.userAgent?{"user-agent":this.userAgent}:{}},...d!==void 0?{body:d}:{},signal:o.signal,redirect:"error",credentials:"omit"}),o.signal,h=>{h.body?.cancel().catch(()=>{})});l=u.status;let p=await VTn(u,o.signal),f;try{f=p?JSON.parse(p):void 0}catch{throw new Tc("Artifact server returned an invalid response.",u.status,"invalid_response")}if(!u.ok){let h=f&&typeof f=="object"?f.code:void 0,m=typeof h=="string"&&HTn.has(h)?h:"http_error";throw u.status===401?new Tc("XENO sign-in has expired or is not valid for artifacts. Run `xeno login` and try again.",401,"unauthorized"):new Tc(`Artifact request refused (HTTP ${u.status}).`,u.status,m)}if(!f||typeof f!="object"||Array.isArray(f))throw new Tc("Artifact server returned an invalid response.",u.status,"invalid_response");return f}catch(c){throw a&&e!=="GET"&&(l===void 0||l<400||l>=500)?new Tc("Artifact action outcome is unconfirmed; do not retry until its state is reconciled.",l,"effect_unknown"):c instanceof Tc?c:new Tc(o.signal.aborted?"Artifact request deadline exceeded.":"Artifact transport is unavailable.",l,o.signal.aborted?"timeout":"unreachable")}finally{clearTimeout(s)}}async create(e,t={}){return(await this.request("POST","/api/artifacts",{...sxt(e),...t.kind?{kind:t.kind}:{},...t.kind==="tool"&&t.category?{category:t.category}:{}})).artifact}async keepAsTool(e,t={}){return(await this.request("POST",`/api/artifacts/${encodeURIComponent(e)}/keep-as-tool`,{...t.category?{category:t.category}:{}})).artifact}async revise(e,t){let r=await this.request("POST",`/api/artifacts/${encodeURIComponent(e)}/revisions`,sxt(t)),{unchanged:n,...i}=r.artifact;return{artifact:i,unchanged:n===!0}}async get(e){try{return(await this.request("GET",`/api/artifacts/${encodeURIComponent(e)}`)).artifact}catch(t){if(t instanceof Tc&&t.status===404)return;throw t}}async list(e={}){return(await this.request("GET",`/api/artifacts${e.kind?`?kind=${encodeURIComponent(e.kind)}`:""}`)).artifacts}async share(e,t,r={}){let n=await this.request("POST",`/api/artifacts/${encodeURIComponent(e)}/share`,{visibility:t,...r.workspaceId?{workspaceId:r.workspaceId}:{},...r.sharedRevision!==void 0?{sharedRevision:r.sharedRevision}:{}});return{artifact:n.artifact,...n.shareUrl?{shareUrl:n.shareUrl}:{}}}async remove(e){await this.request("DELETE",`/api/artifacts/${encodeURIComponent(e)}`)}async undeliveredComments(e){return(await this.request("GET",`/api/artifacts/${encodeURIComponent(e)}/comments?undelivered=1`)).comments}async reply(e,t,r){return(await this.request("POST",`/api/artifacts/${encodeURIComponent(e)}/comments/${encodeURIComponent(t)}/reply`,{body:r})).comment}async acknowledgeComments(e,t){return t.length?(await this.request("POST",`/api/artifacts/${encodeURIComponent(e)}/comments/delivered`,{commentIds:t})).delivered:0}};mGe=30620,lxt=5,gGe=["default-src 'none'","script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net/npm/ https://cdn.tailwindcss.com https://code.jquery.com","style-src 'self' 'unsafe-inline' https://fonts.googleapis.com","font-src 'self' data: https://fonts.gstatic.com","img-src 'self' data: blob:","media-src 'self' data: blob:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; ");g2=128*1024*1024,e2n=new TextDecoder().decode(new Uint8Array([239,191,189]));jFt=class{cloud;options;storeCache;viewerHandle;viewerStarting;constructor(e){this.options=e,this.cloud=e.cloud}cloudAvailable(){return!!this.cloud?.signedIn()}get cloudOrigin(){return this.cloud?.origin}artifactDirectory(){return this.options.artifactDirectory??nxt(this.options.workspace(),".xeno","artifacts")}get store(){let e=this.options.workspace();if(this.storeCache?.workspace===e)return this.storeCache.store;let t=this.artifactDirectory(),r=this.options.repository??new $de({directory:t}),n=new uGe({repository:r,directory:nxt(t,"pages"),maxBytes:g2});return this.storeCache={workspace:e,store:n},n}get viewer(){return this.viewerHandle}get viewerUrlBase(){return this.viewerHandle?`http://127.0.0.1:${this.viewerHandle.port}`:void 0}async ensureViewer(){return this.viewerHandle?this.viewerHandle:(this.viewerStarting||(this.viewerStarting=AGe({store:this.store,commentActorId:K8(),...this.options.viewerBasePort!==void 0?{basePort:this.options.viewerBasePort}:{},onComment:()=>{this.options.onViewerComment?.()}}).then(e=>(this.viewerHandle=e,e)).finally(()=>{this.viewerStarting=void 0})),this.viewerStarting)}async stop(){this.viewerHandle&&await this.viewerHandle.close(),this.viewerHandle=void 0}resolveSource(e){let t=jTn(e)?ixt(e):ixt(this.options.workspace(),e);if(!QTn(t))throw new Error(`File not found: ${e}`);let r=rxt(t);if(!r.isFile())throw new Error(`Not a file: ${e}`);if(r.size>g2)throw new Error(`${e} is ${r.size} bytes; the local revision limit is ${g2} bytes (including supporting files).`);return t}async publish(e){let t,r;if(typeof e.html=="string"&&e.html.trim())t=e.html;else if(e.filePath){let p=txt(this.resolveSource(e.filePath),"utf8");/\.(md|markdown)$/iu.test(e.filePath)?(r=e.title??jde(p,e.filePath.replace(/^.*[\\/]/u,"").replace(/\.(md|markdown)$/iu,"")),t=hGe(p,{title:r})):t=p}else throw new Error("Publish needs a file_path to an HTML or Markdown file (or inline html).");let n=t.indexOf(e2n);if(n!==-1){let p=t.slice(0,n);throw new Error(`The page contains the replacement character U+FFFD at line ${p.split(`
|
|
@@ -3216,7 +3216,7 @@ ${Fe}${z.compose(Qpe(),z.bold)("\u2717")} ${xW(e)}
|
|
|
3216
3216
|
`)}function fD(){return`
|
|
3217
3217
|
${Fe}${Me("Goodbye.")}
|
|
3218
3218
|
`}var WGn,sHt,Qpe,yr,Me,uD,xW,aHt,CS,JGn,XGn,YGn,q,Fe,fHt,_3e,M,Gpe,cHt,M3e,uHt,TW,xa=we(()=>{"use strict";ud();at();Wd();j8t();Npe();P3e();WGn=new Gy(process.stdout),sHt=new Gy(process.stderr),Qpe=()=>Js(),yr=e=>Qpe()(e),Me=z.dim,uD=z.bold,xW=e=>Qpe()(e),aHt="\u25A0",CS="\u2514",JGn={open:"\x1B[4m",close:"\x1B[24m"};XGn={Read:e=>Hm()(e),ReadImage:e=>Hm()(e),Glob:e=>Hm()(e),Grep:e=>Hm()(e),ElfAnalyze:e=>Hm()(e),MemoryRead:e=>Hm()(e),Write:e=>qR()(e),Edit:e=>qR()(e),MemoryWrite:e=>qR()(e),Bash:e=>v3e()(e),GitStatus:e=>Hm()(e),GitDiff:e=>Hm()(e),GitLog:e=>Hm()(e),GitBranch:e=>Hm()(e),GitCommit:e=>v3e()(e),WebSearch:e=>z.cyan(e),WebFetch:e=>z.cyan(e),TaskOutput:e=>Hm()(e),TaskInput:e=>z.cyan(e),TaskStop:e=>rf()(e)};YGn={Edit:"Update",Glob:"Search",Grep:"Search",WebSearch:"Web Search",WebFetch:"Web Fetch"};q={accent:yr,purple:xW,cyan:xW,dim:Me,bold:uD,red:xW,green:xW},Fe=" ",fHt=1e3,_3e=3;M={moveTo:(e,t)=>`\x1B[${e};${t}H`,saveCursor:()=>"\x1B[s",restoreCursor:()=>"\x1B[u",setScrollRegion:(e,t)=>`\x1B[${e};${t}r`,resetScrollRegion:()=>"\x1B[r",eraseLine:()=>"\x1B[2K",clearScreen:()=>"\x1B[2J\x1B[3J\x1B[H",showCursor:()=>"\x1B[?25h",hideCursor:()=>"\x1B[?25l",disableWrap:()=>"\x1B[?7l",enableWrap:()=>"\x1B[?7h",enableMouseReporting:()=>"\x1B[?1000h\x1B[?1006h",disableMouseReporting:()=>"\x1B[?1006l\x1B[?1000l",enableBracketedPaste:()=>"\x1B[?2004h",disableBracketedPaste:()=>"\x1B[?2004l"};Gpe=30;cHt=3;M3e=class{atLineStart=!0;writeFn;constructor(t){this.writeFn=t??(r=>{WGn.writeOrdered(r,"stream")})}write(t){let r="";for(let n of t)this.atLineStart&&(r+=Fe,this.atLineStart=!1),r+=n,n===`
|
|
3219
|
-
`&&(this.atLineStart=!0);this.writeFn(r)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},uHt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],TW=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,r){this.writeFn=t??(n=>{sHt.writeFrame(n,"spinner")}),this.clearFn=r??(()=>{sHt.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let r=uHt[this.frameIndex%uHt.length],n=`${yr(r)} ${Me(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${n}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});import{randomInt as gjn}from"node:crypto";function Ajn(e){return typeof e=="string"&&Ca.some(t=>t.id===e)}function L3e(){let e=yA().uiMascot;return Ajn(e)?e:null}function Th(){return L3e()??wjn}function RW(e){mo({uiMascot:e})}function hD(){let e=yA().uiColor;return typeof e=="string"&&jm(e)?b3e(e):b3e()}function bHt(e=process.stdout){return e.isTTY===!0&&!process.env.NO_COLOR&&process.env.TERM!=="dumb"&&process.env.XENO_ASCII_UI!=="1"&&process.env.XENO_REDUCED_MOTION!=="1"&&!process.env.CI}function yjn(e,t,r){let n=t==="done",i=r%1.6,o=n&&i<.6?-3*Math.sin(Math.PI*i/.6):0,s=n&&i>=.6&&i<.78?.8*Math.sin(Math.PI*(i-.6)/.18):0,a=(Math.sin(r*1.6)+1)/2,l=Math.max(-1,Math.min(1,Math.sin(r*.55)*1.6)),c=r%4.2,d=!n&&(c<.12||c>.26&&c<.36),u=-Math.PI/2.8+.5*Math.sin(r*9),p=(g,A,w,y,b=0,I=.6)=>n?[_n(g-w,A+.4,g,A-y*.55,I,"K"),_n(g,A-y*.55,g+w,A+.4,I,"K")]:d?[_n(g-w,A+y*.35,g+w,A+y*.35,I,"K")]:[dr(g+l*.5,A,w,y,"K",b),dr(g-w*.3+l*.7,A-y*.4,Math.max(.6,w*.36),Math.max(.6,w*.36),"W")],f=g=>g.k==="e"?{...g,cx:32-g.cx,rot:-g.rot}:g.k==="l"?{...g,x1:32-g.x1,x2:32-g.x2}:g,h=[],m=o;if(e==="bean"){h.push(dr(12,28,3.2,1.9,"O"),dr(20,28,3.2,1.9,"O"),_n(8.5,19,5.6,22.5,1.7,"B")),h.push(n?_n(23.5,18,23.5+5*Math.cos(u),18+5*Math.sin(u),1.7,"B"):_n(23.5,19,26.4,22.5,1.7,"B"));let g=n?Math.sin(r*9)*.5:Math.sin(r*1.6)*.4;h.push(_n(17,10,18.2,5.2,.9,"B"),_n(18.2,5.2,20.2,3.6,.9,"B"),dr(21.2,3.4+g,1.9,1.9,"O")),h.push(dr(16,18.5-a*.3,9+s,9.8+a*.4-s,"B"),dr(16,22.2,5.2,4.2,"C"),dr(10.2,19.6,1.3,.9,"O"),dr(21.8,19.6,1.3,.9,"O")),h.push(...p(12.6,15.5,2.1,2.9),...p(19.4,15.5,2.1,2.9)),h.push(n?dr(16,19.9,1.4,1.1,"K"):_n(15,19.6,17,19.6,.45,"K"))}if(e==="ocu"){let g=[_n(10.5,9.5,8.5,5.5,1.3,"O"),_n(8.5,5.5,10.5,3.2,1.1,"O")];h.push(...g,...g.map(f),dr(11.5,27.5,3,1.8,"B"),dr(20.5,27.5,3,1.8,"B"),_n(7,18,4.5,21.5,1.6,"B")),h.push(n?_n(25,17,25+4.5*Math.cos(u),17+4.5*Math.sin(u),1.6,"B"):_n(25,18,27.5,21.5,1.6,"B")),h.push(dr(16,17.5-a*.3,10+s,10+a*.4-s,"B")),n?h.push(_n(11.5,17,16,13.5,.75,"K"),_n(16,13.5,20.5,17,.75,"K")):d?h.push(_n(11.5,16.8,20.5,16.8,.75,"K")):h.push(dr(16,16,4.8,4.3,"C"),dr(16+l*1.4,16.4,2.8,2.8,"O"),dr(16+l*1.6,16.4,1.3,1.3,"K"),dr(15+l*1.4,15,.8,.8,"W")),h.push(n?dr(16,23,1.8,1.2,"K"):_n(14.5,23,17.5,23,.5,"K"))}if(e==="squee"){for(let g=0;g<4;g++){let A=9.8+g*4.13,w=g<2?-1:1;if(n&&g===3){let b=A+6*Math.cos(u),I=19+6*Math.sin(u);h.push(_n(A,19,b,I,1.6,"B"),dr(b,I,1.5,1.5,"O"));continue}let y=Math.sin(r*1.4+g*1.1)*1.3;h.push(_n(A,19,A+y,25,1.6,"B"),_n(A+y,25,A+y+w*2.2,26.8,1.3,"O"))}h.push(dr(16,18.5,8.6,2.6,"B"),dr(16,12.5-a*.3,9.2+s,8.6+a*.4,"B"),dr(11.5,8.2,1.1,1,"S"),dr(20.5,7.5,1.4,1.2,"S"),dr(16,5.8,.9,.8,"S")),h.push(dr(10.4,16.4,1.2,.8,"O"),dr(21.6,16.4,1.2,.8,"O"),...p(12.6,13.5,1.9,2.5),...p(19.4,13.5,1.9,2.5)),h.push(n?dr(16,17.2,1.2,.9,"K"):_n(15.2,17,16.8,17,.45,"K"))}if(e==="greeb"){let g=[_n(12.5,5.5,10.5,2.4,.8,"B"),dr(10,2,1.5,1.5,"O")];h.push(...g,...g.map(f),dr(13.5,29,2.2,1.4,"B"),dr(18.5,29,2.2,1.4,"B"),_n(12,23,9.5,26,1.1,"B")),h.push(n?_n(20,22.5,20+4*Math.cos(u),22.5+4*Math.sin(u),1.1,"B"):_n(20,23,22.5,26,1.1,"B")),h.push(dr(16,24.5,4.6,4.2,"B"),dr(16,16.5,5.6,4.4,"B"),dr(16,11.5-a*.3,10.2+s,8.2+a*.4,"B")),h.push(...p(11.3,12.8,3.4,2.1,.45,.7),...p(20.7,12.8,3.4,2.1,-.45,.7)),h.push(n?dr(16,18.4,1,.8,"K"):_n(15.4,18.4,16.6,18.4,.4,"K"))}if(e==="quad"){let g=y=>y<.5?4*y*y*y:1-Math.pow(-2*y+2,3)/2,A=(n?90*(Math.floor(r/.8)+g(Math.min(1,r%.8/.5))):5*Math.sin(r*1.2))*Math.PI/180,w=(y,b,I)=>{let v=y-16,E=b-16.5;return[16+v*Math.cos(I)-E*Math.sin(I),16.5+v*Math.sin(I)+E*Math.cos(I)]};for(let y=0;y<4;y++){let b=A+y*Math.PI/2,I=w(10.5,11,b),v=w(6.6,7.1,b),E=w(6.6,10.2,b);h.push(_n(I[0],I[1],v[0],v[1],1.7,"B"),_n(v[0],v[1],E[0],E[1],1.5,"B"),dr(E[0],E[1],1.45,1.45,"O"))}h.push({k:"r",cx:16,cy:16.5-a*.2,w:17+s,h:16.5+a*.4,r:5,m:"B"},dr(11.4,19.2,1.2,.8,"O"),dr(20.6,19.2,1.2,.8,"O")),h.push(...p(12.9,15.6,1.9,2.6),...p(19.1,15.6,1.9,2.6),n?dr(16,19.6,1.2,.9,"K"):_n(15.2,19.4,16.8,19.4,.45,"K"))}if(e==="zip"){m=Math.sin(r*1.2)+o*.6,n&&h.push({k:"d",cx:16,cy:27,rx:6.5,ry:5.5,m:"O",ph:Math.floor(r*6)%2}),h.push(dr(16,21.2,6,1.5,"S"),dr(16,18.3,14,3.6,"G"),dr(16,16.7,11,1.6,"B"));let g=Math.floor(r*3)%5;[6,11,16,21,26].forEach((A,w)=>h.push(dr(A,19.3,1,.8,w===g?"O":"K"))),h.push(dr(16,11.5,6.6,6.2,"Q"),_n(16,9,17.6,6.8,.6,"O"),dr(18,6.4,.9,.9,"O"),dr(16,12.4,4,3.8,"O")),h.push(...p(14.4,12.4,1,1.4,0,.45),...p(17.6,12.4,1,1.4,0,.45),_n(11.6,9.4,12.6,7.4,.55,"W")),n&&h.push(_n(22,13.6,22+3.8*Math.cos(u),13.6+3.8*Math.sin(u),.9,"O"))}for(let g of h)g.k==="l"?(g.y1+=m,g.y2+=m):g.cy+=m;return h}function bjn(e,t,r){if(e.k==="e"){let o=t-e.cx,s=r-e.cy;if(e.rot){let c=Math.cos(-e.rot),d=Math.sin(-e.rot);[o,s]=[o*c-s*d,o*d+s*c]}let a=o/e.rx,l=s/e.ry;return a*a+l*l<=1?[a,l]:null}if(e.k==="l"){let o=e.x2-e.x1,s=e.y2-e.y1,a=o*o+s*s||1,l=Math.max(0,Math.min(1,((t-e.x1)*o+(r-e.y1)*s)/a)),c=e.x1+o*l,d=e.y1+s*l;return Math.hypot(t-c,r-d)<=e.r?[(t-c)/e.r,(r-d)/e.r]:null}if(e.k==="r"){let o=t-e.cx,s=r-e.cy,a=Math.max(Math.abs(o)-(e.w/2-e.r),0),l=Math.max(Math.abs(s)-(e.h/2-e.r),0);return Math.hypot(a,l)<=e.r?[o/(e.w/2),s/(e.h/2)]:null}let n=(t-e.cx)/e.rx,i=(r-e.cy)/e.ry;return n*n+i*i<=1&&(Math.floor(t)+Math.floor(r)+e.ph)%2===0&&Math.abs(t-e.cx)<=1+(r-(e.cy-e.ry))*.6?[0,0]:null}function yHt(e,t){return"#"+e.slice(1).match(/../g).map(r=>{let n=parseInt(r,16),i=t>=1?n+(255-n)*(t-1):n*t;return Math.round(Math.max(0,Math.min(255,i))).toString(16).padStart(2,"0")}).join("")}function F3e(e,t,r,n,i=16){let o=yjn(e,t,r),s=32/i,a=[yHt(n,1.3),n,yHt(n,.7)],l=[];for(let c=0;c<i;c++){let d=[];for(let u=0;u<i;u++){let p=null;for(let f=o.length-1;f>=0;f--){let h=o[f],m=bjn(h,(u+.5)*s,(c+.5)*s);if(!m)continue;let g=h.m==="O"?a:vjn[h.m],A=-(m[0]*.6+m[1]*.8);p=g.length===1?g[0]:g[A>.42?0:A<-.38?2:1];break}d.push(p)}l.push(d)}return l}function Jpe(e,t,r,n,i={}){let o=i.size??16,s=i.color??!0,a=F3e(e,t,r,n,o),l=[];for(let c=0;c<o;c+=2){let d="";for(let u=0;u<o;u++){let p=a[c][u],f=a[c+1]?.[u]??null;!p&&!f?d+=" ":s?p&&f?d+=p===f?z.hex(p)("\u2588"):z.compose(z.hex(p),z.bgHex(f))("\u2580"):d+=p?z.hex(p)("\u2580"):z.hex(f)("\u2584"):d+=p&&f?"\u2588":p?"\u2580":"\u2584"}l.push(d)}return l}var Ca,wjn,dr,_n,vjn,YR=we(()=>{"use strict";ud();Qo();Wd();Ca=[{id:"bean",name:"Bean",blurb:"Round, one antenna, always curious."},{id:"ocu",name:"Ocu",blurb:"One big eye and two hooked horns."},{id:"squee",name:"Squee",blurb:"A dome on four swaying tentacles."},{id:"greeb",name:"Greeb",blurb:"The classic visitor. The quiet one."},{id:"quad",name:"Quad",blurb:"Wears the mark's four hooked arms."},{id:"zip",name:"Zip",blurb:"Rides a saucer with chasing lights."}];wjn=Ca[gjn(Ca.length)].id;dr=(e,t,r,n,i,o=0)=>({k:"e",cx:e,cy:t,rx:r,ry:n,m:i,rot:o}),_n=(e,t,r,n,i,o)=>({k:"l",x1:e,y1:t,x2:r,y2:n,r:i,m:o});vjn={B:["#FAF9F4","#E4E3DC","#B4B3AA"],C:["#FFFFFF","#F6F5F0","#DAD9D1"],G:["#D2D1CA","#A3A29B","#6F6E68"],Q:["#4A4A48","#2E2E2D","#1E1E1D"],K:["#0B0B0B"],W:["#FFFFFF"],S:["#B4B3AA"]}});var Pe,wo=we(()=>{"use strict";Pe="0.5.173"});import{createHash as o3n,randomUUID as afe}from"node:crypto";import*as fi from"node:fs/promises";import*as RS from"node:os";import*as qm from"node:path";import{homedir as IVt,platform as s3n,release as a3n}from"node:os";import{resolve as fVt}from"node:path";import{randomUUID as A3n}from"node:crypto";import{hostname as w3n}from"node:os";import{randomUUID as y3n}from"node:crypto";import{constants as bVt}from"node:fs";import{lstat as ufe,mkdir as vVt,open as m8e,realpath as A8e}from"node:fs/promises";import{dirname as f8e,isAbsolute as SVt,join as g8e,relative as b3n,resolve as v3n,sep as I3n}from"node:path";import{createHash as E3n}from"node:crypto";import{createHash as k3n}from"node:crypto";function l3n(){let e=process.env.XENO_AGENT_HOME?.trim();return e?fVt(e):fVt(IVt(),".xeno-agent")}function hVt(e){if(typeof e!="string"||!e.trim()||e.length>512)throw new EVt("INVALID","Invalid quota identity.");return e}function kVt(e){let t=r=>({id:hVt(r?.id),generation:hVt(r?.generation)});if(!e||e.agent&&!e.team)throw new EVt("INVALID","A child quota scope requires its complete ancestry.");return{workspace:t(e.workspace),...e.team?{team:t(e.team)}:{},...e.agent?{agent:t(e.agent)}:{},...e.goal!==void 0?{goal:t(e.goal)}:{}}}function mVt(e){return JSON.stringify(kVt(e))}function $r(e,t,r=16384){let n=e.trim();if(!n||n.length>r)throw new Ce("INVALID",`${t} must be non-empty and no longer than ${r} characters`);return n}function cfe(e,t){return[...new Set((e??[]).map(r=>$r(r,t)))]}function wVt(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Ce("INVALID","Goal limits must be an object when provided");let t={};for(let[r,n]of Object.entries(e)){if(r!=="maxIterations"&&r!=="maxTokens"&&r!=="maxWallClockMs")throw new Ce("INVALID","Unknown goal limit");if(n!==void 0){if(!Number.isSafeInteger(n)||n<=0)throw new Ce("INVALID",`${r} must be a positive safe integer when provided`);t[r]=n}}return t}function h3n(e){if(e){if(e.kind!=="fixed-interval"&&e.kind!=="dynamic")throw new Ce("INVALID","schedule.kind must be fixed-interval or dynamic");if(e.kind==="fixed-interval"&&(!Number.isSafeInteger(e.intervalMs)||(e.intervalMs??0)<=0))throw new Ce("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(e.intervalMs!==void 0&&(!Number.isSafeInteger(e.intervalMs)||e.intervalMs<=0))throw new Ce("INVALID","schedule.intervalMs must be a positive safe integer when provided");for(let t of["nextRunAt","expiresAt"]){let r=e[t];if(r!==void 0&&!Number.isFinite(Date.parse(r)))throw new Ce("INVALID",`schedule.${t} must be an ISO timestamp when provided`)}return Jd(e)}}function Jd(e){return structuredClone(e)}function wI(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function dfe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function m3n(e){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:e}}function g3n(){return{status:"pending",criteria:[],evidence:[]}}function yVt(e){return o3n("sha256").update(e).digest("hex")}function w8e(e){return{algorithm:"sha256",value:E3n("sha256").update(e).digest("hex")}}function RVt(e){if(typeof e!="string"||!e||e.length>2048||SVt(e)||/[\\:*?"<>|]/.test(e)||[...e].some(r=>r.charCodeAt(0)<32))throw new Error("Invalid portable snapshot path");let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."||/[. ]$/.test(r)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(r)))throw new Error("Ambiguous portable snapshot path");if(t.some(r=>/^(?:\.git|\.ssh|\.aws|\.npmrc|\.netrc|\.xeno-handoff-ready|credentials(?:\.json)?|id_rsa|id_ed25519)$/i.test(r)||/^\.env(?:\.|$)/i.test(r)))throw new Error("Credential or repository-control path cannot be transferred");return e}function PVt(e){return w8e(JSON.stringify([e.schemaVersion,e.sessionId,e.totalBytes,e.files.map(t=>[t.path,t.size,t.sha256,t.executable])])).value}function _Vt(e,t){if(e.schemaVersion!==1||e.sessionId!==t||!Array.isArray(e.files)||e.files.length>xVt||!Number.isSafeInteger(e.totalBytes)||e.totalBytes<0||e.totalBytes>TVt)throw new Error("Invalid handoff snapshot manifest");let r=new Set,n=0;for(let i of e.files){if(RVt(i.path),!Number.isSafeInteger(i.size)||i.size<0||i.size>CVt||!/^[a-f0-9]{64}$/.test(i.sha256)||typeof i.executable!="boolean")throw new Error("Invalid handoff snapshot file");let o=i.path.toLowerCase();if(r.has(o))throw new Error("Snapshot paths collide on Windows");r.add(o),n+=i.size}for(let i of r){let o=i.split("/");for(let s=1;s<o.length;s++)if(r.has(o.slice(0,s).join("/")))throw new Error("Snapshot file conflicts with a directory")}if(n!==e.totalBytes||PVt(e)!==e.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function h8e(e,t){let r=e;for(let o of t.split("/"))if(r=g8e(r,o),(await ufe(r)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let n=await A8e(r),i=b3n(e,n);if(i===".."||i.startsWith(`..${I3n}`)||SVt(i))throw new Error("Snapshot path escaped its root");return r}async function BVt(e){if(!e.sessionId||e.sessionId.length>1024||e.paths.length>xVt)throw new Error("Invalid snapshot scope");let t=await A8e(e.root),r=[],n=new Map,i=0;for(let s of[...e.paths].sort()){if(e.signal?.throwIfAborted(),RVt(s),!await e.authorizeFile(s))throw new Error("Snapshot file transfer is not authorized");let a=await h8e(t,s),l=await ufe(a),c=await m8e(a,bVt.O_RDONLY|(bVt.O_NOFOLLOW??0));try{let d=await c.stat();if(await h8e(t,s),l.ino!==d.ino||l.dev!==d.dev||l.ctimeMs!==d.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!d.isFile()||d.size>CVt||i+d.size>TVt)throw new Error("Snapshot file or total byte limit exceeded");let u=Buffer.alloc(d.size),p=0;for(;p<u.length;){e.signal?.throwIfAborted();let{bytesRead:g}=await c.read(u,p,u.length-p,p);if(!g)throw new Error("Snapshot source changed while reading");p+=g}let f=await c.stat(),h=await ufe(a);if(await h8e(t,s),d.size!==f.size||d.mtimeMs!==f.mtimeMs||d.ctimeMs!==f.ctimeMs||h.isSymbolicLink()||h.ino!==d.ino||h.dev!==d.dev)throw new Error("Snapshot source changed while reading");let m=w8e(u).value;r.push({path:s,size:u.length,sha256:m,executable:(d.mode&73)!==0}),n.set(m,u),i+=u.length}finally{await c.close()}}let o={schemaVersion:1,sessionId:e.sessionId,files:r,totalBytes:i,digest:""};return o.digest=PVt(o),_Vt(o,e.sessionId),{manifest:o,blobs:n}}async function $Vt(e){let t=structuredClone(e.manifest);if(_Vt(t,e.sessionId),!await e.authorizeManifest(structuredClone(t)))throw new Error("Snapshot restoration is not authorized");e.signal?.throwIfAborted();let r=v3n(e.destination);if(await A8e(f8e(r))!==f8e(r))throw new Error("Snapshot destination parent must be canonical");try{throw await ufe(r),new Error("Snapshot destination already exists")}catch(o){if(o.code!=="ENOENT")throw o}let n=`${r}.staging-${y3n()}`;await vVt(n,{mode:448});for(let o of t.files){e.signal?.throwIfAborted();let s=await e.readBlob(o.sha256,o.size);if(s.byteLength!==o.size||w8e(s).value!==o.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=g8e(n,...o.path.split("/"));await vVt(f8e(a),{recursive:!0,mode:448});let l=await m8e(a,"wx",o.executable?448:384);try{await l.writeFile(s),await l.sync()}finally{await l.close()}}e.signal?.throwIfAborted();let i=await m8e(g8e(n,".xeno-handoff-ready"),"wx",384);try{await i.writeFile(JSON.stringify({digest:t.digest,sessionId:t.sessionId})),await i.sync()}finally{await i.close()}return{directory:n,digest:t.digest,files:t.files.length,bytes:t.totalBytes}}function MVt(e){return typeof e=="string"&&S3n.test(e)}function PS(e){return`sha256:${k3n("sha256").update(e).digest("hex")}`}var Ce,ces,des,ues,nP,pes,EVt,c3n,d3n,u3n,p3n,lfe,gVt,f3n,AVt,pfe,iP,xVt,CVt,TVt,S3n,oP=we(()=>{"use strict";Ce=class extends Error{constructor(e,t,r={}){super(t),this.code=e,this.details=r,this.name="XenoCoordinationError"}code;details},ces=s3n(),des=a3n(),ues=IVt();nP="[redacted]",pes=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[redacted:private-key]"],[/((?:^|[\s{,;"'(\[])["']?(?:cookie|set-cookie)["']?\s*[:=]\s*["']?)(?!\[redacted)[^\s"',;]+(?:;\s*[^\s"',;=]+=[^\s"',;]*)*/gi,`$1${nP}`],[/((?:^|[\s{,;"'(\[])["']?(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-xeno-api-key|api[-_]?key|apikey|dpop)["']?\s*[:=]\s*["']?)(?:(?:Bearer|Basic|Token|DPoP)\s+)?(?!\[redacted)[^\s"',;]+/gi,`$1${nP}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${nP}`],[/\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|xeno-[A-Za-z0-9]{24,}|xrun_[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{30,}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9]{30,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g,nP],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,nP],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${nP}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${nP}@`]],EVt=class extends Error{constructor(e,t){super(t),this.code=e,this.name="QuotaError"}code;retryable=!1};c3n=3e4,d3n=3e4,u3n=6e4,p3n=2e4,lfe=new Set(["EACCES","EBUSY","EPERM"]),gVt=[5,10,20,40,80,160,320],f3n=[5,10,20,40,80,160,320],AVt=[1,2,3,4];pfe=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??qm.join(l3n(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${afe()}`),this.ownerLeaseMs=e.ownerLeaseMs??c3n,this.lockTimeoutMs=e.lockTimeoutMs??d3n,this.lockStaleMs=e.lockStaleMs??u3n,this.maximumEventsPerSession=e.maximumEventsPerSession??p3n}async getSessionState(e){let t=$r(e,"sessionId",1024);return Jd(await this.readState(t))}async fenceAdmission(e,t,r){let n=$r(r.authorityId,"authorityId",512),i=$r(r.operationId,"operationId",512);if(!Number.isSafeInteger(t)||t<0)throw new Ce("INVALID","Expected session version must be a nonnegative safe integer");if(r.action!=="archive"&&r.action!=="delete")throw new Ce("INVALID","Unsupported admission fence action");return this.mutate(e,o=>{let s=o.admissionFence;if(s?.authorityId===n&&s.operationId===i&&s.action===r.action)return s;if(o.version!==t)throw new Ce("CONFLICT","Session version changed before lifecycle fencing",{expected:t,actual:o.version});if(s?.authorityId===n&&s.action==="archive"&&r.action==="archive")return s;if(s&&!(s.authorityId===n&&s.action==="archive"&&r.action==="delete"))throw new Ce("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:n,operationId:i,action:r.action,createdAt:this.now()};return o.admissionFence=a,o.schemaVersion===1&&(o.schemaVersion=2),this.appendEvent(o,"admission.fenced",{data:{authorityId:n,operationId:i,action:r.action}}),a},!0)}async clearAdmissionFence(e,t,r,n){await this.mutate(e,i=>{this.assertVersion(e,i.version,t);let o=i.admissionFence;if(!o||o.authorityId!==r||o.operationId!==n)throw new Ce("CONFLICT","Lifecycle fence identity does not match");if(o.action==="delete")throw new Ce("CONFLICT","Deleted session admission cannot be restored");if(i.owner)throw new Ce("CONFLICT","Execution ownership must settle before restoration");i.admissionFence=void 0,this.appendEvent(i,"admission.restored",{data:{authorityId:r,operationId:n}})},!0)}async releaseDeadLifecycleOwner(e,t,r,n){await this.mutate(e,i=>{this.assertVersion(e,i.version,t);let o=i.admissionFence;if(!o||o.authorityId!==r||o.operationId!==n)throw new Ce("CONFLICT","Lifecycle fence identity does not match");let s=i.owner;if(s){if(s.host!==RS.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||dfe(s.processId))throw new Ce("CONFLICT","Execution owner exit has not been proved");i.owner=void 0,this.appendEvent(i,"ownership.released",{ownerId:s.ownerId,data:{epoch:s.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=qm.join(this.rootDirectory,"sessions"),t;try{t=await fi.readdir(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return(await Promise.all(t.filter(r=>r.endsWith(".json")).map(async r=>{try{let n=JSON.parse(await fi.readFile(qm.join(e,r),"utf8"));return!AVt.includes(n.schemaVersion)||typeof n.sessionId!="string"?void 0:((!Number.isSafeInteger(n.ownershipEpoch)||n.ownershipEpoch<0)&&(n.ownershipEpoch=Math.max(n.owner?.epoch??0,...n.handoffs.map(i=>i.targetLeaseEpoch??i.sourceLeaseEpoch??0))),n)}catch{return}}))).filter(r=>r!==void 0).sort((r,n)=>wI(n.updatedAt)-wI(r.updatedAt)).map(r=>Jd(r))}async createGoal(e){let t=$r(e.sessionId,"sessionId",1024),r=wVt(e.limits);return this.mutate(t,n=>{let i=n.goals.find(l=>["active","paused","waiting","blocked"].includes(l.status));if(i)throw new Ce("CONFLICT",`Session ${t} already has active goal ${i.id}`);let o=this.now(),s=(e.successCriteria??[]).map(l=>typeof l=="string"?{id:this.idFactory("criterion"),description:$r(l,"successCriteria"),required:!0}:{id:l.id?$r(l.id,"successCriteria.id",512):this.idFactory("criterion"),description:$r(l.description,"successCriteria.description"),required:l.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:t,objective:$r(e.objective,"objective"),...e.why?{why:$r(e.why,"why")}:{},successCriteria:s,constraints:cfe(e.constraints,"constraints"),...r?{limits:r}:{},metadata:Jd(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:m3n(o),verification:g3n(),steering:[],createdAt:o,updatedAt:o};return n.goals.push(a),this.appendEvent(n,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,t){let r=await this.getSessionState(e),n=t?r.goals.find(i=>i.id===t):[...r.goals].reverse().find(i=>["active","paused","waiting","blocked"].includes(i.status));return n?Jd(n):void 0}async updateGoal(e,t,r,n){return this.mutate(e,i=>{let o=this.requireGoal(i,t);if(this.assertVersion(o.id,o.version,r),["completed","cancelled","failed"].includes(o.status))throw new Ce("CONFLICT",`Goal ${o.id} is terminal (${o.status})`);let s=o.status!=="active";if(n.status==="active"&&o.status==="blocked"?o.status="active":n.status&&(o.status=n.status),n.objective!==void 0&&(o.objective=$r(n.objective,"objective")),n.why!==void 0&&(o.why=$r(n.why,"why")),n.constraints&&(o.constraints=cfe(n.constraints,"constraints")),n.successCriteria&&(o.successCriteria=Jd(n.successCriteria)),n.progress&&(o.progress={...o.progress,...Jd(n.progress),outstanding:cfe(n.progress.outstanding??o.progress.outstanding,"progress.outstanding"),decisions:cfe(n.progress.decisions??o.progress.decisions,"progress.decisions"),updatedAt:this.now()}),n.verification&&(o.verification=Jd(n.verification)),n.metadata&&(o.metadata=Jd(n.metadata)),s&&o.status==="active")for(let a of i.loops.filter(l=>l.goalId===t&&l.kind==="goal-continuation"&&l.status==="running"))a.resumeRequested=!0,a.version+=1,a.updatedAt=this.now();return o.version+=1,o.updatedAt=this.now(),this.appendEvent(i,"goal.updated",{goalId:o.id,data:{status:o.status,version:o.version}}),o},n.status!==void 0&&["paused","cancelled","failed"].includes(n.status))}async addMilestone(e,t,r,n){return this.mutateGoal(e,t,r,(i,o)=>{let s={id:this.idFactory("milestone"),title:$r(n.title,"milestone.title"),...n.description?{description:$r(n.description,"milestone.description")}:{},status:i.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:o,updatedAt:o};i.milestones.push(s),i.progress.currentMilestoneId??=s.id,i.progress.updatedAt=o})}async addTask(e,t,r,n){return this.mutateGoal(e,t,r,(i,o)=>{let s=i.milestones.find(c=>c.id===n.milestoneId);if(!s)throw new Ce("NOT_FOUND",`Milestone ${n.milestoneId} was not found`);if(n.parentTaskId&&!i.tasks.some(c=>c.id===n.parentTaskId))throw new Ce("NOT_FOUND",`Parent task ${n.parentTaskId} was not found`);let a=[...new Set(n.dependsOn??[])];for(let c of a)if(!i.tasks.some(d=>d.id===c))throw new Ce("NOT_FOUND",`Task dependency ${c} was not found`);let l={id:this.idFactory("task"),milestoneId:s.id,...n.parentTaskId?{parentTaskId:n.parentTaskId}:{},title:$r(n.title,"task.title"),...n.description?{description:$r(n.description,"task.description")}:{},status:a.length===0?"ready":"pending",...n.assignedAgentId?{assignedAgentId:$r(n.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:o,updatedAt:o};i.tasks.push(l),s.taskIds.push(l.id),s.updatedAt=o,i.progress.totalTaskCount=i.tasks.length,i.progress.outstanding=i.tasks.filter(c=>c.status!=="completed").map(c=>c.title),i.progress.updatedAt=o})}async updateTask(e,t,r,n,i){return this.mutateGoal(e,t,n,(o,s)=>{let a=o.tasks.find(c=>c.id===r);if(!a)throw new Ce("NOT_FOUND",`Task ${r} was not found`);a.status=i.status,i.progress!==void 0&&(a.progress=$r(i.progress,"task.progress")),i.resultEventId!==void 0&&(a.resultEventId=$r(i.resultEventId,"task.resultEventId",512)),i.assignedAgentId!==void 0&&(a.assignedAgentId=$r(i.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let l=o.milestones.find(c=>c.id===a.milestoneId);if(l){let c=o.tasks.filter(d=>d.milestoneId===l.id);c.length>0&&c.every(d=>d.status==="completed")?(l.status="completed",l.completedAt=s):c.some(d=>d.status==="running")?l.status="active":c.some(d=>d.status==="blocked")&&(l.status="blocked"),l.updatedAt=s}for(let c of o.tasks)c.status!=="pending"||!c.dependsOn?.length||c.dependsOn.every(d=>o.tasks.find(u=>u.id===d)?.status==="completed")&&(c.status="ready",c.updatedAt=s);this.recalculateProgress(o,s)})}async steerGoal(e,t,r,n){return this.mutateGoal(e,t,r,(i,o,s)=>{let a=this.idFactory("steer");i.steering.push({id:a,instruction:$r(n,"instruction"),createdAt:o}),this.appendEvent(s,"goal.steered",{goalId:t,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,t,r){let n=[];return{goal:await this.mutateGoal(e,t,r,(i,o)=>{n=i.steering.filter(s=>!s.consumedAt).map(({id:s,instruction:a,createdAt:l})=>({id:s,instruction:a,createdAt:l}));for(let s of i.steering)s.consumedAt||(s.consumedAt=o)}),instructions:n}}async completeGoal(e,t,r,n){if(n.status!=="passed")throw new Ce("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,i=>{let o=this.requireGoal(i,t);this.assertVersion(o.id,o.version,r);let s=o.successCriteria.filter(c=>c.required),a=s.filter(c=>{let d=n.criteria.find(u=>u.criterionId===c.id);return!d?.satisfied||d.evidence.length===0});if(a.length>0)throw new Ce("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(c=>c.id)});if(s.length===0&&n.evidence.length===0)throw new Ce("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let l=this.now();return o.status="completed",o.verification=Jd(n),o.verification.verifiedAt??=l,o.completedAt=l,o.updatedAt=l,o.version+=1,this.appendEvent(i,"goal.completed",{goalId:t,data:{evidence:o.verification.evidence}}),o},!0)}async cancelGoal(e,t,r,n){return this.mutate(e,i=>{let o=this.requireGoal(i,t);if(this.assertVersion(o.id,o.version,r),["completed","cancelled","failed"].includes(o.status))return o;o.status="cancelled",o.updatedAt=this.now(),o.version+=1,this.appendEvent(i,"goal.cancelled",{goalId:t,data:{reason:$r(n,"reason")}});for(let s of i.loops.filter(a=>a.goalId===t&&["running","paused","waiting"].includes(a.status)))s.status="stopped",s.resumeRequested!==void 0&&(s.resumeRequested=!1),s.stopReason=`Goal cancelled: ${n}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return o},!0)}async startLoop(e){return this.mutate(e.sessionId,t=>this.createLoopRecord(t,e))}createLoopRecord(e,t){if(t.kind==="goal-continuation"&&!t.goalId)throw new Ce("INVALID","Goal-continuation loops require a goalId");if(t.goalId){let s=this.requireGoal(e,t.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new Ce("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(t.kind==="scheduled"&&!t.schedule)throw new Ce("INVALID","Scheduled loops require schedule metadata");if(t.kind!=="scheduled"&&t.schedule)throw new Ce("INVALID","Only scheduled loops may carry schedule metadata");let r=h3n(t.schedule),n=e.loops.find(s=>s.goalId===t.goalId&&s.kind===t.kind&&["running","paused","waiting"].includes(s.status));if(n)throw new Ce("CONFLICT",`Loop ${n.id} is already active`);let i=this.now(),o={schemaVersion:1,id:this.idFactory("loop"),version:1,sessionId:e.sessionId,...t.goalId?{goalId:t.goalId}:{},kind:t.kind,status:"running",...t.activity?{currentActivity:$r(t.activity,"activity")}:{},iterations:[],...r?{schedule:r}:{},createdAt:i,updatedAt:i};return e.loops.push(o),this.appendEvent(e,"loop.started",{loopId:o.id,goalId:o.goalId,data:{kind:o.kind}}),o}async getLoop(e,t){let r=await this.getSessionState(e),n=t?r.loops.find(i=>i.id===t):[...r.loops].reverse().find(i=>["running","paused","waiting"].includes(i.status));return n?Jd(n):void 0}async beginLoopIteration(e,t,r,n,i){return this.mutateLoop(e,t,r,(o,s,a)=>{this.appendLoopIteration(a,o,s,n,i)},!1)}appendLoopIteration(e,t,r,n,i,o=!1){if(t.status!=="running")throw new Ce("CONFLICT",`Loop ${t.id} is ${t.status}`);if(t.goalId){let l=this.requireGoal(e,t.goalId);this.isCliGoal(l)&&this.initializeGoalTurnAccounting(e,l)}if(this.assertGoalIterationAdmission(e,t,r,o),t.iterations.some(l=>l.status==="running"))throw new Ce("CONFLICT",`Loop ${t.id} already has a running iteration`);let s=(t.iterations.at(-1)?.number??0)+1;t.currentActivity=$r(n,"activity");let a={number:s,startedAt:r,status:"running",activity:t.currentActivity,...t.goalId&&e.goalTurnAccounting?.[t.goalId]?{goalAccountingVersion:1}:{},...i?{taskId:$r(i,"taskId",512)}:{}};return t.iterations.push(a),t.resumeRequested!==void 0&&(t.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:t.id,goalId:t.goalId,data:{number:s,phase:"started",activity:t.currentActivity}}),a}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitQuotaGoalTurn(e,t,r,n){let i=kVt(r),o=await this.getGoal(e.sessionId,e.goalId);if(!o||o.sessionId!==e.sessionId||o.limits?.maxTokens===void 0)throw new Ce("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(o)&&o.metadata["cli.tokenQuotaVersion"]!==1)throw new Ce("BUDGET_UNAVAILABLE","Legacy CLI goal token spend is unknown; quota admission requires creation-time provenance");if(i.goal?.id!==o.id||i.goal.generation!==o.createdAt)throw new Ce("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await t.policy(i);if(!s||mVt(s.scope)!==mVt(i)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>o.limits.maxTokens)throw new Ce("BUDGET_UNAVAILABLE","Goal quota policy is absent or wider than the goal's explicit token limit");let a=await t.remainingTokens(i);if(a===null)throw new Ce("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new Ce("BUDGET_EXCEEDED","Goal token allowance is exhausted");return this.admitGoalTurnWithOwner(e,n,{goalId:o.id,createdAt:o.createdAt,maximum:o.limits.maxTokens})}async admitOwnedGoalTurn(e,t){if(!t||!Number.isSafeInteger(t.epoch)||t.epoch<1)throw new Ce("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...t})}async admitGoalTurnWithOwner(e,t,r){let n=$r(e.requestId,"requestId",512),i=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,o=>{if(t){let d=this.requireOwner(o,t.ownerId,t.leaseId);if(d.epoch!==t.epoch)throw new Ce("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(d,this.now()))throw new Ce("LEASE_EXPIRED","Execution ownership expired");if(o.handoffs.some(u=>["prepared","available"].includes(u.status)&&u.sourceLeaseEpoch===d.epoch)||o.handoffs.some(u=>u.status==="claimed"&&u.targetLeaseEpoch===d.epoch))throw new Ce("UNSAFE_HANDOFF","Execution handoff has not settled")}let s=this.requireGoal(o,e.goalId);if(r&&(s.id!==r.goalId||s.createdAt!==r.createdAt||s.limits?.maxTokens!==r.maximum))throw new Ce("BUDGET_UNAVAILABLE","Goal token limit changed after quota verification");for(let d of o.loops.filter(u=>u.goalId===s.id)){let u=d.iterations.find(p=>p.goalTurn?.requestId===n);if(u){if(u.goalTurn?.requestHash!==i)throw new Ce("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(o,s,d,u),admitted:!1}}}if(this.assertVersion(s.id,s.version,e.expectedGoalVersion),s.status!=="active")throw new Ce("CONFLICT",`Goal ${s.id} is ${s.status}`);let a=[...o.loops].reverse().find(d=>d.goalId===s.id&&d.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!a||a.id!==e.expectedLoopId)throw new Ce("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new Ce("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new Ce("CONFLICT",`Goal loop ${a.id} is ${a.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(o,s),a??=this.createLoopRecord(o,{sessionId:o.sessionId,goalId:s.id,kind:"goal-continuation"});let l=this.now(),c=this.appendLoopIteration(o,a,l,"Interactive goal turn",void 0,r!==void 0);if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new Ce("INVALID","Unknown goal execution lane");return c.goalTurn={requestId:n,requestHash:i,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:RS.hostname()}:{kind:"external"}},a.version+=1,a.updatedAt=l,{...this.goalTurnState(o,s,a,c),admitted:!0}},!1,o=>o.admitted)}async getGoalTurnState(e,t,r){let n=await this.getSessionState(e),i=t?n.goals.find(l=>l.id===t):[...n.goals].reverse().find(l=>["active","paused","waiting","blocked"].includes(l.status));if(!i)return;let o=n.loops.filter(l=>l.goalId===i.id),s=r?o.find(l=>l.iterations.some(c=>c.goalTurn?.requestId===r)):[...o].reverse().find(l=>l.kind==="goal-continuation"),a=r?s?.iterations.find(l=>l.goalTurn?.requestId===r):s?.iterations.at(-1);if(r&&!a)throw new Ce("NOT_FOUND","Goal turn was not found");return this.goalTurnState(n,i,s,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new Ce("INVALID","Invalid goal turn outcome");let t=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,r=>{let n=this.requireGoal(r,e.goalId),i=r.loops.find(s=>s.goalId===n.id&&s.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),o=i?.iterations.find(s=>s.goalTurn?.requestId===e.requestId);if(!i||!o)throw new Ce("NOT_FOUND","Goal turn was not found");if(o.goalTurn?.requestHash!==t)throw new Ce("CONFLICT","Goal turn settlement identity does not match");return o.status==="running"&&(this.settleLoopIteration(r,i,o,this.now(),{status:n.status==="cancelled"||["stopped","failed"].includes(i.status)?"interrupted":e.status}),i.version+=1,i.updatedAt=this.now()),this.goalTurnState(r,n,i,o)},!0)}async recoverGoalTurn(e,t,r){return this.mutate(e,n=>{let i=this.requireGoal(n,t),o=n.loops.find(a=>a.goalId===t&&a.iterations.some(l=>l.goalTurn?.requestId===r)),s=o?.iterations.find(a=>a.goalTurn?.requestId===r);if(!o||!s)throw new Ce("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new Ce("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(n,o,s,this.now(),{status:"interrupted",error:"Original local SDK executor exited; inspect persisted results before retrying work"}),o.resumeRequested=i.status==="active"&&o.status==="running",o.version+=1,o.updatedAt=this.now()}return this.goalTurnState(n,i,o,s)},!0)}async finishLoopIteration(e,t,r,n){return this.mutateLoop(e,t,r,(i,o,s)=>{let a=[...i.iterations].reverse().find(l=>l.status==="running");if(!a)throw new Ce("CONFLICT",`Loop ${i.id} has no running iteration`);this.settleLoopIteration(s,i,a,o,n)},!1,!0)}settleLoopIteration(e,t,r,n,i){r.status=i.status,r.completedAt=n,i.verificationEventId&&(r.verificationEventId=$r(i.verificationEventId,"verificationEventId",512)),i.error&&(r.error=$r(i.error,"error")),t.status=["stopped","completed","failed"].includes(t.status)?t.status:e.admissionFence?"paused":i.nextStatus??(t.status==="paused"||t.status==="waiting"?t.status:"running"),this.appendEvent(e,"loop.iteration",{loopId:t.id,goalId:t.goalId,data:{number:r.number,phase:"finished",status:i.status}})}async setLoopStatus(e,t,r,n,i){return this.mutateLoop(e,t,r,(o,s,a)=>{let l=o.status;if(["stopped","completed","failed"].includes(l))throw new Ce("CONFLICT",`Loop ${o.id} is terminal (${l})`);let c=[...o.iterations].reverse().find(u=>u.status==="running");if(c&&n==="completed")throw new Ce("CONFLICT",`Loop ${o.id} cannot complete while iteration ${c.number} is running`);c&&(n==="stopped"||n==="failed")&&(c.status=n==="failed"?"failed":"interrupted",c.completedAt=s,c.error=$r(i??n,"reason")),o.status=n,o.kind==="goal-continuation"&&(o.resumeRequested=n==="running"),["stopped","completed","failed"].includes(n)&&(o.stoppedAt=s,o.stopReason=$r(i??n,"reason"));let d=n==="paused"?"loop.paused":n==="waiting"?"loop.waiting":n==="running"&&(l==="paused"||l==="waiting")?"loop.resumed":n==="completed"?"loop.completed":n==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,d,{loopId:t,goalId:o.goalId,data:{previous:l,status:n,...i?{reason:i}:{}}})},!1,n!=="running"&&n!=="waiting")}async acquireOwnership(e,t,r={}){return this.mutate(e,n=>{let i=this.now();if(n.owner&&!this.ownerExpired(n.owner,i)){if(n.owner.ownerId===t&&r.processId!==void 0&&n.owner.processId===r.processId&&(r.host===void 0||n.owner.host===r.host))return n.owner;throw new Ce("CONFLICT",`Session ${e} is owned by ${n.owner.ownerId}`,{owner:n.owner})}let o=n.owner&&this.ownerExpired(n.owner,i)?n.owner:void 0;if(o)for(let l of n.handoffs.filter(c=>c.status==="claimed"&&c.claimedBy===o.ownerId&&c.targetLeaseEpoch===o.epoch))l.status="failed",l.failureReason=`Claimed owner ${o.ownerId} lost its execution lease before completing the handoff.`,l.failedAt=i,l.updatedAt=i,l.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:l.id,goalId:l.goalId,loopId:l.loopId,data:{reason:l.failureReason,expiredLeaseId:o.leaseId}});let s=n.ownershipEpoch+1;for(let l of n.handoffs.filter(c=>["prepared","available"].includes(c.status)&&c.sourceLeaseEpoch<s))l.status="failed",l.failureReason="Source ownership epoch was superseded before the handoff was claimed.",l.failedAt=i,l.updatedAt=i,l.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:l.id,data:{epoch:s,reason:l.failureReason}});let a=this.newOwner(t,s,r,i);return n.owner=a,n.ownershipEpoch=s,this.appendEvent(n,"ownership.acquired",{ownerId:t,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,t,r,n=this.ownerLeaseMs){return this.mutate(e,i=>{let o=this.requireOwner(i,t,r);if(this.ownerExpired(o,this.now()))throw new Ce("LEASE_EXPIRED",`Ownership lease ${r} expired`);return o.heartbeatAt=this.now(),o.expiresAt=new Date(wI(o.heartbeatAt)+n).toISOString(),this.appendEvent(i,"ownership.renewed",{ownerId:t,data:{epoch:o.epoch,leaseId:r}}),o})}async recoverExpiredOwnership(e,t,r,n,i=this.ownerLeaseMs){return this.mutate(e,o=>{let s=this.requireOwner(o,t,r);if(s.processId!==n||s.host!==RS.hostname()||!dfe(n))throw new Ce("LEASE_EXPIRED",`Ownership lease ${r} expired and cannot be recovered by process ${n}`);let a=this.now(),l=Math.max(0,wI(a)-wI(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(wI(a)+i).toISOString(),this.appendEvent(o,l>0?"ownership.recovered":"ownership.renewed",{ownerId:t,data:{epoch:s.epoch,leaseId:r,...l>0?{expiredForMs:l}:{}}}),s})}async releaseOwnership(e,t,r){return this.mutate(e,n=>{let i=this.requireOwner(n,t,r);for(let o of n.handoffs.filter(s=>s.status==="claimed"&&s.claimedBy===t&&s.targetLeaseEpoch===i.epoch))o.status="failed",o.failureReason="Target released execution ownership before completing the handoff.",o.failedAt=this.now(),o.updatedAt=o.failedAt,o.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:o.id,ownerId:t,data:{epoch:i.epoch,reason:o.failureReason}});return n.owner=void 0,this.appendEvent(n,"ownership.released",{ownerId:t,data:{epoch:i.epoch}}),i},!0)}async createHandoff(e){let t=!1,r=e.prepareRequestId===void 0?void 0:$r(e.prepareRequestId,"prepareRequestId",512);return this.mutate(e.sessionId,n=>{let i=this.requireOwner(n,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(i,this.now()))throw new Ce("LEASE_EXPIRED",`Ownership lease ${i.leaseId} expired`);if(r){let c=n.handoffs.find(d=>d.prepareRequestId===r);if(c){if(c.sourceOwnerId!==i.ownerId||c.sourceLeaseEpoch!==i.epoch||c.status!=="available"||c.targetOwnerId!==e.targetOwnerId||c.workspace!==e.workspace||c.goalId!==e.goalId||c.loopId!==e.loopId||c.contextDigest!==e.contextDigest||c.branch!==e.branch||c.currentMilestoneId!==e.currentMilestoneId||c.currentTaskId!==e.currentTaskId||JSON.stringify(c.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(c.operations)!==JSON.stringify(e.operations??[]))throw new Ce("CONFLICT","Prepare identity was reused for different work or ownership");return t=!0,c}}let o=(e.operations??[]).filter(c=>c.status==="running"&&c.sideEffecting);if(o.length>0)throw new Ce("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:o.map(c=>c.operationId)});if(e.goalId&&this.requireGoal(n,e.goalId),e.loopId&&!n.loops.some(c=>c.id===e.loopId))throw new Ce("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=n.handoffs.find(c=>["prepared","available","claimed"].includes(c.status));if(s)throw new Ce("CONFLICT",`Handoff ${s.id} is already active`);let a=this.now(),l={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:n.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:i.ownerId,...r?{prepareRequestId:r}:{},...e.targetOwnerId?{targetOwnerId:$r(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:i.epoch,...e.workspace?{workspace:$r(e.workspace,"workspace",32768)}:{},...e.branch?{branch:$r(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:Jd(e.operations??[]),...e.contextDigest?{contextDigest:$r(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return n.handoffs.push(l),this.appendEvent(n,"handoff.created",{handoffId:l.id,goalId:l.goalId,loopId:l.loopId,ownerId:i.ownerId,data:{targetOwnerId:l.targetOwnerId}}),l},!1,()=>!t)}async claimHandoff(e){let t,r=!1,n=e.claimRequestId===void 0?void 0:$r(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,i=>{let o=i.handoffs.find(l=>l.id===e.handoffId);if(!o)throw new Ce("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(o.status!=="available"){let l=i.owner;if(n&&o.claimRequestId===n&&["claimed","completed"].includes(o.status)&&o.claimedBy===e.targetOwnerId&&l?.ownerId===e.targetOwnerId&&l.epoch===o.targetLeaseEpoch&&l.host===e.host&&l.processId===e.processId&&!this.ownerExpired(l,this.now()))return t=l,r=!0,o;throw new Ce("CONFLICT",`Handoff ${o.id} is ${o.status}`,{claimedBy:o.claimedBy})}if(o.targetOwnerId&&o.targetOwnerId!==e.targetOwnerId)throw new Ce("CONFLICT",`Handoff ${o.id} is reserved for ${o.targetOwnerId}`);let s=i.owner;if(!s||s.ownerId!==o.sourceOwnerId||s.epoch!==o.sourceLeaseEpoch)throw new Ce("CONFLICT",`Handoff ${o.id} no longer matches the source ownership epoch`);let a=this.now();return t=this.newOwner(e.targetOwnerId,s.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},a),i.owner=t,i.ownershipEpoch=t.epoch,o.status="claimed",o.claimedBy=e.targetOwnerId,n&&(o.claimRequestId=n),o.targetOwnerId=e.targetOwnerId,o.targetLeaseEpoch=t.epoch,o.claimedAt=a,o.updatedAt=a,o.version+=1,this.appendEvent(i,"handoff.claimed",{handoffId:o.id,goalId:o.goalId,loopId:o.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:o.sourceOwnerId,epoch:t.epoch}}),o},!1,()=>!r),owner:Jd(t)}}async completeHandoff(e,t,r,n){let i=!1;return this.mutate(e,o=>{let s=this.requireOwner(o,r,n);if(this.ownerExpired(s,this.now()))throw new Ce("LEASE_EXPIRED",`Ownership lease ${n} expired`);let a=o.handoffs.find(l=>l.id===t);if(!a)throw new Ce("NOT_FOUND",`Handoff ${t} was not found`);if(a.claimedBy!==r||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new Ce("CONFLICT",`Handoff ${a.id} cannot be completed by ${r}`);return a.status==="completed"?(i=!0,a):(a.status="completed",a.completedAt=this.now(),a.updatedAt=a.completedAt,a.version+=1,this.appendEvent(o,"handoff.completed",{handoffId:t,goalId:a.goalId,loopId:a.loopId,ownerId:r,data:{epoch:o.owner?.epoch}}),a)},!1,()=>!i)}async cancelHandoff(e,t,r,n){let i=!1;return this.mutate(e,o=>{let s=o.handoffs.find(l=>l.id===t);if(!s)throw new Ce("NOT_FOUND",`Handoff ${t} was not found`);if(s.sourceOwnerId!==r)throw new Ce("CONFLICT",`Handoff ${t} was not offered by ${r}`);if(s.status==="cancelled")return i=!0,s;if(s.status!=="available"&&s.status!=="prepared")throw new Ce("CONFLICT",`Handoff ${t} is ${s.status} and can no longer be cancelled`);let a=this.requireOwner(o,r,n);if(this.ownerExpired(a,this.now()))throw new Ce("LEASE_EXPIRED",`Ownership lease ${n} expired`);if(s.sourceLeaseEpoch!==a.epoch)throw new Ce("CONFLICT",`Handoff ${t} belongs to an earlier ownership epoch`);return s.status="cancelled",s.cancelledAt=this.now(),s.updatedAt=s.cancelledAt,s.version+=1,this.appendEvent(o,"handoff.cancelled",{handoffId:t,goalId:s.goalId,loopId:s.loopId,ownerId:r,data:{epoch:a.epoch}}),s},!1,()=>!i)}async failHandoff(e,t,r){return this.mutate(e,n=>{let i=n.handoffs.find(o=>o.id===t);if(!i)throw new Ce("NOT_FOUND",`Handoff ${t} was not found`);return["completed","cancelled","failed"].includes(i.status)||(i.status="failed",i.failureReason=$r(r,"reason"),i.failedAt=this.now(),i.updatedAt=i.failedAt,i.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:t,goalId:i.goalId,loopId:i.loopId,data:{reason:i.failureReason}})),i},!0)}async mutateGoal(e,t,r,n,i=!0){return this.mutate(e,o=>{let s=this.requireGoal(o,t);this.assertVersion(s.id,s.version,r);let a=this.now();return n(s,a,o),s.version+=1,s.updatedAt=a,i&&this.appendEvent(o,"goal.updated",{goalId:t,data:{status:s.status,version:s.version}}),s})}async mutateLoop(e,t,r,n,i=!0,o=!1){return this.mutate(e,s=>{let a=s.loops.find(c=>c.id===t);if(!a)throw new Ce("NOT_FOUND",`Loop ${t} was not found`);this.assertVersion(a.id,a.version,r);let l=this.now();return n(a,l,s),a.version+=1,a.updatedAt=l,i&&this.appendEvent(s,"loop.iteration",{loopId:t,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},o)}assertGoalIterationAdmission(e,t,r,n=!1){if(!t.goalId)return;let i=this.requireGoal(e,t.goalId);if(i.status!=="active")throw new Ce("CONFLICT",`Goal ${i.id} is ${i.status}; no iteration was admitted`);let o=wVt(i.limits);if(o?.maxTokens!==void 0&&!n)throw new Ce("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:i.id,limit:"maxTokens"});if(o?.maxWallClockMs!==void 0){let s=Date.parse(i.createdAt),a=Date.parse(r);if(!Number.isFinite(s)||!Number.isFinite(a)||a<s)throw new Ce("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:i.id,limit:"maxWallClockMs"});if(a-s>=o.maxWallClockMs)throw new Ce("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:i.id,limit:"maxWallClockMs",maximum:o.maxWallClockMs})}if(o?.maxIterations!==void 0){let s=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,i):void 0;if(s?.coverage==="partial")throw new Ce("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let a=this.goalIterationCount(e,i)+(s?.baseIterations??0);if(!Number.isSafeInteger(a)||a<0)throw new Ce("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=o.maxIterations)throw new Ce("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:i.id,limit:"maxIterations",admitted:a,maximum:o.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,t){let r=0;for(let n of e.loops.filter(i=>i.goalId===t.id)){if(!Array.isArray(n.iterations))throw new Ce("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let i=0;for(let o of n.iterations){if(!o||!Number.isSafeInteger(o.number)||o.number<=i)throw new Ce("BUDGET_UNAVAILABLE","Goal iteration history is invalid");i=o.number}if(r+=i,!Number.isSafeInteger(r))throw new Ce("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return r}resolveGoalTurnAccounting(e,t){let r=e.goalTurnAccounting;if(r!==void 0&&(!r||typeof r!="object"||Array.isArray(r)))throw new Ce("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(r&&Object.hasOwn(r,t.id)){let a=r[t.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new Ce("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===t.id&&a.iterations.some(l=>l.goalTurn||l.goalAccountingVersion)))throw new Ce("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let n=this.goalIterationCount(e,t),i=t.metadata["cli.accountedTurns"],o=typeof i=="number"&&Number.isSafeInteger(i)&&i>=0,s=this.isCliGoal(t)&&(!o||i>0&&n>0);return{schemaVersion:1,baseIterations:o&&n===0?i:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,t){let r=this.resolveGoalTurnAccounting(e,t);if(r.coverage==="partial"&&t.limits?.maxIterations!==void 0)throw new Ce("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,t.id,{value:r,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let t=$r(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Ce("INVALID","Goal turn requestHash must be a SHA-256 digest");return t}goalTurnState(e,t,r,n){let i=this.resolveGoalTurnAccounting(e,t),o=this.goalIterationCount(e,t)+i.baseIterations;if(!Number.isSafeInteger(o))throw new Ce("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return Jd({goal:t,admittedTurns:o,accountingCoverage:i.coverage,...r?{loopId:r.id,loopVersion:r.version,loopStatus:r.status,resumeRequested:r.resumeRequested===!0}:{},...n?{iterationNumber:n.number,iterationStatus:n.status,...n.goalTurn?{requestId:n.goalTurn.requestId,requestHash:n.goalTurn.requestHash}:{},canRecover:n.status==="running"&&this.goalTurnOwnerExited(n)}:{}})}goalTurnOwnerExited(e){let t=e.goalTurn?.executor;if(t?.kind!=="local-sdk"||t.host!==RS.hostname()||!Number.isSafeInteger(t.processId)||t.processId<=0)return!1;try{return process.kill(t.processId,0),!1}catch(r){return r.code==="ESRCH"}}recalculateProgress(e,t){let r=e.tasks.filter(n=>n.status==="completed").length;e.progress.completedTaskCount=r,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(r/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(n=>!["completed","cancelled"].includes(n.status)).map(n=>n.title),e.progress.updatedAt=t}requireGoal(e,t){let r=e.goals.find(n=>n.id===t);if(!r)throw new Ce("NOT_FOUND",`Goal ${t} was not found`);return r}requireOwner(e,t,r){let n=e.owner;if(!n||n.ownerId!==t||n.leaseId!==r)throw new Ce("NOT_OWNER",`${t} does not own session ${e.sessionId}`,{owner:n});return n}assertVersion(e,t,r){if(!Number.isInteger(r)||r<1||t!==r)throw new Ce("CONFLICT",`Expected ${e} version ${r}, found ${t}`,{expected:r,actual:t})}newOwner(e,t,r,n){let i=r.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(i)||i<1)throw new Ce("INVALID","leaseMs must be a positive safe integer");return{ownerId:$r(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:t,acquiredAt:n,heartbeatAt:n,expiresAt:new Date(wI(n)+i).toISOString(),...r.processId!==void 0?{processId:r.processId}:{},...r.host?{host:$r(r.host,"host",512)}:{}}}ownerExpired(e,t){return wI(e.expiresAt)<=wI(t)?!0:e.processId!==void 0&&e.host===RS.hostname()&&!dfe(e.processId)}appendEvent(e,t,r){let n={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:t,sessionId:e.sessionId,...r.goalId?{goalId:r.goalId}:{},...r.loopId?{loopId:r.loopId}:{},...r.handoffId?{handoffId:r.handoffId}:{},...r.ownerId?{ownerId:r.ownerId}:{},timestamp:this.now(),data:Jd(r.data)};e.events.push(n),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,t,r=!1,n=()=>!0){let i=$r(e,"sessionId",1024);return this.withSessionLock(i,async()=>{let o=await this.readState(i);if(o.admissionFence&&!r)throw new Ce("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let s=o.schemaVersion;this.promoteGoalBudgetEnvelope(o),o.schemaVersion!==s&&await this.writeState(o);let a=t(o);return n(a)&&(o.version+=1,o.updatedAt=this.now(),await this.writeState(o)),Jd(a)})}statePath(e){return qm.join(this.rootDirectory,"sessions",`${yVt(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let t=this.statePath(e);try{let r=await fi.readFile(t,"utf8"),n=JSON.parse(r);if(!AVt.includes(n.schemaVersion)||n.sessionId!==e)throw new Ce("INVALID",`Coordination state at ${t} does not match session ${e}`);if(n.admissionFence!==void 0){let i=n.admissionFence;if(!i||i.schemaVersion!==1||typeof i.authorityId!="string"||!i.authorityId.trim()||typeof i.operationId!="string"||!i.operationId.trim()||!["archive","delete"].includes(i.action)||!Number.isFinite(Date.parse(i.createdAt)))throw new Ce("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(n.ownershipEpoch)||n.ownershipEpoch<0)&&(n.ownershipEpoch=Math.max(n.owner?.epoch??0,...n.handoffs.map(i=>i.targetLeaseEpoch??i.sourceLeaseEpoch??0))),n}catch(r){if(r.code!=="ENOENT")throw r;let n=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:n,updatedAt:n}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(t=>t.resumeRequested!==void 0||t.iterations.some(r=>r.goalTurn!==void 0)))&&(e.schemaVersion=4),e.schemaVersion<3&&e.goals.some(t=>t.limits!==void 0&&(!t.limits||typeof t.limits!="object"||Array.isArray(t.limits)||Object.keys(t.limits).length>0))&&(e.schemaVersion=3)}async writeState(e){this.promoteGoalBudgetEnvelope(e);let t=this.statePath(e.sessionId),r=qm.dirname(t);await fi.mkdir(r,{recursive:!0});let n=`${t}.${process.pid}.${afe()}.tmp`,i=await fi.open(n,"wx");try{await i.writeFile(`${JSON.stringify(e,null,2)}
|
|
3219
|
+
`&&(this.atLineStart=!0);this.writeFn(r)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},uHt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],TW=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,r){this.writeFn=t??(n=>{sHt.writeFrame(n,"spinner")}),this.clearFn=r??(()=>{sHt.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let r=uHt[this.frameIndex%uHt.length],n=`${yr(r)} ${Me(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${n}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});import{randomInt as gjn}from"node:crypto";function Ajn(e){return typeof e=="string"&&Ca.some(t=>t.id===e)}function L3e(){let e=yA().uiMascot;return Ajn(e)?e:null}function Th(){return L3e()??wjn}function RW(e){mo({uiMascot:e})}function hD(){let e=yA().uiColor;return typeof e=="string"&&jm(e)?b3e(e):b3e()}function bHt(e=process.stdout){return e.isTTY===!0&&!process.env.NO_COLOR&&process.env.TERM!=="dumb"&&process.env.XENO_ASCII_UI!=="1"&&process.env.XENO_REDUCED_MOTION!=="1"&&!process.env.CI}function yjn(e,t,r){let n=t==="done",i=r%1.6,o=n&&i<.6?-3*Math.sin(Math.PI*i/.6):0,s=n&&i>=.6&&i<.78?.8*Math.sin(Math.PI*(i-.6)/.18):0,a=(Math.sin(r*1.6)+1)/2,l=Math.max(-1,Math.min(1,Math.sin(r*.55)*1.6)),c=r%4.2,d=!n&&(c<.12||c>.26&&c<.36),u=-Math.PI/2.8+.5*Math.sin(r*9),p=(g,A,w,y,b=0,I=.6)=>n?[_n(g-w,A+.4,g,A-y*.55,I,"K"),_n(g,A-y*.55,g+w,A+.4,I,"K")]:d?[_n(g-w,A+y*.35,g+w,A+y*.35,I,"K")]:[dr(g+l*.5,A,w,y,"K",b),dr(g-w*.3+l*.7,A-y*.4,Math.max(.6,w*.36),Math.max(.6,w*.36),"W")],f=g=>g.k==="e"?{...g,cx:32-g.cx,rot:-g.rot}:g.k==="l"?{...g,x1:32-g.x1,x2:32-g.x2}:g,h=[],m=o;if(e==="bean"){h.push(dr(12,28,3.2,1.9,"O"),dr(20,28,3.2,1.9,"O"),_n(8.5,19,5.6,22.5,1.7,"B")),h.push(n?_n(23.5,18,23.5+5*Math.cos(u),18+5*Math.sin(u),1.7,"B"):_n(23.5,19,26.4,22.5,1.7,"B"));let g=n?Math.sin(r*9)*.5:Math.sin(r*1.6)*.4;h.push(_n(17,10,18.2,5.2,.9,"B"),_n(18.2,5.2,20.2,3.6,.9,"B"),dr(21.2,3.4+g,1.9,1.9,"O")),h.push(dr(16,18.5-a*.3,9+s,9.8+a*.4-s,"B"),dr(16,22.2,5.2,4.2,"C"),dr(10.2,19.6,1.3,.9,"O"),dr(21.8,19.6,1.3,.9,"O")),h.push(...p(12.6,15.5,2.1,2.9),...p(19.4,15.5,2.1,2.9)),h.push(n?dr(16,19.9,1.4,1.1,"K"):_n(15,19.6,17,19.6,.45,"K"))}if(e==="ocu"){let g=[_n(10.5,9.5,8.5,5.5,1.3,"O"),_n(8.5,5.5,10.5,3.2,1.1,"O")];h.push(...g,...g.map(f),dr(11.5,27.5,3,1.8,"B"),dr(20.5,27.5,3,1.8,"B"),_n(7,18,4.5,21.5,1.6,"B")),h.push(n?_n(25,17,25+4.5*Math.cos(u),17+4.5*Math.sin(u),1.6,"B"):_n(25,18,27.5,21.5,1.6,"B")),h.push(dr(16,17.5-a*.3,10+s,10+a*.4-s,"B")),n?h.push(_n(11.5,17,16,13.5,.75,"K"),_n(16,13.5,20.5,17,.75,"K")):d?h.push(_n(11.5,16.8,20.5,16.8,.75,"K")):h.push(dr(16,16,4.8,4.3,"C"),dr(16+l*1.4,16.4,2.8,2.8,"O"),dr(16+l*1.6,16.4,1.3,1.3,"K"),dr(15+l*1.4,15,.8,.8,"W")),h.push(n?dr(16,23,1.8,1.2,"K"):_n(14.5,23,17.5,23,.5,"K"))}if(e==="squee"){for(let g=0;g<4;g++){let A=9.8+g*4.13,w=g<2?-1:1;if(n&&g===3){let b=A+6*Math.cos(u),I=19+6*Math.sin(u);h.push(_n(A,19,b,I,1.6,"B"),dr(b,I,1.5,1.5,"O"));continue}let y=Math.sin(r*1.4+g*1.1)*1.3;h.push(_n(A,19,A+y,25,1.6,"B"),_n(A+y,25,A+y+w*2.2,26.8,1.3,"O"))}h.push(dr(16,18.5,8.6,2.6,"B"),dr(16,12.5-a*.3,9.2+s,8.6+a*.4,"B"),dr(11.5,8.2,1.1,1,"S"),dr(20.5,7.5,1.4,1.2,"S"),dr(16,5.8,.9,.8,"S")),h.push(dr(10.4,16.4,1.2,.8,"O"),dr(21.6,16.4,1.2,.8,"O"),...p(12.6,13.5,1.9,2.5),...p(19.4,13.5,1.9,2.5)),h.push(n?dr(16,17.2,1.2,.9,"K"):_n(15.2,17,16.8,17,.45,"K"))}if(e==="greeb"){let g=[_n(12.5,5.5,10.5,2.4,.8,"B"),dr(10,2,1.5,1.5,"O")];h.push(...g,...g.map(f),dr(13.5,29,2.2,1.4,"B"),dr(18.5,29,2.2,1.4,"B"),_n(12,23,9.5,26,1.1,"B")),h.push(n?_n(20,22.5,20+4*Math.cos(u),22.5+4*Math.sin(u),1.1,"B"):_n(20,23,22.5,26,1.1,"B")),h.push(dr(16,24.5,4.6,4.2,"B"),dr(16,16.5,5.6,4.4,"B"),dr(16,11.5-a*.3,10.2+s,8.2+a*.4,"B")),h.push(...p(11.3,12.8,3.4,2.1,.45,.7),...p(20.7,12.8,3.4,2.1,-.45,.7)),h.push(n?dr(16,18.4,1,.8,"K"):_n(15.4,18.4,16.6,18.4,.4,"K"))}if(e==="quad"){let g=y=>y<.5?4*y*y*y:1-Math.pow(-2*y+2,3)/2,A=(n?90*(Math.floor(r/.8)+g(Math.min(1,r%.8/.5))):5*Math.sin(r*1.2))*Math.PI/180,w=(y,b,I)=>{let v=y-16,E=b-16.5;return[16+v*Math.cos(I)-E*Math.sin(I),16.5+v*Math.sin(I)+E*Math.cos(I)]};for(let y=0;y<4;y++){let b=A+y*Math.PI/2,I=w(10.5,11,b),v=w(6.6,7.1,b),E=w(6.6,10.2,b);h.push(_n(I[0],I[1],v[0],v[1],1.7,"B"),_n(v[0],v[1],E[0],E[1],1.5,"B"),dr(E[0],E[1],1.45,1.45,"O"))}h.push({k:"r",cx:16,cy:16.5-a*.2,w:17+s,h:16.5+a*.4,r:5,m:"B"},dr(11.4,19.2,1.2,.8,"O"),dr(20.6,19.2,1.2,.8,"O")),h.push(...p(12.9,15.6,1.9,2.6),...p(19.1,15.6,1.9,2.6),n?dr(16,19.6,1.2,.9,"K"):_n(15.2,19.4,16.8,19.4,.45,"K"))}if(e==="zip"){m=Math.sin(r*1.2)+o*.6,n&&h.push({k:"d",cx:16,cy:27,rx:6.5,ry:5.5,m:"O",ph:Math.floor(r*6)%2}),h.push(dr(16,21.2,6,1.5,"S"),dr(16,18.3,14,3.6,"G"),dr(16,16.7,11,1.6,"B"));let g=Math.floor(r*3)%5;[6,11,16,21,26].forEach((A,w)=>h.push(dr(A,19.3,1,.8,w===g?"O":"K"))),h.push(dr(16,11.5,6.6,6.2,"Q"),_n(16,9,17.6,6.8,.6,"O"),dr(18,6.4,.9,.9,"O"),dr(16,12.4,4,3.8,"O")),h.push(...p(14.4,12.4,1,1.4,0,.45),...p(17.6,12.4,1,1.4,0,.45),_n(11.6,9.4,12.6,7.4,.55,"W")),n&&h.push(_n(22,13.6,22+3.8*Math.cos(u),13.6+3.8*Math.sin(u),.9,"O"))}for(let g of h)g.k==="l"?(g.y1+=m,g.y2+=m):g.cy+=m;return h}function bjn(e,t,r){if(e.k==="e"){let o=t-e.cx,s=r-e.cy;if(e.rot){let c=Math.cos(-e.rot),d=Math.sin(-e.rot);[o,s]=[o*c-s*d,o*d+s*c]}let a=o/e.rx,l=s/e.ry;return a*a+l*l<=1?[a,l]:null}if(e.k==="l"){let o=e.x2-e.x1,s=e.y2-e.y1,a=o*o+s*s||1,l=Math.max(0,Math.min(1,((t-e.x1)*o+(r-e.y1)*s)/a)),c=e.x1+o*l,d=e.y1+s*l;return Math.hypot(t-c,r-d)<=e.r?[(t-c)/e.r,(r-d)/e.r]:null}if(e.k==="r"){let o=t-e.cx,s=r-e.cy,a=Math.max(Math.abs(o)-(e.w/2-e.r),0),l=Math.max(Math.abs(s)-(e.h/2-e.r),0);return Math.hypot(a,l)<=e.r?[o/(e.w/2),s/(e.h/2)]:null}let n=(t-e.cx)/e.rx,i=(r-e.cy)/e.ry;return n*n+i*i<=1&&(Math.floor(t)+Math.floor(r)+e.ph)%2===0&&Math.abs(t-e.cx)<=1+(r-(e.cy-e.ry))*.6?[0,0]:null}function yHt(e,t){return"#"+e.slice(1).match(/../g).map(r=>{let n=parseInt(r,16),i=t>=1?n+(255-n)*(t-1):n*t;return Math.round(Math.max(0,Math.min(255,i))).toString(16).padStart(2,"0")}).join("")}function F3e(e,t,r,n,i=16){let o=yjn(e,t,r),s=32/i,a=[yHt(n,1.3),n,yHt(n,.7)],l=[];for(let c=0;c<i;c++){let d=[];for(let u=0;u<i;u++){let p=null;for(let f=o.length-1;f>=0;f--){let h=o[f],m=bjn(h,(u+.5)*s,(c+.5)*s);if(!m)continue;let g=h.m==="O"?a:vjn[h.m],A=-(m[0]*.6+m[1]*.8);p=g.length===1?g[0]:g[A>.42?0:A<-.38?2:1];break}d.push(p)}l.push(d)}return l}function Jpe(e,t,r,n,i={}){let o=i.size??16,s=i.color??!0,a=F3e(e,t,r,n,o),l=[];for(let c=0;c<o;c+=2){let d="";for(let u=0;u<o;u++){let p=a[c][u],f=a[c+1]?.[u]??null;!p&&!f?d+=" ":s?p&&f?d+=p===f?z.hex(p)("\u2588"):z.compose(z.hex(p),z.bgHex(f))("\u2580"):d+=p?z.hex(p)("\u2580"):z.hex(f)("\u2584"):d+=p&&f?"\u2588":p?"\u2580":"\u2584"}l.push(d)}return l}var Ca,wjn,dr,_n,vjn,YR=we(()=>{"use strict";ud();Qo();Wd();Ca=[{id:"bean",name:"Bean",blurb:"Round, one antenna, always curious."},{id:"ocu",name:"Ocu",blurb:"One big eye and two hooked horns."},{id:"squee",name:"Squee",blurb:"A dome on four swaying tentacles."},{id:"greeb",name:"Greeb",blurb:"The classic visitor. The quiet one."},{id:"quad",name:"Quad",blurb:"Wears the mark's four hooked arms."},{id:"zip",name:"Zip",blurb:"Rides a saucer with chasing lights."}];wjn=Ca[gjn(Ca.length)].id;dr=(e,t,r,n,i,o=0)=>({k:"e",cx:e,cy:t,rx:r,ry:n,m:i,rot:o}),_n=(e,t,r,n,i,o)=>({k:"l",x1:e,y1:t,x2:r,y2:n,r:i,m:o});vjn={B:["#FAF9F4","#E4E3DC","#B4B3AA"],C:["#FFFFFF","#F6F5F0","#DAD9D1"],G:["#D2D1CA","#A3A29B","#6F6E68"],Q:["#4A4A48","#2E2E2D","#1E1E1D"],K:["#0B0B0B"],W:["#FFFFFF"],S:["#B4B3AA"]}});var Pe,wo=we(()=>{"use strict";Pe="0.5.174"});import{createHash as o3n,randomUUID as afe}from"node:crypto";import*as fi from"node:fs/promises";import*as RS from"node:os";import*as qm from"node:path";import{homedir as IVt,platform as s3n,release as a3n}from"node:os";import{resolve as fVt}from"node:path";import{randomUUID as A3n}from"node:crypto";import{hostname as w3n}from"node:os";import{randomUUID as y3n}from"node:crypto";import{constants as bVt}from"node:fs";import{lstat as ufe,mkdir as vVt,open as m8e,realpath as A8e}from"node:fs/promises";import{dirname as f8e,isAbsolute as SVt,join as g8e,relative as b3n,resolve as v3n,sep as I3n}from"node:path";import{createHash as E3n}from"node:crypto";import{createHash as k3n}from"node:crypto";function l3n(){let e=process.env.XENO_AGENT_HOME?.trim();return e?fVt(e):fVt(IVt(),".xeno-agent")}function hVt(e){if(typeof e!="string"||!e.trim()||e.length>512)throw new EVt("INVALID","Invalid quota identity.");return e}function kVt(e){let t=r=>({id:hVt(r?.id),generation:hVt(r?.generation)});if(!e||e.agent&&!e.team)throw new EVt("INVALID","A child quota scope requires its complete ancestry.");return{workspace:t(e.workspace),...e.team?{team:t(e.team)}:{},...e.agent?{agent:t(e.agent)}:{},...e.goal!==void 0?{goal:t(e.goal)}:{}}}function mVt(e){return JSON.stringify(kVt(e))}function $r(e,t,r=16384){let n=e.trim();if(!n||n.length>r)throw new Ce("INVALID",`${t} must be non-empty and no longer than ${r} characters`);return n}function cfe(e,t){return[...new Set((e??[]).map(r=>$r(r,t)))]}function wVt(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Ce("INVALID","Goal limits must be an object when provided");let t={};for(let[r,n]of Object.entries(e)){if(r!=="maxIterations"&&r!=="maxTokens"&&r!=="maxWallClockMs")throw new Ce("INVALID","Unknown goal limit");if(n!==void 0){if(!Number.isSafeInteger(n)||n<=0)throw new Ce("INVALID",`${r} must be a positive safe integer when provided`);t[r]=n}}return t}function h3n(e){if(e){if(e.kind!=="fixed-interval"&&e.kind!=="dynamic")throw new Ce("INVALID","schedule.kind must be fixed-interval or dynamic");if(e.kind==="fixed-interval"&&(!Number.isSafeInteger(e.intervalMs)||(e.intervalMs??0)<=0))throw new Ce("INVALID","Fixed-interval schedules require a positive safe intervalMs");if(e.intervalMs!==void 0&&(!Number.isSafeInteger(e.intervalMs)||e.intervalMs<=0))throw new Ce("INVALID","schedule.intervalMs must be a positive safe integer when provided");for(let t of["nextRunAt","expiresAt"]){let r=e[t];if(r!==void 0&&!Number.isFinite(Date.parse(r)))throw new Ce("INVALID",`schedule.${t} must be an ISO timestamp when provided`)}return Jd(e)}}function Jd(e){return structuredClone(e)}function wI(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function dfe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function m3n(e){return{summary:"Goal created; work has not started.",completedTaskCount:0,totalTaskCount:0,outstanding:[],decisions:[],updatedAt:e}}function g3n(){return{status:"pending",criteria:[],evidence:[]}}function yVt(e){return o3n("sha256").update(e).digest("hex")}function w8e(e){return{algorithm:"sha256",value:E3n("sha256").update(e).digest("hex")}}function RVt(e){if(typeof e!="string"||!e||e.length>2048||SVt(e)||/[\\:*?"<>|]/.test(e)||[...e].some(r=>r.charCodeAt(0)<32))throw new Error("Invalid portable snapshot path");let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."||/[. ]$/.test(r)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(r)))throw new Error("Ambiguous portable snapshot path");if(t.some(r=>/^(?:\.git|\.ssh|\.aws|\.npmrc|\.netrc|\.xeno-handoff-ready|credentials(?:\.json)?|id_rsa|id_ed25519)$/i.test(r)||/^\.env(?:\.|$)/i.test(r)))throw new Error("Credential or repository-control path cannot be transferred");return e}function PVt(e){return w8e(JSON.stringify([e.schemaVersion,e.sessionId,e.totalBytes,e.files.map(t=>[t.path,t.size,t.sha256,t.executable])])).value}function _Vt(e,t){if(e.schemaVersion!==1||e.sessionId!==t||!Array.isArray(e.files)||e.files.length>xVt||!Number.isSafeInteger(e.totalBytes)||e.totalBytes<0||e.totalBytes>TVt)throw new Error("Invalid handoff snapshot manifest");let r=new Set,n=0;for(let i of e.files){if(RVt(i.path),!Number.isSafeInteger(i.size)||i.size<0||i.size>CVt||!/^[a-f0-9]{64}$/.test(i.sha256)||typeof i.executable!="boolean")throw new Error("Invalid handoff snapshot file");let o=i.path.toLowerCase();if(r.has(o))throw new Error("Snapshot paths collide on Windows");r.add(o),n+=i.size}for(let i of r){let o=i.split("/");for(let s=1;s<o.length;s++)if(r.has(o.slice(0,s).join("/")))throw new Error("Snapshot file conflicts with a directory")}if(n!==e.totalBytes||PVt(e)!==e.digest)throw new Error("Handoff snapshot manifest integrity mismatch")}async function h8e(e,t){let r=e;for(let o of t.split("/"))if(r=g8e(r,o),(await ufe(r)).isSymbolicLink())throw new Error("Snapshot symlinks are not supported");let n=await A8e(r),i=b3n(e,n);if(i===".."||i.startsWith(`..${I3n}`)||SVt(i))throw new Error("Snapshot path escaped its root");return r}async function BVt(e){if(!e.sessionId||e.sessionId.length>1024||e.paths.length>xVt)throw new Error("Invalid snapshot scope");let t=await A8e(e.root),r=[],n=new Map,i=0;for(let s of[...e.paths].sort()){if(e.signal?.throwIfAborted(),RVt(s),!await e.authorizeFile(s))throw new Error("Snapshot file transfer is not authorized");let a=await h8e(t,s),l=await ufe(a),c=await m8e(a,bVt.O_RDONLY|(bVt.O_NOFOLLOW??0));try{let d=await c.stat();if(await h8e(t,s),l.ino!==d.ino||l.dev!==d.dev||l.ctimeMs!==d.ctimeMs)throw new Error("Snapshot source was replaced before reading");if(!d.isFile()||d.size>CVt||i+d.size>TVt)throw new Error("Snapshot file or total byte limit exceeded");let u=Buffer.alloc(d.size),p=0;for(;p<u.length;){e.signal?.throwIfAborted();let{bytesRead:g}=await c.read(u,p,u.length-p,p);if(!g)throw new Error("Snapshot source changed while reading");p+=g}let f=await c.stat(),h=await ufe(a);if(await h8e(t,s),d.size!==f.size||d.mtimeMs!==f.mtimeMs||d.ctimeMs!==f.ctimeMs||h.isSymbolicLink()||h.ino!==d.ino||h.dev!==d.dev)throw new Error("Snapshot source changed while reading");let m=w8e(u).value;r.push({path:s,size:u.length,sha256:m,executable:(d.mode&73)!==0}),n.set(m,u),i+=u.length}finally{await c.close()}}let o={schemaVersion:1,sessionId:e.sessionId,files:r,totalBytes:i,digest:""};return o.digest=PVt(o),_Vt(o,e.sessionId),{manifest:o,blobs:n}}async function $Vt(e){let t=structuredClone(e.manifest);if(_Vt(t,e.sessionId),!await e.authorizeManifest(structuredClone(t)))throw new Error("Snapshot restoration is not authorized");e.signal?.throwIfAborted();let r=v3n(e.destination);if(await A8e(f8e(r))!==f8e(r))throw new Error("Snapshot destination parent must be canonical");try{throw await ufe(r),new Error("Snapshot destination already exists")}catch(o){if(o.code!=="ENOENT")throw o}let n=`${r}.staging-${y3n()}`;await vVt(n,{mode:448});for(let o of t.files){e.signal?.throwIfAborted();let s=await e.readBlob(o.sha256,o.size);if(s.byteLength!==o.size||w8e(s).value!==o.sha256)throw new Error("Snapshot blob integrity mismatch; staging retained");let a=g8e(n,...o.path.split("/"));await vVt(f8e(a),{recursive:!0,mode:448});let l=await m8e(a,"wx",o.executable?448:384);try{await l.writeFile(s),await l.sync()}finally{await l.close()}}e.signal?.throwIfAborted();let i=await m8e(g8e(n,".xeno-handoff-ready"),"wx",384);try{await i.writeFile(JSON.stringify({digest:t.digest,sessionId:t.sessionId})),await i.sync()}finally{await i.close()}return{directory:n,digest:t.digest,files:t.files.length,bytes:t.totalBytes}}function MVt(e){return typeof e=="string"&&S3n.test(e)}function PS(e){return`sha256:${k3n("sha256").update(e).digest("hex")}`}var Ce,ces,des,ues,nP,pes,EVt,c3n,d3n,u3n,p3n,lfe,gVt,f3n,AVt,pfe,iP,xVt,CVt,TVt,S3n,oP=we(()=>{"use strict";Ce=class extends Error{constructor(e,t,r={}){super(t),this.code=e,this.details=r,this.name="XenoCoordinationError"}code;details},ces=s3n(),des=a3n(),ues=IVt();nP="[redacted]",pes=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[redacted:private-key]"],[/((?:^|[\s{,;"'(\[])["']?(?:cookie|set-cookie)["']?\s*[:=]\s*["']?)(?!\[redacted)[^\s"',;]+(?:;\s*[^\s"',;=]+=[^\s"',;]*)*/gi,`$1${nP}`],[/((?:^|[\s{,;"'(\[])["']?(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-xeno-api-key|api[-_]?key|apikey|dpop)["']?\s*[:=]\s*["']?)(?:(?:Bearer|Basic|Token|DPoP)\s+)?(?!\[redacted)[^\s"',;]+/gi,`$1${nP}`],[/\b(Bearer|Basic|Token|DPoP)\s+[A-Za-z0-9._~+/=-]{6,}/gi,`$1 ${nP}`],[/\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|xeno-[A-Za-z0-9]{24,}|xrun_[A-Za-z0-9_-]{8,}|AIza[0-9A-Za-z_-]{30,}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9]{30,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g,nP],[/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,nP],[/([?&#;](?:access_token|refresh_token|id_token|token|key|api[_-]?key|secret|client_secret|password|signature|sig)=)[^&#\s"'<>]+/gi,`$1${nP}`],[/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@"']+:[^/\s@"']+@/gi,`$1${nP}@`]],EVt=class extends Error{constructor(e,t){super(t),this.code=e,this.name="QuotaError"}code;retryable=!1};c3n=3e4,d3n=3e4,u3n=6e4,p3n=2e4,lfe=new Set(["EACCES","EBUSY","EPERM"]),gVt=[5,10,20,40,80,160,320],f3n=[5,10,20,40,80,160,320],AVt=[1,2,3,4];pfe=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??qm.join(l3n(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${afe()}`),this.ownerLeaseMs=e.ownerLeaseMs??c3n,this.lockTimeoutMs=e.lockTimeoutMs??d3n,this.lockStaleMs=e.lockStaleMs??u3n,this.maximumEventsPerSession=e.maximumEventsPerSession??p3n}async getSessionState(e){let t=$r(e,"sessionId",1024);return Jd(await this.readState(t))}async fenceAdmission(e,t,r){let n=$r(r.authorityId,"authorityId",512),i=$r(r.operationId,"operationId",512);if(!Number.isSafeInteger(t)||t<0)throw new Ce("INVALID","Expected session version must be a nonnegative safe integer");if(r.action!=="archive"&&r.action!=="delete")throw new Ce("INVALID","Unsupported admission fence action");return this.mutate(e,o=>{let s=o.admissionFence;if(s?.authorityId===n&&s.operationId===i&&s.action===r.action)return s;if(o.version!==t)throw new Ce("CONFLICT","Session version changed before lifecycle fencing",{expected:t,actual:o.version});if(s?.authorityId===n&&s.action==="archive"&&r.action==="archive")return s;if(s&&!(s.authorityId===n&&s.action==="archive"&&r.action==="delete"))throw new Ce("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:n,operationId:i,action:r.action,createdAt:this.now()};return o.admissionFence=a,o.schemaVersion===1&&(o.schemaVersion=2),this.appendEvent(o,"admission.fenced",{data:{authorityId:n,operationId:i,action:r.action}}),a},!0)}async clearAdmissionFence(e,t,r,n){await this.mutate(e,i=>{this.assertVersion(e,i.version,t);let o=i.admissionFence;if(!o||o.authorityId!==r||o.operationId!==n)throw new Ce("CONFLICT","Lifecycle fence identity does not match");if(o.action==="delete")throw new Ce("CONFLICT","Deleted session admission cannot be restored");if(i.owner)throw new Ce("CONFLICT","Execution ownership must settle before restoration");i.admissionFence=void 0,this.appendEvent(i,"admission.restored",{data:{authorityId:r,operationId:n}})},!0)}async releaseDeadLifecycleOwner(e,t,r,n){await this.mutate(e,i=>{this.assertVersion(e,i.version,t);let o=i.admissionFence;if(!o||o.authorityId!==r||o.operationId!==n)throw new Ce("CONFLICT","Lifecycle fence identity does not match");let s=i.owner;if(s){if(s.host!==RS.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||dfe(s.processId))throw new Ce("CONFLICT","Execution owner exit has not been proved");i.owner=void 0,this.appendEvent(i,"ownership.released",{ownerId:s.ownerId,data:{epoch:s.epoch,reason:"fenced-local-owner-exited"}})}},!0)}async listSessionStates(){let e=qm.join(this.rootDirectory,"sessions"),t;try{t=await fi.readdir(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return(await Promise.all(t.filter(r=>r.endsWith(".json")).map(async r=>{try{let n=JSON.parse(await fi.readFile(qm.join(e,r),"utf8"));return!AVt.includes(n.schemaVersion)||typeof n.sessionId!="string"?void 0:((!Number.isSafeInteger(n.ownershipEpoch)||n.ownershipEpoch<0)&&(n.ownershipEpoch=Math.max(n.owner?.epoch??0,...n.handoffs.map(i=>i.targetLeaseEpoch??i.sourceLeaseEpoch??0))),n)}catch{return}}))).filter(r=>r!==void 0).sort((r,n)=>wI(n.updatedAt)-wI(r.updatedAt)).map(r=>Jd(r))}async createGoal(e){let t=$r(e.sessionId,"sessionId",1024),r=wVt(e.limits);return this.mutate(t,n=>{let i=n.goals.find(l=>["active","paused","waiting","blocked"].includes(l.status));if(i)throw new Ce("CONFLICT",`Session ${t} already has active goal ${i.id}`);let o=this.now(),s=(e.successCriteria??[]).map(l=>typeof l=="string"?{id:this.idFactory("criterion"),description:$r(l,"successCriteria"),required:!0}:{id:l.id?$r(l.id,"successCriteria.id",512):this.idFactory("criterion"),description:$r(l.description,"successCriteria.description"),required:l.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:t,objective:$r(e.objective,"objective"),...e.why?{why:$r(e.why,"why")}:{},successCriteria:s,constraints:cfe(e.constraints,"constraints"),...r?{limits:r}:{},metadata:Jd(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:m3n(o),verification:g3n(),steering:[],createdAt:o,updatedAt:o};return n.goals.push(a),this.appendEvent(n,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,t){let r=await this.getSessionState(e),n=t?r.goals.find(i=>i.id===t):[...r.goals].reverse().find(i=>["active","paused","waiting","blocked"].includes(i.status));return n?Jd(n):void 0}async updateGoal(e,t,r,n){return this.mutate(e,i=>{let o=this.requireGoal(i,t);if(this.assertVersion(o.id,o.version,r),["completed","cancelled","failed"].includes(o.status))throw new Ce("CONFLICT",`Goal ${o.id} is terminal (${o.status})`);let s=o.status!=="active";if(n.status==="active"&&o.status==="blocked"?o.status="active":n.status&&(o.status=n.status),n.objective!==void 0&&(o.objective=$r(n.objective,"objective")),n.why!==void 0&&(o.why=$r(n.why,"why")),n.constraints&&(o.constraints=cfe(n.constraints,"constraints")),n.successCriteria&&(o.successCriteria=Jd(n.successCriteria)),n.progress&&(o.progress={...o.progress,...Jd(n.progress),outstanding:cfe(n.progress.outstanding??o.progress.outstanding,"progress.outstanding"),decisions:cfe(n.progress.decisions??o.progress.decisions,"progress.decisions"),updatedAt:this.now()}),n.verification&&(o.verification=Jd(n.verification)),n.metadata&&(o.metadata=Jd(n.metadata)),s&&o.status==="active")for(let a of i.loops.filter(l=>l.goalId===t&&l.kind==="goal-continuation"&&l.status==="running"))a.resumeRequested=!0,a.version+=1,a.updatedAt=this.now();return o.version+=1,o.updatedAt=this.now(),this.appendEvent(i,"goal.updated",{goalId:o.id,data:{status:o.status,version:o.version}}),o},n.status!==void 0&&["paused","cancelled","failed"].includes(n.status))}async addMilestone(e,t,r,n){return this.mutateGoal(e,t,r,(i,o)=>{let s={id:this.idFactory("milestone"),title:$r(n.title,"milestone.title"),...n.description?{description:$r(n.description,"milestone.description")}:{},status:i.milestones.some(a=>a.status==="active")?"pending":"active",taskIds:[],createdAt:o,updatedAt:o};i.milestones.push(s),i.progress.currentMilestoneId??=s.id,i.progress.updatedAt=o})}async addTask(e,t,r,n){return this.mutateGoal(e,t,r,(i,o)=>{let s=i.milestones.find(c=>c.id===n.milestoneId);if(!s)throw new Ce("NOT_FOUND",`Milestone ${n.milestoneId} was not found`);if(n.parentTaskId&&!i.tasks.some(c=>c.id===n.parentTaskId))throw new Ce("NOT_FOUND",`Parent task ${n.parentTaskId} was not found`);let a=[...new Set(n.dependsOn??[])];for(let c of a)if(!i.tasks.some(d=>d.id===c))throw new Ce("NOT_FOUND",`Task dependency ${c} was not found`);let l={id:this.idFactory("task"),milestoneId:s.id,...n.parentTaskId?{parentTaskId:n.parentTaskId}:{},title:$r(n.title,"task.title"),...n.description?{description:$r(n.description,"task.description")}:{},status:a.length===0?"ready":"pending",...n.assignedAgentId?{assignedAgentId:$r(n.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:o,updatedAt:o};i.tasks.push(l),s.taskIds.push(l.id),s.updatedAt=o,i.progress.totalTaskCount=i.tasks.length,i.progress.outstanding=i.tasks.filter(c=>c.status!=="completed").map(c=>c.title),i.progress.updatedAt=o})}async updateTask(e,t,r,n,i){return this.mutateGoal(e,t,n,(o,s)=>{let a=o.tasks.find(c=>c.id===r);if(!a)throw new Ce("NOT_FOUND",`Task ${r} was not found`);a.status=i.status,i.progress!==void 0&&(a.progress=$r(i.progress,"task.progress")),i.resultEventId!==void 0&&(a.resultEventId=$r(i.resultEventId,"task.resultEventId",512)),i.assignedAgentId!==void 0&&(a.assignedAgentId=$r(i.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let l=o.milestones.find(c=>c.id===a.milestoneId);if(l){let c=o.tasks.filter(d=>d.milestoneId===l.id);c.length>0&&c.every(d=>d.status==="completed")?(l.status="completed",l.completedAt=s):c.some(d=>d.status==="running")?l.status="active":c.some(d=>d.status==="blocked")&&(l.status="blocked"),l.updatedAt=s}for(let c of o.tasks)c.status!=="pending"||!c.dependsOn?.length||c.dependsOn.every(d=>o.tasks.find(u=>u.id===d)?.status==="completed")&&(c.status="ready",c.updatedAt=s);this.recalculateProgress(o,s)})}async steerGoal(e,t,r,n){return this.mutateGoal(e,t,r,(i,o,s)=>{let a=this.idFactory("steer");i.steering.push({id:a,instruction:$r(n,"instruction"),createdAt:o}),this.appendEvent(s,"goal.steered",{goalId:t,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,t,r){let n=[];return{goal:await this.mutateGoal(e,t,r,(i,o)=>{n=i.steering.filter(s=>!s.consumedAt).map(({id:s,instruction:a,createdAt:l})=>({id:s,instruction:a,createdAt:l}));for(let s of i.steering)s.consumedAt||(s.consumedAt=o)}),instructions:n}}async completeGoal(e,t,r,n){if(n.status!=="passed")throw new Ce("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,i=>{let o=this.requireGoal(i,t);this.assertVersion(o.id,o.version,r);let s=o.successCriteria.filter(c=>c.required),a=s.filter(c=>{let d=n.criteria.find(u=>u.criterionId===c.id);return!d?.satisfied||d.evidence.length===0});if(a.length>0)throw new Ce("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(c=>c.id)});if(s.length===0&&n.evidence.length===0)throw new Ce("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let l=this.now();return o.status="completed",o.verification=Jd(n),o.verification.verifiedAt??=l,o.completedAt=l,o.updatedAt=l,o.version+=1,this.appendEvent(i,"goal.completed",{goalId:t,data:{evidence:o.verification.evidence}}),o},!0)}async cancelGoal(e,t,r,n){return this.mutate(e,i=>{let o=this.requireGoal(i,t);if(this.assertVersion(o.id,o.version,r),["completed","cancelled","failed"].includes(o.status))return o;o.status="cancelled",o.updatedAt=this.now(),o.version+=1,this.appendEvent(i,"goal.cancelled",{goalId:t,data:{reason:$r(n,"reason")}});for(let s of i.loops.filter(a=>a.goalId===t&&["running","paused","waiting"].includes(a.status)))s.status="stopped",s.resumeRequested!==void 0&&(s.resumeRequested=!1),s.stopReason=`Goal cancelled: ${n}`,s.stoppedAt=this.now(),s.updatedAt=s.stoppedAt,s.version+=1;return o},!0)}async startLoop(e){return this.mutate(e.sessionId,t=>this.createLoopRecord(t,e))}createLoopRecord(e,t){if(t.kind==="goal-continuation"&&!t.goalId)throw new Ce("INVALID","Goal-continuation loops require a goalId");if(t.goalId){let s=this.requireGoal(e,t.goalId);if(["completed","cancelled","failed"].includes(s.status))throw new Ce("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(t.kind==="scheduled"&&!t.schedule)throw new Ce("INVALID","Scheduled loops require schedule metadata");if(t.kind!=="scheduled"&&t.schedule)throw new Ce("INVALID","Only scheduled loops may carry schedule metadata");let r=h3n(t.schedule),n=e.loops.find(s=>s.goalId===t.goalId&&s.kind===t.kind&&["running","paused","waiting"].includes(s.status));if(n)throw new Ce("CONFLICT",`Loop ${n.id} is already active`);let i=this.now(),o={schemaVersion:1,id:this.idFactory("loop"),version:1,sessionId:e.sessionId,...t.goalId?{goalId:t.goalId}:{},kind:t.kind,status:"running",...t.activity?{currentActivity:$r(t.activity,"activity")}:{},iterations:[],...r?{schedule:r}:{},createdAt:i,updatedAt:i};return e.loops.push(o),this.appendEvent(e,"loop.started",{loopId:o.id,goalId:o.goalId,data:{kind:o.kind}}),o}async getLoop(e,t){let r=await this.getSessionState(e),n=t?r.loops.find(i=>i.id===t):[...r.loops].reverse().find(i=>["running","paused","waiting"].includes(i.status));return n?Jd(n):void 0}async beginLoopIteration(e,t,r,n,i){return this.mutateLoop(e,t,r,(o,s,a)=>{this.appendLoopIteration(a,o,s,n,i)},!1)}appendLoopIteration(e,t,r,n,i,o=!1){if(t.status!=="running")throw new Ce("CONFLICT",`Loop ${t.id} is ${t.status}`);if(t.goalId){let l=this.requireGoal(e,t.goalId);this.isCliGoal(l)&&this.initializeGoalTurnAccounting(e,l)}if(this.assertGoalIterationAdmission(e,t,r,o),t.iterations.some(l=>l.status==="running"))throw new Ce("CONFLICT",`Loop ${t.id} already has a running iteration`);let s=(t.iterations.at(-1)?.number??0)+1;t.currentActivity=$r(n,"activity");let a={number:s,startedAt:r,status:"running",activity:t.currentActivity,...t.goalId&&e.goalTurnAccounting?.[t.goalId]?{goalAccountingVersion:1}:{},...i?{taskId:$r(i,"taskId",512)}:{}};return t.iterations.push(a),t.resumeRequested!==void 0&&(t.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:t.id,goalId:t.goalId,data:{number:s,phase:"started",activity:t.currentActivity}}),a}async admitGoalTurn(e){return this.admitGoalTurnWithOwner(e)}async admitQuotaGoalTurn(e,t,r,n){let i=kVt(r),o=await this.getGoal(e.sessionId,e.goalId);if(!o||o.sessionId!==e.sessionId||o.limits?.maxTokens===void 0)throw new Ce("BUDGET_UNAVAILABLE","The exact token-bounded goal is unavailable for quota admission");if(this.isCliGoal(o)&&o.metadata["cli.tokenQuotaVersion"]!==1)throw new Ce("BUDGET_UNAVAILABLE","Legacy CLI goal token spend is unknown; quota admission requires creation-time provenance");if(i.goal?.id!==o.id||i.goal.generation!==o.createdAt)throw new Ce("BUDGET_UNAVAILABLE","Quota scope does not identify this durable goal generation");let s=await t.policy(i);if(!s||mVt(s.scope)!==mVt(i)||s.limits.tokensLifetime===void 0||s.limits.tokensLifetime===null||s.limits.tokensLifetime>o.limits.maxTokens)throw new Ce("BUDGET_UNAVAILABLE","Goal quota policy is absent or wider than the goal's explicit token limit");let a=await t.remainingTokens(i);if(a===null)throw new Ce("BUDGET_UNAVAILABLE","Goal token accounting has no durable remaining allowance");if(a<1)throw new Ce("BUDGET_EXCEEDED","Goal token allowance is exhausted");return this.admitGoalTurnWithOwner(e,n,{goalId:o.id,createdAt:o.createdAt,maximum:o.limits.maxTokens})}async admitOwnedGoalTurn(e,t){if(!t||!Number.isSafeInteger(t.epoch)||t.epoch<1)throw new Ce("INVALID","An exact execution ownership epoch is required");return this.admitGoalTurnWithOwner(e,{...t})}async admitGoalTurnWithOwner(e,t,r){let n=$r(e.requestId,"requestId",512),i=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,o=>{if(t){let d=this.requireOwner(o,t.ownerId,t.leaseId);if(d.epoch!==t.epoch)throw new Ce("NOT_OWNER","Execution ownership epoch changed");if(this.ownerExpired(d,this.now()))throw new Ce("LEASE_EXPIRED","Execution ownership expired");if(o.handoffs.some(u=>["prepared","available"].includes(u.status)&&u.sourceLeaseEpoch===d.epoch)||o.handoffs.some(u=>u.status==="claimed"&&u.targetLeaseEpoch===d.epoch))throw new Ce("UNSAFE_HANDOFF","Execution handoff has not settled")}let s=this.requireGoal(o,e.goalId);if(r&&(s.id!==r.goalId||s.createdAt!==r.createdAt||s.limits?.maxTokens!==r.maximum))throw new Ce("BUDGET_UNAVAILABLE","Goal token limit changed after quota verification");for(let d of o.loops.filter(u=>u.goalId===s.id)){let u=d.iterations.find(p=>p.goalTurn?.requestId===n);if(u){if(u.goalTurn?.requestHash!==i)throw new Ce("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(o,s,d,u),admitted:!1}}}if(this.assertVersion(s.id,s.version,e.expectedGoalVersion),s.status!=="active")throw new Ce("CONFLICT",`Goal ${s.id} is ${s.status}`);let a=[...o.loops].reverse().find(d=>d.goalId===s.id&&d.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!a||a.id!==e.expectedLoopId)throw new Ce("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(a.id,a.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new Ce("INVALID","A goal turn loop version requires its exact loop ID");if(a&&a.status!=="running")throw new Ce("CONFLICT",`Goal loop ${a.id} is ${a.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(o,s),a??=this.createLoopRecord(o,{sessionId:o.sessionId,goalId:s.id,kind:"goal-continuation"});let l=this.now(),c=this.appendLoopIteration(o,a,l,"Interactive goal turn",void 0,r!==void 0);if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new Ce("INVALID","Unknown goal execution lane");return c.goalTurn={requestId:n,requestHash:i,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:RS.hostname()}:{kind:"external"}},a.version+=1,a.updatedAt=l,{...this.goalTurnState(o,s,a,c),admitted:!0}},!1,o=>o.admitted)}async getGoalTurnState(e,t,r){let n=await this.getSessionState(e),i=t?n.goals.find(l=>l.id===t):[...n.goals].reverse().find(l=>["active","paused","waiting","blocked"].includes(l.status));if(!i)return;let o=n.loops.filter(l=>l.goalId===i.id),s=r?o.find(l=>l.iterations.some(c=>c.goalTurn?.requestId===r)):[...o].reverse().find(l=>l.kind==="goal-continuation"),a=r?s?.iterations.find(l=>l.goalTurn?.requestId===r):s?.iterations.at(-1);if(r&&!a)throw new Ce("NOT_FOUND","Goal turn was not found");return this.goalTurnState(n,i,s,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new Ce("INVALID","Invalid goal turn outcome");let t=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,r=>{let n=this.requireGoal(r,e.goalId),i=r.loops.find(s=>s.goalId===n.id&&s.iterations.some(a=>a.goalTurn?.requestId===e.requestId)),o=i?.iterations.find(s=>s.goalTurn?.requestId===e.requestId);if(!i||!o)throw new Ce("NOT_FOUND","Goal turn was not found");if(o.goalTurn?.requestHash!==t)throw new Ce("CONFLICT","Goal turn settlement identity does not match");return o.status==="running"&&(this.settleLoopIteration(r,i,o,this.now(),{status:n.status==="cancelled"||["stopped","failed"].includes(i.status)?"interrupted":e.status}),i.version+=1,i.updatedAt=this.now()),this.goalTurnState(r,n,i,o)},!0)}async recoverGoalTurn(e,t,r){return this.mutate(e,n=>{let i=this.requireGoal(n,t),o=n.loops.find(a=>a.goalId===t&&a.iterations.some(l=>l.goalTurn?.requestId===r)),s=o?.iterations.find(a=>a.goalTurn?.requestId===r);if(!o||!s)throw new Ce("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new Ce("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(n,o,s,this.now(),{status:"interrupted",error:"Original local SDK executor exited; inspect persisted results before retrying work"}),o.resumeRequested=i.status==="active"&&o.status==="running",o.version+=1,o.updatedAt=this.now()}return this.goalTurnState(n,i,o,s)},!0)}async finishLoopIteration(e,t,r,n){return this.mutateLoop(e,t,r,(i,o,s)=>{let a=[...i.iterations].reverse().find(l=>l.status==="running");if(!a)throw new Ce("CONFLICT",`Loop ${i.id} has no running iteration`);this.settleLoopIteration(s,i,a,o,n)},!1,!0)}settleLoopIteration(e,t,r,n,i){r.status=i.status,r.completedAt=n,i.verificationEventId&&(r.verificationEventId=$r(i.verificationEventId,"verificationEventId",512)),i.error&&(r.error=$r(i.error,"error")),t.status=["stopped","completed","failed"].includes(t.status)?t.status:e.admissionFence?"paused":i.nextStatus??(t.status==="paused"||t.status==="waiting"?t.status:"running"),this.appendEvent(e,"loop.iteration",{loopId:t.id,goalId:t.goalId,data:{number:r.number,phase:"finished",status:i.status}})}async setLoopStatus(e,t,r,n,i){return this.mutateLoop(e,t,r,(o,s,a)=>{let l=o.status;if(["stopped","completed","failed"].includes(l))throw new Ce("CONFLICT",`Loop ${o.id} is terminal (${l})`);let c=[...o.iterations].reverse().find(u=>u.status==="running");if(c&&n==="completed")throw new Ce("CONFLICT",`Loop ${o.id} cannot complete while iteration ${c.number} is running`);c&&(n==="stopped"||n==="failed")&&(c.status=n==="failed"?"failed":"interrupted",c.completedAt=s,c.error=$r(i??n,"reason")),o.status=n,o.kind==="goal-continuation"&&(o.resumeRequested=n==="running"),["stopped","completed","failed"].includes(n)&&(o.stoppedAt=s,o.stopReason=$r(i??n,"reason"));let d=n==="paused"?"loop.paused":n==="waiting"?"loop.waiting":n==="running"&&(l==="paused"||l==="waiting")?"loop.resumed":n==="completed"?"loop.completed":n==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,d,{loopId:t,goalId:o.goalId,data:{previous:l,status:n,...i?{reason:i}:{}}})},!1,n!=="running"&&n!=="waiting")}async acquireOwnership(e,t,r={}){return this.mutate(e,n=>{let i=this.now();if(n.owner&&!this.ownerExpired(n.owner,i)){if(n.owner.ownerId===t&&r.processId!==void 0&&n.owner.processId===r.processId&&(r.host===void 0||n.owner.host===r.host))return n.owner;throw new Ce("CONFLICT",`Session ${e} is owned by ${n.owner.ownerId}`,{owner:n.owner})}let o=n.owner&&this.ownerExpired(n.owner,i)?n.owner:void 0;if(o)for(let l of n.handoffs.filter(c=>c.status==="claimed"&&c.claimedBy===o.ownerId&&c.targetLeaseEpoch===o.epoch))l.status="failed",l.failureReason=`Claimed owner ${o.ownerId} lost its execution lease before completing the handoff.`,l.failedAt=i,l.updatedAt=i,l.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:l.id,goalId:l.goalId,loopId:l.loopId,data:{reason:l.failureReason,expiredLeaseId:o.leaseId}});let s=n.ownershipEpoch+1;for(let l of n.handoffs.filter(c=>["prepared","available"].includes(c.status)&&c.sourceLeaseEpoch<s))l.status="failed",l.failureReason="Source ownership epoch was superseded before the handoff was claimed.",l.failedAt=i,l.updatedAt=i,l.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:l.id,data:{epoch:s,reason:l.failureReason}});let a=this.newOwner(t,s,r,i);return n.owner=a,n.ownershipEpoch=s,this.appendEvent(n,"ownership.acquired",{ownerId:t,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,t,r,n=this.ownerLeaseMs){return this.mutate(e,i=>{let o=this.requireOwner(i,t,r);if(this.ownerExpired(o,this.now()))throw new Ce("LEASE_EXPIRED",`Ownership lease ${r} expired`);return o.heartbeatAt=this.now(),o.expiresAt=new Date(wI(o.heartbeatAt)+n).toISOString(),this.appendEvent(i,"ownership.renewed",{ownerId:t,data:{epoch:o.epoch,leaseId:r}}),o})}async recoverExpiredOwnership(e,t,r,n,i=this.ownerLeaseMs){return this.mutate(e,o=>{let s=this.requireOwner(o,t,r);if(s.processId!==n||s.host!==RS.hostname()||!dfe(n))throw new Ce("LEASE_EXPIRED",`Ownership lease ${r} expired and cannot be recovered by process ${n}`);let a=this.now(),l=Math.max(0,wI(a)-wI(s.expiresAt));return s.heartbeatAt=a,s.expiresAt=new Date(wI(a)+i).toISOString(),this.appendEvent(o,l>0?"ownership.recovered":"ownership.renewed",{ownerId:t,data:{epoch:s.epoch,leaseId:r,...l>0?{expiredForMs:l}:{}}}),s})}async releaseOwnership(e,t,r){return this.mutate(e,n=>{let i=this.requireOwner(n,t,r);for(let o of n.handoffs.filter(s=>s.status==="claimed"&&s.claimedBy===t&&s.targetLeaseEpoch===i.epoch))o.status="failed",o.failureReason="Target released execution ownership before completing the handoff.",o.failedAt=this.now(),o.updatedAt=o.failedAt,o.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:o.id,ownerId:t,data:{epoch:i.epoch,reason:o.failureReason}});return n.owner=void 0,this.appendEvent(n,"ownership.released",{ownerId:t,data:{epoch:i.epoch}}),i},!0)}async createHandoff(e){let t=!1,r=e.prepareRequestId===void 0?void 0:$r(e.prepareRequestId,"prepareRequestId",512);return this.mutate(e.sessionId,n=>{let i=this.requireOwner(n,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(i,this.now()))throw new Ce("LEASE_EXPIRED",`Ownership lease ${i.leaseId} expired`);if(r){let c=n.handoffs.find(d=>d.prepareRequestId===r);if(c){if(c.sourceOwnerId!==i.ownerId||c.sourceLeaseEpoch!==i.epoch||c.status!=="available"||c.targetOwnerId!==e.targetOwnerId||c.workspace!==e.workspace||c.goalId!==e.goalId||c.loopId!==e.loopId||c.contextDigest!==e.contextDigest||c.branch!==e.branch||c.currentMilestoneId!==e.currentMilestoneId||c.currentTaskId!==e.currentTaskId||JSON.stringify(c.agentIds)!==JSON.stringify([...new Set(e.agentIds??[])])||JSON.stringify(c.operations)!==JSON.stringify(e.operations??[]))throw new Ce("CONFLICT","Prepare identity was reused for different work or ownership");return t=!0,c}}let o=(e.operations??[]).filter(c=>c.status==="running"&&c.sideEffecting);if(o.length>0)throw new Ce("UNSAFE_HANDOFF","Running side-effecting operations must settle before execution handoff",{operationIds:o.map(c=>c.operationId)});if(e.goalId&&this.requireGoal(n,e.goalId),e.loopId&&!n.loops.some(c=>c.id===e.loopId))throw new Ce("NOT_FOUND",`Loop ${e.loopId} was not found`);let s=n.handoffs.find(c=>["prepared","available","claimed"].includes(c.status));if(s)throw new Ce("CONFLICT",`Handoff ${s.id} is already active`);let a=this.now(),l={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:n.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:i.ownerId,...r?{prepareRequestId:r}:{},...e.targetOwnerId?{targetOwnerId:$r(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:i.epoch,...e.workspace?{workspace:$r(e.workspace,"workspace",32768)}:{},...e.branch?{branch:$r(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:Jd(e.operations??[]),...e.contextDigest?{contextDigest:$r(e.contextDigest,"contextDigest",512)}:{},createdAt:a,updatedAt:a};return n.handoffs.push(l),this.appendEvent(n,"handoff.created",{handoffId:l.id,goalId:l.goalId,loopId:l.loopId,ownerId:i.ownerId,data:{targetOwnerId:l.targetOwnerId}}),l},!1,()=>!t)}async claimHandoff(e){let t,r=!1,n=e.claimRequestId===void 0?void 0:$r(e.claimRequestId,"claimRequestId",512);return{handoff:await this.mutate(e.sessionId,i=>{let o=i.handoffs.find(l=>l.id===e.handoffId);if(!o)throw new Ce("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(o.status!=="available"){let l=i.owner;if(n&&o.claimRequestId===n&&["claimed","completed"].includes(o.status)&&o.claimedBy===e.targetOwnerId&&l?.ownerId===e.targetOwnerId&&l.epoch===o.targetLeaseEpoch&&l.host===e.host&&l.processId===e.processId&&!this.ownerExpired(l,this.now()))return t=l,r=!0,o;throw new Ce("CONFLICT",`Handoff ${o.id} is ${o.status}`,{claimedBy:o.claimedBy})}if(o.targetOwnerId&&o.targetOwnerId!==e.targetOwnerId)throw new Ce("CONFLICT",`Handoff ${o.id} is reserved for ${o.targetOwnerId}`);let s=i.owner;if(!s||s.ownerId!==o.sourceOwnerId||s.epoch!==o.sourceLeaseEpoch)throw new Ce("CONFLICT",`Handoff ${o.id} no longer matches the source ownership epoch`);let a=this.now();return t=this.newOwner(e.targetOwnerId,s.epoch+1,{processId:e.processId,host:e.host,leaseMs:e.leaseMs},a),i.owner=t,i.ownershipEpoch=t.epoch,o.status="claimed",o.claimedBy=e.targetOwnerId,n&&(o.claimRequestId=n),o.targetOwnerId=e.targetOwnerId,o.targetLeaseEpoch=t.epoch,o.claimedAt=a,o.updatedAt=a,o.version+=1,this.appendEvent(i,"handoff.claimed",{handoffId:o.id,goalId:o.goalId,loopId:o.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:o.sourceOwnerId,epoch:t.epoch}}),o},!1,()=>!r),owner:Jd(t)}}async completeHandoff(e,t,r,n){let i=!1;return this.mutate(e,o=>{let s=this.requireOwner(o,r,n);if(this.ownerExpired(s,this.now()))throw new Ce("LEASE_EXPIRED",`Ownership lease ${n} expired`);let a=o.handoffs.find(l=>l.id===t);if(!a)throw new Ce("NOT_FOUND",`Handoff ${t} was not found`);if(a.claimedBy!==r||a.targetLeaseEpoch!==s.epoch||!["claimed","completed"].includes(a.status))throw new Ce("CONFLICT",`Handoff ${a.id} cannot be completed by ${r}`);return a.status==="completed"?(i=!0,a):(a.status="completed",a.completedAt=this.now(),a.updatedAt=a.completedAt,a.version+=1,this.appendEvent(o,"handoff.completed",{handoffId:t,goalId:a.goalId,loopId:a.loopId,ownerId:r,data:{epoch:o.owner?.epoch}}),a)},!1,()=>!i)}async cancelHandoff(e,t,r,n){let i=!1;return this.mutate(e,o=>{let s=o.handoffs.find(l=>l.id===t);if(!s)throw new Ce("NOT_FOUND",`Handoff ${t} was not found`);if(s.sourceOwnerId!==r)throw new Ce("CONFLICT",`Handoff ${t} was not offered by ${r}`);if(s.status==="cancelled")return i=!0,s;if(s.status!=="available"&&s.status!=="prepared")throw new Ce("CONFLICT",`Handoff ${t} is ${s.status} and can no longer be cancelled`);let a=this.requireOwner(o,r,n);if(this.ownerExpired(a,this.now()))throw new Ce("LEASE_EXPIRED",`Ownership lease ${n} expired`);if(s.sourceLeaseEpoch!==a.epoch)throw new Ce("CONFLICT",`Handoff ${t} belongs to an earlier ownership epoch`);return s.status="cancelled",s.cancelledAt=this.now(),s.updatedAt=s.cancelledAt,s.version+=1,this.appendEvent(o,"handoff.cancelled",{handoffId:t,goalId:s.goalId,loopId:s.loopId,ownerId:r,data:{epoch:a.epoch}}),s},!1,()=>!i)}async failHandoff(e,t,r){return this.mutate(e,n=>{let i=n.handoffs.find(o=>o.id===t);if(!i)throw new Ce("NOT_FOUND",`Handoff ${t} was not found`);return["completed","cancelled","failed"].includes(i.status)||(i.status="failed",i.failureReason=$r(r,"reason"),i.failedAt=this.now(),i.updatedAt=i.failedAt,i.version+=1,this.appendEvent(n,"handoff.failed",{handoffId:t,goalId:i.goalId,loopId:i.loopId,data:{reason:i.failureReason}})),i},!0)}async mutateGoal(e,t,r,n,i=!0){return this.mutate(e,o=>{let s=this.requireGoal(o,t);this.assertVersion(s.id,s.version,r);let a=this.now();return n(s,a,o),s.version+=1,s.updatedAt=a,i&&this.appendEvent(o,"goal.updated",{goalId:t,data:{status:s.status,version:s.version}}),s})}async mutateLoop(e,t,r,n,i=!0,o=!1){return this.mutate(e,s=>{let a=s.loops.find(c=>c.id===t);if(!a)throw new Ce("NOT_FOUND",`Loop ${t} was not found`);this.assertVersion(a.id,a.version,r);let l=this.now();return n(a,l,s),a.version+=1,a.updatedAt=l,i&&this.appendEvent(s,"loop.iteration",{loopId:t,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},o)}assertGoalIterationAdmission(e,t,r,n=!1){if(!t.goalId)return;let i=this.requireGoal(e,t.goalId);if(i.status!=="active")throw new Ce("CONFLICT",`Goal ${i.id} is ${i.status}; no iteration was admitted`);let o=wVt(i.limits);if(o?.maxTokens!==void 0&&!n)throw new Ce("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:i.id,limit:"maxTokens"});if(o?.maxWallClockMs!==void 0){let s=Date.parse(i.createdAt),a=Date.parse(r);if(!Number.isFinite(s)||!Number.isFinite(a)||a<s)throw new Ce("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:i.id,limit:"maxWallClockMs"});if(a-s>=o.maxWallClockMs)throw new Ce("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:i.id,limit:"maxWallClockMs",maximum:o.maxWallClockMs})}if(o?.maxIterations!==void 0){let s=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,i):void 0;if(s?.coverage==="partial")throw new Ce("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let a=this.goalIterationCount(e,i)+(s?.baseIterations??0);if(!Number.isSafeInteger(a)||a<0)throw new Ce("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(a>=o.maxIterations)throw new Ce("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:i.id,limit:"maxIterations",admitted:a,maximum:o.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,t){let r=0;for(let n of e.loops.filter(i=>i.goalId===t.id)){if(!Array.isArray(n.iterations))throw new Ce("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let i=0;for(let o of n.iterations){if(!o||!Number.isSafeInteger(o.number)||o.number<=i)throw new Ce("BUDGET_UNAVAILABLE","Goal iteration history is invalid");i=o.number}if(r+=i,!Number.isSafeInteger(r))throw new Ce("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return r}resolveGoalTurnAccounting(e,t){let r=e.goalTurnAccounting;if(r!==void 0&&(!r||typeof r!="object"||Array.isArray(r)))throw new Ce("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(r&&Object.hasOwn(r,t.id)){let a=r[t.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new Ce("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===t.id&&a.iterations.some(l=>l.goalTurn||l.goalAccountingVersion)))throw new Ce("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let n=this.goalIterationCount(e,t),i=t.metadata["cli.accountedTurns"],o=typeof i=="number"&&Number.isSafeInteger(i)&&i>=0,s=this.isCliGoal(t)&&(!o||i>0&&n>0);return{schemaVersion:1,baseIterations:o&&n===0?i:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,t){let r=this.resolveGoalTurnAccounting(e,t);if(r.coverage==="partial"&&t.limits?.maxIterations!==void 0)throw new Ce("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,t.id,{value:r,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let t=$r(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Ce("INVALID","Goal turn requestHash must be a SHA-256 digest");return t}goalTurnState(e,t,r,n){let i=this.resolveGoalTurnAccounting(e,t),o=this.goalIterationCount(e,t)+i.baseIterations;if(!Number.isSafeInteger(o))throw new Ce("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return Jd({goal:t,admittedTurns:o,accountingCoverage:i.coverage,...r?{loopId:r.id,loopVersion:r.version,loopStatus:r.status,resumeRequested:r.resumeRequested===!0}:{},...n?{iterationNumber:n.number,iterationStatus:n.status,...n.goalTurn?{requestId:n.goalTurn.requestId,requestHash:n.goalTurn.requestHash}:{},canRecover:n.status==="running"&&this.goalTurnOwnerExited(n)}:{}})}goalTurnOwnerExited(e){let t=e.goalTurn?.executor;if(t?.kind!=="local-sdk"||t.host!==RS.hostname()||!Number.isSafeInteger(t.processId)||t.processId<=0)return!1;try{return process.kill(t.processId,0),!1}catch(r){return r.code==="ESRCH"}}recalculateProgress(e,t){let r=e.tasks.filter(n=>n.status==="completed").length;e.progress.completedTaskCount=r,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(r/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(n=>!["completed","cancelled"].includes(n.status)).map(n=>n.title),e.progress.updatedAt=t}requireGoal(e,t){let r=e.goals.find(n=>n.id===t);if(!r)throw new Ce("NOT_FOUND",`Goal ${t} was not found`);return r}requireOwner(e,t,r){let n=e.owner;if(!n||n.ownerId!==t||n.leaseId!==r)throw new Ce("NOT_OWNER",`${t} does not own session ${e.sessionId}`,{owner:n});return n}assertVersion(e,t,r){if(!Number.isInteger(r)||r<1||t!==r)throw new Ce("CONFLICT",`Expected ${e} version ${r}, found ${t}`,{expected:r,actual:t})}newOwner(e,t,r,n){let i=r.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(i)||i<1)throw new Ce("INVALID","leaseMs must be a positive safe integer");return{ownerId:$r(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:t,acquiredAt:n,heartbeatAt:n,expiresAt:new Date(wI(n)+i).toISOString(),...r.processId!==void 0?{processId:r.processId}:{},...r.host?{host:$r(r.host,"host",512)}:{}}}ownerExpired(e,t){return wI(e.expiresAt)<=wI(t)?!0:e.processId!==void 0&&e.host===RS.hostname()&&!dfe(e.processId)}appendEvent(e,t,r){let n={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:t,sessionId:e.sessionId,...r.goalId?{goalId:r.goalId}:{},...r.loopId?{loopId:r.loopId}:{},...r.handoffId?{handoffId:r.handoffId}:{},...r.ownerId?{ownerId:r.ownerId}:{},timestamp:this.now(),data:Jd(r.data)};e.events.push(n),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,t,r=!1,n=()=>!0){let i=$r(e,"sessionId",1024);return this.withSessionLock(i,async()=>{let o=await this.readState(i);if(o.admissionFence&&!r)throw new Ce("CONFLICT","Session execution is blocked by a persisted lifecycle fence");let s=o.schemaVersion;this.promoteGoalBudgetEnvelope(o),o.schemaVersion!==s&&await this.writeState(o);let a=t(o);return n(a)&&(o.version+=1,o.updatedAt=this.now(),await this.writeState(o)),Jd(a)})}statePath(e){return qm.join(this.rootDirectory,"sessions",`${yVt(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let t=this.statePath(e);try{let r=await fi.readFile(t,"utf8"),n=JSON.parse(r);if(!AVt.includes(n.schemaVersion)||n.sessionId!==e)throw new Ce("INVALID",`Coordination state at ${t} does not match session ${e}`);if(n.admissionFence!==void 0){let i=n.admissionFence;if(!i||i.schemaVersion!==1||typeof i.authorityId!="string"||!i.authorityId.trim()||typeof i.operationId!="string"||!i.operationId.trim()||!["archive","delete"].includes(i.action)||!Number.isFinite(Date.parse(i.createdAt)))throw new Ce("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(n.ownershipEpoch)||n.ownershipEpoch<0)&&(n.ownershipEpoch=Math.max(n.owner?.epoch??0,...n.handoffs.map(i=>i.targetLeaseEpoch??i.sourceLeaseEpoch??0))),n}catch(r){if(r.code!=="ENOENT")throw r;let n=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:n,updatedAt:n}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(t=>t.resumeRequested!==void 0||t.iterations.some(r=>r.goalTurn!==void 0)))&&(e.schemaVersion=4),e.schemaVersion<3&&e.goals.some(t=>t.limits!==void 0&&(!t.limits||typeof t.limits!="object"||Array.isArray(t.limits)||Object.keys(t.limits).length>0))&&(e.schemaVersion=3)}async writeState(e){this.promoteGoalBudgetEnvelope(e);let t=this.statePath(e.sessionId),r=qm.dirname(t);await fi.mkdir(r,{recursive:!0});let n=`${t}.${process.pid}.${afe()}.tmp`,i=await fi.open(n,"wx");try{await i.writeFile(`${JSON.stringify(e,null,2)}
|
|
3220
3220
|
`,"utf8"),await i.sync()}finally{await i.close()}try{await this.renameReplacing(n,t);try{let o=await fi.open(r,"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{await fi.unlink(n).catch(()=>{})}}async renameReplacing(e,t){for(let r=0;;r+=1)try{await fi.rename(e,t);return}catch(n){let i=n.code,o=gVt[r];if(process.platform!=="win32"||!i||!lfe.has(i)||o===void 0)throw n;await new Promise(s=>setTimeout(s,o))}}async withSessionLock(e,t){let r=this.lockPath(e),n=qm.join(r,"owner.json"),i=afe(),o=`${r}.candidate.${i}`,s=Date.now();await fi.mkdir(qm.dirname(r),{recursive:!0});let a={schemaVersion:1,token:i,pid:process.pid,host:RS.hostname(),acquiredAt:this.now()};await fi.mkdir(o),await fi.writeFile(qm.join(o,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let l=0;;l+=1)try{await fi.rename(o,r);break}catch(c){let d=c.code;if(!(d&&new Set(["EEXIST","ENOTEMPTY","ENOTDIR","EBUSY"]).has(d)||process.platform==="win32"&&d&&lfe.has(d)))throw await fi.rm(o,{recursive:!0,force:!0}).catch(()=>{}),c;let u=await this.staleLockOwner(r,n);if(u){await this.quarantineLock(r,u.token,"stale");continue}if(Date.now()-s>=this.lockTimeoutMs)throw await fi.rm(o,{recursive:!0,force:!0}).catch(()=>{}),new Ce("CONFLICT",`Timed out waiting for coordination lock for session ${e}`);await new Promise(p=>setTimeout(p,Math.min(100,5+l*5)+Math.floor(Math.random()*10)))}try{return await t()}finally{await this.quarantineLock(r,i,"released"),await fi.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,t){try{let[r,n]=await Promise.all([fi.readFile(t,"utf8").catch(()=>""),fi.stat(e)]),i=r?JSON.parse(r):void 0;return!i||i.host!==RS.hostname()||dfe(i.pid)?void 0:Date.now()-n.mtimeMs>this.lockStaleMs?i:void 0}catch{return}}async quarantineLock(e,t,r){let n=qm.join(e,"owner.json"),i=r==="stale"?`${e}.stale.${yVt(t)}`:`${e}.${r}.${t}.${afe()}`;for(let o=0;;o+=1){let s;try{s=JSON.parse(await fi.readFile(n,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==t)return;try{await fi.rename(e,i);break}catch(a){let l=a.code;if(r==="stale")try{if(JSON.parse(await fi.readFile(qm.join(i,"owner.json"),"utf8")).token===t)return}catch{}if(l==="ENOENT"||l==="EEXIST")return;let c=gVt[o];if(process.platform!=="win32"||!l||!lfe.has(l)||c===void 0)throw a;await new Promise(d=>setTimeout(d,c))}}if(r!=="stale")for(let o=0;;o+=1)try{await fi.rm(i,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let l=f3n[o];if(process.platform!=="win32"||!a||!lfe.has(a)||l===void 0)throw s;await new Promise(c=>setTimeout(c,l))}}},iP=class{sessionId;ownerId;store;processId;host;leaseMs;heartbeatMs;claimHandoffId;claimRequestId;onOwnershipLost;prepareDestination;destinationTimeoutMs;initializationAbort=new AbortController;timer;heartbeatInFlight=!1;owner;ready=!1;starting;stopping;stopped=!1;lostError;preparedHandoffId;preparingHandoff=!1;handoffOutcomeUncertain=!1;constructor(e){if(this.store=e.store??new pfe,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??w3n(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${A3n().slice(0,8)}`,this.leaseMs=e.leaseMs??3e4,this.heartbeatMs=e.heartbeatMs??Math.max(250,Math.floor(this.leaseMs/3)),this.heartbeatMs>=this.leaseMs)throw new Error("heartbeatMs must be shorter than leaseMs");if(this.claimHandoffId=e.claimHandoffId,this.claimRequestId=e.claimRequestId,this.onOwnershipLost=e.onOwnershipLost,this.prepareDestination=e.prepareDestination,this.destinationTimeoutMs=e.destinationTimeoutMs??Math.min(1e4,Math.floor(this.leaseMs/2)),!Number.isSafeInteger(this.destinationTimeoutMs)||this.destinationTimeoutMs<1||this.destinationTimeoutMs>=this.leaseMs)throw new Error("destinationTimeoutMs must be a positive integer shorter than leaseMs")}get currentOwner(){return this.active&&this.owner?structuredClone(this.owner):void 0}get active(){return this.ready&&!!this.owner&&!this.stopped&&this.lostError===void 0&&!this.preparingHandoff&&!this.preparedHandoffId}async start(){if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.lostError!==void 0)throw this.lostError;return this.ready&&this.owner?(this.assertExecutionAllowed(),structuredClone(this.owner)):(this.starting??=this.initialize(),structuredClone(await this.starting))}async initialize(){try{if(this.claimHandoffId){let e=await this.store.claimHandoff({sessionId:this.sessionId,handoffId:this.claimHandoffId,targetOwnerId:this.ownerId,processId:this.processId,host:this.host,leaseMs:this.leaseMs,...this.claimRequestId?{claimRequestId:this.claimRequestId}:{}});if(this.owner=e.owner,this.stopped)throw new Error("Execution lease session has already stopped");if(this.prepareDestination&&await this.prepareClaimedDestination(e.handoff),this.stopped)throw new Error("Execution lease session has already stopped");await this.store.completeHandoff(this.sessionId,this.claimHandoffId,this.ownerId,this.owner.leaseId)}else this.owner=await this.store.acquireOwnership(this.sessionId,this.ownerId,{processId:this.processId,host:this.host,leaseMs:this.leaseMs});if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.owner=await this.store.renewOwnership(this.sessionId,this.ownerId,this.owner.leaseId,this.leaseMs),this.stopped)throw new Error("Execution lease session has already stopped");return this.ready=!0,this.timer=setInterval(()=>{this.heartbeat()},this.heartbeatMs),this.timer.unref?.(),structuredClone(this.owner)}catch(e){throw this.ready=!1,this.markLost(e instanceof Error?e:new Error("Execution lease initialization failed",{cause:e})),this.lostError}}async prepareClaimedDestination(e){let t=this.initializationAbort.signal,r,n;try{let i=new Promise((o,s)=>{n=()=>s(t.reason??new Error("Destination preparation cancelled")),t.addEventListener("abort",n,{once:!0}),r=setTimeout(()=>this.initializationAbort.abort(new Error("Destination preparation timed out")),this.destinationTimeoutMs),t.aborted&&n()});await Promise.race([i,Promise.resolve().then(()=>(t.throwIfAborted(),this.prepareDestination({handoff:structuredClone(e),signal:t})))]),t.throwIfAborted()}finally{r&&clearTimeout(r),n&&t.removeEventListener("abort",n)}}async assertOwned(){this.assertExecutionAllowed();let e=await this.renewHeldLease();return this.assertExecutionAllowed(),e}assertExecutionAllowed(){if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(this.preparingHandoff)throw new Error("Execution surface is preparing a handoff and is detached from mutation");if(this.preparedHandoffId)throw new Error(`Execution surface prepared handoff ${this.preparedHandoffId} and is detached from mutation`);if(!this.ready||!this.owner)throw new Error("Execution ownership was not started")}async renewHeldLease(){if(!this.owner)throw new Error("Execution ownership was not started");try{let e=await this.renewOrRecover(this.owner.leaseId);if(this.stopped)throw new Error("Execution surface is detached");return this.owner=e,structuredClone(this.owner)}catch(e){throw this.markLost(e),e}}async renewOrRecover(e){try{return await this.store.renewOwnership(this.sessionId,this.ownerId,e,this.leaseMs)}catch(t){if(!(t instanceof Error&&"code"in t&&t.code==="LEASE_EXPIRED")||!this.store.recoverExpiredOwnership||this.preparingHandoff||this.preparedHandoffId||this.stopped)throw t;return this.store.recoverExpiredOwnership(this.sessionId,this.ownerId,e,this.processId,this.leaseMs)}}async prepareHandoff(e={}){if(this.preparedHandoffId)throw new Error(`Handoff ${this.preparedHandoffId} is already prepared`);this.assertExecutionAllowed(),this.preparingHandoff=!0;try{let t=await this.renewHeldLease();this.handoffOutcomeUncertain=!0;let r=await this.store.createHandoff({...e,sessionId:this.sessionId,sourceOwnerId:t.ownerId,sourceLeaseId:t.leaseId});return this.preparedHandoffId=r.id,this.handoffOutcomeUncertain=!1,r}catch(t){throw this.markLost(t instanceof Error?t:new Error("Handoff preparation failed",{cause:t})),t}finally{this.preparingHandoff=!1}}async cancelPreparedHandoff(){let e=this.preparedHandoffId;if(!e)throw new Error("No prepared handoff to cancel");if(!this.store.cancelHandoff)throw new Error("This execution store cannot cancel a prepared handoff");if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(!this.owner)throw new Error("Execution ownership was not started");let t=await this.store.cancelHandoff(this.sessionId,e,this.ownerId,this.owner.leaseId);if(t.id!==e||t.status!=="cancelled")throw new Error(`Handoff ${e} was not cancelled`);return this.preparedHandoffId=void 0,await this.renewHeldLease(),t}async stop(e={}){return this.stopping?this.stopping:(this.stopped=!0,this.ready=!1,this.initializationAbort.abort(new Error("Execution lease session has already stopped")),this.timer&&clearInterval(this.timer),this.timer=void 0,this.stopping=this.finishStop(e),this.stopping)}async finishStop(e){await this.starting?.catch(()=>{});let t=this.owner;if(this.owner=void 0,!(e.release===!1||this.preparedHandoffId||this.handoffOutcomeUncertain||!t))try{await this.store.releaseOwnership(this.sessionId,t.ownerId,t.leaseId)}catch{}}async heartbeat(){if(!(!this.ready||!this.owner||this.stopped||this.lostError!==void 0||this.heartbeatInFlight)){this.heartbeatInFlight=!0;try{await this.renewHeldLease()}catch(e){this.markLost(e)}finally{this.heartbeatInFlight=!1}}}markLost(e){this.lostError===void 0&&(this.lostError=e,this.timer&&clearInterval(this.timer),this.timer=void 0,this.onOwnershipLost?.(e))}};xVt=1e4,CVt=8*1024*1024,TVt=64*1024*1024;S3n=/^sha256:[0-9a-f]{64}$/});var OVt=we(()=>{"use strict"});function NVt(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(t.success===!1)return typeof t.error=="string";if(t.success!==!0||!t.snapshot||typeof t.snapshot!="object"||Array.isArray(t.snapshot))return!1;let r=t.snapshot,n=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,i=(o,s,a,l=!1)=>Array.isArray(o)&&o.every(c=>c&&typeof c=="object"&&!Array.isArray(c)&&typeof c[s]=="string"&&n(c[a])&&(!l||c.cost===null));return r.source==="local-runtime-journal"&&r.billingStatus==="unavailable"&&r.totalCost===null&&typeof r.observedAt=="string"&&Number.isFinite(Date.parse(r.observedAt))&&n(r.totalTokens)&&n(r.totalRequests)&&n(r.unmeasuredRequests)&&r.unmeasuredRequests<=r.totalRequests&&i(r.dailyUsage,"label","value")&&i(r.weeklyUsage,"label","value")&&i(r.monthlyUsage,"label","value")&&i(r.costByModel,"model","tokens",!0)&&i(r.topAgents,"name","tokens",!0)}var DVt=we(()=>{"use strict"});var LVt=we(()=>{"use strict"});function FVt(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.success===!1?typeof t.error=="string":t.success===!0&&t.source==="local-runtime-journal"&&typeof t.observedAt=="string"&&Number.isFinite(Date.parse(t.observedAt))&&typeof t.complete=="boolean"&&(t.complete?t.nextCursor===null:typeof t.nextCursor=="string"&&t.nextCursor.length>0&&t.nextCursor.length<=4096)&&Array.isArray(t.entries)&&t.entries.length<=1e4&&t.entries.every(r=>r&&typeof r=="object"&&["id","timestamp","action","actor","target","details"].every(n=>typeof r[n]=="string")&&Number.isFinite(Date.parse(r.timestamp)))}var UVt=we(()=>{"use strict"});function GVt(e){return!y8e(e)||typeof e.success!="boolean"||e.error!==void 0&&(typeof e.error!="string"||e.error.length>1e3)?!1:e.success?e.content!==void 0&&(typeof e.content!="string"||e.content.length>128e3)||e.loadedModel!==void 0&&!QVt(e.loadedModel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length>1e3||!e.models.every(t=>y8e(t)&&QVt(t.id)&&typeof t.name=="string"&&t.name.length<=512&&(t.contextWindowTokens===void 0||Number.isSafeInteger(t.contextWindowTokens)&&t.contextWindowTokens>0)))||e.usage!==void 0&&(!y8e(e.usage)||!["inputTokens","outputTokens"].every(t=>Number.isSafeInteger(e.usage[t])&&(e.usage[t]??-1)>=0))?!1:e.content!==void 0||e.models!==void 0||e.loadedModel!==void 0:typeof e.error=="string"&&!!e.error}var y8e,QVt,jVt=we(()=>{"use strict";y8e=e=>!!e&&typeof e=="object"&&!Array.isArray(e),QVt=e=>typeof e=="string"&&e.length>0&&e.length<=512&&!/[\x00-\x1f\x7f]/.test(e)});var Pes,HVt=we(()=>{"use strict";Pes=new TextEncoder});function T3n(e){return b8e(e)&&typeof e.method=="string"&&C3n.has(e.method)&&typeof e.url=="string"&&e.url.length<=2048&&e.url.startsWith("https://")}function VVt(e){if(e===null)return!0;if(!b8e(e))return!1;let t=(r,n)=>typeof r=="string"&&r.length>0&&r.length<=n&&!/[\s\r\n]/.test(r.replace(/^(Bearer|DPoP) /,""));return t(e.authorization,16384)&&/^(Bearer|DPoP) /.test(e.authorization)&&(e.dpop===void 0||t(e.dpop,8192))}function qVt(e){return b8e(e)&&e.kind==="host-request"&&typeof e.id=="string"&&e.id.length>0&&e.method===x3n&&T3n(e.input)}var x3n,C3n,b8e,WVt=we(()=>{"use strict";x3n="account.authorize",C3n=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),b8e=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var JVt=we(()=>{"use strict"});var zVt=we(()=>{"use strict"});var v8e,XVt=we(()=>{"use strict";v8e="1.0.0"});var nqt={};$o(nqt,{TERMINAL_WEB_JOB_STATES:()=>ffe,WEB_JOB_PROGRESS_OPERATIONS:()=>E8e,WEB_JOB_PROGRESS_SCHEMA:()=>sP,WEB_JOB_PROGRESS_SCHEMA_VERSION:()=>UW,WEB_JOB_PROGRESS_STATES:()=>k8e,deriveWebJobProgress:()=>hfe,isTerminalWebJobState:()=>yI,isWebJobProgress:()=>x8e,parseWebJobProgress:()=>QW,webJobProgressSignature:()=>C8e});function yI(e){return ffe.includes(e)}function KVt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ZVt(e,t){return Object.keys(e).every(r=>t.has(r))}function S8e(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/u.test(e)}function I8e(e){return S8e(e,64)&&Number.isFinite(Date.parse(e))}function rqt(e){return S8e(e,120)&&/^[A-Za-z0-9._:-]+$/u.test(e)}function eqt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function QW(e){if(!KVt(e)||!ZVt(e,R3n))throw new TypeError("invalid Web Context progress object");if(e.schema!==sP||e.schemaVersion!==UW||e.contractVersion!==v8e)throw new TypeError("unsupported Web Context progress schema");if(!S8e(e.jobId,256))throw new TypeError("invalid Web Context progress jobId");if(!E8e.includes(e.operation))throw new TypeError("invalid Web Context progress operation");if(!k8e.includes(e.state))throw new TypeError("invalid Web Context progress state");let t=yI(e.state);if(e.terminal!==t)throw new TypeError("inconsistent Web Context terminal state");if(t){if(e.terminalState!==e.state)throw new TypeError("invalid Web Context terminalState")}else if("terminalState"in e)throw new TypeError("non-terminal Web Context progress cannot carry terminalState");if("terminalReason"in e&&(!t||!rqt(e.terminalReason)))throw new TypeError("invalid Web Context terminalReason");if(!KVt(e.counters)||!ZVt(e.counters,YVt))throw new TypeError("invalid Web Context progress counters");for(let n of YVt)if(!eqt(e.counters[n]))throw new TypeError(`invalid Web Context counter ${n}`);let r=Number(e.counters.queuedPages)+Number(e.counters.activePages)+Number(e.counters.completedPages)+Number(e.counters.failedPages)+Number(e.counters.excludedPages);if(e.counters.knownPages!==r)throw new TypeError("inconsistent Web Context knownPages counter");if(!eqt(e.sequence))throw new TypeError("invalid Web Context progress sequence");if(!I8e(e.observedAt))throw new TypeError("invalid Web Context observedAt");if("createdAt"in e&&!I8e(e.createdAt))throw new TypeError("invalid Web Context createdAt");if("updatedAt"in e&&!I8e(e.updatedAt))throw new TypeError("invalid Web Context updatedAt");return structuredClone(e)}function x8e(e){try{return QW(e),!0}catch{return!1}}function FW(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function tqt(e){return typeof e=="string"&&e.length>0?e:void 0}function hfe(e,t,r=new Date().toISOString()){let n=FW(e.queuedPages),i=FW(e.activePages),o=FW(e.completedPages),s=FW(e.failedPages),a=FW(e.excludedPages),l={queuedPages:n,activePages:i,completedPages:o,failedPages:s,excludedPages:a,knownPages:n+i+o+s+a},c=yI(e.state),d=rqt(e.terminalReason)?e.terminalReason:void 0,u=tqt(e.createdAt),p=tqt(e.updatedAt);return{schema:sP,schemaVersion:UW,contractVersion:v8e,jobId:e.jobId,operation:e.operation,state:e.state,terminal:c,...c?{terminalState:e.state}:{},...d?{terminalReason:d}:{},counters:l,sequence:t,observedAt:r,...u?{createdAt:u}:{},...p?{updatedAt:p}:{}}}function C8e(e){let t=e.counters;return[e.jobId,e.operation,e.state,e.terminalReason??"",e.updatedAt??"",t.queuedPages,t.activePages,t.completedPages,t.failedPages,t.excludedPages].join("|")}var sP,UW,ffe,E8e,k8e,R3n,YVt,xD=we(()=>{"use strict";XVt();sP="xeno.web-context.job-progress",UW="1.0.0",ffe=["completed","partial","failed","cancelled"],E8e=["scrape","batch-scrape","map","crawl","render","extract"],k8e=["queued","running",...ffe];R3n=new Set(["schema","schemaVersion","contractVersion","jobId","operation","state","terminal","terminalState","terminalReason","counters","sequence","observedAt","createdAt","updatedAt"]),YVt=new Set(["queuedPages","activePages","completedPages","failedPages","excludedPages","knownPages"])});var iqt=we(()=>{"use strict"});var oqt=we(()=>{"use strict"});var sqt=we(()=>{"use strict"});var aqt=we(()=>{"use strict"});var lqt=we(()=>{"use strict"});var cqt=we(()=>{"use strict";lqt()});var dqt=we(()=>{"use strict"});var uqt=we(()=>{"use strict"});var pqt=we(()=>{"use strict"});var fqt=we(()=>{"use strict"});var P3n,hqt=we(()=>{"use strict";Vy();P3n=1024*1024});function $3n(e){return ds(e)?e.kind==="xeno-credits"||e.kind==="local"?!0:e.kind==="own-key"&&In(e.provider)&&In(e.label)&&(e.status===void 0||typeof e.status=="string"):!1}function O3n(e){if(!ds(e)||!["loading","fresh","stale","unavailable"].includes(String(e.state))||typeof e.refreshing!="boolean"||e.source!==void 0&&e.source!=="api"&&e.source!=="platform-auth")return!1;for(let t of["lastSuccessAt","freshUntil","staleUntil","nextRetryAt"])if(e[t]!==void 0&&(typeof e[t]!="number"||!Number.isSafeInteger(e[t])||e[t]<0))return!1;if(e.lastSuccessAt!==void 0&&e.freshUntil!==void 0&&Number(e.freshUntil)<Number(e.lastSuccessAt)||e.freshUntil!==void 0&&e.staleUntil!==void 0&&Number(e.staleUntil)<Number(e.freshUntil)||(e.state==="fresh"||e.state==="stale")&&(e.lastSuccessAt===void 0||e.freshUntil===void 0||e.staleUntil===void 0))return!1;if(e.failure!==void 0){let t=e.failure;if(!ds(t)||!M3n.includes(t.code)||typeof t.retryable!="boolean"||t.retryAfterMs!==void 0&&(typeof t.retryAfterMs!="number"||!Number.isSafeInteger(t.retryAfterMs)||t.retryAfterMs<0||t.retryAfterMs>6e5))return!1}return!0}function F3n(e){return typeof e=="string"&&L3n.test(e)?e:void 0}function U3n(e){return typeof e=="string"&&_3n.includes(e)}function mqt(e){return ds(e)?In(e.clientId)&&In(e.clientVersion)&&In(e.instanceId)&&U3n(e.surface):!1}function Aqt(e){return!ds(e)||!ds(e.protocol)||!ds(e.host)||!ds(e.storage)?!1:Number.isInteger(e.protocol.current)&&q3n(e.protocol.supported)&&In(e.host.instanceId)&&In(e.host.version)&&(e.host.buildIdentity===void 0||typeof e.host.buildIdentity=="string"&&/^[a-f0-9]{64}$/.test(e.host.buildIdentity))&&(e.host.runtimeVersion===void 0||typeof e.host.runtimeVersion=="string"&&/^\d+\.\d+\.\d+$/.test(e.host.runtimeVersion))&&(e.host.catalogRecoveryVersion===void 0||e.host.catalogRecoveryVersion===1)&&(e.host.maintenanceVersion===void 0||e.host.maintenanceVersion===1)&&(e.host.authority==="primary"||e.host.authority==="diagnostic-read-only")&&(e.host.processBoundary==="in-process"||e.host.processBoundary==="per-user-service")&&e.storage.owner==="xeno-agent-host"&&Number.isInteger(e.storage.schemaVersion)&&Number.isInteger(e.storage.eventSchemaVersion)&&mqt(e.surface)}function T8e(e){return!ds(e)||!In(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(H3n)}function Q3n(e){return!ds(e)||!ds(e.event)?!1:In(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&In(e.timestamp)&&In(e.conversationId)&&In(e.requestId)&&In(e.type)&&In(e.source)}function wqt(e){return!ds(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(Q3n)}function yqt(e){return!ds(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&In(e.conversationId)&&In(e.requestId)&&In(e.adapterId)&&ds(e.selection)&&In(e.selection.providerId)&&In(e.selection.catalogRevision):In(e.code)&&In(e.safeError)}function bqt(e){return!ds(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&In(e.conversationId)&&In(e.requestId):In(e.code)&&In(e.safeError)}function vqt(e){return ds(e)&&In(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&G3n(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e&&(e.type!=="account.state.changed"||ds(e.payload)&&typeof e.payload.pending=="boolean")}function G3n(e){return typeof e=="string"&&D3n.includes(e)}function Iqt(e,t,r){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new Ra("surface_mismatch",`Agent host acknowledged ${e.surface.surface}/${e.surface.instanceId} instead of ${t.surface}/${t.instanceId}.`);if(e.protocol.current<r.min||e.protocol.current>r.max||r.max<e.protocol.supported.min||r.min>e.protocol.supported.max)throw new Ra("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${r.min}-${r.max}.`)}function j3n(e){return!(!ds(e)||e.chatExecution!==void 0&&!GW(e.chatExecution)||e.durableResume!==void 0&&!GW(e.durableResume)||e.nativeTuiAttach!==void 0&&!GW(e.nativeTuiAttach)||e.reconciliation!==void 0&&!GW(e.reconciliation)||e.modelSwitchInPlace!==void 0&&!GW(e.modelSwitchInPlace)||e.resumeCompatibilityKey!==void 0&&typeof e.resumeCompatibilityKey!="string")}function GW(e){return ds(e)?(e.status==="available"||e.status==="degraded"||e.status==="blocked"||e.status==="unsupported")&&(e.source==="provider"||e.source==="host"||e.source==="policy")&&(e.reason===void 0||typeof e.reason=="string")&&(e.version===void 0||typeof e.version=="string"):!1}function H3n(e){return ds(e)?In(e.id)&&typeof e.kind=="string"&&B3n.includes(e.kind)&&In(e.displayName)&&Eqt(e.availability)&&ds(e.capabilities)&&(e.providerSession===void 0||j3n(e.providerSession))&&(e.catalogState===void 0||O3n(e.catalogState))&&Array.isArray(e.models)&&e.models.every(V3n)&&In(e.catalogRevision):!1}function V3n(e){return ds(e)&&In(e.id)&&In(e.displayName)&&Eqt(e.availability)&&(e.funding===void 0||$3n(e.funding))&&(e.reasoningOptions===void 0||Array.isArray(e.reasoningOptions)&&e.reasoningOptions.every(t=>ds(t)&&In(t.id)&&In(t.label)&&(t.runtimeModelId===void 0||In(t.runtimeModelId))&&(t.runtimeReasoningEffort===void 0||typeof t.runtimeReasoningEffort=="string"&&/^[a-z][a-z0-9_-]{0,79}$/i.test(t.runtimeReasoningEffort))&&(t.isDefault===void 0||typeof t.isDefault=="boolean")))}function Eqt(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function q3n(e){return ds(e)&&Number.isInteger(e.min)&&Number.isInteger(e.max)&&typeof e.min=="number"&&typeof e.max=="number"&&e.min>0&&e.max>=e.min}function In(e){return typeof e=="string"&&e.trim().length>0}function ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gfe(e){for(let t of J3n)for(let r of W3n)if(e===`${t}tool.${r}`)return r;return null}function aP(e,t){let r=e?.[t];return typeof r=="string"&&r.trim()?r:void 0}function Afe(e){let t=e.event;return aP(t,"toolName")||aP(t,"tool")||aP(t,"name")||aP(t,"title")||aP(t,"kind")}function TD(e){let t=e.event;return aP(t,"toolCallId")||aP(t,"tool_call_id")}function wfe(e){let t=e.event;for(let r of["rawInput","input","arguments","parameters","args"]){let n=t?.[r];if(n&&typeof n=="object"&&!Array.isArray(n))return n}}function yfe(e){let t=e.event;for(let r of["rawOutput","output","result","content"]){let n=t?.[r];if(typeof n=="string")return n.length>0?n:void 0;if(n!=null)try{let i=JSON.stringify(n);if(i&&i!=="{}"&&i!=="[]")return i}catch{}}}function bfe(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var CD,gqt,_3n,B3n,M3n,mfe,N3n,Ves,D3n,L3n,Ra,W3n,J3n,Vy=we(()=>{"use strict";OVt();DVt();LVt();UVt();jVt();HVt();WVt();JVt();zVt();xD();iqt();oqt();sqt();aqt();cqt();dqt();uqt();pqt();fqt();hqt();CD=1,gqt=1,_3n=["standalone-desktop","hub-embed","shell-embed","embed-preview","panel-embed","headless-client","extension-panel"],B3n=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"];M3n=["timeout","network","rate-limited","server","auth-required","forbidden","invalid-response","configuration","cancelled"];mfe=128e3,N3n=["workspace.usage","workspace.audit","inference.request","workspace.schedule","workspace.backup","workspace.environment","host.maintenance","account.request","workforce.request","workspace.notifications","workspace.rules","workspace.browser","workspace.browser.session","workspace.machine.devices","workspace.machine.grant","workspace.machine.grants","workspace.machine.revoke","workspace.machine.act","host.handshake","providers.list","providers.refresh","surface.tools.list","runtime.events.list","workspace.lifecycle.apply","state.workspaces.load","state.workspaces.save","state.conversations.load","state.conversations.save","state.conversations.delete","workspace.access.grant","workspace.access.list","workspace.access.revoke","coordination.held.list","coordination.held.release","coordination.policy.set","coordination.state.get","coordination.action","workspace.application.grant","workspace.directory.list","workspace.file.read","workspace.file.write","workspace.command.run","workspace.terminal.start","workspace.terminal.stop","workspace.pty.start","workspace.pty.snapshot","workspace.pty.input","workspace.pty.resize","workspace.pty.clear","workspace.pty.stop","conversation.open","conversation.fork","conversation.resume","conversation.transcript","conversation.annotate","conversation.attachment.read","conversation.branch.select","conversation.rewind","conversation.compact","xeno.tui.attach","provider.lanes.list","provider.lanes.get","provider.lanes.select","provider.native.attach","provider.native.detach","provider.native.reattach","provider.native.stop","provider.reconcile","turn.start","turn.cancel","turn.steer","context.inject","turn.queue","turn.queue.list","run.observation.snapshot","run.observation.change","run.observation.overlaps","fleet.view","fleet.route","fleet.plan","subagent.run.create","subagent.run.list","subagent.run.cancel","subagent.scheduler.status","subagent.scheduler.recover","session.list","session.attach","session.detach","session.snapshot","session.input","session.takeover","session.release","session.setMode","acp.agents.list","acp.agents.addPreset","acp.agents.remove","acp.capabilitySnapshot.get","acp.command.invoke","intake.sources.list","intake.items.list","intake.item.claim","intake.item.release","intake.item.dispatch","knowledge.list","knowledge.record","knowledge.forget","knowledge.context","turn.queue.drop","elicitation.choose-directory.answer","elicitation.workspace-placement.answer","elicitation.permission.answer","turn.resume","acp.provider.approve","permissions.rules.list","permissions.rules.revoke","elicitation.ask-user.answer","sdk.sessions.list","sdk.sessions.show","sdk.sessions.attach","sdk.sessions.detach","sdk.sessions.delete","sdk.sessions.clean","sdk.checkpoints.list","sdk.checkpoints.restore","sdk.checkpoints.delete","sdk.tasks.output","sdk.tasks.stop","engineering.git.status","engineering.git.diff","engineering.git.stage","engineering.git.unstage","engineering.git.commit","engineering.git.branch","engineering.git.push","engineering.git.pr.create","engineering.landing.enqueue","engineering.landing.remove","engineering.landing.status","engineering.landing.land","engineering.landing.verify","engineering.checks.discover","engineering.checks.run","engineering.background.start","engineering.background.list","engineering.background.output","engineering.background.stop","engineering.runs.list","engineering.diagnostics","engineering.patches.list","engineering.patches.enqueue","engineering.patches.update","engineering.patches.review","engineering.checkpoints.list","engineering.checkpoints.compare","engineering.checkpoints.restore","engineering.sessions.list","engineering.runtime.timeline","pluginMcp.snapshot","pluginMcp.installPlugin","pluginMcp.installLocalPlugin","pluginMcp.activatePlugin","pluginMcp.deactivatePlugin","pluginMcp.uninstallPlugin","pluginMcp.updatePlugin","pluginMcp.setPluginTrust","pluginMcp.trustPublisher","pluginMcp.untrustPublisher","pluginMcp.setRequireSignedPlugins","pluginMcp.upsertMcpServer","pluginMcp.removeMcpServer","pluginMcp.setMcpApproval","pluginMcp.reloadMcp","pluginMcp.setMcpRegistryPolicy","pluginMcp.setScopedPolicy","pluginMcp.deleteScopedPolicy","pluginMcp.searchMarketplace","pluginMcp.syncProjectMcp","pluginMcp.callMcpTool","pluginMcp.getMcpPrompt","pluginMcp.readMcpResource","pluginMcp.preflightTrust","skills.list","skills.get","skills.setEnabled","hooks.list","hooks.trust","hooks.disable","approvals.list","approvals.revoke","approvals.clear","recipes.list","recipes.compile","recipes.run","evals.list","evals.inspect","evals.run","evals.report","evals.compare","org.knowledge","org.playbooks","org.secrets","org.serviceUsers","github.appPlan","github.appVerify","github.mapWebhook","share.export","share.inspect","mcpAuth.status","mcpAuth.login","mcpAuth.loginStatus","mcpAuth.logout","runs.list","runs.get","runs.events","runs.stop","workflows.definitions","workflows.validate","workflows.create","workflows.list","workflows.get","workflows.events","workflows.start","workflows.pause","workflows.resume","workflows.cancel","workflows.retryChild","workflows.skipChild","workflows.rerun","workflows.save","artifacts.list","artifacts.get","artifacts.read","artifacts.publish","artifacts.promote","artifacts.keep-as-tool","artifacts.share","artifacts.comment","artifacts.reply","artifacts.comments","coordination.peers.list","coordination.peers.send","coordination.peers.messages","coordination.peers.decide"],Ves=new Set(N3n),D3n=["host.ready","provider.catalog.changed","account.state.changed","state.workspaces.changed","state.conversations.changed","runtime.event.appended","runtime.event.transient","turn.execution.completed","turn.execution.failed","turn.execution.abandoned","elicitation.choose-directory.requested","elicitation.workspace-placement.requested","elicitation.permission.requested","elicitation.ask-user.requested","task.changed","workspace.terminal.data","workspace.terminal.exit","workspace.pty.data","workspace.pty.exit","coordination.event","run.observation","session.event","provider.lane.created","provider.lane.selected","provider.lane.resumed","provider.lane.invalidated","provider.writer.acquired","provider.writer.renewed","provider.writer.released","provider.writer.recovery_classified","provider.native_tui.started","provider.native_tui.detached","provider.native_tui.exited","provider.reconciliation.started","provider.reconciliation.completed","provider.reconciliation.failed","provider.portable_context.acknowledged_partial"],L3n=/^[A-Z][A-Z0-9_]{1,63}$/;Ra=class extends Error{code;reason;constructor(t,r,n){super(r),this.name="AgentHostProtocolError",this.code=t,this.reason=F3n(n)}};W3n=["started","updated","completed","failed","cancelled"],J3n=["","acp."]});import{createHash as fts,randomBytes as z3n,timingSafeEqual as hts}from"node:crypto";import{createConnection as X3n}from"node:net";function Z3n(e,t,r){if(e!=="workspace.command.run")return r;let n=Ife(t)?t:void 0,i=typeof n?.timeoutMs=="number"&&Number.isFinite(n.timeoutMs)?Math.max(1e3,Math.min(12e4,Math.floor(n.timeoutMs))):2e4;return Math.max(r,i+5e3)}function e8n(e){return!Ife(e)||e.kind!=="response"||typeof e.id!="string"||typeof e.ok!="boolean"?!1:e.ok?"output"in e:Ife(e.error)&&o8n(e.error.code)&&typeof e.error.message=="string"&&(e.error.reason===void 0||typeof e.error.reason=="string")}function t8n(e){return Ife(e)&&e.kind==="event"&&vqt(e.event)}function r8n(e,t,r){xqt(e,t,r)}function xqt(e,t,r){let n=`${JSON.stringify(t)}
|
|
3221
3221
|
`;if(Buffer.byteLength(n,"utf8")>r)throw new Ra("invalid_response","Local Agent host RPC frame exceeds the size limit.");e.write(n,"utf8")}function n8n(e,t){if(!e.trim())throw new Error("Local Agent host endpoint is required.");if(t.length<32)throw new Error("Local Agent host transportToken must contain at least 32 characters.")}function lP(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:void 0}function i8n(e){let t=lP(e)||Y3n;if(t>kqt)throw new Error(`Local Agent host RPC frame limit cannot exceed ${kqt} bytes.`);return t}function o8n(e){return e==="invalid_handshake"||e==="protocol_mismatch"||e==="surface_mismatch"||e==="not_connected"||e==="invalid_response"}function Sqt(e){return e instanceof Error?e:new Error(String(e))}function Ife(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Efe(e,t){return e instanceof Error&&"code"in e&&e.code===t}var Y3n,kqt,K3n,vfe,R8e,kfe=we(()=>{"use strict";Vy();Y3n=32*1024*1024,kqt=64*1024*1024,K3n=3e4,vfe=class{endpoint;transportToken;protocolVersion;maxFrameBytes;requestTimeoutMs;listeners=new Set;pending=new Map;requestPrefix=z3n(12).toString("hex");requestSequence=0;socket=null;connectPromise=null;accountAuthorizer=null;setAccountAuthorizer(t){this.accountAuthorizer=t}constructor(t){n8n(t.endpoint,t.transportToken),this.endpoint=t.endpoint,this.transportToken=t.transportToken,this.protocolVersion=lP(t.protocolVersion)||CD,this.maxFrameBytes=i8n(t.maxFrameBytes),this.requestTimeoutMs=lP(t.requestTimeoutMs)||K3n}get connected(){return this.socket!==null&&!this.socket.destroyed}async connect(){if(!this.connected)return this.connectPromise?this.connectPromise:(this.connectPromise=new Promise((t,r)=>{let n=X3n(this.endpoint),i=new R8e(this.maxFrameBytes,a=>this.receive(a)),o=a=>{n.off("connect",s),this.socket=null,r(a)},s=()=>{n.off("error",o),n.setNoDelay(!0),this.socket=n,t()};n.once("error",o),n.once("connect",s),n.on("data",a=>{try{i.push(a)}catch(l){this.disconnect(Sqt(l))}}),n.on("error",a=>this.disconnect(a)),n.on("close",()=>this.disconnect(new Error("Local Agent host connection closed.")))}).finally(()=>{this.connectPromise=null}),this.connectPromise)}async request(t,r){await this.connect();let n=this.socket;if(!n||n.destroyed)throw new Ra("not_connected","Local Agent host is not connected.");let i=`${this.requestPrefix}:${++this.requestSequence}`,o={kind:"request",id:i,protocolVersion:this.protocolVersion,token:this.transportToken,method:t,input:structuredClone(r)};return new Promise((s,a)=>{let l=Z3n(t,r,this.requestTimeoutMs),c=setTimeout(()=>{this.pending.delete(i),a(new Ra("not_connected",`Local Agent host request timed out: ${t}.`))},l);this.pending.set(i,{resolve:d=>s(d),reject:a,timeout:c});try{r8n(n,o,this.maxFrameBytes)}catch(d){clearTimeout(c),this.pending.delete(i),a(Sqt(d))}})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}close(){this.disconnect(new Error("Local Agent host client closed."))}receive(t){let r;try{r=JSON.parse(t)}catch{this.disconnect(new Ra("invalid_response","Local Agent host returned malformed JSON."));return}if(t8n(r)){for(let i of[...this.listeners])i(structuredClone(r.event));return}if(qVt(r)){this.answerHostRequest(r);return}if(!e8n(r)){this.disconnect(new Ra("invalid_response","Local Agent host returned an invalid RPC frame."));return}let n=this.pending.get(r.id);n&&(clearTimeout(n.timeout),this.pending.delete(r.id),r.ok?n.resolve(structuredClone(r.output)):n.reject(new Ra(r.error.code,r.error.message,r.error.reason)))}async answerHostRequest(t){let r=null;try{let i=this.accountAuthorizer?await this.accountAuthorizer({method:t.input.method,url:t.input.url}):null;r=VVt(i)?i:null}catch{r=null}let n=this.socket;if(!(!n||n.destroyed))try{xqt(n,{kind:"host-response",id:t.id,ok:!0,output:r},this.maxFrameBytes)}catch{}}disconnect(t){let r=this.socket;this.socket=null,r&&!r.destroyed&&r.destroy();for(let n of this.pending.values())clearTimeout(n.timeout),n.reject(t);this.pending.clear()}};R8e=class{maxFrameBytes;onFrame;buffer=Buffer.alloc(0);constructor(t,r){this.maxFrameBytes=t,this.onFrame=r}push(t){if(this.buffer=this.buffer.length===0?t:Buffer.concat([this.buffer,t]),this.buffer.length>this.maxFrameBytes&&this.buffer.indexOf(10)<0)throw new Ra("invalid_response","Local Agent host RPC frame exceeds the size limit.");let r=this.buffer.indexOf(10);for(;r>=0;){if(r>this.maxFrameBytes)throw new Ra("invalid_response","Local Agent host RPC frame exceeds the size limit.");let n=this.buffer.subarray(0,r);this.buffer=this.buffer.subarray(r+1);let i=n.toString("utf8").replace(/\r$/,"");i&&this.onFrame(i),r=this.buffer.indexOf(10)}}}});function Cqt(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.value!="string"?!1:t.kind==="windows-start-ticks-v1"&&/^\d{16,22}$/.test(t.value)||t.kind==="linux-boot-start-v1"&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}:\d+$/.test(t.value)}var P8e=we(()=>{"use strict"});import{readFile as s8n}from"node:fs/promises";import{join as Tqt}from"node:path";function Sfe(e){let t=e.isProcessAlive||l8n;try{return!t(e.pid)}catch{return!1}}async function xfe(e){let t=Tqt(e,"agent-host.lock");try{let r=await Pqt(t);return r.state==="released"?null:_qt(r)}catch(r){if(Efe(r,"ENOENT"))return null;throw r}}async function Rqt(e){let t=Tqt(e,"agent-host.lock");try{let r=await Pqt(t);return r.state==="released"?null:{descriptor:_qt(r),transportToken:r.transportToken}}catch(r){if(Efe(r,"ENOENT"))return null;throw r}}async function Pqt(e){return a8n(await s8n(e,"utf8"))}function a8n(e){if(Buffer.byteLength(e)>16384)throw new Error("Agent host authority lease exceeds its size bound.");let t;try{t=JSON.parse(e)}catch{throw new Error("Agent host authority lease is malformed.")}if(!c8n(t)||t.schemaVersion!==1&&t.schemaVersion!==2||typeof t.instanceId!="string"||typeof t.pid!="number"||typeof t.endpoint!="string"||typeof t.protocolVersion!="number"||typeof t.acquiredAt!="number"||typeof t.heartbeatAt!="number"||typeof t.transportToken!="string"||t.transportToken.length<32||t.transportToken.length>256||!t.instanceId.trim()||t.instanceId.length>256||!t.endpoint.trim()||t.endpoint.length>4096||!Number.isSafeInteger(t.pid)||t.pid<=0||!Number.isSafeInteger(t.protocolVersion)||t.protocolVersion<=0||!Number.isSafeInteger(t.acquiredAt)||t.acquiredAt<0||!Number.isSafeInteger(t.heartbeatAt)||t.heartbeatAt<0||t.processBirth!==void 0&&!Cqt(t.processBirth)||t.schemaVersion===2&&t.state!=="active"&&t.state!=="released"||t.schemaVersion===1&&t.state!==void 0)throw new Error("Agent host authority lease is invalid.");return t}function _qt(e){return{schemaVersion:e.schemaVersion,instanceId:e.instanceId,pid:e.pid,endpoint:e.endpoint,protocolVersion:e.protocolVersion,acquiredAt:e.acquiredAt,heartbeatAt:e.heartbeatAt,...e.processBirth?{processBirth:{...e.processBirth}}:{}}}function l8n(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!Efe(t,"ESRCH")}}function c8n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var _8e=we(()=>{"use strict";kfe();P8e()});async function $8e(e){let t=lP(e.protocolVersion)||CD,r=lP(e.connectTimeoutMs)||5e3,n=lP(e.requestTimeoutMs)||3e4,i=await xfe(e.rootDirectory);if(!i)return{attached:!1,reason:"no-host",detail:"No XENO Agent host is running for this user. Start the Agent app, or run the host detached."};if(Sfe({heartbeatAt:i.heartbeatAt,pid:i.pid,at:(e.now||Date.now)(),...e.staleAfterMs===void 0?{}:{staleAfterMs:e.staleAfterMs},...e.isProcessAlive?{isProcessAlive:e.isProcessAlive}:{}}))return{attached:!1,reason:"host-gone",detail:`The recorded Agent host (pid ${i.pid}) is no longer running. Start the Agent app again.`};if(i.protocolVersion!==t)return{attached:!1,reason:"protocol-mismatch",hostProtocol:i.protocolVersion,clientProtocol:t,detail:`The running Agent host speaks protocol ${i.protocolVersion} and this client speaks ${t}. Update whichever is older.`};let o=await Rqt(e.rootDirectory);if(!o||o.descriptor.instanceId!==i.instanceId)return{attached:!1,reason:"unreachable",detail:"The Agent host changed while connecting. Retry."};let s=new vfe({endpoint:o.descriptor.endpoint,transportToken:o.transportToken,protocolVersion:t,requestTimeoutMs:n});try{await d8n(s,r)}catch(a){return s.close(),{attached:!1,reason:"unreachable",detail:a instanceof Error?a.message:String(a)}}return{attached:!0,session:new B8e({role:"attached-client",descriptor:o.descriptor,transport:s})}}async function d8n(e,t){let r=Date.now()+t,n;do try{await e.connect();return}catch(i){if(n=Bqt(i),!u8n(n)||Date.now()>=r)break;await p8n(Math.min(50,Math.max(1,r-Date.now())))}while(Date.now()<r);throw n||new Error("Unable to connect to the local Agent host authority.")}function u8n(e){if(!("code"in e))return!1;let t=e.code;return t==="ENOENT"||t==="ECONNREFUSED"||t==="EPIPE"}function p8n(e){return new Promise(t=>setTimeout(t,e))}function Bqt(e){return e instanceof Error?e:new Error(String(e))}var B8e,$qt=we(()=>{"use strict";Vy();_8e();kfe();B8e=class{role;descriptor;transport;server;lease;onAuthorityLost;heartbeatTimer;heartbeatPending=!1;closed=!1;closeFlight;constructor(t){this.role=t.role,this.descriptor={...t.descriptor},this.transport=t.transport,this.server=t.server,this.lease=t.lease,this.onAuthorityLost=t.onAuthorityLost,this.lease&&t.heartbeatIntervalMs&&(this.heartbeatTimer=setInterval(()=>{this.heartbeat()},t.heartbeatIntervalMs),this.heartbeatTimer.unref?.())}close(){return this.closed?Promise.resolve():this.closeFlight?this.closeFlight:(this.closeFlight=(async()=>{this.transport.close(),await this.server?.close(),await this.lease?.release(),this.closed=!0,this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)})().catch(t=>{throw this.closeFlight=void 0,t}),this.closeFlight)}async heartbeat(){if(!(this.closed||this.heartbeatPending||!this.lease)){this.heartbeatPending=!0;try{await this.lease.heartbeat()}catch(t){let r=Bqt(t);await this.close().catch(()=>{}),this.onAuthorityLost?.(r)}finally{this.heartbeatPending=!1}}}}});import{join as f8n,resolve as Oqt}from"node:path";function RD(e){let t=Mqt(e.homeDirectory);if(!t)throw new Error("Agent host homeDirectory is required.");let r=Mqt(e.hostRootDirectory);return r||f8n(Oqt(t,h8n),m8n)}function Mqt(e){return typeof e=="string"&&e.trim()?Oqt(e.trim()):void 0}var h8n,m8n,Nqt=we(()=>{"use strict";h8n=".xeno",m8n="agent-host-v1"});var Cfe=we(()=>{"use strict";kfe();_8e();P8e();$qt();Nqt()});import{existsSync as g8n}from"fs";import{join as of}from"path";import{createDirs as A8n}from"@xenosystem/primitives/dirs";function w8n(e,t=[]){return{pluginDir:of(e,"plugins"),mcpConfigDir:of(e,"mcp"),mcpDataDir:of(e,"mcp"),protectedPaths:[...t,of(e,"credentials.json")],layout:"legacy"}}function y8n(e,t=[]){return{pluginDir:of(e.data,"extensions","plugins"),mcpConfigDir:of(e.config,"extensions","mcp"),mcpDataDir:of(e.data,"extensions","mcp"),protectedPaths:[...t,e.secrets],layout:"extensions"}}function b8n(e,t){return!Dqt(e)&&Dqt(t)?t:e}function Lqt(e,t=process.env){let r=A8n({home:e,env:t}),n=of(e,".ssh");return b8n(y8n({data:r.root("data"),config:r.root("config"),secrets:r.root("secrets")},[n]),w8n(of(e,".xeno"),[n]))}function Fqt(e,t){return e.XENO_AGENT_HOST_ROOT?.trim()?of(t,"coordination"):void 0}var Dqt,M8e=we(()=>{"use strict";Dqt=e=>[of(e.pluginDir,"plugins.json"),of(e.pluginDir,"trust.json"),of(e.mcpConfigDir,"servers.json"),of(e.mcpConfigDir,"sdk-approvals.json")].some(t=>g8n(t))});import{homedir as v8n}from"node:os";function Ki(e={}){if(e.rootDirectory)return new pfe(e);let t=RD({homeDirectory:v8n(),...process.env.XENO_AGENT_HOST_ROOT?{hostRootDirectory:process.env.XENO_AGENT_HOST_ROOT}:{}}),r=Fqt(process.env,t);return new pfe({...e,...r?{rootDirectory:r}:{}})}var NA=we(()=>{"use strict";oP();Cfe();M8e()});function S8n(e){if(e===void 0||e==="")return"";if(!k8n.test(e)||e.split("/").includes(".."))throw new TypeError("pathPrefix must be an absolute path such as /v1/web");return e}function VW(e){return e.signal?{signal:e.signal}:{}}function x8n(e,t){if(!t)return`scrape job ended in ${e}`;let[r,n]=t.split(":",2),i=n?` (${n})`:"";switch(r){case"SITE_BLOCKED":return`the site refused the request${i}; it blocks automated access, so use another source`;case"RATE_LIMITED":return"the site is rate-limiting requests; try again later";case"NOT_FOUND":return"the page does not exist (HTTP 404/410)";case"NETWORK_ERROR":return"the site could not be reached (network error)";case"DEADLINE_EXCEEDED":return"the page did not respond within the time budget";case"MIME_DENIED":return"the page is not a supported document type";case"ROBOTS_DENIED":case"ROBOTS_DISALLOWED":return"the site's robots.txt does not allow this page to be fetched";case"ROBOTS_UNAVAILABLE":return"the site's robots.txt could not be read, so the page was not fetched";default:return/^HTTP_\d{3}$/.test(r??"")?`the site answered HTTP ${r.slice(5)}`:`the page could not be retrieved (${t})`}}function Gqt(e,t){let r=e;return{message:t,...typeof r?.code=="string"?{code:r.code}:{},...typeof r?.status=="number"?{status:r.status}:{}}}function C8n(e,t){if(typeof e!="object"||e===null||!Object.isExtensible(e))return e;try{Object.defineProperty(e,"cancellation",{value:t,enumerable:!0,configurable:!0,writable:!0})}catch{}return e}function T8n(e,t){let r=0,n,i=!1;return async o=>{if(!e)return;let s=yI(o.state);if(s&&i)return;let a=hfe(o,r),l=C8e(a);if(!(n===l&&!s)){n=l,r+=1,s&&(i=!0);try{await e(a)}catch(c){throw Object.assign(new Error("job progress listener failed"),{code:"PROGRESS_LISTENER_FAILED",jobId:t,state:a.state,cause:c})}}}}var k8n,qW,jqt=we(()=>{"use strict";xD();xD();k8n=/^\/[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*$/;qW=class{#e;#r;#n;#i;constructor(t){if(this.#e=new URL(t.baseUrl),this.#r=t.token,this.#i=S8n(t.pathPrefix),!this.#r.trim())throw new TypeError("token is required");this.#n=t.fetchImpl??fetch}#o(t){if(this.#i==="")return new URL(t,this.#e);if(!t.startsWith("/v1/"))throw new TypeError("pathPrefix can only rewrite /v1 routes");return new URL(`${this.#i}${t.slice(3)}`,this.#e)}async#t(t,r={}){let n=await this.#n(this.#o(t),{...r,redirect:"error",headers:{authorization:`Bearer ${this.#r}`,...r.body?{"content-type":"application/json"}:{},...r.headers}});if(!n.ok){let i=`HTTP ${n.status}`,o;try{let s=await n.json();i=s.error?.message??i,o=s.error?.code}catch{}throw Object.assign(new Error(i),{status:n.status,...o?{code:o}:{}})}return n.status===204?void 0:await n.json()}async#s(t,r={}){let n=await this.#n(this.#o(t),{...r,redirect:"error",headers:{authorization:`Bearer ${this.#r}`,...r.headers}});if(!n.ok){let i=`HTTP ${n.status}`,o;try{let s=await n.json();i=s.error?.message??i,o=s.error?.code}catch{}throw Object.assign(new Error(i),{status:n.status,...o?{code:o}:{}})}return n}capabilities(){return this.#t("/v1/capabilities")}account(t={}){return this.#t("/v1/account",VW(t))}usage(){return this.#t("/v1/usage")}search(t,r={}){return this.#t("/v1/search",{method:"POST",body:JSON.stringify(t),...VW(r)})}searchAndScrape(t,r={}){return this.#t("/v1/search-and-scrape",{method:"POST",body:JSON.stringify(t),...VW(r)})}scrape(t){return this.#t("/v1/scrape",{method:"POST",body:JSON.stringify(t)})}render(t){return this.#t("/v1/render",{method:"POST",body:JSON.stringify(t)})}map(t){return this.#t("/v1/map",{method:"POST",body:JSON.stringify(t)})}crawl(t){return this.#t("/v1/crawl",{method:"POST",body:JSON.stringify(t)})}batchScrape(t){return this.#t("/v1/batch-scrape",{method:"POST",body:JSON.stringify(t)})}activity(t={}){let r=new URLSearchParams;return t.limit&&r.set("limit",String(t.limit)),t.cursor&&r.set("cursor",t.cursor),this.#t(`/v1/activity?${r}`)}job(t){return this.#t(`/v1/jobs/${encodeURIComponent(t)}`)}frontier(t,r={}){let n=new URLSearchParams;return r.limit&&n.set("limit",String(r.limit)),r.cursor&&n.set("cursor",r.cursor),this.#t(`/v1/jobs/${encodeURIComponent(t)}/frontier?${n}`)}results(t,r={}){let n=new URLSearchParams;return r.limit&&n.set("limit",String(r.limit)),r.cursor&&n.set("cursor",r.cursor),this.#t(`/v1/jobs/${encodeURIComponent(t)}/results?${n}`,VW(r))}async artifact(t,r,n={}){if(!/^artifact:[a-f0-9]{64}$/i.test(r))throw new TypeError("artifactId is invalid");let i=await this.#s(`/v1/jobs/${encodeURIComponent(t)}/artifacts/${r}`,VW(n)),o=i.headers.get("etag")??void 0;return{jobId:t,artifactId:r,mediaType:i.headers.get("content-type")?.split(";",1)[0]?.trim()||"application/octet-stream",bytes:new Uint8Array(await i.arrayBuffer()),...o?{etag:o}:{}}}cancel(t){return this.#t(`/v1/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"})}resume(t){return this.#t(`/v1/jobs/${encodeURIComponent(t)}/resume`,{method:"POST"})}webhookDeliveries(t){return this.#t(`/v1/jobs/${encodeURIComponent(t)}/webhooks`)}upload(t){return this.#t("/v1/artifacts",{method:"POST",body:JSON.stringify(t)})}parse(t){return this.#t("/v1/parse",{method:"POST",body:JSON.stringify(t)})}extract(t){return this.#t("/v1/extract",{method:"POST",body:JSON.stringify(t)})}monitors(){return this.#t("/v1/monitors")}createMonitor(t){return this.#t("/v1/monitors",{method:"POST",body:JSON.stringify(t)})}monitorChecks(t,r=100){return this.#t(`/v1/monitors/${encodeURIComponent(t)}/checks?limit=${r}`)}setMonitorState(t,r){return this.#t(`/v1/monitors/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({state:r})})}removeMonitor(t){return this.#t(`/v1/monitors/${encodeURIComponent(t)}`,{method:"DELETE"})}async#a(t,r,n,i){let o;try{({job:o}=await this.cancel(t))}catch(p){return{attempted:!0,trigger:r,jobId:t,outcome:"failed",error:Gqt(p,"Web Context cancellation failed")}}let s=i.cancelConfirmationMs??2e3,a=Date.now()+(Number.isFinite(s)&&s>0?s:0),l=i.pollMs??500,c,d=async p=>{try{await n(p)}catch(f){c??=Gqt(f,"Web Context progress listener failed during cancellation confirmation")}};for(await d(o);!yI(o.state)&&Date.now()<a;){await new Promise(f=>{setTimeout(f,Math.min(l,Math.max(0,a-Date.now())))});let p;try{({job:p}=await this.job(t))}catch{break}o=p,await d(o)}let u=yI(o.state)?hfe(o,0):void 0;return{attempted:!0,trigger:r,jobId:t,outcome:o.state==="cancelled"?"cancelled":"requested",...u?{terminalProgress:u}:{},...c?{listenerError:c}:{}}}async waitForJob(t,r={}){let n=Date.now()+(r.timeoutMs??12e4),i=T8n(r.onProgress,t),o;try{for(;Date.now()<n;){if(r.signal?.aborted)throw o="abort",r.signal.reason;let{job:s}=await this.job(t);if(await i(s),yI(s.state))return s;await new Promise((a,l)=>{let c=setTimeout(a,r.pollMs??500);r.signal?.addEventListener("abort",()=>{clearTimeout(c),o="abort",l(r.signal?.reason)},{once:!0})})}throw o="timeout",Object.assign(new Error("job wait timed out"),{code:"WAIT_TIMEOUT",jobId:t})}catch(s){let a=o==="abort"?r.cancelOnAbort===!0:o==="timeout"?r.cancelOnTimeout===!0:!1;throw!o||!a?s:C8n(s,await this.#a(t,o,i,r))}}async scrapeAndWait(t,r={}){let n=await this.scrape(t),i=await this.waitForJob(n.job.jobId,r);if(i.state!=="completed"&&i.state!=="partial"){let l;try{let d=(await this.results(i.jobId,{limit:1})).items.find(u=>typeof u.errorCode=="string")?.errorCode;typeof d=="string"&&(l=d)}catch{}throw Object.assign(new Error(x8n(i.state,l)),{code:"JOB_NOT_COMPLETED",jobId:i.jobId,state:i.state,...l?{reason:l}:{}})}let o=await this.results(i.jobId,{limit:1}),s=o.items.find(l=>l.state==="completed"&&typeof l.artifactId=="string")??o.items.find(l=>typeof l.artifactId=="string");if(!s?.artifactId)throw Object.assign(new Error("completed scrape job has no readable artifact"),{code:"JOB_ARTIFACT_MISSING",jobId:i.jobId});let a=await this.artifact(i.jobId,s.artifactId);return{job:i,item:s,artifact:a,text:new TextDecoder().decode(a.bytes)}}}});import{readFileSync as R8n}from"node:fs";function F8e(e=process.env,t){let r=t??e.XENO_WEB_CONTEXT_MAX_PROVIDER_COST_USD;if(r===void 0)return;let n=Number(r.trim());if(!/^[0-9]+(?:\.[0-9]+)?$/.test(r.trim())||!Number.isFinite(n)||n<0)throw Object.assign(new Error("Web Context provider cost budget must be a finite non-negative decimal USD amount."),{code:"WEB_CONTEXT_INVALID_BUDGET"});return n}function WW(e,t,r,n=5){if(r!==void 0&&(!Number.isSafeInteger(r)||r<1))throw Object.assign(new Error("Web Context account returned an invalid page quota."),{code:"WEB_CONTEXT_INVALID_ACCOUNT"});if(e==="search"&&(!Number.isSafeInteger(n)||n<1||n>20))throw Object.assign(new Error("Web Context search result count must be an integer from 1 to 20."),{code:"WEB_CONTEXT_INVALID_BUDGET"});let i=e==="map"||e==="crawl"?100:e==="search"?n:1;return{maxAttempts:3,maxConcurrency:4,maxBytes:1e7,maxPages:Math.min(i,r??i),maxDurationMs:12e4,maxRedirects:8,maxProviderCostUsd:t??0,...t===void 0?{providerCostMode:"account-default"}:{}}}function _8n(e=process.env){let t=e.XENO_WEB_CONTEXT_TOKEN?.trim();if(t)return t;let r=e.XENO_WEB_CONTEXT_TOKEN_FILE?.trim();if(r){let n=R8n(r,"utf8").trim();if(n)return n}throw Object.assign(new Error("XENO Web Context is not configured. Set XENO_WEB_CONTEXT_TOKEN or XENO_WEB_CONTEXT_TOKEN_FILE."),{code:"WEB_CONTEXT_NOT_CONFIGURED"})}function B8n(e=process.env,t={}){let r=e.XENO_WEB_CONTEXT_URL?.trim(),n=!!(e.XENO_WEB_CONTEXT_TOKEN?.trim()||e.XENO_WEB_CONTEXT_TOKEN_FILE?.trim());if(r||n)return{baseUrl:r||P8n,token:_8n(e),source:"explicit",auth:"bearer"};let i=e.XENO_API_KEY?.trim();return i?{baseUrl:Hqt,token:i,pathPrefix:Vqt,source:"account",auth:"bearer"}:{baseUrl:Hqt,pathPrefix:Vqt,source:"account",auth:"dpop"}}function $8n(){return Object.assign(new Error("XENO Web Context needs a XENO account. Sign in with `xeno`, or set XENO_WEB_CONTEXT_URL and XENO_WEB_CONTEXT_TOKEN."),{code:"WEB_CONTEXT_NOT_CONFIGURED"})}function M8n(e={}){return async(t,r)=>{let n=typeof t=="string"?t:t instanceof URL?t.href:t.url,i=(r?.method??"GET").toUpperCase(),s=await(e.accountHost?await e.accountHost():await Rl()).authorize(i,n,["inference:run"]),a=new Headers(r?.headers);if(s)return a.set("authorization",`DPoP ${s.token}`),a.set("dpop",s.headers.dpop),fetch(t,{...r,headers:a});let l=Uy(e);if(l.state!=="present")throw $8n();return a.set("authorization",`Bearer ${l.key}`),fetch(t,{...r,headers:a})}}function U8e(e=process.env,t={}){let r=B8n(e,t);return r.auth==="dpop"?new qW({baseUrl:r.baseUrl,token:"dpop-account-session",pathPrefix:r.pathPrefix,fetchImpl:M8n(t)}):new qW({baseUrl:r.baseUrl,token:r.token??"",...r.pathPrefix?{pathPrefix:r.pathPrefix}:{}})}function qqt(e=process.env){let t=F8e(e),r=WW("fetch",t),n=_le({actor:{id:"xeno-agent-cli",kind:"agent"},scope:{kind:"local-profile",profileId:"pending-token-scope"},classification:"public",purposePrefix:"xeno-agent-cli:chat",budget:{...r,maxProviderCostUsd:t,durationMs:r.maxDurationMs}});return{client:new L8e(e),createRequest:(i,o)=>{let s=n(i,o);return i==="search"&&(s.budget.maxPages=WW("search",r.maxProviderCostUsd,void 0,typeof o.maxResults=="number"?o.maxResults:5).maxPages),s}}}var P8n,Hqt,Vqt,L8e,Q8e=we(()=>{"use strict";jqt();CA();ef();at();P8n="http://127.0.0.1:8080",Hqt="https://api.xenostudio.ai",Vqt="/v1/web";L8e=class{constructor(t){this.env=t}env;client;account;async search(t){return this.getClient().search(await this.bindTenant(t,"search",t.count))}async scrapeAndWait(t,r){return this.getClient().scrapeAndWait(await this.bindTenant(t,"fetch"),r)}getClient(){return this.client??=U8e(this.env),this.client}async bindTenant(t,r,n){this.account??=this.getClient().account();let i=await this.account,o=WW(r,t.budget.maxProviderCostUsd,i.quota?.maxPagesPerJob,n);return{...t,scope:{kind:"tenant",tenantId:i.tenantId},budget:{...t.budget,maxPages:Math.min(t.budget.maxPages,o.maxPages)}}}}});function JW(e){return e.type==="run.self_review"}function zW(e){return{status:e.status,summary:e.summary,findings:[...e.findings],fixes:[...e.fixes],unverified:[...e.unverified],fixToolCalls:e.fixToolCalls,verificationsRerun:e.verificationsRerun,changedFiles:[...e.changedFiles],durationMs:e.durationMs}}function Wqt(e){return e.replace(/\s+/g," ").trim()}function XW(e){let t=Wqt(e.summary).replace(/^(?:self[ -]review:\s*)+/i,""),r=[];e.findings.length>0&&r.push(`${e.findings.length} finding${e.findings.length===1?"":"s"}`),e.fixes.length>0&&r.push(`${e.fixes.length} fix${e.fixes.length===1?"":"es"}`),e.unverified.length>0&&r.push(`${e.unverified.length} unverified`);let n=r.length>0?` (${r.join(", ")})`:"";return e.status==="failed"?`Self-review failed: ${t||"no summary"}${n}`:e.status==="timed_out"?`Self-review timed out: ${t||"no summary"}${n}`:`Self-review: ${t||"no issues reported"}${n}`}function G8e(e){let t=[],r=(n,i)=>{if(i.length!==0){t.push(`${n}:`);for(let o of i)t.push(` - ${Wqt(o)}`)}};return r("Findings",e.findings),r("Fixes",e.fixes),r("Unverified",e.unverified),e.changedFiles.length>0&&t.push(`Changed files: ${e.changedFiles.join(", ")}`),t.push(`Fix tool calls: ${e.fixToolCalls} \xB7 verifications rerun: ${e.verificationsRerun} \xB7 ${(e.durationMs/1e3).toFixed(1)}s`),t.join(`
|
|
3222
3222
|
`)}function j8e(e){return e.findings.length+e.fixes.length+e.unverified.length>0}function Jqt(e,t=process.env){let r=t.XENO_SELF_REVIEW?.trim().toLowerCase();if(r==="0"||r==="false"||r==="off")return!1;if(!(r==="1"||r==="true"||r==="on")&&e===!1)return!1}var Tfe=we(()=>{"use strict"});function Rfe(e){let t=e.type.toLowerCase();if(!(t.includes("tool")||TD(e))&&!(!t.includes("text")&&!t.includes("message")&&!t.includes("delta"))&&!(t.includes("complete")||t.includes("final")||t.includes("end")))for(let r of["delta","text","content","chunk"]){let n=e.event[r];if(typeof n=="string"&&n.length>0)return n}}function zqt(e){let t=e.type;if(t==="turn.failed"){for(let r of["error","message","safeError"]){let n=e.event[r];if(typeof n=="string"&&n.trim())return{failed:n.trim().slice(0,2e3)}}return{failed:"The agent run failed."}}if(t==="turn.completed"){let r=e.event.tokenUsage;if(r&&typeof r=="object"&&!Array.isArray(r)){let n=r,[i,o,s]=[n.input,n.output,n.total];if(typeof i=="number"&&typeof o=="number"&&typeof s=="number")return{tokenUsage:{input:i,output:o,total:s}}}}}var H8e=we(()=>{"use strict";Vy()});import{createHash as O8n}from"node:crypto";import{setTimeout as N8n}from"node:timers/promises";function F8n(e,t){return`subrun-${O8n("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}async function U8n(e,t,r){return((await e.listRuntimeEvents({conversationId:t,subagentRunId:r,limit:500}))?.events??[]).map(i=>Rfe(i)??"").join("")}function Q8n(e,t,r,n){let i=new Set,o=typeof n.onToolStart=="function"||typeof n.onToolEnd=="function",s=a=>{try{a()}catch{}};return async function(){if(!o)return;let l=await e.listRuntimeEvents({conversationId:t,subagentRunId:r,limit:500}).catch(()=>null);for(let c of l?.events??[]){let d=gfe(String(c.type??""));if(!d)continue;let u=`${TD(c)??c.id}:${d}`;if(i.has(u))continue;i.add(u);let p=Afe(c)??"unknown";if(d==="started"&&n.onToolStart){let h=n.onToolStart;s(()=>h(p,wfe(c)??{}))}let f=bfe(d);if(f!==null&&n.onToolEnd){let h=n.onToolEnd;s(()=>h(p,{success:f,output:yfe(c)??""}))}}}}function Xqt(e){let t=e.pollIntervalMs??250;return async r=>{let n=r.task,i=F8n(e.rootTraceId,n.id),o={lastTraceId:null,tokenUsage:{input:0,output:0,total:0},async run(s){let a=Math.max(1e3,e.deadline-Date.now()),l={parentConversationId:e.parentConversationId,...e.parentRequestId===void 0?{}:{parentRequestId:e.parentRequestId},parentAgentId:e.parentAgentId,childConversationId:i,childAgentId:n.role?`delegated-${n.role}`:"delegated-branch",workspaceId:e.workspaceId,teamId:e.teamId,objective:s,...n.role===void 0?{}:{role:n.role},policy:{maxRuntimeMs:a}},c=await e.client.createSubagentRun(l);if(!c?.success||!c.run)throw new Error(c?.safeError??"The Agent host refused to create a subagent run for this delegated branch.");let d=c.run.id;o.lastTraceId=d;let u=Q8n(e.client,i,d,{onToolStart:r.onToolStart,onToolEnd:r.onToolEnd});for(;;){if(e.signal?.aborted){await e.client.cancelSubagentRun({runId:d}).catch(()=>{});let m=new Error("Delegated branch was cancelled.");throw m.name="AgentInterruptedError",m}let f=((await e.client.listSubagentRuns({parentConversationId:e.parentConversationId}))?.runs??[]).find(m=>m.id===d),h=String(f?.status??"");if(D8n.has(h)){if(L8n.has(h))throw new Error(f?.error??`The delegated branch ended as '${h}' without reporting a reason.`);await u();let m=await U8n(e.client,i,d);if(m.length===0)throw new Error(`The delegated branch reported '${h}' but produced no readable output. Its runtime events carry no text for this run id.`);return m}if(Date.now()>=e.deadline)throw await e.client.cancelSubagentRun({runId:d}).catch(()=>{}),new Error("The delegated branch exceeded the time this run was given to wait.");await u(),await N8n(t,void 0,{signal:e.signal})}}};return o}}var D8n,L8n,Yqt=we(()=>{"use strict";Vy();H8e();D8n=new Set(["completed","succeeded","failed","cancelled","error"]),L8n=new Set(["failed","cancelled","error"])});function YW(e,t){let r=e.run.bind(e);return e.run=async n=>{try{return await t.start(),await r(n)}finally{await t.stop()}},e}function bI(e){return!e||e.status==="completed"}function KW(e,t=r=>{wt.cleanupOwner(r)}){if(e)try{t(e)}catch{}}async function qy(e){let{agent:t,signal:r}=e,n=()=>KW(e.ownerSessionId,e.cleanupOwner),i=()=>{t.cancelCurrentTurn()};if(r?.aborted)throw n(),await e.lifecycle?.stop(),new Qi;r?.addEventListener("abort",i,{once:!0});let o=!1;try{if(e.lifecycle&&(await e.lifecycle.start(r),r?.aborted))throw new Qi;let s=await(e.run??(()=>t.run(e.prompt)))(),a=t.lastRunTermination??void 0;o=bI(a);let l=a?{status:a.status,reason:a.reason,...a.message?{message:a.message}:{}}:void 0;return{output:s,...l?{termination:l}:{},tokenUsage:{...t.tokenUsage}}}finally{r?.removeEventListener("abort",i),o||n(),await e.lifecycle?.stop()}}function cP(e,t,r){if(!t)return e;let n=e.run.bind(e);return e.run=async i=>{let o=!1;try{let s=await n(i);return o=bI(e.lastRunTermination),s}finally{o||KW(t,r)}},e}function V8e(e){return e.stopRequested||e.termination?.status==="interrupted"?"stopped":e.threw||e.termination?.status==="error"?"failed":bI(e.termination)?"completed":"unfinished"}function ZW(e){let t=e.summary.cancelled??0,r=e.summary.incomplete??0,n=[];return r>0&&n.push(`${r} stopped before finishing`),t>0&&n.push(`${t} cancelled`),e.incomplete?`Delegation incomplete: no branch finished${n.length?` (${n.join(", ")})`:""}. The answer below is partial output from a branch that stopped early, not a final answer.`:n.length?`Delegation finished with unfinished branches: ${n.join(", ")}.`:void 0}var e6=we(()=>{"use strict";at()});import{promises as CWe}from"node:fs";import{readdirSync as $zt,renameSync as K8n}from"node:fs";import{existsSync as Z8n}from"node:fs";import*as nl from"node:fs/promises";import*as sn from"node:path";import{spawn as sHn,spawnSync as aHn}from"node:child_process";import{homedir as Hzt,platform as uHn,release as pHn}from"node:os";import{resolve as tWt}from"node:path";import{isIP as nWt}from"node:net";import{createHash as aWt}from"node:crypto";import{mkdirSync as HHn,readFileSync as VHn,rmSync as oXt,writeFileSync as qHn}from"node:fs";import{hostname as sXt}from"node:os";import{dirname as WHn}from"node:path";import{existsSync as cWt,realpathSync as oVn}from"node:fs";import{dirname as sVn,isAbsolute as aVn,join as lVn,resolve as jhe,sep as cVn}from"node:path";import{existsSync as DI,mkdirSync as HWe,renameSync as VWe,rmSync as iJ,writeFileSync as qWe}from"node:fs";import{execFile as mVn,spawnSync as gVn}from"node:child_process";import{createHash as pXt,randomUUID as fXt}from"node:crypto";import{tmpdir as hXt}from"node:os";import{join as ob}from"node:path";import{spawnSync as uWt}from"node:child_process";import{accessSync as bVn,constants as vVn,existsSync as SXt,realpathSync as xXt,statSync as CXt}from"node:fs";import{delimiter as IVn,isAbsolute as EVn,join as kVn,resolve as TXt}from"node:path";import{createHash as RVn,createPublicKey as PVn,verify as _Vn}from"node:crypto";import{readFileSync as BVn,statSync as $Vn}from"node:fs";import{isAbsolute as MVn}from"node:path";import{createHash as hhe,randomUUID as NXt}from"node:crypto";import{accessSync as FVn,chmodSync as fWt,constants as UVn,existsSync as qhe,lstatSync as RVe,mkdirSync as QVn,readFileSync as H6,realpathSync as DXt,statSync as LXt,unlinkSync as GVn,writeFileSync as jVn}from"node:fs";import{tmpdir as FXt}from"node:os";import{dirname as UXt,isAbsolute as PVe,join as HS,parse as hWt}from"node:path";import{spawnSync as mWt}from"node:child_process";import{fileURLToPath as HVn}from"node:url";import{randomBytes as hqn}from"node:crypto";import*as Ym from"path";import*as Wu from"path";import*as zhe from"os";import*as Ju from"node:fs/promises";import{createHash as Pqn,randomUUID as _qn}from"node:crypto";import{createHash as Uqn}from"node:crypto";import{constants as xWt}from"node:fs";import{open as Qqn,stat as Gqn}from"node:fs/promises";import{resolve as jqn}from"node:path";import*as bP from"path";import{randomUUID as qqn}from"crypto";import*as x6 from"path";import{randomUUID as Wqn}from"crypto";import{stat as Jqn}from"fs/promises";import*as GA from"path";import*as PI from"path";import{resolve as iHe}from"node:path";import{existsSync as PYt,statSync as _Yt}from"node:fs";import{extname as NYt}from"node:path";import{createHash as oWn,randomBytes as sWn}from"node:crypto";import{closeSync as aWn,existsSync as Zhe,mkdirSync as lWn,openSync as cWn,readFileSync as WYt,readSync as dWn,readdirSync as uWn,statSync as JYt,unlinkSync as TWt,writeFileSync as jVe}from"node:fs";import{join as EJ,resolve as pWn}from"node:path";import{closeSync as AWn,existsSync as wWn,openSync as yWn,readSync as bWn,statSync as vWn}from"node:fs";import{readFile as IWn}from"node:fs/promises";import{extname as KYt}from"node:path";import{existsSync as CWn}from"node:fs";import{dirname as PWt}from"node:path";import{existsSync as PWn}from"node:fs";import{dirname as _Wn,extname as BWn}from"node:path";import{existsSync as oHe}from"node:fs";import{promises as UWn}from"node:fs";import{dirname as QWn,extname as GWn}from"node:path";import{readdir as r6n,stat as n6n}from"node:fs/promises";import{basename as i6n,join as o6n,relative as fKt}from"node:path";import{execFile as c6n}from"node:child_process";import{existsSync as d6n,statSync as u6n}from"node:fs";import YVe,{dirname as p6n}from"node:path";import{execFile as b6n}from"node:child_process";import{existsSync as ZVe,statSync as rme}from"node:fs";import eqe,{dirname as v6n}from"node:path";import{readFile as I6n}from"node:fs/promises";import{createHash as lHe,randomUUID as Lfe}from"node:crypto";import{accessSync as U6n,appendFileSync as Q6n,constants as MWt,existsSync as G6n,lstatSync as j6n,mkdirSync as cHe,readFileSync as H6n,readdirSync as V6n,statSync as q6n,writeFileSync as W6n}from"node:fs";import{join as dHe,resolve as J6n}from"node:path";import{spawn as nJn}from"node:child_process";import{randomUUID as iJn}from"node:crypto";import{platform as ome}from"node:os";import{resolve as zKt}from"node:path";import{StringDecoder as FWt}from"node:string_decoder";import{createHash as lJn,randomUUID as ZWt}from"node:crypto";import{closeSync as cJn,createWriteStream as e6t,existsSync as dJn,lstatSync as uJn,mkdirSync as pJn,openSync as fJn,readSync as i9t,rmSync as t6t,statSync as r6t}from"node:fs";import{join as bHe,resolve as vHe,sep as hJn}from"node:path";import{randomUUID as AJn}from"node:crypto";import{spawn as wJn}from"node:child_process";import{existsSync as yJn,mkdirSync as bJn,readFileSync as vJn,rmSync as f6t}from"node:fs";import{tmpdir as IJn}from"node:os";import{join as o9t,resolve as h6t}from"node:path";import{existsSync as w9t,statSync as y9t}from"node:fs";import{delimiter as LJn,isAbsolute as FJn,join as lqe,resolve as UJn}from"node:path";import{statSync as WJn}from"node:fs";import{isAbsolute as JJn,normalize as zJn}from"node:path";import{randomUUID as kHe}from"node:crypto";import{existsSync as S6e,statSync as v9t}from"node:fs";import{tmpdir as ZJn}from"node:os";import{join as ezn}from"node:path";import{randomUUID as S9t}from"node:crypto";import{promises as k6t}from"node:fs";import Lzn from"node:path";import{createHash as _7t}from"node:crypto";import{existsSync as WYn,lstatSync as JYn,mkdirSync as zYn,rmSync as XYn}from"node:fs";import{open as YYn,readFile as KYn,stat as q6t,writeFile as ZYn}from"node:fs/promises";import{tmpdir as eKn}from"node:os";import{extname as Dqe,join as ege}from"node:path";import{existsSync as yKn,readFileSync as bKn,statSync as vKn}from"node:fs";import{spawnSync as LKn}from"node:child_process";import{spawnSync as QKn}from"node:child_process";import{existsSync as zKn,readFileSync as XKn,statSync as YKn}from"node:fs";import{existsSync as u9n}from"node:fs";import{mkdir as p9n,readFile as f9n,writeFile as iJt}from"node:fs/promises";import{dirname as h9n,extname as oJt,join as m9n}from"node:path";import{spawnSync as O9n}from"node:child_process";import{mkdtempSync as N9n,rmSync as D9n,writeFileSync as lJt}from"node:fs";import{tmpdir as L9n}from"node:os";import{join as YHe}from"node:path";import{existsSync as wme,mkdirSync as H9n,mkdtempSync as dJt,readFileSync as Vqe,rmSync as V9n,statSync as yme}from"node:fs";import{spawnSync as q9n}from"node:child_process";import{basename as uJt,isAbsolute as wer,join as Vfe,relative as W9n}from"node:path";import{tmpdir as ZHe}from"node:os";import{createHash as J9n}from"node:crypto";import{spawn as rge}from"node:child_process";import{accessSync as iZn,constants as oZn,readFileSync as nge}from"node:fs";import{delimiter as sZn,extname as jP,isAbsolute as aZn,join as lZn,resolve as ige}from"node:path";import{fileURLToPath as Ser,pathToFileURL as Xm}from"node:url";import{readdirSync as CZn}from"node:fs";import{basename as TZn,relative as RZn,resolve as PZn,sep as aL}from"node:path";import{readdirSync as NZn}from"node:fs";import{dirname as DZn,join as Ler,relative as LZn}from"node:path";import{randomBytes as zZn}from"node:crypto";import{existsSync as Her}from"node:fs";import{extname as Ver}from"node:path";import{execFile as u7n}from"node:child_process";import{promisify as p7n}from"node:util";import{posix as tWe}from"node:path";import{posix as M6}from"node:path";import{randomUUID as lWe}from"node:crypto";import{existsSync as N6,mkdirSync as tJe,readFileSync as O7n,readdirSync as Nhe,rmSync as Dhe,statSync as N7n,writeFileSync as D7n}from"node:fs";import{hostname as L7n,userInfo as F7n}from"node:os";import{dirname as vtr,join as uf}from"node:path";import{performance as nVe}from"node:perf_hooks";import{execFileSync as Rei}from"node:child_process";import{randomUUID as Pei}from"node:crypto";import{createRequire as $ei}from"node:module";import{createHash as Gei,randomUUID as jei}from"node:crypto";import{appendFileSync as Hei,closeSync as Vei,existsSync as nhe,fstatSync as qei,mkdirSync as L6,openSync as Wei,readFileSync as Jei,readSync as zei,readdirSync as g6,rmSync as A6,writeFileSync as Lhe}from"node:fs";import{basename as sVe,dirname as rrr,join as Xd,resolve as Xei}from"node:path";import{closeSync as Yei,fstatSync as Kei,openSync as Zei,readSync as eti}from"node:fs";import{createHash as nti}from"node:crypto";import{closeSync as iti,fstatSync as LJt,openSync as oti,readSync as sti}from"node:fs";import{resolve as ati}from"node:path";import{existsSync as lti,linkSync as cti,mkdirSync as dti,readFileSync as uti,rmSync as gJe,statSync as pti,writeFileSync as fti}from"node:fs";import{hostname as nrr}from"node:os";import{dirname as hti}from"node:path";import{randomUUID as mti}from"node:crypto";import{createHash as gti,randomBytes as Ati}from"node:crypto";import{chmodSync as wti,existsSync as yti,mkdirSync as irr,readFileSync as bti,unlinkSync as orr,writeFileSync as vti}from"node:fs";import{dirname as Iti,join as _J}from"node:path";import{execFile as srr,execFileSync as AJe}from"node:child_process";import{promisify as arr}from"node:util";import{createHash as Eti}from"node:crypto";import{existsSync as lrr,readFileSync as wJe,readlinkSync as kti}from"node:fs";import{hostname as ZS}from"node:os";import{createHash as yrr,randomBytes as Fti,randomUUID as brr}from"node:crypto";import{closeSync as vrr,existsSync as RJe,fstatSync as Uti,fsyncSync as Qti,mkdirSync as PJe,openSync as Irr,readFileSync as fWe,readSync as Gti,writeFileSync as Err}from"node:fs";import{cpus as jti}from"node:os";import{dirname as krr,isAbsolute as Hti,join as lL,resolve as Vti}from"node:path";import{renameSync as eri}from"node:fs";import{createHash as rri}from"node:crypto";import{join as nri}from"node:path";import{createHash as ari,randomUUID as lri}from"node:crypto";import{link as cri,lstat as dri,mkdir as uri,open as lVe,readdir as pri,unlink as qJt}from"node:fs/promises";import{join as cVe,resolve as fri}from"node:path";import{join as Nrr}from"node:path";import{createHash as gWe,randomUUID as AWe}from"node:crypto";import{appendFileSync as y6,closeSync as xri,existsSync as kI,fstatSync as Cri,mkdirSync as eL,openSync as Tri,readFileSync as Drr,readSync as Rri,readdirSync as zJt,writeFileSync as Lrr}from"node:fs";import{cpus as Pri}from"node:os";import{basename as _ri,dirname as Frr,isAbsolute as Urr,join as mi,relative as Bri,resolve as rJ}from"node:path";import{closeSync as $ri,fstatSync as Mri,openSync as Ori,readSync as Nri}from"node:fs";import{randomUUID as XJt}from"node:crypto";import{closeSync as Lri,fstatSync as YJt,linkSync as Fri,openSync as Uri,readSync as Qri,unlinkSync as Gri,writeFileSync as jri}from"node:fs";import{basename as Hri,join as Qrr}from"node:path";import{spawn as Vri}from"node:child_process";import{openSync as wWe,closeSync as yWe,fstatSync as qri,readSync as Wri}from"node:fs";import{StringDecoder as KJt}from"node:string_decoder";import{setTimeout as Jri}from"node:timers/promises";import{execFileSync as zri}from"node:child_process";import{randomUUID as Xri}from"node:crypto";import{existsSync as Yri,lstatSync as Kri,mkdirSync as Zri,readdirSync as eni,rmdirSync as tni,unlinkSync as rni}from"node:fs";import{isAbsolute as nni,join as BJe,resolve as pJ}from"node:path";import*as $ge from"fs";import{exec as rii}from"node:child_process";import{promisify as nii}from"node:util";function j8n(e){return e.startsWith("local:")}function q8n(e){let t=e.trim().toLowerCase();return!t||t.length>64||Tzt.test(t)||!Czt.test(t)?null:t}function W8n(e,t){if(typeof t=="boolean")return t;if(typeof t=="number")return e!=="protocol_version"||!Number.isInteger(t)||t<0||t>100?null:t;if(typeof t!="string")return null;let r=q8n(t);if(!r)return null;let n=wVe.get(e);return n||(n=new Set,wVe.set(e,n)),!n.has(r)&&n.size>=Szt?"other":(n.add(r),r)}function J8n(e={}){let t={};for(let[r,n]of Object.entries(e)){if(Object.keys(t).length>=kzt)break;if(!Rzt.has(r))continue;let i=W8n(r,n);i!==null&&(t[r]=i)}return Object.freeze(t)}function Izt(e){if(AVe.size===0||!xzt.test(e.name)||e.name.length>128)return;let t=e.kind==="event"?1:e.value??1;if(!Number.isFinite(t)||t<0)return;let r=Object.freeze({schemaVersion:Ezt,kind:e.kind,name:e.name,value:Math.min(t,Number.MAX_SAFE_INTEGER),timestamp:(e.timestamp??new Date).toISOString(),attributes:J8n(e.attributes)});for(let n of AVe)try{n(r)}catch{}}function VD(e,t=1,r){Izt({kind:"counter",name:e,value:t,attributes:r})}function gVe(e,t,r){Izt({kind:"histogram",name:e,value:t,attributes:r})}function _zt(e){QA.delete(e)}async function z8n(e){try{let t=await CWe.stat(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(t.code==="ENOENT")return null;throw t}}function Zqt(e,t){for(QA.delete(e),QA.set(e,t);QA.size>Bzt;){let r=QA.keys().next().value;if(r===void 0)break;QA.delete(r)}}async function X8n(e,t,r){let n=await CWe.open(e,"r");try{let i=Math.min(r,t),o=Buffer.alloc(i);return await n.read(o,0,i,t-i),o.toString("utf-8")}finally{await n.close()}}async function TWe(e,t,r,n={}){let i=await z8n(e);if(!i)return QA.delete(e),null;let o=QA.get(e);if(o&&o.mtimeMs===i.mtimeMs&&o.size===i.size&&o.values.has(t))return lhe.hits+=1,Zqt(e,o),o.values.get(t);let s,a=n.tailBytes;if(a!==void 0&&i.size>a&&(lhe.reads+=1,s=r(await X8n(e,i.size,a),!0)),s===void 0){let d;try{d=await CWe.readFile(e,"utf-8")}catch(u){if(u.code==="ENOENT")return QA.delete(e),null;throw u}lhe.reads+=1,s=r(d,!1)}let l=QA.get(e),c=l&&l.mtimeMs===i.mtimeMs&&l.size===i.size?l:{mtimeMs:i.mtimeMs,size:i.size,values:new Map};return c.values.set(t,s),Zqt(e,c),s}function Y8n(e){return TWe(e,"text",t=>t)}async function EL(e){await nl.mkdir(e,{recursive:!0})}async function Yd(e,t){let r=sn.dirname(e);await EL(r);let n=Math.random().toString(36).substring(2,15),i=`${e}.tmp.${process.pid}.${n}`;try{await nl.writeFile(i,t),await eHn(i,e),_zt(e)}finally{try{await nl.unlink(i)}catch{}}}async function eHn(e,t){for(let r=0;;r+=1)try{await nl.rename(e,t);return}catch(n){let i=n.code,o=OWe[r];if(process.platform!=="win32"||!i||!MWe.has(i)||o===void 0)throw n;await new Promise(s=>setTimeout(s,o))}}function kL(e,t,r=K8n){for(let n=0;;n+=1)try{r(e,t);return}catch(i){let o=i.code,s=OWe[n];if(process.platform!=="win32"||!o||!MWe.has(o)||s===void 0)throw i;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,s)}}async function J8e(e,t){let r=sn.dirname(e);await EL(r),await nl.appendFile(e,t+`
|
|
@@ -5345,7 +5345,7 @@ public static class XenoProtectedWrite {
|
|
|
5345
5345
|
$request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
5346
5346
|
$result = [XenoProtectedWrite]::Run([string]$request.path, [Convert]::FromBase64String([string]$request.payload), [bool]$request.ifAbsent, [string]$request.operationId, [string]$request.operation, [int]$request.parentPid, [long]$request.parentBirth)
|
|
5347
5347
|
$result | ConvertTo-Json -Compress
|
|
5348
|
-
`});Nei=Y(()=>{"use strict";fs(),DJt(),DJt(),Oei=Mei()?.isPlatformSupported===!0}),dJe=Y(()=>{"use strict";fge(),kei(),_tr(),Ptr(),SL(),PXt(),Pme(),UP(),yJ(),Jtr(),Sei(),Cei(),XWe(),Tei(),YWe(),KWe(),Nei(),ZWe(),rYt()}),hge=Y(()=>{"use strict"}),mge=Y(()=>{"use strict";Tme(),hge(),Dei=2*1024*1024,Lei=64*1024*1024}),uJe=Y(()=>{"use strict";mge(),hge(),Fei=128*1024}),Ktr=Y(()=>{"use strict"}),xL=Y(()=>{"use strict";uJe(),mge(),HI(),QI(),sJe(),iJe(),Gtr(),fs(),cJe(),Ktr(),nc(),Lme(),dJe(),HP()}),Ztr=Y(()=>{"use strict";aJe(),lJe(),dJe(),xL()}),err="0.10.109";QI();Pzt();Uei={producerVersion:err,defaultModel:()=>bzt,recordCounter:(e,t,r)=>VD(e,t,r),recordHistogram:(e,t,r)=>gVe(e,t,r)},pJe=Symbol.for("xenosystem.agent-sdk.runs.runtime.v1"),fJe=globalThis;trr=class extends Error{code="RUN_WORKER_UNAVAILABLE";constructor(){super("No run worker program is bound in this process, so a background run cannot be started here.")}};tti=1024*1024,rti=64*1024;vL=64*1024;wn();fs();crr=3e3,yJe=crr,bJe=4e3,drr=15e3,vJe=2e3,TL=1e4,bme={platform:process.platform,now:()=>Date.now(),runSync:(e,t,r)=>AJe(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,stdio:["ignore","pipe","ignore"]}),run:async(e,t,r)=>(await arr(srr)(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,maxBuffer:1024*1024,signal:r.signal})).stdout},Bh=bme,SP=new Map,cJ=0;yge=e=>$J(e,{fresh:!0});Ege=3e4;wn();Fhe=64,Srr=16,hWe=16*1024*1024,QJt=15*6e4,Zs=class extends Error{constructor(e,t,r){super(t,r),this.code=e,this.name="WorkflowResourceError"}code},qti={control:1e3,foreground:900,reconciliation:850,terminal:800,"app-server":700,workflow:500,background:400,scheduled:300};Bl=class{policy;rootDir;ledgerPath;lockPath;now;owner;fault;constructor(e={}){this.rootDir=e.rootDir??lL(ti(),"governor"),this.ledgerPath=lL(this.rootDir,"resource-ledger.json"),this.lockPath=lL(this.rootDir,"resource-ledger.lock"),this.policy=e.policy??Crr(),this.now=e.now??Date.now,this.owner=e.owner??RL,this.fault=e.fault,PJe(this.rootDir,{recursive:!0})}acquire(e){Zti(e);let t=0,r=this.withLedger((s,a)=>{this.cleanupExpired(s,a);let l=s.permits.find(b=>b.requestId===e.requestId||b.attemptId===e.attemptId);if(l)return t=s.permits.length,{value:{status:"active",permit:l,reason:"attempt_already_active"},changed:!0};let c=Yti(e,a,this.policy.maxQueueWaitMs);if(a>Date.parse(c.deadlineAt))return{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!1};let d=s.queue.find(b=>b.requestId===e.requestId);if(d&&a>Date.parse(d.queueDeadlineAt??c.deadlineAt))return s.queue=s.queue.filter(b=>b.requestId!==e.requestId),{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!0};if(!d&&s.queue.length>=this.policy.maxQueueLength)return{value:{status:"rejected",code:"WORKFLOW_QUEUE_FULL",reason:"The host workflow queue is full."},changed:!1};let u=e.owner??this.owner(),p=d?{...d,...e,owner:d.owner,updatedAt:us(a)}:{...e,owner:u,requestedAt:c.requestedAt,queueDeadlineAt:c.deadlineAt,enqueuedAt:us(a),updatedAt:us(a)};d?s.queue=s.queue.map(b=>b.requestId===p.requestId?p:b):s.queue.push(p);let f=Kti(s.queue,a,this.policy),h,m={};for(let b of f){let I=VJt(s,b,this.policy,a);if(b.requestId===p.requestId&&(m=I),!I.reason){h=b;break}}if(m.code==="WORKFLOW_ATTEMPT_LIMIT"||m.code==="WORKFLOW_TOKEN_LIMIT"||m.code==="WORKFLOW_COST_LIMIT")return s.queue=s.queue.filter(b=>b.requestId!==p.requestId),{value:{status:"rejected",code:m.code,reason:m.reason??"resource_limit"},changed:!0};if(!h||h.requestId!==p.requestId){let b=s.permits.map(S=>Date.parse(S.expiresAt)).filter(Number.isFinite).sort((S,x)=>S-x)[0],I=Trr(this.policy,p.providerId),v=s.providerRates.filter(S=>S.providerId===p.providerId&&(!p.credentialFingerprint||S.credentialFingerprint===p.credentialFingerprint)).map(S=>Date.parse(S.timestamp)+I.windowMs).filter(S=>Number.isFinite(S)&&S>a).sort((S,x)=>S-x)[0],E=[b,v].filter(S=>typeof S=="number").sort((S,x)=>S-x)[0];return{value:{status:"queued",request:p,reason:m.reason??"waiting_for_fair_turn",...E?{estimatedEligibleAt:us(E)}:{}},changed:!0}}let g=VJt(s,p,this.policy,a);if(g.reason)return g.code==="WORKFLOW_ATTEMPT_LIMIT"||g.code==="WORKFLOW_TOKEN_LIMIT"||g.code==="WORKFLOW_COST_LIMIT"?(s.queue=s.queue.filter(b=>b.requestId!==p.requestId),{value:{status:"rejected",code:g.code,reason:g.reason},changed:!0}):{value:{status:"queued",request:p,reason:g.reason},changed:!0};let A=us(a),w={permitId:`permit_${brr()}`,requestId:p.requestId,operationId:p.operationId,surface:p.surface,priorityClass:p.priorityClass,runId:p.runId,...p.parentId?{parentId:p.parentId}:{},providerId:p.providerId,...p.credentialFingerprint?{credentialFingerprint:p.credentialFingerprint}:{},logicalChildId:p.logicalChildId,attemptId:p.attemptId,idempotencyKey:p.idempotencyKey,fencingToken:s.nextFencingToken++,owner:p.owner,acquiredAt:A,heartbeatAt:A,expiresAt:us(a+this.policy.leaseTtlMs),reservedTokens:ZD(p.reservedTokens),reservedCostUsd:ZD(p.reservedCostUsd),lastDurableSequence:0};s.queue=s.queue.filter(b=>b.requestId!==p.requestId),s.permits.push(w),t=s.permits.length;let y=s.attempts.find(b=>b.attemptId===p.attemptId);return y?Object.assign(y,{state:"active",permitId:w.permitId,operationId:p.operationId,endedAt:void 0,outcome:void 0,refusedClaim:void 0}):s.attempts.push({runId:p.runId,operationId:p.operationId,logicalChildId:p.logicalChildId,attemptId:p.attemptId,idempotencyKey:p.idempotencyKey,state:"active",permitId:w.permitId,startedAt:A}),s.providerRates.push({providerId:p.providerId,...p.credentialFingerprint?{credentialFingerprint:p.credentialFingerprint}:{},timestamp:A,tokens:w.reservedTokens}),this.fault?.("acquire.before_commit"),{value:{status:"acquired",permit:w},changed:!0,afterCommit:()=>this.fault?.("acquire.after_commit")}}),n=r.status==="rejected"?r.code:r.status==="acquired"?"admitted":r.reason;jo().recordCounter("xeno.workflow.admission_results",1,{component:"resource_governor",provider:e.providerId,state:r.status,reason:n,...r.status==="rejected"?{error_code:r.code}:{}}),(n==="provider_request_rate"||n==="provider_token_rate"||n==="provider_concurrency"||n==="credential_concurrency")&&jo().recordCounter("xeno.workflow.provider_throttles",1,{component:"resource_governor",provider:e.providerId,reason:n});let i=Date.parse((r.status==="queued"?r.request.requestedAt:e.requestedAt)??""),o=r.status==="acquired"||r.status==="active"?Date.parse(r.permit.acquiredAt):this.now();return Number.isFinite(i)&&Number.isFinite(o)&&jo().recordHistogram("xeno.workflow.queue_wait_ms",Math.max(0,o-i),{component:"resource_governor",provider:e.providerId,state:r.status}),t>0&&jo().recordHistogram("xeno.workflow.active_concurrency",t,{component:"resource_governor",provider:e.providerId}),r}heartbeat(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r),i=e.owner??this.owner();if(!HJt(n.owner,i))throw new Zs("WORKER_IDENTITY_MISMATCH","Permit heartbeat came from a different worker identity.");return n.heartbeatAt=us(r),n.expiresAt=us(r+this.policy.leaseTtlMs),n.lastDurableSequence=Math.max(n.lastDurableSequence,Math.max(0,e.lastDurableSequence??0)),{value:{...n},changed:!0}})}assertFence(e,t){return this.withLedger((r,n)=>({value:{...this.currentPermit(r,e,t,n)},changed:!1}))}beginHandoff(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r);if(n.claimedAt)return{value:{...n},changed:!1};let i=Math.max(Date.parse(n.expiresAt),r+this.policy.handoffTtlMs);return n.handoff={target:{...e.target},startedAt:us(r),deadlineAt:us(i)},n.owner={...e.target},n.expiresAt=us(i),{value:{...n},changed:!0}})}transfer(e,t,r){let n=this.withLedger((i,o)=>{this.cleanupExpired(i,o);let s=l=>{let c=i.attempts.find(d=>d.permitId===e);return c?(c.refusedClaim={pid:r.pid,code:l.code,at:us(o)},{value:{error:l},changed:!0}):{value:{error:l},changed:!1}},a=i.permits.find(l=>l.permitId===e);if(!a||a.fencingToken!==t){let l=i.attempts.find(c=>c.permitId===e);return s(l?.outcome==="WORKER_HANDOFF_EXPIRED"||l?.outcome==="WORKER_HANDOFF_ABANDONED"?new Zs("WORKER_HANDOFF_EXPIRED",`The worker hand-off window closed (${l.outcome} at ${l.endedAt??"unknown"}) before this worker claimed its permit.`):new Zs("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out."))}if(a.handoff){let l=a.handoff.target;if(l.pid!==r.pid||l.hostname!==r.hostname)return s(new Zs("WORKER_IDENTITY_MISMATCH","The permit hand-off is bound to a different worker process."))}else if(a.claimedAt&&!HJt(a.owner,r))return s(new Zs("WORKER_IDENTITY_MISMATCH","The permit is already claimed by another worker process."));return a.owner=r,delete a.handoff,a.claimedAt??=us(o),a.heartbeatAt=us(o),a.expiresAt=us(o+this.policy.leaseTtlMs),{value:{permit:{...a}},changed:!0}});if("error"in n)throw n.error;return n.permit}settle(e){return this.withLedger((t,r)=>{let n=t.permits.find(a=>a.permitId===e.permitId);if(!n)return{value:!1,changed:!1};if(n.fencingToken!==e.fencingToken||Date.parse(n.expiresAt)<=r)throw new Zs("WORKER_LEASE_EXPIRED","The worker fencing token is stale.");t.permits=t.permits.filter(a=>a.permitId!==n.permitId);let i=t.attempts.find(a=>a.attemptId===n.attemptId);i&&Object.assign(i,{state:"settled",endedAt:us(r),outcome:e.outcome});let o=t.usage.find(a=>a.runId===n.runId),s={runId:n.runId,tokens:(o?.tokens??0)+ZD(e.actualTokens),costUsd:(o?.costUsd??0)+ZD(e.actualCostUsd),attempts:(o?.attempts??0)+1,updatedAt:us(r)};return t.usage=[...t.usage.filter(a=>a.runId!==n.runId),s],{value:!0,changed:!0}})}settleOperation(e,t,r=0,n=0){let i=this.snapshot().permits.find(o=>o.operationId===e);return i?this.settle({permitId:i.permitId,fencingToken:i.fencingToken,outcome:t,actualTokens:r,actualCostUsd:n}):!1}cancelQueued(e){return this.withLedger(t=>{let r=t.queue.some(n=>n.requestId===e);return t.queue=t.queue.filter(n=>n.requestId!==e),{value:r,changed:r}})}claimEffect(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r),i=t.effects.find(o=>o.effectKey===e.effectKey||o.idempotencyKey===n.idempotencyKey);return i?{value:i.permitId===n.permitId&&i.fencingToken===n.fencingToken&&i.state==="claimed",changed:!1}:(t.effects.push({effectKey:e.effectKey,idempotencyKey:n.idempotencyKey,permitId:n.permitId,fencingToken:n.fencingToken,state:"claimed",claimedAt:us(r)}),{value:!0,changed:!0})})}commitEffect(e){return this.withLedger((t,r)=>{this.currentPermit(t,e.permitId,e.fencingToken,r);let n=t.effects.find(i=>i.effectKey===e.effectKey);return!n||n.permitId!==e.permitId||n.fencingToken!==e.fencingToken?{value:!1,changed:!1}:n.state==="committed"?{value:!0,changed:!1}:(n.state="committed",n.committedAt=us(r),{value:!0,changed:!0})})}reconcile(e){let t=this.withLedger((r,n)=>{let i=[...r.permits],o=[...r.queue],s=e??BJ(i.map(A=>A.owner.pid)),a=new Set,l=new Set,c=new Set;for(let A of i){let w=zu(A.owner,y=>s.get(y)??null);if(A.handoff){let y=w.status==="mismatch"&&w.observed&&Date.parse(w.observed.processStartedAt)>Date.parse(A.owner.processStartedAt);w.status==="dead"||y?c.add(A.permitId):w.status!=="live"&&l.add(A.permitId);continue}w.status==="mismatch"&&a.add(A.permitId),(w.status==="degraded"||w.status==="remote")&&l.add(A.permitId)}this.cleanupExpired(r,n,a,c);let d=new Set(r.permits.map(A=>A.permitId)),u=i.filter(A=>!d.has(A.permitId)&&!a.has(A.permitId)),p=i.filter(A=>a.has(A.permitId)),f=new Set(r.queue.map(A=>A.requestId)),h=o.filter(A=>!f.has(A.requestId)),m=new Map(r.effects.map(A=>[A.permitId,A.fencingToken]));for(let A of i)m.set(A.permitId,A.fencingToken);let g=new Map(r.attempts.filter(A=>A.state==="expired"&&A.permitId&&(A.outcome==="WORKER_HANDOFF_EXPIRED"||A.outcome==="WORKER_HANDOFF_ABANDONED")&&n-Date.parse(A.endedAt??"")<=QJt).map(A=>[A.attemptId,{...A.operationId?{operationId:A.operationId}:{},permitId:A.permitId,fencingToken:m.get(A.permitId)??0,outcome:A.outcome,...A.endedAt?{endedAt:A.endedAt}:{},...A.refusedClaim?{refusedClaim:{...A.refusedClaim}}:{}}]));return{value:{expiredPermits:u,handoffFailures:g,identityMismatches:p,expiredQueue:h,livePermits:r.permits.length,degradedPermits:r.permits.filter(A=>l.has(A.permitId)).length},changed:u.length>0||p.length>0||h.length>0}});return jo().recordHistogram("xeno.worker.live_leases",t.livePermits,{component:"resource_governor",operation:"reconcile"}),jo().recordHistogram("xeno.worker.degraded_leases",t.degradedPermits,{component:"resource_governor",operation:"reconcile"}),t.expiredPermits.length>0&&jo().recordCounter("xeno.worker.lease_expirations",t.expiredPermits.length,{component:"resource_governor",operation:"reconcile"}),t.identityMismatches.length>0&&jo().recordCounter("xeno.worker.identity_mismatches",t.identityMismatches.length,{component:"resource_governor",operation:"reconcile"}),t}snapshot(){return this.withLedger(e=>({value:structuredClone(e),changed:!1}))}recentHandoffFailureOperations(){return this.withLedger((e,t)=>({value:[...new Set(e.attempts.filter(r=>r.operationId&&r.state==="expired"&&(r.outcome==="WORKER_HANDOFF_EXPIRED"||r.outcome==="WORKER_HANDOFF_ABANDONED")&&t-Date.parse(r.endedAt??"")<=QJt).map(r=>r.operationId))],changed:!1}))}cleanupExpired(e,t,r=new Set,n=new Set){let i=new Map(e.permits.filter(s=>Date.parse(s.expiresAt)<=t||r.has(s.permitId)||n.has(s.permitId)).map(s=>[s.permitId,s]));if(i.size>0){e.permits=e.permits.filter(s=>!i.has(s.permitId));for(let s of e.attempts)s.permitId&&i.has(s.permitId)&&s.state==="active"&&(s.state="expired",s.endedAt=us(t),s.outcome=r.has(s.permitId)?"WORKER_IDENTITY_MISMATCH":n.has(s.permitId)?"WORKER_HANDOFF_ABANDONED":i.get(s.permitId)?.handoff?"WORKER_HANDOFF_EXPIRED":"WORKER_LEASE_EXPIRED")}e.queue=e.queue.filter(s=>Date.parse(s.queueDeadlineAt??s.updatedAt)>t);let o=Math.max(this.policy.providerDefault.windowMs,...Object.values(this.policy.providers).map(s=>s.windowMs??0));if(e.providerRates=e.providerRates.filter(s=>Date.parse(s.timestamp)>t-o),e.attempts.length>2e4){let s=e.attempts.filter(l=>l.state==="active"),a=e.attempts.filter(l=>l.state!=="active").slice(-Math.max(0,2e4-s.length));e.attempts=[...a,...s]}e.effects.length>2e4&&(e.effects=e.effects.slice(-2e4)),e.usage.length>1e4&&(e.usage=e.usage.slice(-1e4))}currentPermit(e,t,r,n){let i=e.permits.find(o=>o.permitId===t);if(!i||Date.parse(i.expiresAt)<=n||i.fencingToken!==r)throw new Zs("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out.");return i}readLedger(e){if(!RJe(this.ledgerPath))return Jti(e);let t;try{t=Irr(this.ledgerPath,"r");let r=Uti(t).size;if(!Number.isSafeInteger(r)||r>hWe)throw new Error(`ledger exceeds the ${hWe} byte limit`);let n=Buffer.alloc(r),i=0;for(;i<r;){let a=Gti(t,n,i,r-i,i);if(a===0)throw new Error("Resource ledger changed during read");i+=a}let o=n.toString("utf8"),s=JSON.parse(o);if(!zti(s))throw new Error("Unsupported resource ledger schema.");return s}catch(r){throw new Zs("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource ledger is unreadable and was not overwritten: ${r instanceof Error?r.message:String(r)}`)}finally{t!==void 0&&vrr(t)}}withLedger(e){let t=Date.now()+Ege+5e3,r=new Int32Array(new SharedArrayBuffer(4)),n,i;for(;!n&&Date.now()<=t;)try{n=md(this.lockPath,"workflow-resource-governor",jo().producerVersion)}catch(o){if(i=o,!(o instanceof Error)||!o.message.includes("is already locked"))break;Atomics.wait(r,0,0,10)}if(!n)throw new Zs("WORKFLOW_GOVERNOR_UNAVAILABLE",i instanceof Error?i.message:String(i??"Resource governor lock unavailable."),{cause:i});try{let o=this.now(),s=this.readLedger(o),a=e(s,o);return a.changed&&(s.revision+=1,s.updatedAt=us(o),Xti(this.ledgerPath,s)),a.afterCommit?.(),a.value}finally{n.release()}}};tri=new Int32Array(new SharedArrayBuffer(4)),Rrr=6e4;jI();jI();NP();NP();QI();iXt();jI();gJ();UWe();QWe();gJ();iri=1,gP={streaming:!0,textInput:!0,imageInput:!0,tools:!0,parallelToolCalls:!0,structuredOutput:!1,reasoningMetadata:!0,usageAccounting:!0,promptCaching:!1,modelDiscovery:!0},ihe={...gP,reasoningMetadata:!1},xos=[Xy("xeno","XENO hosted","xeno","openai-compatible","https://api.xenosystem.ai","public-https","bearer-env","XENO_API_KEY","/v1/models",gP),Xy("openai","OpenAI","direct","openai-responses","https://api.openai.com","public-https","bearer-env","OPENAI_API_KEY","/v1/models",gP),Xy("anthropic","Anthropic","direct","anthropic","https://api.anthropic.com","public-https","header-env","ANTHROPIC_API_KEY","/v1/models",{...gP,structuredOutput:!1}),Xy("google","Google AI Studio","direct","google","https://generativelanguage.googleapis.com","public-https","header-env","GOOGLE_API_KEY","/v1beta/models",gP),Xy("openrouter","OpenRouter","gateway","openai-compatible","https://openrouter.ai/api","public-https","bearer-env","OPENROUTER_API_KEY","/v1/models",ihe),Xy("xeno-rt","xeno-rt","local","openai-compatible","http://127.0.0.1:3338","local-network","none",void 0,"/v1/models",ihe,["running xeno-rt endpoint"]),Xy("ollama","Ollama","local","openai-compatible","http://127.0.0.1:11434","local-network","none",void 0,"/v1/models",ihe,["Ollama OpenAI compatibility endpoint"]),Xy("azure-openai","Azure OpenAI","cloud","openai-compatible",void 0,"public-https","header-env","AZURE_OPENAI_API_KEY",void 0,ihe,["resource endpoint","deployment","API version","host adapter for deployment-shaped requests"]),Xy("aws-bedrock","Amazon Bedrock","cloud","aws-bedrock",void 0,"public-https","cloud-chain",void 0,void 0,{...gP,modelDiscovery:!1},["AWS credential chain","region","Bedrock host adapter"]),Xy("vertex-ai","Google Vertex AI","cloud","vertex-ai",void 0,"public-https","cloud-chain",void 0,void 0,{...gP,modelDiscovery:!1},["Google application-default credentials","project","region","Vertex host adapter"])];wn();LP();pL();pL();ohe=e=>ari("sha256").update(sri(e)).digest("hex"),UD=e=>new Date(e).toISOString().slice(0,10);mri=class{constructor(e,t=Date.now,r=1e5){this.now=t,this.maximumEntries=r,this.directory=fri(e),Ys(r)}now;maximumEntries;directory;async policy(e){return(await this.load()).policies.get(SI(e))??null}async setPolicy(e,t,r){let n={scope:jS(e),limits:JJt(t),revision:Ys(r)+1};return await this.append(()=>({kind:"policy",policy:n,expectedRevision:r})),n}async reservation(e){return(await this.load()).reservations.get(FA(e))??null}async reserve(e){if(e.basis!==void 0&&e.basis!=="estimated")throw new ei("INVALID","Unknown reservation basis.");let t={id:FA(e.id),scope:jS(e.scope),requestHash:FA(e.requestHash),reservedTokens:Ys(e.reservedTokens),...e.basis?{basis:e.basis}:{}};return await this.append((r,n)=>{let i=r.reservations.get(t.id);if(i){if(ohe([i.scope,i.requestHash,i.reservedTokens,i.basis??null])!==ohe([t.scope,t.requestHash,t.reservedTokens,t.basis??null]))throw new ei("CONFLICT","Reservation identity was reused for different work.");return null}return{kind:"reserve",reservation:{...t,admittedAt:n,state:"reserved"}}}),await this.reservation(t.id)}async dispatch(e){await this.append(()=>({kind:"dispatch",id:FA(e)}))}async void(e){await this.append(t=>t.reservations.get(e)?.state==="void"?null:{kind:"void",id:FA(e)})}async settle(e,t){Ys(t),await this.append(r=>{let n=r.reservations.get(e);return n?.state==="settled"&&n.actualTokens===t?null:{kind:"settle",id:FA(e),actualTokens:t}})}async snapshot(e){let t=await this.load(),r=Ys(this.now()),n=jS(e);if(r<t.at)throw new ei("CLOCK_ROLLBACK","Quota clock moved backwards.");let i=[...t.reservations.values()].filter(s=>dVe(s.scope,n)),o=i.filter(s=>UD(s.admittedAt)===UD(r));return{authority:"local-file",policies:phe(n).flatMap(s=>t.policies.get(SI(s))?[t.policies.get(SI(s))]:[]),heldTokens:pP(o.filter(s=>s.state==="reserved"||s.state==="dispatched").map(s=>s.reservedTokens)),usedTokens:pP(o.filter(s=>s.state==="settled").map(s=>s.actualTokens)),lifetimeHeldTokens:pP(i.filter(s=>s.state==="reserved"||s.state==="dispatched").map(s=>s.reservedTokens)),lifetimeUsedTokens:pP(i.filter(s=>s.state==="settled").map(s=>s.actualTokens)),requestsInLastMinute:i.filter(s=>s.state!=="void"&&s.admittedAt>r-6e4).length,unresolved:i.filter(s=>s.state==="dispatched").length}}async remainingTokens(e){let t=await this.load(),r=Ys(this.now());if(r<t.at)throw new ei("CLOCK_ROLLBACK","Quota clock moved backwards.");let n=null;for(let i of phe(e)){let o=t.policies.get(SI(i));if(!o)continue;let s=[...t.reservations.values()].filter(d=>dVe(d.scope,i)&&d.state!=="void"),a=d=>pP(d.map(u=>u.state==="settled"?u.actualTokens:u.reservedTokens)),l=[o.limits.tokensLifetime===void 0?null:o.limits.tokensLifetime,o.limits.tokensPerDay===null?null:o.limits.tokensPerDay],c=[a(s),a(s.filter(d=>UD(d.admittedAt)===UD(r)))];for(let d=0;d<l.length;d+=1){let u=l[d];if(u===null)continue;let p=Math.max(0,u-c[d]);n=n===null?p:Math.min(n,p)}}return n}apply(e,t,r,n=!0){if(t.kind==="policy"){let o=t.policy,s=SI(o.scope);if((e.policies.get(s)?.revision??0)!==t.expectedRevision||o.revision!==t.expectedRevision+1)throw new ei("CONFLICT","Quota policy revision changed.");e.policies.set(s,{scope:jS(o.scope),revision:Ys(o.revision),limits:JJt(o.limits)});return}if(t.kind==="reserve"){let o=t.reservation;if(FA(o.id),FA(o.requestHash),jS(o.scope),Ys(o.reservedTokens),o.state!=="reserved"||o.admittedAt!==r||e.reservations.has(o.id))throw new ei("CORRUPT","Invalid reservation record.");for(let s of n?phe(o.scope):[]){let a=e.policies.get(SI(s));if(!a)continue;let l=[...e.reservations.values()].filter(d=>dVe(d.scope,s)&&d.state!=="void");if(a.limits.requestsPerMinute!==null&&l.filter(d=>d.admittedAt>r-6e4).length>=a.limits.requestsPerMinute)throw new ei("EXCEEDED","Ancestor request rate limit reached.");let c=pP(l.filter(d=>UD(d.admittedAt)===UD(r)).map(d=>d.state==="settled"?d.actualTokens:d.reservedTokens));if(a.limits.tokensPerDay!==null&&Ys(c+o.reservedTokens)>a.limits.tokensPerDay)throw new ei("EXCEEDED","Ancestor daily token limit reached.");if(a.limits.tokensLifetime!==void 0&&a.limits.tokensLifetime!==null){let d=pP(l.map(u=>u.state==="settled"?u.actualTokens:u.reservedTokens));if(Ys(d+o.reservedTokens)>a.limits.tokensLifetime)throw new ei("EXCEEDED","Ancestor lifetime token limit reached.")}}e.reservations.set(o.id,structuredClone(o));return}let i=e.reservations.get(t.id);if(!i)throw new ei("CONFLICT","Reservation does not exist.");if(t.kind==="dispatch"||t.kind==="void"){if(i.state!=="reserved")throw new ei("CONFLICT","Reservation cannot be dispatched twice or release unknown usage.");i.state=t.kind==="dispatch"?"dispatched":"void"}else if(t.kind==="settle"){if(i.state!=="dispatched"||i.basis!=="estimated"&&Ys(t.actualTokens)>i.reservedTokens)throw new ei("CONFLICT","Invalid reservation settlement.");i.state="settled",i.actualTokens=t.actualTokens}else throw new ei("CORRUPT","Unknown quota journal operation.")}async load(){let e={sequence:0,hash:"",at:0,policies:new Map,reservations:new Map},t;try{t=await pri(this.directory)}catch(n){if(n.code==="ENOENT")return e;throw n}let r=t.filter(n=>n.endsWith(".quota")).sort();if(r.length>this.maximumEntries)throw new ei("CAPACITY","Quota journal requires archival maintenance.");for(let n of r){if(n!==`${String(e.sequence+1).padStart(12,"0")}.quota`)throw new ei("CORRUPT","Quota journal sequence is incomplete.");let i=cVe(this.directory,n),o=await dri(i);if(!o.isFile()||o.isSymbolicLink()||o.size>16384)throw new ei("CORRUPT","Invalid quota record file.");let s=await lVe(i,"r"),a;try{let d=Buffer.alloc(16385),u=await s.read(d,0,d.length,0);if(u.bytesRead>16384)throw new ei("CORRUPT","Oversized quota record.");a=JSON.parse(d.subarray(0,u.bytesRead).toString("utf8"))}finally{await s.close()}let{hash:l,...c}=a;if(a.version!==1&&a.version!==2&&a.version!==3||a.sequence!==e.sequence+1||a.previousHash!==e.hash||l!==ohe(c)||Ys(a.at)<e.at)throw new ei("CORRUPT","Quota journal integrity failed.");if(a.version===1&&WJt(a.operation))throw new ei("CORRUPT","Lifetime or goal scope requires quota journal version 2.");this.apply(e,a.operation,a.at,!1),e.sequence=a.sequence,e.hash=l,e.at=a.at}return e}async append(e){await uri(this.directory,{recursive:!0,mode:448});for(let t=0;t<100;t++){let r=await this.load(),n=Ys(this.now());if(n<r.at)throw new ei("CLOCK_ROLLBACK","Quota clock moved backwards.");let i=e(r,n);if(!i)return;if(r.sequence>=this.maximumEntries)throw new ei("CAPACITY","Quota journal requires archival maintenance.");this.apply(r,i,n);let o={version:hri(i)?3:WJt(i)?2:1,sequence:r.sequence+1,previousHash:r.hash,at:n,operation:i},s=JSON.stringify({...o,hash:ohe(o)});if(Buffer.byteLength(s)>16384)throw new ei("CAPACITY","Quota record exceeds its bound.");let a=cVe(this.directory,`${lri()}.tmp`),l=cVe(this.directory,`${String(o.sequence).padStart(12,"0")}.quota`),c=await lVe(a,"wx",384);try{await c.writeFile(s),await c.sync()}catch(d){throw await c.close(),await qJt(a).catch(()=>{}),d}await c.close();try{if(await cri(a,l),process.platform!=="win32"){let d=await lVe(this.directory,"r");try{await d.sync()}finally{await d.close()}}return}catch(d){if(d.code!=="EEXIST")throw d}finally{await qJt(a).catch(()=>{})}}throw new ei("CONFLICT","Quota admission contention exceeded the retry bound.")}};FP();xme();wn();Mc();jWe();Rme();Prr=new Set(["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read"]),_rr=new Set(["browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download","browser.record.start","browser.record.stop"]),Brr=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),$rr=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),_Je=[...Prr,..._rr,...Brr,...$rr];gd();Pos=new Set(["Read","Glob","Grep","LS","GitStatus","GitDiff","GitLog","WebFetch","WebSearch","MemoryRead","NotebookRead","ReadImage","SqliteAnalyze","ElfAnalyze","GcodeAnalyze","HtmlSanitizerAudit","ArtifactCompare","Think","ToolSearch","Skill",..._Je.filter(e=>gri(e).effect==="observe")]);KWe();Ari=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation","page"],wri=["draft","pending_review","approved","rejected","superseded","archived"],yri=["public","internal","confidential","restricted"],bri=["agent","tool","user","system","integration"],Mrr=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],Orr=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];Bme();vri="[\\u0000-\\u001f\\u007f]",_os=new RegExp(vri),Bos=new Set(wri),$os=new Set(yri),Mos=new Set(bri),Oos=new Set(Ari),Nos=new Set(Mrr),Dos=new Set(Orr),Los=32*1024*1024,Fos=1024*1024*1024,Uos=16*1024*1024,Qos=48*1024*1024;yJ();Gos=4*1024*1024;wn();LP();jos=64*1024*1024;yJ();KWe();Hos=8*1024*1024;ZWe();Vos=_Je.filter(e=>e.startsWith("browser.")),qos=_Je.filter(e=>e.startsWith("computer."));Bme();Wos=new Set(Mrr),Jos=new Set(Orr),zos=16*1024*1024;Bme();wn();Xos=16*1024*1024,Yos=1024*1024,Kos=["default-src 'none'","script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net/npm/ https://cdn.tailwindcss.com https://code.jquery.com","style-src 'self' 'unsafe-inline' https://fonts.googleapis.com","font-src 'self' data: https://fonts.gstatic.com","img-src 'self' data: blob:","media-src 'self' data: blob:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; "),Zos=128*1024*1024,ess=new TextDecoder().decode(new Uint8Array([239,191,189]));$me();eYt();tYt();e6e();fs();e6e();UP();HI();HI();QI();HI();Mc();Mc();HI();Mc();Mme();Jhe();sJe();Ftr();Utr();Qtr();$tr();oJe();Ntr();Dtr();Ltr();Ttr();HP();Gtr();Mtr();Otr();wJ();GP();vJ();aJe();x6e();iJe();jtr();lJe();cJe();Lme();P7t();Wtr();l6e();l6e();dJe();hge();mge();uJe();wn();fs();Tme();mge();uJe();hge();HP();h6e();IJ();iKt();btr();m6e();dKt();pKt();KS();xKt();$Kt();E9t();B9t();$9t();O9t();U9t();E6e();zme();jer();L9t();q9t();J9t();q7t();z7t();aer();per();Aer();ker();Ber();Der();Ker();str();ctr();utr();gtr();Atr();Str();gd();Ho();Iri=["completed","partial","failed","cancelled"],tss=["queued","running",...Iri];pge();ab();wn();LP();LP();fs();Eri=Nrr(GI(),"daemon"),sss=Nrr(Eri,"runs");wn();fs();fs();LP();ktr();rJe();kri=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,ass=new RegExp(String.raw`${kri}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i");rJe();wn();lss=512*1024*1024,css=10080*60*1e3,dss=365*24*60*60*1e3;wn();LP();fs();pL();uss=8*1024*1024,pss=64*1024*1024,fss=744*60*60*1e3;FP();hss=Object.freeze({"thread.run":"prompt","turn.start":"input","turn.steer":"input","schedule.create":"prompt","schedule.update":"prompt"}),Sri=["Read","Write","Edit","Glob","Grep","WebFetch"],mss=new Set(Sri),Dri=64*1024;Mc();OP();bWe=2e4,cni=String.raw`
|
|
5348
|
+
`});Nei=Y(()=>{"use strict";fs(),DJt(),DJt(),Oei=Mei()?.isPlatformSupported===!0}),dJe=Y(()=>{"use strict";fge(),kei(),_tr(),Ptr(),SL(),PXt(),Pme(),UP(),yJ(),Jtr(),Sei(),Cei(),XWe(),Tei(),YWe(),KWe(),Nei(),ZWe(),rYt()}),hge=Y(()=>{"use strict"}),mge=Y(()=>{"use strict";Tme(),hge(),Dei=2*1024*1024,Lei=64*1024*1024}),uJe=Y(()=>{"use strict";mge(),hge(),Fei=128*1024}),Ktr=Y(()=>{"use strict"}),xL=Y(()=>{"use strict";uJe(),mge(),HI(),QI(),sJe(),iJe(),Gtr(),fs(),cJe(),Ktr(),nc(),Lme(),dJe(),HP()}),Ztr=Y(()=>{"use strict";aJe(),lJe(),dJe(),xL()}),err="0.10.110";QI();Pzt();Uei={producerVersion:err,defaultModel:()=>bzt,recordCounter:(e,t,r)=>VD(e,t,r),recordHistogram:(e,t,r)=>gVe(e,t,r)},pJe=Symbol.for("xenosystem.agent-sdk.runs.runtime.v1"),fJe=globalThis;trr=class extends Error{code="RUN_WORKER_UNAVAILABLE";constructor(){super("No run worker program is bound in this process, so a background run cannot be started here.")}};tti=1024*1024,rti=64*1024;vL=64*1024;wn();fs();crr=3e3,yJe=crr,bJe=4e3,drr=15e3,vJe=2e3,TL=1e4,bme={platform:process.platform,now:()=>Date.now(),runSync:(e,t,r)=>AJe(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,stdio:["ignore","pipe","ignore"]}),run:async(e,t,r)=>(await arr(srr)(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,maxBuffer:1024*1024,signal:r.signal})).stdout},Bh=bme,SP=new Map,cJ=0;yge=e=>$J(e,{fresh:!0});Ege=3e4;wn();Fhe=64,Srr=16,hWe=16*1024*1024,QJt=15*6e4,Zs=class extends Error{constructor(e,t,r){super(t,r),this.code=e,this.name="WorkflowResourceError"}code},qti={control:1e3,foreground:900,reconciliation:850,terminal:800,"app-server":700,workflow:500,background:400,scheduled:300};Bl=class{policy;rootDir;ledgerPath;lockPath;now;owner;fault;constructor(e={}){this.rootDir=e.rootDir??lL(ti(),"governor"),this.ledgerPath=lL(this.rootDir,"resource-ledger.json"),this.lockPath=lL(this.rootDir,"resource-ledger.lock"),this.policy=e.policy??Crr(),this.now=e.now??Date.now,this.owner=e.owner??RL,this.fault=e.fault,PJe(this.rootDir,{recursive:!0})}acquire(e){Zti(e);let t=0,r=this.withLedger((s,a)=>{this.cleanupExpired(s,a);let l=s.permits.find(b=>b.requestId===e.requestId||b.attemptId===e.attemptId);if(l)return t=s.permits.length,{value:{status:"active",permit:l,reason:"attempt_already_active"},changed:!0};let c=Yti(e,a,this.policy.maxQueueWaitMs);if(a>Date.parse(c.deadlineAt))return{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!1};let d=s.queue.find(b=>b.requestId===e.requestId);if(d&&a>Date.parse(d.queueDeadlineAt??c.deadlineAt))return s.queue=s.queue.filter(b=>b.requestId!==e.requestId),{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!0};if(!d&&s.queue.length>=this.policy.maxQueueLength)return{value:{status:"rejected",code:"WORKFLOW_QUEUE_FULL",reason:"The host workflow queue is full."},changed:!1};let u=e.owner??this.owner(),p=d?{...d,...e,owner:d.owner,updatedAt:us(a)}:{...e,owner:u,requestedAt:c.requestedAt,queueDeadlineAt:c.deadlineAt,enqueuedAt:us(a),updatedAt:us(a)};d?s.queue=s.queue.map(b=>b.requestId===p.requestId?p:b):s.queue.push(p);let f=Kti(s.queue,a,this.policy),h,m={};for(let b of f){let I=VJt(s,b,this.policy,a);if(b.requestId===p.requestId&&(m=I),!I.reason){h=b;break}}if(m.code==="WORKFLOW_ATTEMPT_LIMIT"||m.code==="WORKFLOW_TOKEN_LIMIT"||m.code==="WORKFLOW_COST_LIMIT")return s.queue=s.queue.filter(b=>b.requestId!==p.requestId),{value:{status:"rejected",code:m.code,reason:m.reason??"resource_limit"},changed:!0};if(!h||h.requestId!==p.requestId){let b=s.permits.map(S=>Date.parse(S.expiresAt)).filter(Number.isFinite).sort((S,x)=>S-x)[0],I=Trr(this.policy,p.providerId),v=s.providerRates.filter(S=>S.providerId===p.providerId&&(!p.credentialFingerprint||S.credentialFingerprint===p.credentialFingerprint)).map(S=>Date.parse(S.timestamp)+I.windowMs).filter(S=>Number.isFinite(S)&&S>a).sort((S,x)=>S-x)[0],E=[b,v].filter(S=>typeof S=="number").sort((S,x)=>S-x)[0];return{value:{status:"queued",request:p,reason:m.reason??"waiting_for_fair_turn",...E?{estimatedEligibleAt:us(E)}:{}},changed:!0}}let g=VJt(s,p,this.policy,a);if(g.reason)return g.code==="WORKFLOW_ATTEMPT_LIMIT"||g.code==="WORKFLOW_TOKEN_LIMIT"||g.code==="WORKFLOW_COST_LIMIT"?(s.queue=s.queue.filter(b=>b.requestId!==p.requestId),{value:{status:"rejected",code:g.code,reason:g.reason},changed:!0}):{value:{status:"queued",request:p,reason:g.reason},changed:!0};let A=us(a),w={permitId:`permit_${brr()}`,requestId:p.requestId,operationId:p.operationId,surface:p.surface,priorityClass:p.priorityClass,runId:p.runId,...p.parentId?{parentId:p.parentId}:{},providerId:p.providerId,...p.credentialFingerprint?{credentialFingerprint:p.credentialFingerprint}:{},logicalChildId:p.logicalChildId,attemptId:p.attemptId,idempotencyKey:p.idempotencyKey,fencingToken:s.nextFencingToken++,owner:p.owner,acquiredAt:A,heartbeatAt:A,expiresAt:us(a+this.policy.leaseTtlMs),reservedTokens:ZD(p.reservedTokens),reservedCostUsd:ZD(p.reservedCostUsd),lastDurableSequence:0};s.queue=s.queue.filter(b=>b.requestId!==p.requestId),s.permits.push(w),t=s.permits.length;let y=s.attempts.find(b=>b.attemptId===p.attemptId);return y?Object.assign(y,{state:"active",permitId:w.permitId,operationId:p.operationId,endedAt:void 0,outcome:void 0,refusedClaim:void 0}):s.attempts.push({runId:p.runId,operationId:p.operationId,logicalChildId:p.logicalChildId,attemptId:p.attemptId,idempotencyKey:p.idempotencyKey,state:"active",permitId:w.permitId,startedAt:A}),s.providerRates.push({providerId:p.providerId,...p.credentialFingerprint?{credentialFingerprint:p.credentialFingerprint}:{},timestamp:A,tokens:w.reservedTokens}),this.fault?.("acquire.before_commit"),{value:{status:"acquired",permit:w},changed:!0,afterCommit:()=>this.fault?.("acquire.after_commit")}}),n=r.status==="rejected"?r.code:r.status==="acquired"?"admitted":r.reason;jo().recordCounter("xeno.workflow.admission_results",1,{component:"resource_governor",provider:e.providerId,state:r.status,reason:n,...r.status==="rejected"?{error_code:r.code}:{}}),(n==="provider_request_rate"||n==="provider_token_rate"||n==="provider_concurrency"||n==="credential_concurrency")&&jo().recordCounter("xeno.workflow.provider_throttles",1,{component:"resource_governor",provider:e.providerId,reason:n});let i=Date.parse((r.status==="queued"?r.request.requestedAt:e.requestedAt)??""),o=r.status==="acquired"||r.status==="active"?Date.parse(r.permit.acquiredAt):this.now();return Number.isFinite(i)&&Number.isFinite(o)&&jo().recordHistogram("xeno.workflow.queue_wait_ms",Math.max(0,o-i),{component:"resource_governor",provider:e.providerId,state:r.status}),t>0&&jo().recordHistogram("xeno.workflow.active_concurrency",t,{component:"resource_governor",provider:e.providerId}),r}heartbeat(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r),i=e.owner??this.owner();if(!HJt(n.owner,i))throw new Zs("WORKER_IDENTITY_MISMATCH","Permit heartbeat came from a different worker identity.");return n.heartbeatAt=us(r),n.expiresAt=us(r+this.policy.leaseTtlMs),n.lastDurableSequence=Math.max(n.lastDurableSequence,Math.max(0,e.lastDurableSequence??0)),{value:{...n},changed:!0}})}assertFence(e,t){return this.withLedger((r,n)=>({value:{...this.currentPermit(r,e,t,n)},changed:!1}))}beginHandoff(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r);if(n.claimedAt)return{value:{...n},changed:!1};let i=Math.max(Date.parse(n.expiresAt),r+this.policy.handoffTtlMs);return n.handoff={target:{...e.target},startedAt:us(r),deadlineAt:us(i)},n.owner={...e.target},n.expiresAt=us(i),{value:{...n},changed:!0}})}transfer(e,t,r){let n=this.withLedger((i,o)=>{this.cleanupExpired(i,o);let s=l=>{let c=i.attempts.find(d=>d.permitId===e);return c?(c.refusedClaim={pid:r.pid,code:l.code,at:us(o)},{value:{error:l},changed:!0}):{value:{error:l},changed:!1}},a=i.permits.find(l=>l.permitId===e);if(!a||a.fencingToken!==t){let l=i.attempts.find(c=>c.permitId===e);return s(l?.outcome==="WORKER_HANDOFF_EXPIRED"||l?.outcome==="WORKER_HANDOFF_ABANDONED"?new Zs("WORKER_HANDOFF_EXPIRED",`The worker hand-off window closed (${l.outcome} at ${l.endedAt??"unknown"}) before this worker claimed its permit.`):new Zs("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out."))}if(a.handoff){let l=a.handoff.target;if(l.pid!==r.pid||l.hostname!==r.hostname)return s(new Zs("WORKER_IDENTITY_MISMATCH","The permit hand-off is bound to a different worker process."))}else if(a.claimedAt&&!HJt(a.owner,r))return s(new Zs("WORKER_IDENTITY_MISMATCH","The permit is already claimed by another worker process."));return a.owner=r,delete a.handoff,a.claimedAt??=us(o),a.heartbeatAt=us(o),a.expiresAt=us(o+this.policy.leaseTtlMs),{value:{permit:{...a}},changed:!0}});if("error"in n)throw n.error;return n.permit}settle(e){return this.withLedger((t,r)=>{let n=t.permits.find(a=>a.permitId===e.permitId);if(!n)return{value:!1,changed:!1};if(n.fencingToken!==e.fencingToken||Date.parse(n.expiresAt)<=r)throw new Zs("WORKER_LEASE_EXPIRED","The worker fencing token is stale.");t.permits=t.permits.filter(a=>a.permitId!==n.permitId);let i=t.attempts.find(a=>a.attemptId===n.attemptId);i&&Object.assign(i,{state:"settled",endedAt:us(r),outcome:e.outcome});let o=t.usage.find(a=>a.runId===n.runId),s={runId:n.runId,tokens:(o?.tokens??0)+ZD(e.actualTokens),costUsd:(o?.costUsd??0)+ZD(e.actualCostUsd),attempts:(o?.attempts??0)+1,updatedAt:us(r)};return t.usage=[...t.usage.filter(a=>a.runId!==n.runId),s],{value:!0,changed:!0}})}settleOperation(e,t,r=0,n=0){let i=this.snapshot().permits.find(o=>o.operationId===e);return i?this.settle({permitId:i.permitId,fencingToken:i.fencingToken,outcome:t,actualTokens:r,actualCostUsd:n}):!1}cancelQueued(e){return this.withLedger(t=>{let r=t.queue.some(n=>n.requestId===e);return t.queue=t.queue.filter(n=>n.requestId!==e),{value:r,changed:r}})}claimEffect(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r),i=t.effects.find(o=>o.effectKey===e.effectKey||o.idempotencyKey===n.idempotencyKey);return i?{value:i.permitId===n.permitId&&i.fencingToken===n.fencingToken&&i.state==="claimed",changed:!1}:(t.effects.push({effectKey:e.effectKey,idempotencyKey:n.idempotencyKey,permitId:n.permitId,fencingToken:n.fencingToken,state:"claimed",claimedAt:us(r)}),{value:!0,changed:!0})})}commitEffect(e){return this.withLedger((t,r)=>{this.currentPermit(t,e.permitId,e.fencingToken,r);let n=t.effects.find(i=>i.effectKey===e.effectKey);return!n||n.permitId!==e.permitId||n.fencingToken!==e.fencingToken?{value:!1,changed:!1}:n.state==="committed"?{value:!0,changed:!1}:(n.state="committed",n.committedAt=us(r),{value:!0,changed:!0})})}reconcile(e){let t=this.withLedger((r,n)=>{let i=[...r.permits],o=[...r.queue],s=e??BJ(i.map(A=>A.owner.pid)),a=new Set,l=new Set,c=new Set;for(let A of i){let w=zu(A.owner,y=>s.get(y)??null);if(A.handoff){let y=w.status==="mismatch"&&w.observed&&Date.parse(w.observed.processStartedAt)>Date.parse(A.owner.processStartedAt);w.status==="dead"||y?c.add(A.permitId):w.status!=="live"&&l.add(A.permitId);continue}w.status==="mismatch"&&a.add(A.permitId),(w.status==="degraded"||w.status==="remote")&&l.add(A.permitId)}this.cleanupExpired(r,n,a,c);let d=new Set(r.permits.map(A=>A.permitId)),u=i.filter(A=>!d.has(A.permitId)&&!a.has(A.permitId)),p=i.filter(A=>a.has(A.permitId)),f=new Set(r.queue.map(A=>A.requestId)),h=o.filter(A=>!f.has(A.requestId)),m=new Map(r.effects.map(A=>[A.permitId,A.fencingToken]));for(let A of i)m.set(A.permitId,A.fencingToken);let g=new Map(r.attempts.filter(A=>A.state==="expired"&&A.permitId&&(A.outcome==="WORKER_HANDOFF_EXPIRED"||A.outcome==="WORKER_HANDOFF_ABANDONED")&&n-Date.parse(A.endedAt??"")<=QJt).map(A=>[A.attemptId,{...A.operationId?{operationId:A.operationId}:{},permitId:A.permitId,fencingToken:m.get(A.permitId)??0,outcome:A.outcome,...A.endedAt?{endedAt:A.endedAt}:{},...A.refusedClaim?{refusedClaim:{...A.refusedClaim}}:{}}]));return{value:{expiredPermits:u,handoffFailures:g,identityMismatches:p,expiredQueue:h,livePermits:r.permits.length,degradedPermits:r.permits.filter(A=>l.has(A.permitId)).length},changed:u.length>0||p.length>0||h.length>0}});return jo().recordHistogram("xeno.worker.live_leases",t.livePermits,{component:"resource_governor",operation:"reconcile"}),jo().recordHistogram("xeno.worker.degraded_leases",t.degradedPermits,{component:"resource_governor",operation:"reconcile"}),t.expiredPermits.length>0&&jo().recordCounter("xeno.worker.lease_expirations",t.expiredPermits.length,{component:"resource_governor",operation:"reconcile"}),t.identityMismatches.length>0&&jo().recordCounter("xeno.worker.identity_mismatches",t.identityMismatches.length,{component:"resource_governor",operation:"reconcile"}),t}snapshot(){return this.withLedger(e=>({value:structuredClone(e),changed:!1}))}recentHandoffFailureOperations(){return this.withLedger((e,t)=>({value:[...new Set(e.attempts.filter(r=>r.operationId&&r.state==="expired"&&(r.outcome==="WORKER_HANDOFF_EXPIRED"||r.outcome==="WORKER_HANDOFF_ABANDONED")&&t-Date.parse(r.endedAt??"")<=QJt).map(r=>r.operationId))],changed:!1}))}cleanupExpired(e,t,r=new Set,n=new Set){let i=new Map(e.permits.filter(s=>Date.parse(s.expiresAt)<=t||r.has(s.permitId)||n.has(s.permitId)).map(s=>[s.permitId,s]));if(i.size>0){e.permits=e.permits.filter(s=>!i.has(s.permitId));for(let s of e.attempts)s.permitId&&i.has(s.permitId)&&s.state==="active"&&(s.state="expired",s.endedAt=us(t),s.outcome=r.has(s.permitId)?"WORKER_IDENTITY_MISMATCH":n.has(s.permitId)?"WORKER_HANDOFF_ABANDONED":i.get(s.permitId)?.handoff?"WORKER_HANDOFF_EXPIRED":"WORKER_LEASE_EXPIRED")}e.queue=e.queue.filter(s=>Date.parse(s.queueDeadlineAt??s.updatedAt)>t);let o=Math.max(this.policy.providerDefault.windowMs,...Object.values(this.policy.providers).map(s=>s.windowMs??0));if(e.providerRates=e.providerRates.filter(s=>Date.parse(s.timestamp)>t-o),e.attempts.length>2e4){let s=e.attempts.filter(l=>l.state==="active"),a=e.attempts.filter(l=>l.state!=="active").slice(-Math.max(0,2e4-s.length));e.attempts=[...a,...s]}e.effects.length>2e4&&(e.effects=e.effects.slice(-2e4)),e.usage.length>1e4&&(e.usage=e.usage.slice(-1e4))}currentPermit(e,t,r,n){let i=e.permits.find(o=>o.permitId===t);if(!i||Date.parse(i.expiresAt)<=n||i.fencingToken!==r)throw new Zs("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out.");return i}readLedger(e){if(!RJe(this.ledgerPath))return Jti(e);let t;try{t=Irr(this.ledgerPath,"r");let r=Uti(t).size;if(!Number.isSafeInteger(r)||r>hWe)throw new Error(`ledger exceeds the ${hWe} byte limit`);let n=Buffer.alloc(r),i=0;for(;i<r;){let a=Gti(t,n,i,r-i,i);if(a===0)throw new Error("Resource ledger changed during read");i+=a}let o=n.toString("utf8"),s=JSON.parse(o);if(!zti(s))throw new Error("Unsupported resource ledger schema.");return s}catch(r){throw new Zs("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource ledger is unreadable and was not overwritten: ${r instanceof Error?r.message:String(r)}`)}finally{t!==void 0&&vrr(t)}}withLedger(e){let t=Date.now()+Ege+5e3,r=new Int32Array(new SharedArrayBuffer(4)),n,i;for(;!n&&Date.now()<=t;)try{n=md(this.lockPath,"workflow-resource-governor",jo().producerVersion)}catch(o){if(i=o,!(o instanceof Error)||!o.message.includes("is already locked"))break;Atomics.wait(r,0,0,10)}if(!n)throw new Zs("WORKFLOW_GOVERNOR_UNAVAILABLE",i instanceof Error?i.message:String(i??"Resource governor lock unavailable."),{cause:i});try{let o=this.now(),s=this.readLedger(o),a=e(s,o);return a.changed&&(s.revision+=1,s.updatedAt=us(o),Xti(this.ledgerPath,s)),a.afterCommit?.(),a.value}finally{n.release()}}};tri=new Int32Array(new SharedArrayBuffer(4)),Rrr=6e4;jI();jI();NP();NP();QI();iXt();jI();gJ();UWe();QWe();gJ();iri=1,gP={streaming:!0,textInput:!0,imageInput:!0,tools:!0,parallelToolCalls:!0,structuredOutput:!1,reasoningMetadata:!0,usageAccounting:!0,promptCaching:!1,modelDiscovery:!0},ihe={...gP,reasoningMetadata:!1},xos=[Xy("xeno","XENO hosted","xeno","openai-compatible","https://api.xenosystem.ai","public-https","bearer-env","XENO_API_KEY","/v1/models",gP),Xy("openai","OpenAI","direct","openai-responses","https://api.openai.com","public-https","bearer-env","OPENAI_API_KEY","/v1/models",gP),Xy("anthropic","Anthropic","direct","anthropic","https://api.anthropic.com","public-https","header-env","ANTHROPIC_API_KEY","/v1/models",{...gP,structuredOutput:!1}),Xy("google","Google AI Studio","direct","google","https://generativelanguage.googleapis.com","public-https","header-env","GOOGLE_API_KEY","/v1beta/models",gP),Xy("openrouter","OpenRouter","gateway","openai-compatible","https://openrouter.ai/api","public-https","bearer-env","OPENROUTER_API_KEY","/v1/models",ihe),Xy("xeno-rt","xeno-rt","local","openai-compatible","http://127.0.0.1:3338","local-network","none",void 0,"/v1/models",ihe,["running xeno-rt endpoint"]),Xy("ollama","Ollama","local","openai-compatible","http://127.0.0.1:11434","local-network","none",void 0,"/v1/models",ihe,["Ollama OpenAI compatibility endpoint"]),Xy("azure-openai","Azure OpenAI","cloud","openai-compatible",void 0,"public-https","header-env","AZURE_OPENAI_API_KEY",void 0,ihe,["resource endpoint","deployment","API version","host adapter for deployment-shaped requests"]),Xy("aws-bedrock","Amazon Bedrock","cloud","aws-bedrock",void 0,"public-https","cloud-chain",void 0,void 0,{...gP,modelDiscovery:!1},["AWS credential chain","region","Bedrock host adapter"]),Xy("vertex-ai","Google Vertex AI","cloud","vertex-ai",void 0,"public-https","cloud-chain",void 0,void 0,{...gP,modelDiscovery:!1},["Google application-default credentials","project","region","Vertex host adapter"])];wn();LP();pL();pL();ohe=e=>ari("sha256").update(sri(e)).digest("hex"),UD=e=>new Date(e).toISOString().slice(0,10);mri=class{constructor(e,t=Date.now,r=1e5){this.now=t,this.maximumEntries=r,this.directory=fri(e),Ys(r)}now;maximumEntries;directory;async policy(e){return(await this.load()).policies.get(SI(e))??null}async setPolicy(e,t,r){let n={scope:jS(e),limits:JJt(t),revision:Ys(r)+1};return await this.append(()=>({kind:"policy",policy:n,expectedRevision:r})),n}async reservation(e){return(await this.load()).reservations.get(FA(e))??null}async reserve(e){if(e.basis!==void 0&&e.basis!=="estimated")throw new ei("INVALID","Unknown reservation basis.");let t={id:FA(e.id),scope:jS(e.scope),requestHash:FA(e.requestHash),reservedTokens:Ys(e.reservedTokens),...e.basis?{basis:e.basis}:{}};return await this.append((r,n)=>{let i=r.reservations.get(t.id);if(i){if(ohe([i.scope,i.requestHash,i.reservedTokens,i.basis??null])!==ohe([t.scope,t.requestHash,t.reservedTokens,t.basis??null]))throw new ei("CONFLICT","Reservation identity was reused for different work.");return null}return{kind:"reserve",reservation:{...t,admittedAt:n,state:"reserved"}}}),await this.reservation(t.id)}async dispatch(e){await this.append(()=>({kind:"dispatch",id:FA(e)}))}async void(e){await this.append(t=>t.reservations.get(e)?.state==="void"?null:{kind:"void",id:FA(e)})}async settle(e,t){Ys(t),await this.append(r=>{let n=r.reservations.get(e);return n?.state==="settled"&&n.actualTokens===t?null:{kind:"settle",id:FA(e),actualTokens:t}})}async snapshot(e){let t=await this.load(),r=Ys(this.now()),n=jS(e);if(r<t.at)throw new ei("CLOCK_ROLLBACK","Quota clock moved backwards.");let i=[...t.reservations.values()].filter(s=>dVe(s.scope,n)),o=i.filter(s=>UD(s.admittedAt)===UD(r));return{authority:"local-file",policies:phe(n).flatMap(s=>t.policies.get(SI(s))?[t.policies.get(SI(s))]:[]),heldTokens:pP(o.filter(s=>s.state==="reserved"||s.state==="dispatched").map(s=>s.reservedTokens)),usedTokens:pP(o.filter(s=>s.state==="settled").map(s=>s.actualTokens)),lifetimeHeldTokens:pP(i.filter(s=>s.state==="reserved"||s.state==="dispatched").map(s=>s.reservedTokens)),lifetimeUsedTokens:pP(i.filter(s=>s.state==="settled").map(s=>s.actualTokens)),requestsInLastMinute:i.filter(s=>s.state!=="void"&&s.admittedAt>r-6e4).length,unresolved:i.filter(s=>s.state==="dispatched").length}}async remainingTokens(e){let t=await this.load(),r=Ys(this.now());if(r<t.at)throw new ei("CLOCK_ROLLBACK","Quota clock moved backwards.");let n=null;for(let i of phe(e)){let o=t.policies.get(SI(i));if(!o)continue;let s=[...t.reservations.values()].filter(d=>dVe(d.scope,i)&&d.state!=="void"),a=d=>pP(d.map(u=>u.state==="settled"?u.actualTokens:u.reservedTokens)),l=[o.limits.tokensLifetime===void 0?null:o.limits.tokensLifetime,o.limits.tokensPerDay===null?null:o.limits.tokensPerDay],c=[a(s),a(s.filter(d=>UD(d.admittedAt)===UD(r)))];for(let d=0;d<l.length;d+=1){let u=l[d];if(u===null)continue;let p=Math.max(0,u-c[d]);n=n===null?p:Math.min(n,p)}}return n}apply(e,t,r,n=!0){if(t.kind==="policy"){let o=t.policy,s=SI(o.scope);if((e.policies.get(s)?.revision??0)!==t.expectedRevision||o.revision!==t.expectedRevision+1)throw new ei("CONFLICT","Quota policy revision changed.");e.policies.set(s,{scope:jS(o.scope),revision:Ys(o.revision),limits:JJt(o.limits)});return}if(t.kind==="reserve"){let o=t.reservation;if(FA(o.id),FA(o.requestHash),jS(o.scope),Ys(o.reservedTokens),o.state!=="reserved"||o.admittedAt!==r||e.reservations.has(o.id))throw new ei("CORRUPT","Invalid reservation record.");for(let s of n?phe(o.scope):[]){let a=e.policies.get(SI(s));if(!a)continue;let l=[...e.reservations.values()].filter(d=>dVe(d.scope,s)&&d.state!=="void");if(a.limits.requestsPerMinute!==null&&l.filter(d=>d.admittedAt>r-6e4).length>=a.limits.requestsPerMinute)throw new ei("EXCEEDED","Ancestor request rate limit reached.");let c=pP(l.filter(d=>UD(d.admittedAt)===UD(r)).map(d=>d.state==="settled"?d.actualTokens:d.reservedTokens));if(a.limits.tokensPerDay!==null&&Ys(c+o.reservedTokens)>a.limits.tokensPerDay)throw new ei("EXCEEDED","Ancestor daily token limit reached.");if(a.limits.tokensLifetime!==void 0&&a.limits.tokensLifetime!==null){let d=pP(l.map(u=>u.state==="settled"?u.actualTokens:u.reservedTokens));if(Ys(d+o.reservedTokens)>a.limits.tokensLifetime)throw new ei("EXCEEDED","Ancestor lifetime token limit reached.")}}e.reservations.set(o.id,structuredClone(o));return}let i=e.reservations.get(t.id);if(!i)throw new ei("CONFLICT","Reservation does not exist.");if(t.kind==="dispatch"||t.kind==="void"){if(i.state!=="reserved")throw new ei("CONFLICT","Reservation cannot be dispatched twice or release unknown usage.");i.state=t.kind==="dispatch"?"dispatched":"void"}else if(t.kind==="settle"){if(i.state!=="dispatched"||i.basis!=="estimated"&&Ys(t.actualTokens)>i.reservedTokens)throw new ei("CONFLICT","Invalid reservation settlement.");i.state="settled",i.actualTokens=t.actualTokens}else throw new ei("CORRUPT","Unknown quota journal operation.")}async load(){let e={sequence:0,hash:"",at:0,policies:new Map,reservations:new Map},t;try{t=await pri(this.directory)}catch(n){if(n.code==="ENOENT")return e;throw n}let r=t.filter(n=>n.endsWith(".quota")).sort();if(r.length>this.maximumEntries)throw new ei("CAPACITY","Quota journal requires archival maintenance.");for(let n of r){if(n!==`${String(e.sequence+1).padStart(12,"0")}.quota`)throw new ei("CORRUPT","Quota journal sequence is incomplete.");let i=cVe(this.directory,n),o=await dri(i);if(!o.isFile()||o.isSymbolicLink()||o.size>16384)throw new ei("CORRUPT","Invalid quota record file.");let s=await lVe(i,"r"),a;try{let d=Buffer.alloc(16385),u=await s.read(d,0,d.length,0);if(u.bytesRead>16384)throw new ei("CORRUPT","Oversized quota record.");a=JSON.parse(d.subarray(0,u.bytesRead).toString("utf8"))}finally{await s.close()}let{hash:l,...c}=a;if(a.version!==1&&a.version!==2&&a.version!==3||a.sequence!==e.sequence+1||a.previousHash!==e.hash||l!==ohe(c)||Ys(a.at)<e.at)throw new ei("CORRUPT","Quota journal integrity failed.");if(a.version===1&&WJt(a.operation))throw new ei("CORRUPT","Lifetime or goal scope requires quota journal version 2.");this.apply(e,a.operation,a.at,!1),e.sequence=a.sequence,e.hash=l,e.at=a.at}return e}async append(e){await uri(this.directory,{recursive:!0,mode:448});for(let t=0;t<100;t++){let r=await this.load(),n=Ys(this.now());if(n<r.at)throw new ei("CLOCK_ROLLBACK","Quota clock moved backwards.");let i=e(r,n);if(!i)return;if(r.sequence>=this.maximumEntries)throw new ei("CAPACITY","Quota journal requires archival maintenance.");this.apply(r,i,n);let o={version:hri(i)?3:WJt(i)?2:1,sequence:r.sequence+1,previousHash:r.hash,at:n,operation:i},s=JSON.stringify({...o,hash:ohe(o)});if(Buffer.byteLength(s)>16384)throw new ei("CAPACITY","Quota record exceeds its bound.");let a=cVe(this.directory,`${lri()}.tmp`),l=cVe(this.directory,`${String(o.sequence).padStart(12,"0")}.quota`),c=await lVe(a,"wx",384);try{await c.writeFile(s),await c.sync()}catch(d){throw await c.close(),await qJt(a).catch(()=>{}),d}await c.close();try{if(await cri(a,l),process.platform!=="win32"){let d=await lVe(this.directory,"r");try{await d.sync()}finally{await d.close()}}return}catch(d){if(d.code!=="EEXIST")throw d}finally{await qJt(a).catch(()=>{})}}throw new ei("CONFLICT","Quota admission contention exceeded the retry bound.")}};FP();xme();wn();Mc();jWe();Rme();Prr=new Set(["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read"]),_rr=new Set(["browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download","browser.record.start","browser.record.stop"]),Brr=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),$rr=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),_Je=[...Prr,..._rr,...Brr,...$rr];gd();Pos=new Set(["Read","Glob","Grep","LS","GitStatus","GitDiff","GitLog","WebFetch","WebSearch","MemoryRead","NotebookRead","ReadImage","SqliteAnalyze","ElfAnalyze","GcodeAnalyze","HtmlSanitizerAudit","ArtifactCompare","Think","ToolSearch","Skill",..._Je.filter(e=>gri(e).effect==="observe")]);KWe();Ari=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation","page"],wri=["draft","pending_review","approved","rejected","superseded","archived"],yri=["public","internal","confidential","restricted"],bri=["agent","tool","user","system","integration"],Mrr=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],Orr=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];Bme();vri="[\\u0000-\\u001f\\u007f]",_os=new RegExp(vri),Bos=new Set(wri),$os=new Set(yri),Mos=new Set(bri),Oos=new Set(Ari),Nos=new Set(Mrr),Dos=new Set(Orr),Los=32*1024*1024,Fos=1024*1024*1024,Uos=16*1024*1024,Qos=48*1024*1024;yJ();Gos=4*1024*1024;wn();LP();jos=64*1024*1024;yJ();KWe();Hos=8*1024*1024;ZWe();Vos=_Je.filter(e=>e.startsWith("browser.")),qos=_Je.filter(e=>e.startsWith("computer."));Bme();Wos=new Set(Mrr),Jos=new Set(Orr),zos=16*1024*1024;Bme();wn();Xos=16*1024*1024,Yos=1024*1024,Kos=["default-src 'none'","script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net/npm/ https://cdn.tailwindcss.com https://code.jquery.com","style-src 'self' 'unsafe-inline' https://fonts.googleapis.com","font-src 'self' data: https://fonts.gstatic.com","img-src 'self' data: blob:","media-src 'self' data: blob:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; "),Zos=128*1024*1024,ess=new TextDecoder().decode(new Uint8Array([239,191,189]));$me();eYt();tYt();e6e();fs();e6e();UP();HI();HI();QI();HI();Mc();Mc();HI();Mc();Mme();Jhe();sJe();Ftr();Utr();Qtr();$tr();oJe();Ntr();Dtr();Ltr();Ttr();HP();Gtr();Mtr();Otr();wJ();GP();vJ();aJe();x6e();iJe();jtr();lJe();cJe();Lme();P7t();Wtr();l6e();l6e();dJe();hge();mge();uJe();wn();fs();Tme();mge();uJe();hge();HP();h6e();IJ();iKt();btr();m6e();dKt();pKt();KS();xKt();$Kt();E9t();B9t();$9t();O9t();U9t();E6e();zme();jer();L9t();q9t();J9t();q7t();z7t();aer();per();Aer();ker();Ber();Der();Ker();str();ctr();utr();gtr();Atr();Str();gd();Ho();Iri=["completed","partial","failed","cancelled"],tss=["queued","running",...Iri];pge();ab();wn();LP();LP();fs();Eri=Nrr(GI(),"daemon"),sss=Nrr(Eri,"runs");wn();fs();fs();LP();ktr();rJe();kri=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,ass=new RegExp(String.raw`${kri}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i");rJe();wn();lss=512*1024*1024,css=10080*60*1e3,dss=365*24*60*60*1e3;wn();LP();fs();pL();uss=8*1024*1024,pss=64*1024*1024,fss=744*60*60*1e3;FP();hss=Object.freeze({"thread.run":"prompt","turn.start":"input","turn.steer":"input","schedule.create":"prompt","schedule.update":"prompt"}),Sri=["Read","Write","Edit","Glob","Grep","WebFetch"],mss=new Set(Sri),Dri=64*1024;Mc();OP();bWe=2e4,cni=String.raw`
|
|
5349
5349
|
using System;
|
|
5350
5350
|
using System.Collections.Generic;
|
|
5351
5351
|
using System.Runtime.InteropServices;
|
|
@@ -5619,7 +5619,7 @@ revision: ${i.page.revision}
|
|
|
5619
5619
|
title: ${i.page.title}
|
|
5620
5620
|
|
|
5621
5621
|
${i.html}`}:{success:!1,output:"",error:`No page artifact ${n} in this workspace.`}}case"list":{let n=await e.list();return{success:!0,output:JSON.stringify(n.map(i=>({artifactId:i.artifactId,title:i.title,revision:i.revision,...i.description?{description:i.description}:{},updatedAt:i.updatedAt??i.createdAt,homes:i.publications.map(o=>o.home),...i.publications.find(o=>o.home==="cloud")?.url?{cloudUrl:i.publications.find(o=>o.home==="cloud").url}:{}})))}}case"open":{if(!e.open)return{success:!1,output:"",error:"This surface cannot open a browser. Give the person the page's URL instead."};let n=await e.open(ms(t,"artifact_id"));return{success:!0,output:JSON.stringify({status:"opened",...n})}}case"reply":{let n=ms(t,"artifact_id"),i=ms(t,"comment_id"),o=ms(t,"body");if(!n||!i||!o)return{success:!1,output:"",error:"reply needs artifact_id, comment_id and body."};let s=await e.reply(n,i,o);return{success:!0,output:JSON.stringify({status:"replied",...s})}}default:return{success:!1,output:"",error:`Unknown action ${r}; use publish, read, list, open, promote, keep_as_tool, share or reply.`}}}catch(n){return{success:!1,output:"",error:n instanceof Error?n.message:String(n)}}}}}function swe(e,t){return e.register(owe(t)),e.activateMatchingDefinitions("Artifact",1),e}function awe(){return{name:"artifacts",order:216,provide(){return["","# Artifacts","When a rendered page would show the work better than text \u2014 a layout, a dashboard, a chart, a comparison, a prototype, a document to read \u2014 write an .html file and publish it with the Artifact tool. The person gets a private link and can comment on the page; comments arrive here. Republish the same artifact_id to update it in place.",'Pages are local and private by default. Publish with home "cloud" \u2014 or promote an existing one \u2014 only when the person asks for a hosted page or a link they can send to someone; the hosted copy is private to their account until they ask you to share it.','When the person wants something they keep and run again (a converter, a generator, a calculator), make it a tool: publish with home "cloud" and kind "tool" plus a category. A tool is self-contained: all logic in the page, no network requests, no calls to any host.'].join(`
|
|
5622
|
-
`)}}}var far,xdi,Cdi,Tdi,Rdi,har,mar,_di,Bdi,zXe,$di,Mdi,Odi,Ndi,gar,Ddi,Ldi,Fdi,Udi,Qdi,Gdi,jdi,kfs,Sfs,or,bar,xar,Car,XXe,Bfs,$fs,Tar,Rar,fui,$ar,hui,mui,gui,Aui,YXe,Eui,kui,Sui,xui,Cui,gf,CF,y_,ZAe,Ku,Oz,Gar,Hui,Vui,nw,jar,Ab,lpi,ear,cpi,ppi,yx,gpi,Dc,sar,wpi,olr,xpi,car,Cpi,SF,Bpi,llr,UXe,tg=we(()=>{"use strict";far=1,xdi=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation","page"],Cdi=["draft","pending_review","approved","rejected","superseded","archived"],Tdi=["public","internal","confidential","restricted"],Rdi=["agent","tool","user","system","integration"],har=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],mar=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];_di=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Bdi="custom:";zXe=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(r=>({...r}))}},$di=class extends Error{constructor(e,t){super(`Artifact state cannot transition from ${e} to ${t}`),this.fromState=e,this.toState=t,this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},Mdi={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},Odi="[\\u0000-\\u001f\\u007f]",Ndi=new RegExp(Odi),gar=/^[a-f0-9]{64}$/,Ddi=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ldi=new Set(Cdi),Fdi=new Set(Tdi),Udi=new Set(Rdi),Qdi=new Set(xdi),Gdi=new Set(har),jdi=new Set(mar);kfs=new Set(har),Sfs=new Set(mar),or=class extends Error{constructor(e,t,r,n){super(t,n),this.code=e,this.detail=r,this.name="XenoArtifactRepositoryError"}code;detail},bar=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(e={}){this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>(this.idCounter+=1,`${t}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),e.initialState&&this.hydrate(e.initialState)}exportState(){return{schemaVersion:1,records:[...this.records.values()].flatMap(t=>[...t.values()]).sort(Usr).map(t=>({artifact:Bz(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(wx(e),this.assertInitialState(e),e.revision!==1)throw new or("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:e.artifactId,revision:e.revision});if(this.records.has(e.artifactId))throw new or("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=Bz(e),r=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),n={artifact:t,recordVersion:1,lifecycleEvents:[r],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,n]])),this.currentRevisions.set(t.artifactId,t.revision),h_(n)}async createRevision(e,t={}){wx(e),this.assertInitialState(e);let r=this.getMutable(e.artifactId);this.assertVersion(r,t.expectedRecordVersion);let n=r.artifact.revision+1;if(e.revision!==n||e.predecessorRevision!==r.artifact.revision)throw new or("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${r.artifact.revision}`,{artifactId:e.artifactId,currentRevision:r.artifact.revision,requestedRevision:e.revision});if(Wdi(e,r.artifact))throw new or("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(r.artifact.state==="archived")throw new or("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:r.artifact.revision});if(r.artifact.state!=="superseded"){jXe(r.artifact.state,"superseded");let a=this.now(),l=this.createLifecycleEvent({artifact:r.artifact,sequence:r.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:r.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});r.artifact.state="superseded",r.artifact.updatedAt=a,r.lifecycleEvents.push(l),r.recordVersion+=1}let i=Bz(e),o=this.createLifecycleEvent({artifact:i,sequence:1,actor:t.actor??i.provenance.producer,fromState:null,toState:i.state,reason:t.reason??`revision-created-from-${r.artifact.revision}`}),s={artifact:i,recordVersion:1,lifecycleEvents:[o],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,s),this.currentRevisions.set(i.artifactId,i.revision),h_(s)}async get(e,t){let r=this.records.get(e);if(!r)return;let n=t??this.currentRevisions.get(e);if(n===void 0)return;let i=r.get(n);return i?h_(i):void 0}async require(e,t){let r=await this.get(e,t);if(!r)throw new or("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return r}async list(e={}){let t=[];for(let[r,n]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(r)))if(e.includeSuperseded)t.push(...n.values());else{let i=this.currentRevisions.get(r);if(i!==void 0){let o=n.get(i);o&&t.push(o)}}return t.filter(r=>Jdi(r.artifact,e)).sort(Usr).map(h_)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((r,n)=>r.artifact.revision-n.artifact.revision).map(h_):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),jXe(t.artifact.state,e.toState),e.toState==="approved"||e.toState==="rejected"){let o=e.reviewEventId?t.reviewEvents.find(a=>a.eventId===e.reviewEventId&&a.type==="decision-recorded"):void 0,s=yar(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new or("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${e.toState} requires a matching decision event`,{artifactId:e.artifactId,revision:t.artifact.revision});if(e.toState==="approved"&&s.unresolvedComments>0)throw new or("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let r=this.now(),n=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:n,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:r});return t.artifact.state=e.toState,t.artifact.updatedAt=r,t.lifecycleEvents.push(i),t.recordVersion+=1,h_(t)}async appendReviewEvent(e){let t=e.event,r=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(r,e.expectedRecordVersion),r.artifact.state==="archived"||r.artifact.state==="superseded")throw new or("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${r.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(r,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&r.artifact.state!=="pending_review")throw new or("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let n={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:r.reviewEvents.length+1,recordedAt:this.now()},i=war(n,r.artifact);if(i.length>0)throw new zXe("XENO artifact review event validation failed",i);return r.reviewEvents.push(n),r.recordVersion+=1,h_(r)}getMutable(e,t){let r=this.records.get(e),n=t??this.currentRevisions.get(e),i=n===void 0?void 0:r?.get(n);if(!i)throw new or("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return i}assertVersion(e,t){if(t!==void 0&&t!==e.recordVersion)throw new or("ARTIFACT_CONFLICT",`Expected record version ${t}, found ${e.recordVersion}`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision,expectedRecordVersion:t,actualRecordVersion:e.recordVersion})}assertInitialState(e){if(e.state!=="draft"&&e.state!=="pending_review")throw new or("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:e.artifactId,revision:e.revision})}assertReviewCommentState(e,t){if(t.type==="comment-added"){if(e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.commentId))throw new or("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.parentCommentId))throw new or("ARTIFACT_REVIEW_INVALID",`Parent comment ${t.parentCommentId} does not exist`);return}if(t.type!=="comment-resolved"&&t.type!=="comment-reopened")return;if(!e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.commentId))throw new or("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let r=zdi(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&r.resolved)throw new or("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!r.resolved)throw new or("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is not resolved`)}createLifecycleEvent(e){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:e.artifact.artifactId,revision:e.artifact.revision,sequence:e.sequence,recordedAt:e.recordedAt??this.now(),actor:{...e.actor},fromState:e.fromState,toState:e.toState,...e.reason?{reason:e.reason}:{},...e.reviewEventId?{reviewEventId:e.reviewEventId}:{}}}nextEventId(e){let t=this.idFactory(e);if(typeof t!="string"||t.trim().length===0||this.eventIds.has(t))throw new or("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${e} ID`);return this.eventIds.add(t),t}hydrate(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new or("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((r,n)=>r.artifact.artifactId.localeCompare(n.artifact.artifactId)||r.artifact.revision-n.artifact.revision);for(let r of t){let n=qdi(r,this.eventIds),i=this.records.get(n.artifact.artifactId);if(i||(i=new Map,this.records.set(n.artifact.artifactId,i)),i.has(n.artifact.revision))throw new or("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${n.artifact.artifactId}:${n.artifact.revision}`);i.set(n.artifact.revision,n),this.currentRevisions.set(n.artifact.artifactId,n.artifact.revision)}for(let[r,n]of this.records){let i=[...n.values()].sort((o,s)=>o.artifact.revision-s.artifact.revision);for(let o=0;o<i.length;o+=1){let s=i[o],a=o+1;if(s.artifact.revision!==a)throw new or("ARTIFACT_REVISION_INVALID",`Persisted artifact ${r} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new or("ARTIFACT_REVISION_INVALID",`Initial revision for ${r} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new or("ARTIFACT_REVISION_INVALID",`Persisted revision ${r}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new or("ARTIFACT_REVISION_INVALID",`Non-current revision ${r}:${a} must be superseded`)}}}};xar=Symbol.for("@xenosystem/agent-sdk/file-cache"),Car=globalThis,XXe=Car[xar]??{entries:new Map,counters:{reads:0,hits:0}};Car[xar]=XXe;Bfs=XXe.entries,$fs=XXe.counters,Tar=new Set(["EACCES","EBUSY","EPERM"]),Rar=[10,20,40,80,160,320,640];fui="0.10.109",$ar=1,hui="repository.v1.json",mui=5e3,gui=20,Aui=64*1024*1024,YXe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let t=e.snapshotFileName??hui;if(Gsr(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=Zdi(e.directory),this.snapshotPath=Kdi(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=BXe(e.lockTimeoutMs,mui,100,6e4,"lockTimeoutMs"),this.lockRetryMs=BXe(e.lockRetryMs,gui,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=BXe(e.maxSnapshotBytes,Aui,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(t=>t.create(e))}async createRevision(e,t){return this.mutate(r=>r.createRevision(e,t))}async get(e,t){return(await this.load()).repository.get(e,t)}async require(e,t){return(await this.load()).repository.require(e,t)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(t=>t.transition(e))}async appendReviewEvent(e){return this.mutate(t=>t.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let t=await this.acquireLock();try{let r=await this.load(),n=await e(r.repository);return await this.persist(r),n}finally{t.release()}})}async enqueueMutation(e){let t=this.mutationTail.then(e,e);return this.mutationTail=t.then(()=>{},()=>{}),t}async acquireLock(){let e=Date.now(),t;for(;Date.now()-e<=this.lockTimeoutMs;)try{return pui(this.lockPath,`artifact-repository:${Gsr(this.snapshotPath)}`,fui)}catch(r){if(!(r instanceof Error)||!/already locked by PID/.test(r.message))throw r;t=r,await Iui(this.lockRetryMs)}throw new or("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,r=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=YAe(i)}if(!t&&(e||await vui(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),t=i,r=!0)}catch(i){throw e?new or("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,YAe(i)])}):i}if(!t&&e)throw e;let n=t?.state??{schemaVersion:1,records:[]};return{repository:new bar({now:this.now,idFactory:i=>`${i}_${Iar()}`,initialState:n}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:r,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),r={schemaVersion:$ar,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},n=yui(r),i=`${JSON.stringify(n,null,2)}
|
|
5622
|
+
`)}}}var far,xdi,Cdi,Tdi,Rdi,har,mar,_di,Bdi,zXe,$di,Mdi,Odi,Ndi,gar,Ddi,Ldi,Fdi,Udi,Qdi,Gdi,jdi,kfs,Sfs,or,bar,xar,Car,XXe,Bfs,$fs,Tar,Rar,fui,$ar,hui,mui,gui,Aui,YXe,Eui,kui,Sui,xui,Cui,gf,CF,y_,ZAe,Ku,Oz,Gar,Hui,Vui,nw,jar,Ab,lpi,ear,cpi,ppi,yx,gpi,Dc,sar,wpi,olr,xpi,car,Cpi,SF,Bpi,llr,UXe,tg=we(()=>{"use strict";far=1,xdi=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation","page"],Cdi=["draft","pending_review","approved","rejected","superseded","archived"],Tdi=["public","internal","confidential","restricted"],Rdi=["agent","tool","user","system","integration"],har=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],mar=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];_di=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Bdi="custom:";zXe=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(r=>({...r}))}},$di=class extends Error{constructor(e,t){super(`Artifact state cannot transition from ${e} to ${t}`),this.fromState=e,this.toState=t,this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},Mdi={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},Odi="[\\u0000-\\u001f\\u007f]",Ndi=new RegExp(Odi),gar=/^[a-f0-9]{64}$/,Ddi=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ldi=new Set(Cdi),Fdi=new Set(Tdi),Udi=new Set(Rdi),Qdi=new Set(xdi),Gdi=new Set(har),jdi=new Set(mar);kfs=new Set(har),Sfs=new Set(mar),or=class extends Error{constructor(e,t,r,n){super(t,n),this.code=e,this.detail=r,this.name="XenoArtifactRepositoryError"}code;detail},bar=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(e={}){this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>(this.idCounter+=1,`${t}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),e.initialState&&this.hydrate(e.initialState)}exportState(){return{schemaVersion:1,records:[...this.records.values()].flatMap(t=>[...t.values()]).sort(Usr).map(t=>({artifact:Bz(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(wx(e),this.assertInitialState(e),e.revision!==1)throw new or("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:e.artifactId,revision:e.revision});if(this.records.has(e.artifactId))throw new or("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=Bz(e),r=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),n={artifact:t,recordVersion:1,lifecycleEvents:[r],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,n]])),this.currentRevisions.set(t.artifactId,t.revision),h_(n)}async createRevision(e,t={}){wx(e),this.assertInitialState(e);let r=this.getMutable(e.artifactId);this.assertVersion(r,t.expectedRecordVersion);let n=r.artifact.revision+1;if(e.revision!==n||e.predecessorRevision!==r.artifact.revision)throw new or("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${r.artifact.revision}`,{artifactId:e.artifactId,currentRevision:r.artifact.revision,requestedRevision:e.revision});if(Wdi(e,r.artifact))throw new or("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(r.artifact.state==="archived")throw new or("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:r.artifact.revision});if(r.artifact.state!=="superseded"){jXe(r.artifact.state,"superseded");let a=this.now(),l=this.createLifecycleEvent({artifact:r.artifact,sequence:r.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:r.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});r.artifact.state="superseded",r.artifact.updatedAt=a,r.lifecycleEvents.push(l),r.recordVersion+=1}let i=Bz(e),o=this.createLifecycleEvent({artifact:i,sequence:1,actor:t.actor??i.provenance.producer,fromState:null,toState:i.state,reason:t.reason??`revision-created-from-${r.artifact.revision}`}),s={artifact:i,recordVersion:1,lifecycleEvents:[o],reviewEvents:[]};return this.records.get(i.artifactId)?.set(i.revision,s),this.currentRevisions.set(i.artifactId,i.revision),h_(s)}async get(e,t){let r=this.records.get(e);if(!r)return;let n=t??this.currentRevisions.get(e);if(n===void 0)return;let i=r.get(n);return i?h_(i):void 0}async require(e,t){let r=await this.get(e,t);if(!r)throw new or("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return r}async list(e={}){let t=[];for(let[r,n]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(r)))if(e.includeSuperseded)t.push(...n.values());else{let i=this.currentRevisions.get(r);if(i!==void 0){let o=n.get(i);o&&t.push(o)}}return t.filter(r=>Jdi(r.artifact,e)).sort(Usr).map(h_)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((r,n)=>r.artifact.revision-n.artifact.revision).map(h_):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),jXe(t.artifact.state,e.toState),e.toState==="approved"||e.toState==="rejected"){let o=e.reviewEventId?t.reviewEvents.find(a=>a.eventId===e.reviewEventId&&a.type==="decision-recorded"):void 0,s=yar(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new or("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${e.toState} requires a matching decision event`,{artifactId:e.artifactId,revision:t.artifact.revision});if(e.toState==="approved"&&s.unresolvedComments>0)throw new or("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let r=this.now(),n=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:n,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:r});return t.artifact.state=e.toState,t.artifact.updatedAt=r,t.lifecycleEvents.push(i),t.recordVersion+=1,h_(t)}async appendReviewEvent(e){let t=e.event,r=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(r,e.expectedRecordVersion),r.artifact.state==="archived"||r.artifact.state==="superseded")throw new or("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${r.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(r,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&r.artifact.state!=="pending_review")throw new or("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let n={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:r.reviewEvents.length+1,recordedAt:this.now()},i=war(n,r.artifact);if(i.length>0)throw new zXe("XENO artifact review event validation failed",i);return r.reviewEvents.push(n),r.recordVersion+=1,h_(r)}getMutable(e,t){let r=this.records.get(e),n=t??this.currentRevisions.get(e),i=n===void 0?void 0:r?.get(n);if(!i)throw new or("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return i}assertVersion(e,t){if(t!==void 0&&t!==e.recordVersion)throw new or("ARTIFACT_CONFLICT",`Expected record version ${t}, found ${e.recordVersion}`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision,expectedRecordVersion:t,actualRecordVersion:e.recordVersion})}assertInitialState(e){if(e.state!=="draft"&&e.state!=="pending_review")throw new or("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:e.artifactId,revision:e.revision})}assertReviewCommentState(e,t){if(t.type==="comment-added"){if(e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.commentId))throw new or("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.parentCommentId))throw new or("ARTIFACT_REVIEW_INVALID",`Parent comment ${t.parentCommentId} does not exist`);return}if(t.type!=="comment-resolved"&&t.type!=="comment-reopened")return;if(!e.reviewEvents.some(n=>n.type==="comment-added"&&n.commentId===t.commentId))throw new or("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let r=zdi(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&r.resolved)throw new or("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!r.resolved)throw new or("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is not resolved`)}createLifecycleEvent(e){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:e.artifact.artifactId,revision:e.artifact.revision,sequence:e.sequence,recordedAt:e.recordedAt??this.now(),actor:{...e.actor},fromState:e.fromState,toState:e.toState,...e.reason?{reason:e.reason}:{},...e.reviewEventId?{reviewEventId:e.reviewEventId}:{}}}nextEventId(e){let t=this.idFactory(e);if(typeof t!="string"||t.trim().length===0||this.eventIds.has(t))throw new or("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${e} ID`);return this.eventIds.add(t),t}hydrate(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new or("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((r,n)=>r.artifact.artifactId.localeCompare(n.artifact.artifactId)||r.artifact.revision-n.artifact.revision);for(let r of t){let n=qdi(r,this.eventIds),i=this.records.get(n.artifact.artifactId);if(i||(i=new Map,this.records.set(n.artifact.artifactId,i)),i.has(n.artifact.revision))throw new or("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${n.artifact.artifactId}:${n.artifact.revision}`);i.set(n.artifact.revision,n),this.currentRevisions.set(n.artifact.artifactId,n.artifact.revision)}for(let[r,n]of this.records){let i=[...n.values()].sort((o,s)=>o.artifact.revision-s.artifact.revision);for(let o=0;o<i.length;o+=1){let s=i[o],a=o+1;if(s.artifact.revision!==a)throw new or("ARTIFACT_REVISION_INVALID",`Persisted artifact ${r} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new or("ARTIFACT_REVISION_INVALID",`Initial revision for ${r} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new or("ARTIFACT_REVISION_INVALID",`Persisted revision ${r}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new or("ARTIFACT_REVISION_INVALID",`Non-current revision ${r}:${a} must be superseded`)}}}};xar=Symbol.for("@xenosystem/agent-sdk/file-cache"),Car=globalThis,XXe=Car[xar]??{entries:new Map,counters:{reads:0,hits:0}};Car[xar]=XXe;Bfs=XXe.entries,$fs=XXe.counters,Tar=new Set(["EACCES","EBUSY","EPERM"]),Rar=[10,20,40,80,160,320,640];fui="0.10.110",$ar=1,hui="repository.v1.json",mui=5e3,gui=20,Aui=64*1024*1024,YXe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let t=e.snapshotFileName??hui;if(Gsr(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=Zdi(e.directory),this.snapshotPath=Kdi(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=BXe(e.lockTimeoutMs,mui,100,6e4,"lockTimeoutMs"),this.lockRetryMs=BXe(e.lockRetryMs,gui,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=BXe(e.maxSnapshotBytes,Aui,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(t=>t.create(e))}async createRevision(e,t){return this.mutate(r=>r.createRevision(e,t))}async get(e,t){return(await this.load()).repository.get(e,t)}async require(e,t){return(await this.load()).repository.require(e,t)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(t=>t.transition(e))}async appendReviewEvent(e){return this.mutate(t=>t.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let t=await this.acquireLock();try{let r=await this.load(),n=await e(r.repository);return await this.persist(r),n}finally{t.release()}})}async enqueueMutation(e){let t=this.mutationTail.then(e,e);return this.mutationTail=t.then(()=>{},()=>{}),t}async acquireLock(){let e=Date.now(),t;for(;Date.now()-e<=this.lockTimeoutMs;)try{return pui(this.lockPath,`artifact-repository:${Gsr(this.snapshotPath)}`,fui)}catch(r){if(!(r instanceof Error)||!/already locked by PID/.test(r.message))throw r;t=r,await Iui(this.lockRetryMs)}throw new or("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,r=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=YAe(i)}if(!t&&(e||await vui(this.backupPath)))try{let i=await this.readSnapshot(this.backupPath,!0);i&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),t=i,r=!0)}catch(i){throw e?new or("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,YAe(i)])}):i}if(!t&&e)throw e;let n=t?.state??{schemaVersion:1,records:[]};return{repository:new bar({now:this.now,idFactory:i=>`${i}_${Iar()}`,initialState:n}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:r,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),r={schemaVersion:$ar,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},n=yui(r),i=`${JSON.stringify(n,null,2)}
|
|
5623
5623
|
`;if(Buffer.byteLength(i,"utf8")>this.maxSnapshotBytes)throw new or("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await Ear(this.directory,{recursive:!0,mode:448}),e.hasSnapshot&&!e.recoveredFromBackup&&e.sourceSnapshot&&await Vsr(this.backupPath,`${JSON.stringify(e.sourceSnapshot,null,2)}
|
|
5624
5624
|
`),await Vsr(this.snapshotPath,i)}async readSnapshot(e,t){let r;try{r=await kar(e)}catch(n){if(!t&&HXe(n,"ENOENT")||t&&HXe(n,"ENOENT"))return;throw VXe("Unable to inspect artifact repository snapshot",e,n)}if(!r.isFile()||r.size>this.maxSnapshotBytes)throw new or("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:e,sizeBytes:r.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let n=await Xdi(e);if(n.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return wui(JSON.parse(n.toString("utf8")),e)}catch(n){throw n instanceof or?n:VXe("Unable to parse artifact repository snapshot",e,n,!0)}}};Eui=16*1024*1024,kui=5e3,Sui=1e5,xui=1e6,Cui=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,gf=class extends Error{constructor(e,t){super(t===void 0?e:`${e} at diff line ${t}`),this.line=t,this.name="XenoDiffParseError"}line;code="XENO_DIFF_INVALID"};CF=class{repository;actor;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");if(!e.actor?.kind||!e.actor.id?.trim())throw new TypeError("Review actor is required");this.repository=e.repository,this.actor=structuredClone(e.actor),this.idFactory=e.idFactory??(()=>`comment_${$ui()}`)}async addComment(e){let t=iwe(e.body,"Review comment body",65536),r=await this.repository.require(e.artifactId,e.revision),n=zsr(r,e),i=KAe(this.idFactory(),"Comment ID"),o=Oui(e.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:r.recordVersion,event:{type:"comment-added",artifactId:r.artifact.artifactId,artifactRevision:r.artifact.revision,artifactHash:r.artifact.content.hash,actor:this.actor,commentId:i,body:t,...n?{anchor:n}:{},...o?{parentCommentId:o}:{}}})}async setCommentResolution(e){let t=KAe(e.commentId,"Review comment ID"),r=Xsr(e.reason,"Resolution reason",16*1024),n=await this.repository.require(e.artifactId,e.revision);return this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:e.resolved?"comment-resolved":"comment-reopened",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,commentId:t,...r?{reason:r}:{}}})}async decide(e){let t=await this.repository.require(e.artifactId,e.revision);if(t.artifact.state!=="pending_review")throw new or("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${t.artifact.state}`);let r=zsr(t,e),n=Xsr(e.rationale,"Decision rationale",64*1024),i=await this.repository.appendReviewEvent({expectedRecordVersion:t.recordVersion,event:{type:"decision-recorded",artifactId:t.artifact.artifactId,artifactRevision:t.artifact.revision,artifactHash:t.artifact.content.hash,actor:this.actor,decision:e.decision,...n?{rationale:n}:{},...r?{scope:r}:{}}});if(r||e.decision==="changes_requested")return i;let o=i.reviewEvents.at(-1);if(!o||o.type!=="decision-recorded")throw new or("ARTIFACT_REVIEW_INVALID","Artifact decision event was not recorded");return this.repository.transition({artifactId:i.artifact.artifactId,revision:i.artifact.revision,expectedRecordVersion:i.recordVersion,toState:e.decision,actor:this.actor,reviewEventId:o.eventId,...n?{reason:n}:{}})}};y_="xeno.spec.v1",ZAe="xeno.spec-execution.v1",Ku=class extends Error{constructor(e){super(`XENO spec is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},Oz=class{repository;now;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");this.repository=e.repository,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(()=>Nui())}async create(e,t){if(e.revision!==1||e.predecessorRevision!==void 0)throw new Ku(["A new spec must begin at revision 1 without a predecessor"]);let r=Ysr(e,t);return await this.repository.create(r.requirements),await this.repository.create(r.design),await this.repository.create(r.taskGraph),await this.repository.create(r.plan),r}async revise(e,t){let r=A_(e.specId),n=await this.repository.require(r.plan);if(e.revision!==n.artifact.revision+1||e.predecessorRevision!==n.artifact.revision)throw new Ku([`Revision ${e.revision} must follow approved or reviewed revision ${n.artifact.revision}`]);let i=Ysr(e,t);return await this.repository.createRevision(i.requirements,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.design,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.taskGraph,{actor:t.producer,reason:"spec-revised"}),await this.repository.createRevision(i.plan,{actor:t.producer,reason:"spec-revised"}),i}async approve(e,t,r){return new CF({repository:this.repository,actor:t}).decide({artifactId:A_(e).plan,decision:"approved",...r?{rationale:r}:{}})}async reject(e,t,r){return new CF({repository:this.repository,actor:t}).decide({artifactId:A_(e).plan,decision:"rejected",rationale:r})}async startExecution(e,t){let r=await this.repository.require(A_(e).plan);if(r.artifact.state!=="approved")throw new Ku([`Spec ${e} must be approved before execution`]);let n=v_(r.artifact),i=this.now(),o={schemaVersion:ZAe,executionId:`spec_execution_${this.idFactory()}`,specId:n.specId,specRevision:n.revision,planArtifactId:r.artifact.artifactId,planHash:{...r.artifact.content.hash},state:"ready",createdAt:i,updatedAt:i,observedPaths:[],tasks:n.tasks.map(s=>({taskId:s.id,status:"pending",evidence:[],acceptanceEvidence:Object.fromEntries(s.acceptanceCriterionIds.map(a=>[a,[]]))}))};return this.repository.create(Ksr(o,{producer:t,identity:r.artifact.identity,sensitivity:r.artifact.sensitivity,accessPolicyId:r.artifact.accessPolicyId}))}async updateExecution(e,t,r){let n=await this.repository.require(e),i=Nz(n.artifact),o=await this.repository.require(i.planArtifactId,i.specRevision);if(o.artifact.state!=="approved"||!Mz(o.artifact.content.hash,i.planHash))throw new Ku(["Execution is no longer bound to the approved plan revision"]);let s=t(structuredClone(i));s.schemaVersion=ZAe,s.executionId=i.executionId,s.specId=i.specId,s.specRevision=i.specRevision,s.planArtifactId=i.planArtifactId,s.planHash={...i.planHash},s.createdAt=i.createdAt,s.updatedAt=this.now(),Lar(s,v_(o.artifact));let a=Ksr(s,{producer:r,identity:n.artifact.identity,sensitivity:n.artifact.sensitivity,accessPolicyId:n.artifact.accessPolicyId},n.artifact.revision+1,n.artifact.revision);return this.repository.createRevision(a,{actor:r,reason:"spec-execution-updated"})}};Gar="xeno.review-report.v1",Hui=["correctness","security","performance","api","tests","documentation"],Vui=["source","test","trace","artifact","reproduction","benchmark"],nw=class extends Error{constructor(e){super(`XENO review is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},jar=class{reviewer;verifier;now;idFactory;constructor(e){if(typeof e?.reviewer!="function")throw new TypeError("Review agent executor is required");this.reviewer=e.reviewer,this.verifier=e.verifier,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${jui()}`)}async run(e){Var(e.pack),qar(e.target),twe(e.runId,"runId");let t=this.now(),r=await Promise.all(e.pack.dimensions.map(async(a,l)=>{let c=await this.reviewer({...e,dimension:a,reviewerSlot:l});return Jui(c,a,e.pack.maxFindings),structuredClone(c)})),n=r.flatMap(a=>a.findings.map(l=>({finding:l,reviewerAgentId:a.reviewerAgentId})));if(n.length>e.pack.maxFindings)throw new nw([`Reviewers returned ${n.length} findings, exceeding maxFindings ${e.pack.maxFindings}`]);let i=qui(n,this.idFactory);for(let a of i){let l=this.verifier?await Promise.all(Array.from({length:e.pack.verifierCount},async(f,h)=>{let m=await this.verifier({...e,finding:structuredClone(a),verifierSlot:h});return zui(m),structuredClone(m)})):[];a.verifications=Xui(l),a.evidence=Xar([...a.evidence,...a.verifications.flatMap(f=>f.evidence)]);let c=new Set(a.verifications.filter(f=>f.outcome==="reproduced").map(f=>f.verifierAgentId)).size,d=a.verifications.length>0&&a.verifications.every(f=>f.outcome==="rejected"),u=new Set(a.evidence.map(f=>f.producerId)).size;c>=e.pack.minimumVerifierReproductions?(a.state="verified",a.verificationBasis="verifier"):e.pack.allowIndependentEvidenceVerification&&u>=e.pack.minimumIndependentEvidenceProducers?(a.state="verified",a.verificationBasis="independent-evidence"):d?(a.state="rejected",a.verificationBasis="verifier"):(a.state="unverified",a.verificationBasis="none");let p=a.verifications.map(f=>f.confidence).filter(f=>f!==void 0);p.length>0&&(a.confidence=rlr(Math.min(a.confidence,...p)))}i.sort(Yui);let o=this.now(),s={schemaVersion:Gar,reportId:twe(this.idFactory("report"),"reportId"),runId:e.runId,pack:structuredClone(e.pack),target:structuredClone(e.target),startedAt:t,completedAt:o,reviewers:r.map(a=>({agentId:a.reviewerAgentId,dimension:a.dimension,findingCount:a.findings.length})),findings:i,summary:Zar(i)};return War(s),s}};Ab="index.html",lpi=16*1024*1024,ear=255,cpi={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".md":"text/markdown; charset=utf-8",".txt":"text/plain; charset=utf-8",".csv":"text/csv; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".pdf":"application/pdf",".wasm":"application/wasm"};ppi=class{repository;directory;now;maxBytes;constructor(e){if(!e?.repository)throw new TypeError("XenoPageStore requires an artifact repository");if(typeof e.directory!="string"||!e.directory.trim())throw new TypeError("XenoPageStore requires a directory");this.repository=e.repository,this.directory=Zsr(e.directory),this.now=e.now??(()=>new Date().toISOString()),this.maxBytes=e.maxBytes??lpi}revisionDirectory(e,t){if(!/^[A-Za-z0-9_-]+$/u.test(e))throw new TypeError(`Unsafe artifact id: ${e}`);return gb(this.directory,e,`r${t}`)}async publish(e){let t=typeof e.html=="string"?e.html:"";if(!t.trim())throw new TypeError("A page needs HTML content.");let r=new Map;for(let I of e.files??[]){let v=tar(I.path);if("error"in v)throw new TypeError(v.error);if(r.has(v.path))throw new TypeError(`Duplicate file path: ${v.path}`);r.set(v.path,{bytes:NXe(I.bytes),contentType:I.contentType??OXe(v.path)})}if(r.size>ear)throw new TypeError(`A page may carry at most ${ear} files.`);let n=NXe(t),i=n.byteLength+[...r.values()].reduce((I,v)=>I+v.bytes.byteLength,0);if(i>this.maxBytes)throw new TypeError(`Page revision is ${i} bytes; the limit is ${this.maxBytes}.`);let o=ilr("sha256").update(n),s={};for(let[I,v]of[...r.entries()].sort(([E],[S])=>E.localeCompare(S)))s[I]={sha256:upi(v.bytes),sizeBytes:v.bytes.byteLength,contentType:v.contentType},o.update(`\0${I}\0${s[I].sha256}`);let a=o.digest("hex"),l=e.artifactId?await this.repository.get(e.artifactId):void 0;if(e.artifactId&&!l)throw new TypeError(`Unknown page artifact ${e.artifactId}.`);if(l&&l.artifact.kind!=="page")throw new TypeError(`Artifact ${e.artifactId} is a ${l.artifact.kind}, not a page.`);if(l&&l.artifact.content.hash.value===a)return{...await this.toPublished(l),unchanged:!0};let c=l?.artifact.artifactId??`page_${qXe().replaceAll("-","").slice(0,20)}`,d=l?l.artifact.revision+1:1,u=this.revisionDirectory(c,d);MXe(u,{recursive:!0});let p=gb(u,Ab);DXe(p,n);for(let[I,v]of r){let E=gb(u,...I.split("/"));MXe(gb(E,".."),{recursive:!0}),DXe(E,v.bytes)}let f=l?LXe(l):{},h=e.title?.trim()||dpi(t)||(typeof f.title=="string"?f.title:void 0)||"Untitled page",m=e.icon?.trim()||(typeof f.icon=="string"?f.icon:void 0),g=e.description?.trim()||l?.artifact.description,A=Array.isArray(f.publications)?f.publications:[],w=this.now(),y={schemaVersion:1,artifactId:c,revision:d,kind:"page",title:h,...g?{description:g}:{},state:"draft",createdAt:l?.artifact.createdAt??w,updatedAt:w,mediaType:"text/html",sensitivity:l?.artifact.sensitivity??"internal",...e.identity??l?.artifact.identity?{identity:e.identity??l.artifact.identity}:{},content:{hash:{algorithm:"sha256",value:a},sizeBytes:i,storage:{type:"file",path:p},encoding:"utf8",redactedPreview:t.slice(0,200)},provenance:{producer:e.producer},...l?{predecessorRevision:l.artifact.revision}:{},extensions:{page:{entry:Ab,htmlSha256:Io(n).value,files:s,...m?{icon:m}:{},title:h,publications:A,...e.home?{requestedHome:e.home}:{}}}},b=l?await this.repository.createRevision(y,{actor:e.producer,reason:"page republished"}):await this.repository.create(y);return this.toPublished(b)}async recordPublication(e,t){let r=await this.repository.require(e),n=LXe(r),i=(await this.toPublished(r)).publications.filter(s=>s.home!==t.home);i.push(t);let o={...r.artifact,revision:r.artifact.revision,extensions:{...r.artifact.extensions,page:{...n,publications:i}}};return this.writeSidecar(e,{publications:i}),this.toPublished({...r,artifact:o})}sidecarPath(e){return gb(this.directory,e,"publications.json")}writeSidecar(e,t){MXe(gb(this.directory,e),{recursive:!0}),DXe(this.sidecarPath(e),NXe(`${JSON.stringify(t,null,2)}
|
|
5625
5625
|
`))}readSidecar(e){try{let t=JSON.parse(zAe(this.sidecarPath(e),"utf8"));return Array.isArray(t.publications)?t.publications:[]}catch{return[]}}async get(e,t){let r=await this.repository.get(e,t);if(!(!r||r.artifact.kind!=="page"))return this.toPublished(r)}async list(){let e=await this.repository.list({kinds:["page"]});return(await Promise.all(e.map(t=>this.toPublished(t)))).sort((t,r)=>(r.updatedAt??r.createdAt).localeCompare(t.updatedAt??t.createdAt))}resolveFile(e,t,r){let n=r===Ab||r===""?{path:Ab}:tar(r);if("error"in n)return;let i=this.revisionDirectory(e,t),o=Zsr(i,...n.path.split("/"));if(!(o!==i&&!o.startsWith(i+api))&&!(!tpi(o)||!npi(o).isFile()))return{path:o,contentType:OXe(o)}}readEntry(e,t){let r=this.resolveFile(e,t,Ab);return r?zAe(r.path,"utf8"):void 0}readRevision(e,t){let r=this.revisionDirectory(e,t),n=zAe(gb(r,Ab),"utf8"),i=[],o=(s,a)=>{for(let l of rpi(s,{withFileTypes:!0})){let c=a?`${a}/${l.name}`:l.name;l.isDirectory()?o(gb(s,l.name),c):c!==Ab&&i.push({path:c,bytes:zAe(gb(s,l.name)),contentType:OXe(c)})}};return o(r,""),{html:n,files:i}}async addComment(e,t,r,n){let i=await this.repository.require(e);if(i.artifact.kind!=="page")throw new TypeError(`Artifact ${e} is a ${i.artifact.kind}, not a page.`);let o=t.trim();if(!o)throw new TypeError("A comment needs text.");let s=(await this.repository.appendReviewEvent({event:{type:"comment-added",artifactId:e,artifactRevision:i.artifact.revision,artifactHash:i.artifact.content.hash,actor:r,commentId:`cmt_${qXe().replaceAll("-","").slice(0,16)}`,body:o.slice(0,2e4),...n?{anchor:n}:{}}})).reviewEvents.at(-1);if(!s||s.type!=="comment-added")throw new Error("Comment was not recorded.");return s}async listComments(e){await this.repository.require(e);let t=await this.repository.listRevisions(e),r=new Set,n=[];for(let i of t)for(let o of i.reviewEvents)o.type!=="comment-added"||r.has(o.commentId)||(r.add(o.commentId),n.push(o));return n.sort((i,o)=>i.recordedAt.localeCompare(o.recordedAt)||i.sequence-o.sequence)}async toPublished(e){let t=LXe(e),r=t.files&&typeof t.files=="object"&&!Array.isArray(t.files)?t.files:{},n=this.readSidecar(e.artifact.artifactId),i=[...(Array.isArray(t.publications)?t.publications:[]).filter(o=>!n.some(s=>s.home===o.home)),...n];return{artifactId:e.artifact.artifactId,revision:e.artifact.revision,title:e.artifact.title,...e.artifact.description?{description:e.artifact.description}:{},...typeof t.icon=="string"?{icon:t.icon}:{},hash:e.artifact.content.hash.value,sizeBytes:e.artifact.content.sizeBytes,files:r,directory:this.revisionDirectory(e.artifact.artifactId,e.artifact.revision),entryPath:gb(this.revisionDirectory(e.artifact.artifactId,e.artifact.revision),Ab),publications:i,createdAt:e.artifact.createdAt,...e.artifact.updatedAt?{updatedAt:e.artifact.updatedAt}:{}}}},yx=["generator","extractor","converter","ai","capture","utility"],gpi="https://tools.xenosystem.ai";Dc=class extends Error{constructor(e,t,r){super(e),this.status=t,this.code=r,this.name="ArtifactCloudError"}status;code;retryable=!1},sar=1024*1024,wpi=new Set(["missing_html","not_found","invalid_parent","bad_input","denied","needs_approval","conflict","rate_limited"]);olr=class{baseUrl;getToken;authorize;accountDisplay;fetchImpl;timeoutMs;userAgent;constructor(e){if(this.baseUrl=e.baseUrl.replace(/\/+$/u,""),e.getToken&&e.authorize)throw new Error("Artifact credentials and canonical authorizer are mutually exclusive.");if(e.authorize){let t=new URL(e.baseUrl);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw new Error("Canonical artifact transport requires an HTTPS origin.")}if(this.getToken=e.getToken??(()=>{}),this.authorize=e.authorize,this.accountDisplay=e.accountDisplay,this.fetchImpl=e.fetchImpl??fetch,this.timeoutMs=e.timeoutMs??6e4,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>3e5)throw new Error("Artifact request deadline must be between 1 and 300000 milliseconds.");this.userAgent=e.userAgent}get origin(){return this.baseUrl}signedIn(){return this.authorize?this.accountDisplay?.()===!0:!!this.getToken()}async request(e,t,r){let n=this.getToken(),i=`${this.baseUrl}${t}`,o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs),a=!1,l;try{let c;try{c=this.authorize?await WXe(this.authorize(e,i),o.signal):void 0}catch(h){throw h instanceof Dc?h:new Dc("Canonical artifact account authority is unavailable.",void 0,"unreachable")}if(this.authorize?!c:!n)throw new Dc("Not signed in to XENO. Run `xeno login`, then promote the page again.",401,"not_signed_in");if(this.authorize&&(typeof c?.authorization!="string"||!/^DPoP [\x21-\x7e]{1,16384}$/.test(c.authorization)||typeof c.dpop!="string"||!/^[\x21-\x7e]{1,16384}$/.test(c.dpop)))throw new Dc("Canonical artifact authorization refused.",401,"not_signed_in");let d=r!==void 0?JSON.stringify(r):void 0;o.signal.throwIfAborted(),a=!0;let u=await WXe(this.fetchImpl(i,{method:e,headers:{authorization:c?.authorization??`Bearer ${n}`,...c?.dpop?{dpop:c.dpop}:{},accept:"application/json",...r!==void 0?{"content-type":"application/json"}:{},...this.userAgent?{"user-agent":this.userAgent}:{}},...d!==void 0?{body:d}:{},signal:o.signal,redirect:"error",credentials:"omit"}),o.signal,h=>{h.body?.cancel().catch(()=>{})});l=u.status;let p=await ypi(u,o.signal),f;try{f=p?JSON.parse(p):void 0}catch{throw new Dc("Artifact server returned an invalid response.",u.status,"invalid_response")}if(!u.ok){let h=f&&typeof f=="object"?f.code:void 0,m=typeof h=="string"&&wpi.has(h)?h:"http_error";throw u.status===401?new Dc("XENO sign-in has expired or is not valid for artifacts. Run `xeno login` and try again.",401,"unauthorized"):new Dc(`Artifact request refused (HTTP ${u.status}).`,u.status,m)}if(!f||typeof f!="object"||Array.isArray(f))throw new Dc("Artifact server returned an invalid response.",u.status,"invalid_response");return f}catch(c){throw a&&e!=="GET"&&(l===void 0||l<400||l>=500)?new Dc("Artifact action outcome is unconfirmed; do not retry until its state is reconciled.",l,"effect_unknown"):c instanceof Dc?c:new Dc(o.signal.aborted?"Artifact request deadline exceeded.":"Artifact transport is unavailable.",l,o.signal.aborted?"timeout":"unreachable")}finally{clearTimeout(s)}}async create(e,t={}){return(await this.request("POST","/api/artifacts",{...aar(e),...t.kind?{kind:t.kind}:{},...t.kind==="tool"&&t.category?{category:t.category}:{}})).artifact}async keepAsTool(e,t={}){return(await this.request("POST",`/api/artifacts/${encodeURIComponent(e)}/keep-as-tool`,{...t.category?{category:t.category}:{}})).artifact}async revise(e,t){let r=await this.request("POST",`/api/artifacts/${encodeURIComponent(e)}/revisions`,aar(t)),{unchanged:n,...i}=r.artifact;return{artifact:i,unchanged:n===!0}}async get(e){try{return(await this.request("GET",`/api/artifacts/${encodeURIComponent(e)}`)).artifact}catch(t){if(t instanceof Dc&&t.status===404)return;throw t}}async list(e={}){return(await this.request("GET",`/api/artifacts${e.kind?`?kind=${encodeURIComponent(e.kind)}`:""}`)).artifacts}async share(e,t,r={}){let n=await this.request("POST",`/api/artifacts/${encodeURIComponent(e)}/share`,{visibility:t,...r.workspaceId?{workspaceId:r.workspaceId}:{},...r.sharedRevision!==void 0?{sharedRevision:r.sharedRevision}:{}});return{artifact:n.artifact,...n.shareUrl?{shareUrl:n.shareUrl}:{}}}async remove(e){await this.request("DELETE",`/api/artifacts/${encodeURIComponent(e)}`)}async undeliveredComments(e){return(await this.request("GET",`/api/artifacts/${encodeURIComponent(e)}/comments?undelivered=1`)).comments}async reply(e,t,r){return(await this.request("POST",`/api/artifacts/${encodeURIComponent(e)}/comments/${encodeURIComponent(t)}/reply`,{body:r})).comment}async acknowledgeComments(e,t){return t.length?(await this.request("POST",`/api/artifacts/${encodeURIComponent(e)}/comments/delivered`,{commentIds:t})).delivered:0}};xpi=30620,car=5,Cpi=["default-src 'none'","script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net/npm/ https://cdn.tailwindcss.com https://code.jquery.com","style-src 'self' 'unsafe-inline' https://fonts.googleapis.com","font-src 'self' data: https://fonts.gstatic.com","img-src 'self' data: blob:","media-src 'self' data: blob:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; ");SF=128*1024*1024,Bpi=new TextDecoder().decode(new Uint8Array([239,191,189]));llr=class{cloud;options;storeCache;viewerHandle;viewerStarting;constructor(e){this.options=e,this.cloud=e.cloud}cloudAvailable(){return!!this.cloud?.signedIn()}get cloudOrigin(){return this.cloud?.origin}artifactDirectory(){return this.options.artifactDirectory??iar(this.options.workspace(),".xeno","artifacts")}get store(){let e=this.options.workspace();if(this.storeCache?.workspace===e)return this.storeCache.store;let t=this.artifactDirectory(),r=this.options.repository??new YXe({directory:t}),n=new ppi({repository:r,directory:iar(t,"pages"),maxBytes:SF});return this.storeCache={workspace:e,store:n},n}get viewer(){return this.viewerHandle}get viewerUrlBase(){return this.viewerHandle?`http://127.0.0.1:${this.viewerHandle.port}`:void 0}async ensureViewer(){return this.viewerHandle?this.viewerHandle:(this.viewerStarting||(this.viewerStarting=_pi({store:this.store,commentActorId:FXe(),...this.options.viewerBasePort!==void 0?{basePort:this.options.viewerBasePort}:{},onComment:()=>{this.options.onViewerComment?.()}}).then(e=>(this.viewerHandle=e,e)).finally(()=>{this.viewerStarting=void 0})),this.viewerStarting)}async stop(){this.viewerHandle&&await this.viewerHandle.close(),this.viewerHandle=void 0}resolveSource(e){let t=mpi(e)?oar(e):oar(this.options.workspace(),e);if(!fpi(t))throw new Error(`File not found: ${e}`);let r=nar(t);if(!r.isFile())throw new Error(`Not a file: ${e}`);if(r.size>SF)throw new Error(`${e} is ${r.size} bytes; the local revision limit is ${SF} bytes (including supporting files).`);return t}async publish(e){let t,r;if(typeof e.html=="string"&&e.html.trim())t=e.html;else if(e.filePath){let p=rar(this.resolveSource(e.filePath),"utf8");/\.(md|markdown)$/iu.test(e.filePath)?(r=e.title??alr(p,e.filePath.replace(/^.*[\\/]/u,"").replace(/\.(md|markdown)$/iu,"")),t=bpi(p,{title:r})):t=p}else throw new Error("Publish needs a file_path to an HTML or Markdown file (or inline html).");let n=t.indexOf(Bpi);if(n!==-1){let p=t.slice(0,n);throw new Error(`The page contains the replacement character U+FFFD at line ${p.split(`
|
|
@@ -6628,7 +6628,7 @@ ${n}`}}import{execFileSync as Our}from"node:child_process";function dwi(){let e=
|
|
|
6628
6628
|
`),i.model||i.baseURL||i.apiKey||i.maxTokens||i.permissionMode||i.plugins&&i.plugins.length>0||i.mcpServers&&i.mcpServers.length>0||r.onOutput(` (no settings configured)
|
|
6629
6629
|
`),r.onOutput(`
|
|
6630
6630
|
`),{handled:!0}}function Px(e){let t=Math.max(0,Math.floor(e)),r=Math.floor(t/1e3),n=Math.floor(r/3600),i=Math.floor(r%3600/60),o=r%60;return n>0?`${n}h ${i}m ${o}s`:i>0?`${i}m ${o}s`:`${o}s`}function qur(e){let t=["Last Session Summary",`- model: ${e.model}`,`- mode: ${e.mode??"unknown"}`,`- status: ${e.status??"unknown"}`,`- started: ${e.startedAt}`,`- ended: ${e.endedAt}`,`- duration: ${Px(e.durationMs)}`,`- tokens: ${e.tokenUsage.input.toLocaleString()} in / ${e.tokenUsage.output.toLocaleString()} out / ${e.tokenUsage.total.toLocaleString()} total`,`- estimated cost: ${UR(e.estimatedCostUsd)}`];return e.sessionId&&t.splice(1,0,`- session: ${e.sessionId}`),e.role&&t.splice(e.sessionId?2:1,0,`- role: ${e.role}`),e.messageCount!==void 0&&t.push(`- messages: ${e.messageCount}`),t.join(`
|
|
6631
|
-
`)}function Qwi(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function Iye(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${Qwi(e.targetPrompt)}"`,r=await e.checkpointManager.create({trigger:"manual",messages:e.messages,description:t});if(e.sessionManager){let n=[r.id,...e.sessionManager.meta.checkpoints.filter(i=>i!==r.id)];await e.sessionManager.updateMeta({checkpoints:n}),await e.sessionManager.transcript.append({type:"checkpoint",data:{id:r.id,action:"create",name:t,trigger:"manual",messageCount:e.messages.length}})}return r.id}Qo();wo();var Gwi={"0.5.173":["xeno run --mcp and xeno run --image now run on the shared Agent host.","The default model can see images a tool returns: gpt-6-luna and gpt-6.1-sol receive the picture instead of a note saying they cannot."],"0.5.172":["xeno run now goes through the shared Agent host when you are signed in, with its tool lists, fallback models and required JSON answer."],"0.5.171":["Fixed: a chat on the shared Agent host stopped after 10 tool rounds. It now uses your limit, 50 by default.",'--continue no longer fails with "already locked" after a chat on the shared Agent host.',"A chat on the host keeps its web limits and keeps short questions short."],"0.5.170":["MCP servers you approved now work in a chat on the shared Agent host, each started in its own folder.","A chat tells you when a folder's server is waiting for approval."],"0.5.169":["Windows: the helper that runs commands is now one fixed program, so antivirus is far less likely to delete it."],"0.5.168":["A chat with MCP enabled stays in the CLI process again, so its MCP tools are there; the shared Agent host does not load them yet."],"0.5.167":["Windows: commands no longer fail with spawn UNKNOWN when antivirus quarantines the process launcher.","xeno host status now says whether a chat runs on the shared Agent host."],"0.5.166":["Interactive chat now runs on the shared Agent host by default, so conversations appear in the desktop app. XENO_AGENT_ATTACH=0 turns it off."],"0.5.165":["Several CLI jobs can share one sign-in: one renews at a time, and a half-finished renewal recovers by itself instead of asking for xeno login.","On the shared Agent host, a turn now draws its tools and token counts like any other, and Esc stops it and the command it was running.","If the direct route is down, a turn on the shared Agent host takes the Cloudflare route instead of failing."],"0.5.164":["On the shared Agent host, an edit made in the desktop app now reaches the terminal: the turn you edited away stops going to the model, and what you attach or rate there is kept too.","Windows: a scanner briefly holding a file no longer fails a scheduled job or other background write."],"0.5.163":["Conversations you start on the shared Agent host now appear in the XENO Agent desktop app, marked as started in the terminal, and you can carry on from either side."],"0.5.162":["On the shared Agent host, /rewind now puts your files back too: /rewind files shows what would change, /rewind files --confirm restores them. A file you edited since is never overwritten unless you add --overwrite.","Turns on the shared Agent host now remember what earlier turns did, not only what they said, so the model no longer doubts work it already finished."],"0.5.161":["On the shared Agent host, /rewind <n> continues from just before turn n in a new conversation; the original is kept. /rewind lists the turns.","On the shared Agent host, /compact summarises on the host: later turns are sent the summary, and every original turn is kept.","/fork [n] on the shared Agent host branches the host's conversation, all of it or through turn n."],"0.5.160":["In xeno chat on the shared Agent host, the host now keeps the conversation: a turn sends only your new message, and the host supplies the rest from its own record.","Conversations the host did not record from the start keep sending the CLI's own history, so nothing loses context."],"0.5.159":["--security-level process-hardened now runs on the shared Agent host instead of being refused, with the same restricted Windows token as a local run.","--security-level contained and --untrusted are still refused on the host, and say why."],"0.5.158":["An MCP server you signed into with xeno mcp login now works in the XENO Agent app too: the app uses the same stored credentials.","Opening a sign-in or app-server link no longer goes through cmd on Windows, so a crafted URL cannot run a command.","Share bundles now hide credentials found in a prompt or a tool's output, not only under secret-named fields.","xeno org, xeno github, xeno share and xeno mcp run on the same SDK code as the app; their behaviour is unchanged."],"0.5.157":["Chat turns run on the shared Agent host now carry this chat's permission mode and folders. Before, they ran with the host's defaults.","--mode chat can run on the Agent host: its turns ask the host for no tools, and a host that cannot enforce that refuses the turn. Before, a chat-only turn could not attach at all.","A chat turn whose settings the host cannot honour (such as --security-level contained) is refused with the reason, instead of running with weaker settings.","Plan mode works on the Agent host: the host's turn plans without changing anything, and its plan comes to you here for approval.","The agent can make a tool you keep and run again: it publishes a page as a tool on your XENO account. /artifacts publish|promote take --tool [--category <c>], and /artifacts keep-as-tool <id> keeps a hosted page as one."],"0.5.156":["xeno eval now uses the same eval code as the XENO Agent app, from the SDK; the app runs a project's eval suites itself. Nothing about how xeno eval behaves changes."],"0.5.155":["xeno recipes run now starts the recipe's workflow through the XENO Agent host, like xeno workflow run: the host drives it and runs each step, so it keeps going after this terminal closes, and the XENO Agent app's Recipes and Workflows tabs show it."],"0.5.154":["/approved-tools now also shows the folders you always allowed (they were remembered but never listed); remove takes a folder as well as a tool key, and clear forgets both. The XENO Agent app's Approvals tab manages the same list."],"0.5.153":["Your hooks now run in the XENO Agent app as well: the CLI and the app share one hook loader, one trust store and one runtime, from the SDK. A hook you trust with xeno hooks trust runs in both; an untrusted or disabled one runs in neither."],"0.5.152":["xeno ws: when a capability is not granted, the message names Settings \u203A Connected apps once instead of twice.","Scheduled workflows (xeno schedule workflow \u2026) now also run while the XENO Agent app is open, without the CLI daemon. Each schedule is claimed before it starts, so it never starts twice."],"0.5.150":["Scheduled prompts (/loop, the Cron tools and xeno app-server's schedules) now use the same scheduler as the XENO Agent app, from the SDK. The XENO Agent app runs a folder's scheduled jobs itself now, so they run while the app is open even without a terminal; a job is claimed before it runs, so it never runs twice. Schedules you already have keep working unchanged.","Security: built with XENO Agent Interface 0.1.140 (Electron 45.1.0, Node 24.22.1, fixing CVE-2026-111497) and XENO Agent SDK 0.10.92."],"0.5.149":["/artifacts publish (a local page) and adding a comment with /artifacts comments now go through the XENO Agent host, the same pages the app shows. Pages, links and comments work as before."],"0.5.148":["A policy you set with /peers policy now wins over the automatic rule: accept delivers even from a session running with more autonomy than this one. Leave it unset and messages that would move trust upward are still held for you.","Messages between sessions follow the coordination rules everywhere: the same message sent twice in a row is refused, and when a session's queue is full the oldest unread message is dropped and its sender told."],"0.5.147":["Messages between sessions now go through the XENO Agent host: /peers send, accept, refuse and cancel, the peer tool and the peer cockpit. The host checks that a session is really the one it says it is, and every surface sees the change as it happens."],"0.5.146":["xeno workflow run, pause, resume, cancel, retry, skip, rerun, save and create now go through the XENO Agent host, the same one the app's Workflows tab uses. The host runs the workflow, so it keeps going after this terminal closes, and after the host restarts.","Fixed: cancelling a workflow the host was running could stop the host itself. It now cancels only the workflow."],"0.5.145":['xeno run can approve a list of commands: --allowed-tools "Bash(command:python3 *)" lets an unattended run use matching commands without asking, and still refuses anything else, including a listed command that chains on a second one.',"An agent file's permissionMode is now reported as not applied, instead of being ignored silently. Choose the permission mode where the run is started.","xeno run --prompt-file - reads the prompt from standard input."],"0.5.144":["Background runs and workflows now run on the XENO Agent SDK's run store, the same one the XENO Agent app reads, so a workflow you start or pause in either one is the same workflow. Your existing runs and workflows are read as they are."],"0.5.143":["Goals and loops are now changed through the XENO Agent host, the same one the app uses: /goal, xeno goal and /loop send their changes there, so the app shows them as they happen.","Pausing, resuming or clearing a running goal still wins, now through the host as well.","Fixed (--line-input): a line you type while a command or an automatic turn is still running now runs next and its reply stays on screen. Before, the reply could be erased, or the line never ran."],"0.5.142":["Plugins and MCP servers are now managed by the XENO Agent host, the same one the app uses: xeno plugin, /plugin, /mcp and xeno mcp send their changes there, so the CLI and the app follow one set of rules.","Enabling a plugin now records that you trust it, so the app's host keeps it on instead of switching it off.","Fixed: /plugin uninstall no longer deletes the folder of a plugin you installed from your own project.","Fixed: xeno plugin list no longer crashes on an empty plugins.json."],"0.5.141":["Skills are the same in the CLI and the XENO Agent app. /skills and xeno skills now read one shared skill set, the same one the app's new Skills tab shows, so a skill you turn on in one is on in the other.","Turns run in the shared Agent host (XENO_AGENT_ATTACH) now have your skills too; before, they had none."],"0.5.140":["The CLI and the XENO Agent app no longer replace each other's background host. A running Agent host is now replaced only by a newer one; before, whichever started last swapped in its own copy, so an older app could downgrade the host the CLI started."],"0.5.139":["xeno plugin and the XENO Agent app now share one plugin store, ~/.xeno/data/extensions/plugins, so a plugin installed in one shows up in the other. Plugins still in ~/.xeno-agent/plugins keep working until xeno-home migrate copies them across; nothing is moved or deleted for you.","Your XENO files live in ~/.xeno. Installed updates and run logs used to go to the AppData folders; the CLI still reads them there, so nothing is lost, and the next xeno update installs into ~/.xeno.","An Agent-mode session grants the shared host the folders it was given, which you can see and revoke in the XENO Agent app under Settings > Folder Access, and /mcp decisions are recorded in the host too."],"0.5.138":["With XENO_AGENT_ATTACH set, the CLI starts the shared XENO Agent host itself when none is running, the same host the desktop app uses. It keeps running after the CLI exits, and the next CLI or the desktop app joins it.","A turn that fails in the host now fails the run. Before, a provider error could print status ok with an empty answer.","Turns through the host report real token usage and tool calls instead of zeros.","A long shell command collapses with a vertical \u22EE in the gutter, so the card's left rule stays unbroken."],"0.5.137":["XENO Agent turns can run in the shared Agent host, the same one the desktop app uses: set XENO_AGENT_ATTACH=1 (or require) for xeno run, or use /provider use sdk-native in chat. Turns run as your own XENO account; you never sign in twice.","Full Access carries through to the host as its full-access mode: no prompts inside the workspace, and writes outside it are still refused."],"0.5.136":["Security update: the bundled XENO account library moves to 0.4.1 and zod 4.6.7 (fixes a memory-exhaustion advisory that affects every zod 3 release), and undici moves to 6.29.1."],"0.5.135":["A slash command you have typed in full now shows in your accent colour, so you can see it will run, and deleting a letter brings the matching suggestions back.","After /logout, the next start shows the sign-in screen straight away instead of flashing the chat first.",'The sign-in waiting screens keep "Esc or Ctrl+C to cancel" on the bottom row, and the browser page you land on after approving is now a designed XENO page with your alien.'],"0.5.134":["Closing the terminal or ending xeno during a sign-in refresh no longer leaves you signed out: the next start finishes that refresh instead of asking you to sign in again.","The status bar keeps its colours on a narrow terminal, so Ctrl+Down shows which item you are on; long rows drop their least useful parts instead of turning grey.","After xeno login, your alien waves above the XENO name."],"0.5.133":["If your sign-in turns out to be invalid after chat has opened (expired, or a refresh that was cut off), chat now shows the sign-in screen right there and carries on once you sign in, instead of exiting and asking you to run xeno login.","The sign-in screen now animates the whole crew of six aliens, one after another, with its key hints along the bottom of the terminal. Esc on the sign-in screen exits straight away.","A CLI installed with npm no longer hands off to an older version that xeno update activated earlier."],"0.5.132":['New sign-in screen: six animated XENO aliens. Pick yours on first sign-in or any time with /alien; its detail follows your /color. The long browser link is now a clickable "Open the sign-in page" where your terminal supports it, and the device page now also answers at xenosystem.ai/device.',"Escape stops the running turn and clears queued messages; double Escape opens rewind only when the agent is idle and the input box and queue are empty.","/color adds Add color: type a #RRGGBB hex code and it stays in the picker after restarting.","xeno update installs beside running sessions, so an open session no longer makes the update fail with EBUSY. Pairs with @xenosystem/agent-sdk 0.10.77.","xeno run -y no longer overrides a --permission-mode you chose; device sign-in waits through short platform outages; XENO_ACCOUNT_PROFILE keeps a separate sign-in beside your normal one.","Chat draws its screen right away and checks your sign-in in the background; quitting during startup lets an in-progress sign-in refresh finish, so it can no longer leave your sign-in interrupted."],"0.5.131":["Escape interrupts the running turn and clears queued follow-ups without scheduling rewind. Double Escape opens rewind only on an idle, empty composer with no queued prompts; clearing input never counts as a rewind press."],"0.5.130":["/color now offers Add color: enter a #RRGGBB hex code, save it, and select it again after restarting. /theme and direct /color #RRGGBB commands support the same saved colors."],"0.5.129":["Updates install beside running sessions and activate atomically after signature, integrity, dependency and version checks; open sessions keep their loaded runtime."],"0.5.128":["Streamed partial paragraphs now appear before the next newline, with a replaceable preview that becomes formatted Markdown without duplicate text.","Gateway keepalives display Waiting for model output instead of Receiving model response. Fullscreen progress separates each model request's elapsed time from whole-turn elapsed time and labels cumulative turn tokens explicitly."],"0.5.127":["Long fenced code lines now wrap inside the code block: every continuation row repeats the left border and indentation instead of spilling to the terminal's left edge. Blank rows and wide Unicode characters remain aligned."],"0.5.126":["Self-review appears below the Worked for turn divider in fullscreen and line mode, with one Self-review label. Review limitations remain visible.","Shell calls show a readable command block with PowerShell labels, terminal-width wrapping and expandable long scripts instead of truncated multiline parentheses."],"0.5.125":["xeno update now recognizes Linux/macOS npm command symlinks as npm installs, so it installs the latest version instead of incorrectly asking for a native download. Background update eligibility uses the same resolved entry path.","Native checksum links use the correct GitHub Release download URL. Genuine native binaries still retain their own installation channel."],"0.5.124":["Chat now requires XENO account sign-in even with a model API key or local model. A valid account session is reused; signed-out piped chat stops with sign-in guidance. Use xeno run for unattended API-key execution.","SSH sign-in uses a device code in the running terminal. Browser and device sign-in open xenosystem.ai; existing token issuer and credential storage remain unchanged.","Linux without a system keyring keeps account sign-in only for the running process. Sign in inside xeno to use chat, or configure a Secret Service keyring for persistence."],"0.5.123":['After a turn that changed files, the agent now reviews its own work and shows one line after the reply, such as "Self-review: checked the edit; tests pass". Findings, fixes and anything left unverified expand with ctrl+o. A review that failed or ran out of time says so (SDK 0.10.75).',"`xeno run --json` includes the review as a `selfReview` field. Turn it off with `selfReview: false` in config or XENO_SELF_REVIEW=0.","Read-only commands containing JavaScript arrow functions no longer trigger a review by mistake. Windows commands also work when a deeply nested temporary directory would prevent the process launcher from starting."],"0.5.122":["Chat no longer gets a second, confused reply: the check that stops the agent claiming it made a file without verifying it now runs only when the turn actually wrote something (SDK 0.10.73)."],"0.5.121":['Signing in works again. 0.5.117 to 0.5.120 were published without the bundled account module, so `xeno login` reported "XENO sign-in is unavailable". This release is built with the isolated release builder, which refuses a package without it.'],"0.5.120":['`xeno update` works on Windows again: it failed with "spawn EINVAL" because newer Node refuses to start npm.cmd without a shell.',"The background auto-updater uses the same safe launch, so it no longer prints a Node deprecation warning."],"0.5.119":["`/import` turns a Claude Code, Codex or opencode session into a real XENO session, keeping turns, tool calls and results, lists what could not be carried, and offers to resume it. `xeno import <agent> <session> --json` does the same from a script.",'Updates install themselves in the background for global npm installs: at most every 12 hours, never a downgrade, rolled back if the new version does not start. A green "Update installed \xB7 Restart to update" appears above the input. Turn it off with XENO_NO_AUTOUPDATE=1 or `autoUpdates: false`.','Typing `!` shows a pink `!` prompt and "! for shell mode", so a shell command no longer looks like a chat message.',"Pasting or typing the path of an image turns it into an [Image #N] chip, like a clipboard image; Backspace removes the whole chip.",'`/exit` no longer reports "cleanup remains unconfirmed" for harmless steps. When something real is left behind it names the step, with details in ~/.xeno-agent/logs/cli.log.',"Resuming a session whose history has an unfinished tool call or an orphaned tool result repairs it once and saves the repair, so the provider accepts the next turn (`xeno --resume`, `/resume`, `xeno run --resume` and imported sessions).",'When an agent profile asks before an external action (a push, a publish, a deploy), chat asks "Allow <action> <target>?" with Yes / Yes for this session / No. Headless runs deny unless permissions are bypassed (SDK 0.10.72).',"A turn refused for an unfinished tool call shows the SDK's own explanation and what to do, instead of a generic error."],"0.5.118":['A turn no longer dies with "An error occurred while processing your request." after the agent changes directory: a `cd` inside a Bash call moves the session\'s working directory, and that is no longer mistaken for another terminal taking over the conversation.',"Failures now say what went wrong instead of hiding the cause in the session audit log (SDK 0.10.70)."],"0.5.117":["Act as one of your XENO agents: `xeno run --as <agent>` and `/as <agent>` in chat use the agent's identity, instructions, model and tools.","As an agent, xeno sees the tasks delegated to it, claims one while it works and releases it when the run ends. New comments arrive before the turn finishes."],"0.5.116":["Sign in with your XENO account on Linux, including Google Cloud Shell and SSH: `xeno login`, `xeno login --device`, or the chat welcome screen.","On Linux the sign-in is kept in the desktop keyring (Secret Service). Without a keyring it lasts until the process exits, and xeno says so; it is never written to a file."],"0.5.115":["On Linux and macOS, chat says account sign-in is Windows-only for now and names the API-key route, instead of a menu that could only fail.","Long sessions no longer freeze after you send a message: skills are no longer rescanned hundreds of times per request.","Rewind puts the removed message back in the input box. Restore notices disappear instead of staying in the conversation.","Published artifacts return to the tray when you resume a session, with fresh working local links.","Context usage uses the model's real window. The working row says when history is compacting, a model is responding, or a request is retrying; token totals say input+output.","SDK 0.10.66 retries incomplete tool calls instead of ending on a promise. A single denial no longer stops the loop; unattended denials name the allowed commands. Incomplete turns say so."],"0.5.114":["ReadImage shows the model the actual picture instead of text."],"0.5.113":["Overwriting a file shows a diff; Esc Esc opens a redesigned rewind picker; tables and long lines wrap cleanly.","Ctrl+Down moves into the footer; the status row shows context usage in plain words."],"0.5.112":['A long run is no longer refused with "Historical arguments violate schema" after the model sends an invalid tool call.',"A request that reads like a question (for example with a typo) is no longer refused its file changes; the permission mode decides."],"0.5.111":["Headless runs can use the skills they were given: loading a skill no longer asks for permission. What a skill does still asks as usual.","Uses SDK 0.10.61."],"0.5.110":["Acting as one of your XENO agents (`xeno run --as`, `/as`), the agent can also use the platform's image, video, Library and chat services, within its division budget.","`xeno auth status` says when a previous sign-in was interrupted, and that `xeno login` fixes it.","Uses SDK 0.10.60."],"0.5.109":["`xeno login` works without an interactive terminal (from an agent's `!` prompt, a pipe or a script): it uses device sign-in and says so, instead of ending silently.",'A failed sign-in says why (the account error and its code), with anything token-shaped removed, instead of only "could not be completed".',"`xeno auth status` reports whether you are signed in even when an API key pays for model requests."],"0.5.108":['Signing in works again. Since 0.5.95 the npm package was missing the module that holds your XENO sign-in, so `xeno login` said "XENO sign-in is unavailable". The release check now refuses any package that cannot load it.'],"0.5.107":["`/as` in chat: act as one of your XENO agents in the same conversation. `/as` lists them, `/as <name>` switches, `/as me` returns to you. Each switch revokes the previous agent credential, and leaving the chat revokes the last one.","`xeno run --resume` acts as the agent the session acted as before, with a fresh credential. Only the agent id is stored; `--as me` clears it.","Lines piped into `xeno chat` now run in order. Before, a slash command could end the session while later lines were still waiting.","Uses SDK 0.10.59."],"0.5.106":["`xeno run` takes its prompt from standard input (`xeno run -`, or piped with no prompt) or from `--prompt-file <path>`, so a prompt longer than a command line allows reaches the model as the message itself, up to 8 MB.","`xeno run --as <agent>` acts as one of your XENO agents: its instructions, model, effort and tool policy, with the XENO Tasks tools ready. Its credential stays in memory and is revoked when the run ends, however it ends. `--json` reports `acting_as`.","`xeno spawn <args>` hands the rest of the command to XENO Spawn.","Uses SDK 0.10.58."],"0.5.105":["`xeno run` saves every run as a session and prints its `session_id` in `--json` output. `--resume <id>` continues that conversation with a new prompt, and `--continue` picks up this folder's most recent session. Both work for local runs, not with --delegate, --remote or --bg."],"0.5.104":["`xeno run --output-schema <file>`: the final answer must be JSON that matches the given JSON Schema. An answer that does not match is sent back with the errors to fix, and the valid result is returned as `structured_output` in the JSON output. If no valid answer arrives, the run ends incomplete (exit 1).","Uses SDK 0.10.55."],"0.5.103":["A run that produced every output named in XENO_REQUIRED_OUTPUT_PATHS_JSON now reports ok (exit 0) even if one of its tool calls was denied along the way. The denial is still listed in tool_summary and the audit. Without declared outputs, a denial is still the outcome.","`xeno run --allowed-tools` and `--disallowed-tools` (comma-separated) control which tools the agent is offered. The limit also applies to helpers it starts."],"0.5.102":["A research run whose answer is a written document that cites its sources is no longer held open asking for the sources again in chat.","Uses SDK 0.10.54."],"0.5.101":["Skills found by default are named project:<name> or user:<name>, so the Skill tool resolves the name it was given, and the same name in project and user folders is two skills.","Child agents and background workers inherit their parent's skills again; the interactive-child inheritance tests pass.","Uses SDK 0.10.53."],"0.5.100":["You can set how much web research one turn may do. `xeno run` and chat accept --max-web-searches (1 to 200), --max-web-fetches (1 to 500) and --max-web-calls, or the environment variables XENO_MAX_WEB_SEARCHES, XENO_MAX_WEB_FETCHES and XENO_MAX_WEB_CALLS. Without them the limits are unchanged: 5 searches and 12 fetches for a research request, 3 and 4 for a quick question. A value that is not a whole number in range stops the command with a message. Each search can cost provider money, up to the per-request cap.","Uses SDK 0.10.42."],"0.5.99":["Web search uses your account's configured provider allowance when you have not set a limit. Explicit limits still narrow it, including zero: XENO_WEB_CONTEXT_MAX_PROVIDER_COST_USD and --provider-cost-budget-usd never silently authorize additional spending.","WebFetch reports the recorded reason when a page cannot be retrieved, such as site refusal, a missing page, rate limiting or a network error, instead of only saying the scrape failed. Conversational tools preserve the specific error code for the agent. Explicit site refusals are not bypassed.","Uses SDK 0.10.41 and Web Context client 0.1.5. The HTML transcript redesign and /provider picker remain outside this release."],"0.5.98":["Chat draws its composer before loading session state or building the agent. You can type immediately; early submissions wait until restoration, permission state and execution ownership are ready. In five real-terminal runs on our large workspace, the usable frame appeared in 579 ms median. Line-input chat also preserves input received before readiness, including piped input ending at EOF.","Terminal updates repaint only changed lines; typing and in-place tool updates no longer redraw the whole screen. The status command refreshes on changes with a bounded cadence. --version runs from a tiny entry without loading the agent runtime.","Background dispatch helpers report their results back when they settle. The footer separates the agent list from status by one blank row, keeps main and helpers adjacent, shows state on the left and aligns elapsed time and tokens on the right.","Web Context uses your signed-in XENO account by default, with a fresh DPoP proof for each request. XENO_API_KEY also works; explicit Web Context endpoint/token settings still take precedence. Gateway-prefixed search, fetch and artifact reads use Web Context client 0.1.3.","Uses SDK 0.10.40, including faster startup, background reports and the compatible Web Context client peer. The new transcript design and /provider picker are not part of this release."],"0.5.97":["Long sessions stay fast. Adding a line to the conversation no longer redraws the whole history: with 2,000 rows on screen, a new tool row went from about 8.5 seconds to about 5 milliseconds.","Each screen update is sent to the terminal in one piece, wrapped so terminals that support it paint it all at once, which removes flicker and half-drawn frames.","Typing @ to pick a file no longer reads the folder on every key; the listing is reused for two seconds. Set XENO_RENDER_STATS=1 to log frame times and key-to-screen latency to ~/.xeno/render-stats.jsonl."],"0.5.96":['The /model list is the full list the XENO API serves, read live. It shows "Loading models..." while it loads, says so plainly if the list cannot be loaded instead of offering a short built-in list, and keeps models that are temporarily unavailable at the bottom with the reason; picking one is refused with that reason.',"Switching to a model from the live list no longer makes a second network check, so the switch is immediate. Uses @xenosystem/agent-sdk 0.10.38."],"0.5.95":['Messages between sessions are now one line each. A sent message reads "sent to SESSION2: ... \xB7 queued" and its state (queued, held, delivered, running, reported, failed) updates in place; a received one reads "from SESSION1: ...". The full text and message id are behind ctrl+o, and the Send tool no longer prints its own call and JSON result.',"Tool rows no longer wait. A finished tool row settles at once instead of staying for at least 0.7 seconds, and the end of a turn no longer waits for it. Tool results open collapsed (ctrl+o to expand) instead of opening expanded and collapsing 2.2 seconds later."],"0.5.94":["You can save a model API key once with `xeno auth login --api-key`. It is read from a hidden prompt or from standard input, never from the command line, and it is checked with XENO before it is saved. XENO_API_KEY still takes precedence when it is set.","Where the key is kept: on Windows it is protected by Windows DPAPI for your Windows user account, using the native system call, and nothing is saved if that protection is unavailable. On Linux it goes into the desktop keyring (Secret Service, via secret-tool) when one is available, and otherwise into a file only you can read. On macOS it is a file only you can read.","If you used an earlier version, your saved API key moves to the new protected store the first time you start this version, and the old plaintext file loses only that key. Your previous sign-in cannot be carried over: run `xeno login` once to sign in again.","`xeno auth status` shows where the model credential is stored without printing any part of a key. On a machine that has never signed in it says 'not signed in' and how to sign in, rather than reporting a fault. `xeno logout` and `xeno auth logout` remove a saved key.","Account sign-in is available on Windows only for now. On macOS and Linux, `xeno login` says so and points to `xeno auth login --api-key` or XENO_API_KEY. Account sign-in is also bundled inside the CLI, so installing from npm needs nothing from a private registry.","Plan mode now works through the model's own tools: it starts planning by itself when the work calls for it and hands you the plan to approve. You can approve, approve with edits typed in your editor or the input box (your version is what gets carried out), or send it back with feedback. Tools from connected servers that only read keep working while planning. From @xenosystem/agent-sdk 0.10.35.","Stopping a helper at the exact moment it starts a tool no longer crashes the app.","Notification history and dismissal stay within the selected workspace, including isolated helper worktrees and deleted-parent recovery. Control Room actions accept the exact displayed snapshot for 60 seconds and refuse changed state.","MCP authentication failures identify the exact server and its dedicated login command. Repeated failures do not produce duplicate notices, and line-input chat shows the same recovery guidance as fullscreen chat.","Web fetch requests one page instead of exceeding the connected account's page quota. Map and crawl respect the account's page limit. Paid web search supports an explicit per-request USD budget and still defaults to no spending.","A prepared session handoff can now be cancelled from the original fullscreen or line-input chat. The exact offer is withdrawn before the conversation writer resumes; other detached execution stays refused."],"0.5.93":["Plan mode is here. Start with --permission-mode plan, type /plan, or press Shift+Tab: the agent can read and investigate but every change is refused until you approve its plan, including changes a helper agent would make. Plan mode survives a crash and resume, and xeno run returns the plan instead of waiting for an approval.","A session can now move to another enrolled computer with its conversation: the receiving computer downloads it from the execution authority and checks it is exactly the same before taking over. A computer that loses ownership now also stops the background tasks, helper sessions and workflow runs that session started.","Helper agents can be stopped one at a time from the agent list, cancelling a turn stops its helpers, and a helper that ran out of budget is shown as unfinished instead of done.","Every command that takes a prompt now refuses a /command it cannot run instead of sending it to the model, pause and resume on Windows really suspend the work, and slow Windows process queries no longer make commands time out. /goal clear, /goal pause and /loop stop now always win against a running goal loop, and a !command typed during a turn runs as a shell command."],"0.5.92":["A /command the chat does not know is no longer sent to the model as a prompt. Typos like /revew, commands this mode does not support, and commands from another lane now stop with a message naming the command and why, and nothing is sent. This covers the chat, xeno run, background runs and the app server.","Moving a session between computers through an execution authority now recovers safely: a computer that loses contact stops working on the session before another can take it, a failed or abandoned move hands the session back to the computer that offered it, and /handoff cancel withdraws an offer. The receiving computer checks it has exactly the same conversation before taking over.","Helper agents now keep their background tasks private: a helper can no longer read or stop its parent's or another helper's tasks, and the reverse."],"0.5.91":["You can now stop two computers from working on the same session at once. Run xeno app-server --http --execution-authority on one machine, enrol each computer with xeno executors add, and start chats with --execution-authority. While one computer has a session, another is refused until the first lets go or stops responding. Before, each computer only checked its own records, so two could both think they had the session."],"0.5.90":["Forking a conversation now makes you choose, instead of deciding silently: the whole conversation or only up to a checkpoint, and whether the fork shares this folder or gets its own git worktree. Use /fork in the chat, or xeno sessions fork with --history and --working-tree. An isolated fork says how many uncommitted changes it does not carry over. Before, every fork quietly shared the same folder, so both conversations changed the same files."],"0.5.89":["A helper started with dispatch_agent now shows in the agent list below the input while it works. Press Enter on it to open its conversation; what you type there reaches it at its next step, and once it finishes the conversation stays open to read. Before, it was one line in the transcript and its conversation could not be seen.","/agents now lists the agents started from this chat, numbered, so /attach 2 opens the one shown as 2."],"0.5.88":["With helper agents working, pressing Enter on a helper now opens its conversation in the chat, as it happens. While it is still working, what you type there reaches it at its next step. Once it has finished, the conversation stays open to read. Before, Enter showed only a status panel.","A large delegation budget no longer breaks the helpers. Given 200,000 tokens or more, a helper stopped before sending anything, because its whole budget was being reserved as room for one reply. From @xenosystem/agent-sdk 0.10.29."],"0.5.87":["Open a background agent's conversation right in the chat with /attach, by its name, its number in the agent list, or its id. Inside it, /attach opens an agent it started. Esc or /back goes back one level, and /main returns to your own chat. Before, opening an agent's agent lost the way back to the one you came from.","With helper agents working, the Down key now reaches the background agents below them too. Before, it stopped at the helpers."],"0.5.86":["An agent file's max-tokens and deadline now also apply when the agent is called as a helper in the middle of a chat, not only when it runs in the background."],"0.5.85":["xeno agents new now takes --max-tokens and --deadline (for example 30m), so a background run can have its own budget and time limit. They are kept with the run, so relaunching it does not reset them, and a reply in progress is stopped when the time limit passes.","An agent file can set a default budget with max-tokens and deadline at the top. It applies to background work started as that agent, unless you give a budget yourself. From @xenosystem/agent-sdk 0.10.28."],"0.5.84":["A background agent can now be given its own token budget and time limit when it is started. It stops once it has spent the budget, and when the time limit passes it stops, even in the middle of a reply. Both are kept with the session, so restarting the worker does not reset them. Before, a background agent had no limit of its own unless its parent goal had one."],"0.5.83":["With delegation on, each helper agent now stays inside its share of the delegation token budget. Before, the budget only limited each single reply, so a helper given 1,200 tokens could keep calling tools and spend several times that. It now stops once its share is spent and says how much it used. From @xenosystem/agent-sdk 0.10.26."],"0.5.82":["If the CLI closes while the agent is waiting for your answer, the question comes back when you resume the session, with the same choices. Before, the question was lost: the agent was told it had been interrupted and not to repeat it, so it never asked again. Press Esc to skip it and answer in your own words instead."],"0.5.81":["Tools from MCP servers now work with every model. Their names contain dots, and several models refused any request that included one: Claude and DeepSeek failed the whole turn, and gpt-6 answered with nothing. The tool still shows its real name in the terminal and in permission prompts. From @xenosystem/agent-sdk 0.10.23."],"0.5.80":["A tool server that sends a huge reply no longer ties up the agent. A reply over 16 MB is refused as it arrives, and the request fails right away with a clear error. Before, a 200 MB reply was read in full, which took about 48 seconds, and then almost all of it was thrown away. From @xenosystem/agent-sdk 0.10.22."],"0.5.79":["Long sessions stay fast to scroll. In a session of 10,000 messages, one scroll step took about 430 ms and now takes about 24 ms, and a keypress went from about 27 ms to about 4 ms. Resizing and entering scroll mode got faster too.","Images from tools now reach models that accept images even when the name is new, such as gpt-6, because the model list says which models take images. From @xenosystem/agent-sdk 0.10.21.","A reply that ends without the model sending anything now shows as an error instead of an empty, finished turn. From @xenosystem/agent-sdk 0.10.21."],"0.5.78":["When a tool's output is too long and gets shortened, the agent can now read the part that was left out. The full output is kept, and the new ToolOutput tool reads it back. Before, a long shell command lost its middle for good. From @xenosystem/agent-sdk 0.10.19.","ToolOutput reads appear in the compact tool-activity row with the other reads, and the tool line shows which stored output and offset it read."],"0.5.77":["Long sessions no longer slow down as they grow. Adding output used to re-draw the whole conversation every time, so each new line took longer the more was already on screen. Now 10,000 blocks of output take under a second instead of minutes, and memory stays flat.","The spinner on a running tool stays in the right place as output scrolls, including after it scrolls off screen and back."],"0.5.76":["Model endpoints behind a proxy that ignores streaming now work. Their reply is read as one complete answer instead of failing as a broken stream. From @xenosystem/agent-sdk 0.10.18."],"0.5.75":["A model reply cut off in the middle of a tool call no longer runs that tool with empty input. The agent is told the call was not run and nothing was changed.","If you stop the agent after it has sent a change, it is told the change may have happened, and to check before trying again, instead of being told it was cancelled. The same applies to a change that timed out.","The request time limit now covers the whole reply, not just the moment the reply starts. A reply that stalls part-way now ends at the limit instead of hanging. A timed-out request is not repeated automatically, because it may still be running.","`xeno harbor` analysis recognises the new timeout and dropped-stream messages as transport failures, as it did the old wording.","Uses @xenosystem/agent-sdk 0.10.17."],"0.5.74":["New Patch tool: the agent can change several files in one all-or-nothing edit, including adding, moving and deleting files. Nothing is written unless every change matches the files as they are. In accept-edits mode it is approved automatically, like Edit. From @xenosystem/agent-sdk 0.10.16.","Patch is treated as a file write everywhere a write is: it is denied in hosted runs that allow no edits, shown with the files it touches in the tool line and background session details, and counted by the completion checks that look at which files a run wrote."],"0.5.73":["Background and workflow workers that start slowly, for example on a busy machine, now claim their slot reliably. Before, a worker that took more than about 4 seconds to start could lose its slot and exit without a trace, leaving its run stuck as running. A worker that misses the longer start-up window is now refused with a recorded reason.","Stopping all of an agent's background processes now always finishes (from @xenosystem/agent-sdk 0.10.14)."],"0.5.72":['When no approval screen is available and the agent asks for permission in a plain terminal, typing "y" now approves. Before, every answer was recorded as a denial. For a command asking for extra access, the question now lists exactly what it wants and why. Uses @xenosystem/agent-sdk 0.10.13.'],"0.5.71":["Approving or rejecting an agent session's permission request in the Control Room now takes effect. Before, the session ignored the answer and kept waiting until it was stopped.","Control Room approvals and the SDK's built-in approval screens show a command's exact extra access and its reason, the same as the terminal prompt. Uses @xenosystem/agent-sdk 0.10.12."],"0.5.70":['When a command asks for access beyond its sandbox (network or extra folders), the approval prompt lists exactly what it wants and the reason it gave. It offers "Yes, for this call only" instead of "always", because an elevated command needs your approval every time. Uses @xenosystem/agent-sdk 0.10.11.'],"0.5.69":[`The agent can run a command in a specific directory, or through a specific shell (bash, sh, powershell, pwsh or cmd), for that one call, without moving the session's directory. The tool call line shows both, e.g. "npm test (in packages/app, via pwsh)".`,'Approving a command "always" covers only the directory and shell it was approved in, and the approval prompt names both.',"Requires @xenosystem/agent-sdk 0.10.10."],"0.5.68":["New: `xeno ctx-viz --audit` reports tools that are defined but registered by no lane, defined twice, or pointed at by an alias that goes nowhere. Run it from a CLI checkout; it exits 1 when it finds anything.",'Saving artifacts and other local records no longer fails intermittently on Windows with "EPERM: operation not permitted, rename" when another program briefly holds the file.',"Requires @xenosystem/agent-sdk 0.10.9."],"0.5.67":["Auto permission mode no longer asks before ElfAnalyze or ToolSearch, which default mode allows without asking.","The permission audit log labels every tool with the same risk level shown everywhere else.","New generated references: docs/TOOL_CATALOGUE.md (every tool per chat/run/ACP lane) and docs/TOOL_MAPPING.md (the permission decision per mode, how the terminal shows it, and its tests).","Requires @xenosystem/agent-sdk 0.10.8."],"0.5.66":["When a goal token budget runs out, the message now says how many tokens are left and how many the next request needs.",'A goal run no longer fails with "Ownership lease expired" when the process briefly stalls; the session keeps its lease as long as nobody else took it.',"Requires @xenosystem/agent-sdk 0.10.7."],"0.5.65":["Goal token limits now work on the XENO cloud route as a SOFT budget: each request's output is capped to what is left, measured usage is charged, and the goal stops once the limit is spent. One request may overshoot slightly, and the overshoot is recorded.","Local xeno-rt keeps its exact, hard limit. /goal status, xeno run and the chat notice say which kind of limit applies.","Requires @xenosystem/agent-sdk 0.10.5."],"0.5.64":["Removed the direct OpenAI Responses lane for bounded goals that 0.5.63 added. Token-limited goals run on local xeno-rt; other lanes refuse bounded work before inference, as in 0.5.62.","Background runs still refuse inline --api-key arguments, so a credential never reaches a worker's process arguments."],"0.5.63":["Bounded CLI goals can now use the official OpenAI Responses endpoint through an explicit OpenAI base URL and API key. Exact input counting, capped output and durable settlement share the same goal allowance as local xeno-rt.","The Responses lane refuses mutable remote image URLs, invalid counts and unsupported hosts before inference. It is fixture-qualified; live OpenAI and hosted/ACP quota qualification remain open.","Background runs refuse inline API keys before daemon handoff or worker spawn; use an environment or saved credential. Headless quota admission and execution now resolve the same provider endpoint."],"0.5.62":["Goals can use a durable total token limit in the local xeno-rt lane. The allowance survives restarts and is shared with local child agents; unsupported provider lanes refuse bounded work before inference.","TUI commands now execute in order, so renaming a session and immediately preparing a handoff cannot race their transcript and ownership changes.","Automatic goal continuation no longer inserts text into the command you are typing."],"0.5.61":["Goals can now carry an explicit total token limit with /goal set --max-tokens or xeno run --goal-max-tokens. The allowance survives restarts and is shared with local child agents.","Token-limited goals require a local xeno-rt runtime that advertises exact prompt counting and an enforced token ceiling. Other execution lanes report that requirement before starting work.","Automatic goal continuation no longer inserts text into a command you are typing. Human input received during a turn is queued for the next turn."],"0.5.60":[`The four canonical tools \u2014 Send, Receive, ListAgents, ListSessions \u2014 are now the CLI's own, bound to this session's peer runtime. 0.5.58 announced them and shipped the SDK's stock versions, which have no host: they recorded every message as coming from "unknown", so a delegated task's report had no sender to return to, and they forced every message to kind "task", so a note or a question ran a whole turn in the receiving session instead of being injected or asked. Both were silent. The name the release notes told the model to prefer was the one that got this wrong, while the legacy CoordinationSend it replaced got it right.`,"CoordinationSend and CoordinationQuery keep working, and are hidden again. They had been promoted back into the model's tool list beside their own canonical names, so one capability was offered twice.","ListAgents and ListSessions exist for the first time. They answer different questions on purpose \u2014 who you can send to, versus what is running where.","Sending now writes a Sent to row whoever sends. It was rendered only by the /peers command, so a human saw it and the model did not \u2014 the same asymmetry 0.5.59 fixed for arriving messages, in the other direction."],"0.5.59":["Inbound messages from other sessions now land as durable transcript rows on the live path: Received from, including a task waiting until idle and a held message with /peers accept, not a notice that scrolls away."],"0.5.58":["Unified agent architecture: sub-agents are full sessions, docked under the main-agent in the panel beneath the input box or detached as their own window \u2014 one engine, two presentations.","Messages between sessions are now first-class transcript rows in both directions: Sent to / Received from with the message visible, not a transient notice that scrolled away.","Wire vocabulary: the model gets four canonical tools \u2014 Send, Receive, ListAgents, ListSessions. CoordinationSend/CoordinationQuery keep working as hidden aliases.","Picks up SDK 0.10.0, which ships the canonical wire vocabulary and the alias layer."],"0.5.57":["Reliability pass from the goal-reconciliation: one shared projection now turns runtime events into assistant text (run turns and host-delegated branches used to keep separate copies, the class of bug where a tool payload renders as chat text).","Provider cockpit hardening: the host's durable conversation binding is validated before any mode or scope change, a mismatched host can no longer receive your project as a side effect, and the active provider lane is re-read every turn so a selection changed in another window takes effect immediately.","Tool start/end events are now driven by the interface contract's own vocabulary (phase, call id, success) instead of re-parsing raw type strings.","Release plumbing: the packed CLI manifest now records the publishable SDK version rather than the local build reference, and the security-boundary audit resolves file: SDK links through the installed package."],"0.5.56":["Independent sessions can now delegate to each other, the way Claude Code's SendMessage works: /rename names this session (shown on the input border), /peers lists every XENO Agent session on this machine, and /message <session> <task> hands it work that runs INSIDE that session with its own workspace and permissions; the result comes back here automatically.","The model has the same two primitives as the Interface - CoordinationQuery and CoordinationSend - so 'ask my DB - PLUGIN session to audit the auth flow' works in plain language. Delivery and completion are separate states; a task left running by a crashed session is marked recovery-required and never re-run.","Picks up SDK 0.9.39: the durable peer store behind this, a strict /rename commit (a failed disk write is a failed rename), and permission classification of the two coordination tools.","Typing a slash command that takes an argument ghosts its placeholder after the cursor, e.g. /rename [name].","Rendered artifacts, the way Claude Code's Artifact tool works: the model writes an HTML page and publishes it with the Artifact tool; the page appears as a link tray under the status bar (ctrl+] opens it) and is served from a private loopback viewer under a sandboxing CSP. Comments left on the page come back into the conversation as turns, and republishing the same artifact_id keeps the link.","Two homes, your choice: local is private to this machine and needs no account; home cloud (or /artifacts promote <id>) hosts the same revision on your XENO account at xenostudio.ai/a/<id>, private until /artifacts share <id> turns link sharing on. Hosted comments reach the session the same way local ones do."],"0.5.55":["Updated to SDK 0.9.38: app-server retries and permission responses enforce current tenant, workspace, and connection authority.","Fixed standalone startup by bundling the web-context client with the CLI.","Qualified context recovery, schemas, scheduling, subagents, skills, and app-server regression checks on Windows and Linux."],"0.5.54":["Picks up SDK 0.9.37, which corrects the root cause published in 0.9.36: the Linux install failure came from lockfile metadata, not from the dependency itself.","The 0.9.36 fix was correct and is retained; only its explanation was wrong, and a wrong cause is worse than none because the next person reasons from it.","Fixes a crash where a second CLI session in the same workspace killed the first one: listing schedules took a cross-process mutation lock, and the resulting error came from a background timer with no catch, which terminates the process."],"0.5.53":["Picks up SDK 0.9.36: a Windows-only native addon was a hard dependency, so `npm ci` failed outright on Linux - the SDK could not be installed there at all.","The addon is now optional and loaded lazily, which is what its call sites already assumed. Found by running the full suite on a real Linux filesystem rather than a mounted Windows drive."],"0.5.52":["Picks up SDK 0.9.35: a model the gateway cannot route was classified as a retryable server error, so a permanently wrong model id would be retried on a backoff loop forever.","A model that is temporarily unavailable stays retryable, so only the unroutable case changed. Found by a live provider conformance run against the XENO gateway."],"0.5.51":["Picks up SDK 0.9.34, which fixes provider error classification: a bad API key returning HTTP 400 was reported as a missing model capability rather than an authentication failure.","That told you your model lacked a feature when your key was simply wrong. Found by a live provider canary - offline tests prove what we send, never how we read what comes back."],"0.5.50":["Picks up SDK 0.9.33, which fixes a permission-rule wildcard that could span a carriage return: Bash(command:git*) matched 'git status\\rrm -rf /', so a prefix rule an operator wrote as a constraint could authorize a composed command.","On a terminal a carriage return returns the cursor to column zero, so an approval preview could display one command while the shell received a second one. A single * now stops at every line terminator and ** remains strictly broader."],"0.5.49":["Picks up SDK 0.9.32, which fixes a single-writer violation: a live session owner whose heartbeat stalled could be treated as stale and have its lock taken by a second writer.","A long tool call, a paused debugger or a saturated event loop no longer risks losing session ownership; a genuinely dead owner is still reclaimed immediately."],"0.5.48":["xeno handoff status gains --since-revision and --wait-ms: a caller passes the revision it already saw and the command returns when the session actually moves, instead of re-reading the whole session in a loop.","A wait that reaches its deadline exits 2 rather than 1, so an unchanged session reads as a retryable observation rather than a failure."],"0.5.47":["xeno sessions show gains --history and --cursor: recent transcript activity is read in a bounded window with a continuation cursor, instead of loading an entire transcript to display the last few entries.","New xeno agents wait <run-ids...> waits for the first of several background runs to reach a terminal state, or every run with --all. A deadline exits 2 rather than 1, so a caller can tell a timeout from a failure.","New xeno mcp resource-templates lists parameterized resources a connected MCP server offers; servers without template support are unaffected.","AskUser questions can now be cancelled, so an unanswered question no longer holds a turn open indefinitely (via SDK 0.9.31)."],"0.5.46":["Sessions can be branched: xeno sessions fork <id> creates a new session from an existing one without changing the original, carrying its transcript history and linking back to its parent, so both lines of work stay resumable.","Sessions can be titled, pinned and archived: xeno sessions title, pin and archive. Pinned sessions lead every listing regardless of activity, and archiving retains the transcript rather than deleting it.","xeno sessions list gains --archived, and shows titles and pin state inline."],"0.5.45":["The top-level xeno ctx-viz command now exposes the same bounded live tool inventory as the interactive TUI, with cursor paging and permission-safe metadata.","Inventory output clearly separates registered tools from request-loaded schemas and never grants execution authority."],"0.5.44":["File tools now complete reliably in standalone and packaged CLI processes, including guarded Edit and Write results after permission approval.","Durable interrupted-session recovery now preserves receipt-before-status crash ordering and requires explicit respawn for fresh input.","Worker stop, lease revocation, permission approval, workflow recovery, and goal-budget controls are qualified through the unsigned Windows candidate package.","Synced Agent SDK 0.9.28 with the awaited tool-operation liveness repair and recovery contracts."],"0.5.43":["Provider-native Codex and Claude continuations can be attached from the XENO provider cockpit without replacing the XENO TUI; exact provider session identity, workspace, and ownership survive detach, reattach, and Interface handoff.","The native terminal path mirrors user messages into the owning graphical conversation and keeps XENO application system instructions out of provider-visible chat text.","Synced XENO ACP 0.2.13 and Agent Interface 0.1.23 after the earlier immutable candidates were published without moving their npm latest tags."],"0.5.42":["Durable Web Context operations now render the canonical typed evidence progress stream in human and NDJSON modes without inventing counters.","SIGINT and external abort request exactly one service-side cancellation and report whether the durable job reached a confirmed terminal state.","Synced Web Context 0.1.1, Agent SDK 0.9.25, and Agent Interface 0.1.22 for the negotiated ACP v2 evidence contract."],"0.5.41":["Durable compaction now flushes the recoverable session snapshot before mutating resident history, so repeated long-context cycles and crash recovery retain completed turns.","Chat and non-interactive run paths bind the real host parent-session identity before delegating, keeping nested work and results attached to the correct resumable conversation.","Execution handoff preserves writer fencing and live ownership across A-to-B-to-C resume while Loop continuation remains unbounded by default.","Synced the public Agent SDK 0.9.24 and Agent Interface 0.1.21 registry packages for the qualified Goal / Loop / Handoff contract."],"0.5.40":["Added durable Goal records with explicit criteria, milestones, delegated tasks, progress, steering, and evidence-gated completion.","Added distinct scheduled, development, and goal-continuation loops that are unbounded by default, persist every iteration, survive restart, and remain recoverable after an iteration failure.","Added live, heartbeat-backed execution handoff across resumed terminals with atomic A-to-B-to-C transfer and immediate source fencing; one-shot commands cannot impersonate a live owner.","Handoff now flushes and relinquishes the source session-writer lock before printing the resume command, so the target can resume the same transcript without either terminal deleting or rewriting the other's lock state.","Synced Agent SDK 0.9.23 and Agent Interface 0.1.20 for the shared Goal / Loop / Handoff runtime contract."],"0.5.39":["Added XENO Web Context search, fetch, render, map, crawl, extract, job wait/cancel/resume, and Browser handoff commands with canonical evidence metadata.","Preserved Chat and Agent session mode/workspace identity across CLI and Interface resume paths.","Synced Agent SDK 0.9.22 and Agent Interface 0.1.19 for the typed Web Context runtime event contract."],"0.5.38":["Corrective Agent Interface handoff: explicit Chat, Agent, and resume launch intent now wins over restored persisted desktop tabs after session hydration.","`xeno agent --interface` preserves the exact granted workspace even when the desktop has existing Chat history, while `xeno chat --interface` remains Chat-only with no project grant.","Synced the Agent Interface client and contract packages to the installable 0.1.18 release."],"0.5.37":["`xeno chat --interface` opens the canonical desktop surface as XENO Chat with Chat-only authority and no project grant.","`xeno agent --interface` opens the same surface as XENO Agent and grants the exact current local workspace.","Synced the Agent Interface client and contract packages to 0.1.16."],"0.5.36":["`xeno chat` and `xeno agent` now launch the same canonical XENO terminal interface while preserving their invoked identity: Chat is branded XENO CHAT and Agent is branded XENO AGENT.","Chat mode owns a private managed workspace and cannot be promoted to Agent authority by saved settings or `--mode`; Agent mode keeps the explicit local-workspace and full-capability contract.","Windows Terminal multiline paste remains one editable composer item and submits as one persisted user message, including fragmented bracketed-paste frames.","Synced the Agent Interface client and contract packages to 0.1.15 and the Agent SDK to 0.9.21."],"0.5.35":["The provider cockpit now exposes durable provider lanes, exact native attach and detach, explicit stop and reconcile controls, and persists whether each Agent session is Chat mode or Agent mode.","The status bar shows the active provider lane, and non-interactive provider, lane, attach, and reconcile commands expose the same control plane to scripts.","The local release gate now builds the native Windows XENO PTY before integration tests and typechecks the complete test surface from a clean checkout.","Synced the Agent Interface client and contract packages to 0.1.12 and the Agent SDK to 0.9.18."],"0.5.34":["Windows multiline-paste recovery now keys off the actual win32 runtime even when terminal TTY capability probing reports an inconclusive profile.","Input diagnostics now record the runtime platform, terminal profile, and stdin/stdout TTY state so real-terminal evidence explains which paste path ran."],"0.5.33":["Windows Terminal multiline paste now remains one editable composer message even when Windows omits bracketed-paste markers because virtual-terminal input is unavailable.","Real bracketed-paste frames still retain stateful fragmented-stream handling, and an ordinary Enter remains a submit after the short paste-boundary grace period.","Synced the Agent Interface client and contract packages to 0.1.11 and the Agent SDK to 0.9.17."],"0.5.32":["Recent-session state now stays inside XENO_AGENT_HOME and uses durable per-workspace updates, preventing Windows EPERM contention and lost concurrent session entries.","PowerShell command completion now drains the final stdout pipe data before settling, so successful commands cannot intermittently return empty output."],"0.5.31":["Windows Terminal bracketed-paste mode is now explicitly negotiated for the full composer lifetime, correcting 0.5.30's incomplete decoder-only repair.","Native TUI and external-editor handoffs release terminal paste mode before transfer and restore it only after XENO regains terminal ownership.","`--interface` now waits for an exact nonce-bound acknowledgement from the desktop renderer instead of reporting success when an older app merely spawned and ignored the resume request.","Managed finite operations can continue beyond the generic three-turn safety cap, recent-session writes are serialized across processes, and background commands receive privacy-safe semantic fallback labels."],"0.5.30":["Multiline terminal pastes now remain one editable composer message even when Windows Terminal fragments the bracketed-paste frame across multiple input chunks.","Complete bracketed-paste frames are handled before generic Escape sequences, and their terminal markers never leak into the submitted prompt."],"0.5.29":["ACP provider cockpit: resume durable Codex, Claude, and compatible provider lanes without replaying the XENO transcript into a new native session.","Attach, detach, reattach, stop, and reconcile native provider TUIs with one-writer ownership between the XENO TUI, Agent Interface, and provider terminal.","`--interface` handoff now preserves the selected conversation host binding and exact provider continuation identity.","Background work uses semantic task names, and continuation checkpoints retain the original objective instead of ending a live operation at an arbitrary automatic-turn boundary.","Synced Agent Interface client/contract to 0.1.8 and @xenosystem/agent-sdk to 0.9.14."],"0.5.28":["The root `xeno --help` output now exposes `--interface` and `--resume [id]`, so terminal-to-desktop session handoff is discoverable at the exact command surface where it is used."],"0.5.27":["Open the XENO Agent Interface from the terminal with `xeno --interface`, resuming an exact session ID or the latest session in the current workspace.","Long-running background commands now stay alive while active, preserve native PowerShell syntax, and display meaningful task names.","Short follow-through messages such as do it and proceed now retain implementation authority, while nested continuations preserve the original objective.","Synced @xenosystem/agent-sdk to 0.9.13."],"0.5.26":["Terminal bracketed paste & multi-line input: bracketed paste frames are cleanly decoded, collapsed into `[Pasted text #N +N lines]` tokens for large blocks, and submitted with full uncorrupted text without escape code dropouts.","Dynamic terminal reflow: turn receipts, turn dividers, and prompt bubbles adapt smoothly to window resize events without clipping."],"0.5.25":["Interactive `/status`, `/config`, `/usage`, `/stats`, `/settings` multi-tab modal with live search, keyboard cycling, and instant ~/.xeno/config.json persistence.","Live 52-week session activity heatmap, longest/current streak metrics, active days summary, lifetime token metrics, and favorite model analytics.","Real-time git workspace analytics including active branch, ahead/behind counts, working tree diff additions/deletions, and live turn API elapsed times.","Turn receipt visual polish with right-margin padding and formatted recap indentation.","Interactive `/handoff` command: switch seamlessly between specialist agents with prompt context and intent transfer.","Zero-config `.claude/agents/*.md` & `.xeno/agents/*.md` discovery with level-ordered priority shadowing.","Host mid-turn steering (`turn.steer`) and subagent wire payload artifacts integration.","Synced @xenosystem/agent-sdk to 0.9.12 with enhanced offline grace monetization validation.","xeno-rt: resolved Qwen 3.8 / 3.5 MTP NextN architecture prefixes and prevented layer 32 recurrent tensor probe failure."],"0.5.24":["Published with exact matching CLI_VERSION literal, guarded by verify:version in CI.","Synced @xenosystem/agent-sdk to 0.9.11, pulling model-aware context budgets from live gateway `/v1/models` catalog.","`/import` now immediately triggers context reconstruction turns rather than pausing at the input prompt."],"0.5.23":["Model-aware context budget: queries gateway `/v1/models` catalog for authoritative `context_window` limits.","Context compaction request byte budget scaled to prevent false refusals on large toolsets."],"0.5.22":["`/context` divided by a hardcoded 200,000 regardless of which model you are on. That figure is XENO's window and nobody else's: on a 128,000-token OpenAI model the gauge read about 12% where the truth was 19%, and near the limit it said \"Context is healthy\" with compaction imminent; on Google's 1,000,000-token window it pegged at 100% from a fifth of the way in and warned permanently. It now divides by the budget the SDK actually resolved for the run.","The gauge also says how well it knows that number. A configured budget is exact and prints a plain percentage; a provider profile is one window for every model that provider serves, so it prints `~62%` and labels itself approximate. Before any turn has reported, it says the 200,000 is an assumption rather than presenting it as fact.","The numerator was always right and is unchanged: it sums the messages currently in context, so it falls when a compaction drops them. Only the denominator was asserted rather than resolved."],"0.5.21":["Security: undici 6.27.0 -> 6.28.0, closing a cookie-injection advisory. This repo had 12 open alerts and this was the ONLY one that reaches shipped code \u2014 the five rated HIGH are all build and test tooling. Fixing by severity rank would have addressed the wrong thing first.","Worktree cleanup could delete THROUGH a junction. That is the failure that destroyed two repositories on 2026-08-03: on Windows a recursive delete follows a junction and removes the target, and npm creates one for every file: dependency. Cleanup now clears the reparse point itself and never the thing it points at.","Worktree cleanup had also decayed into a no-op \u2014 its filter excluded every orphan it existed to remove, so it ran, reported success, and cleaned nothing. And a reparse-point scan that hits its cap now REFUSES rather than returning a short list, because a truncated scan that looks complete is how the delete above becomes safe-looking.","The control-plane `list()` was not a read: it wrote once per stale record, every time anything listed runs. Listing is now free of side effects.","`/import` brings a session from another agent CLI into XENO and continues it \u2014 including agy stores, where the obvious store turned out not to be the best source. `--imported` shows what is on disk and says plainly that it persists. The source transcript is never touched, and that is enforced rather than intended.","Delegated branches now run on the Agent host under XENO_AGENT_ATTACH, report tool progress while they work, and the CLI reads the HOST's audit rather than only its own. Previously a host-routed branch was silent until it finished, and a refusal blamed a missing stream that in fact existed.","`xeno host status` now reports WHICH lanes the host offers and why a blocked one is blocked \u2014 including whose environment the blockage is about, which was the part that made the old message useless.","Pinned to @xenosystem/agent-sdk 0.9.10. The pin had been two releases stale, so work that shipped in 0.9.9 reached nobody. 0.9.10 also reports how full an agent's context is: turn.completed carries the RESIDENT token count, not the cumulative billing counter, and context.pressure arrives after every model response. The obvious field re-adds the whole prompt each turn \u2014 measured live, three one-word turns reported 3049, 6106 then 9171 tokens while the context grew by about eight.","Budget accounting no longer reads the entire run store when no budget cap is configured."],"0.5.20":["Pinned to @xenosystem/agent-sdk 0.9.8. The SDK's ownership policy still labelled this CLI by a scope retired in 8363d30c, which had failed the release smoke on every run since 2026-08-13 \u2014 the mismatch was never in this repo, so the fix was a repin rather than a workaround.","The release smoke now derives how strict it should be from the release trust policy: while no signing identity is approved it holds the engineering bar, and it tightens by itself the moment one lands. It previously demanded a signature no ordinary CI run could produce, and had failed for long enough to read as background noise.","First test coverage of the native manifest signing path, which had never executed once. Signer and verifier each carry their own copy of the canonical-JSON serializer and cannot import each other, so a drift as small as key ordering would have invalidated every release signature \u2014 and would have surfaced on release day, looking like a key problem.","Windows: temporary-directory cleanup no longer loses a race with exiting child processes, and the certification matrix checks out correctly on Windows ARM. `force: true` suppresses ENOENT, not EPERM, so the previous cleanup looked defensive and was not.","Groundwork for interactive Ctrl+C on Windows: the native addon can now raise a real console interrupt. Writing 0x03 into a ConPTY does not raise a signal, which is why Ctrl+C has never worked there. NOT yet wired \u2014 the console attach succeeds and the event is raised, and a ConPTY client still does not observe it."],"0.5.19":["The CLI did nothing at all on Linux and macOS. Its entry point did not resolve symlinks, so every npx and global install ran the wrong path and exited silently \u2014 the install looked successful and the binary did nothing. Fixed.","Agent permission decisions now reach an actual human on both rails, rather than being resolved without one.","A remote run that is read-only now says so, instead of failing silently and leaving you to work out why nothing changed.","The version the binary REPORTS is now bound to the version npm publishes, and a test enforces it. They had drifted: 0.5.18 was published as a package whose `--version` said 0.5.17.","\u26A0\uFE0F 0.5.18 exists on npm and was published from a branch that was never merged. It is superseded by this release, which is cut from `main`. If you installed 0.5.18, upgrade."],"0.5.17":["The CLI now ships as @xenosystem/agent-cli. The former name @xeno-corporation/xeno-agent-cli is deprecated on npm and receives no further releases; the `xeno`, `xeno-agent` and `xeno-code` binaries are unchanged, so nothing in your shell or scripts has to change.","The exact SDK pin moves with it: the CLI is bound to @xenosystem/agent-sdk 0.8.12. 0.8.11 was never published under either name and cannot be \u2014 GitLab evaluates .gitlab-ci.yml as it exists at the tag, and tag sdk-v0.8.11 predates that pipeline.","This release cannot be installed until @xenosystem/agent-sdk 0.8.12 is live on the registry; the release pipeline fails closed on --require-dependencies-published until it is."],"0.5.16":["Windows 11 ARM64 containment certification now performs architecture-neutral MXC host preparation with the reviewed x64 helper through operating-system emulation while keeping the contained runtime native ARM64.","The CLI is bound exactly to SDK 0.8.11, whose host-preparation reports distinguish the host architecture from the reviewed setup-helper architecture and retain timeout diagnostics."],"0.5.15":["macOS and Linux standalone diagnostics now report their verified POSIX process-group lifecycle independently from the stronger process-hardened sandbox level, preserving truthful security status while certifying full-tree cancellation, timeout, and shutdown behavior.","Generated Harbor benchmark and audit workspaces are excluded from source control, keeping Windows ARM64 checkouts below platform path limits and removing 9,938 generated artifacts from release candidates."],"0.5.14":["Windows 11 24H2 containment admission now uses the authoritative non-server NT client build floor instead of rejecting current Azure and GitHub Windows 11 images whose legacy registry ProductName still says Windows 10.","Windows Server remains fail-closed, pre-26100 clients remain ineligible, and both x64 and ARM64 host identities have regression coverage."],"0.5.13":["Hosted Windows x64 containment certification now fails closed unless the runner is Windows 11 24H2 or newer, the platform supported by Microsoft MXC, instead of treating Windows Server runner failures as product failures.","The certification matrix accepts a protected XENO_WINDOWS_X64_RUNNER label for an ephemeral Windows 11 x64 runner while keeping all other hosted platform rows unchanged.","Containment failure reports preserve bounded head-and-tail diagnostics through SDK 0.8.10 so the actionable trailing Win32 or MXC error is retained."],"0.5.12":["Windows MXC containment now launches its unrestricted host from the prepared system-drive temporary directory, outside directories whose DACLs are mutated by the contained policy, and certification captures official redacted MXC diagnostics.","Internal background session workers no longer start a competing global reconciler, preventing slower macOS hosts from quarantining a healthy turn between transcript append and checkpoint commit.","The interactive attach/input/stop smoke now follows the actual persisted inbox sequence and records worker logs on failure; the CLI is bound exactly to SDK 0.8.9."],"0.5.11":["Windows x64 containment certification now launches the MXC host and contained runtime with working-directory and temporary paths on the prepared system drive, matching split-drive GitHub runners.","The CLI is bound exactly to SDK 0.8.8, preserving the passing Linux, macOS, and Windows ARM64 conformance behavior while repairing Windows x64 ProcessContainer startup."],"0.5.10":["Linux containment certification now keeps disposable fixtures under the OS-private temporary mount instead of GitHub's workspace-projected runner directory, preserving the unlisted-filesystem boundary probe.","Windows certification retains the MXC-prepared system-drive fixture root required by hosted runners whose workspace and default temp directory use another volume."],"0.5.9":["Windows containment certification now creates its disposable fixtures on the MXC-prepared system drive, including hosted runners whose workspace and default temp directory live on another volume.","Standalone Windows certification now performs the same explicit host preparation and temporary-root binding as the native package matrix."],"0.5.8":["Native containment certification now compiles its macOS UI-policy probe against the stable libsystem_sandbox ABI without depending on private SDK headers.","Windows certification now distinguishes MXC's persistent per-policy DACL requirement from its explicit one-time host-preparation warnings."],"0.5.7":["The immutable CLI candidate now binds SDK 0.8.5 to the exact canonical Linux npm tarball bytes used by certification."],"0.5.6":["Windows containment certification now performs Microsoft MXC's explicit idempotent host preparation before AppContainer+DACL conformance.","macOS ARM64 certification now records behavioral Seatbelt evidence for pasteboard, WindowServer, LaunchServices, and HID isolation."],"0.5.5":["Native certification now resolves the SDK candidate artifact from the same workspace path on Bash and PowerShell runners.","SDK containment assets retain executable package modes on Linux and macOS, with a source regression check for every reviewed Unix binary."],"0.5.4":["Native engineering certification jobs now download the exact SDK tarball produced by the successful parent gate before installing dependencies.","The six-platform matrix remains source-bound to one immutable CLI tag and one immutable SDK candidate artifact."],"0.5.3":["Candidate packaging accepts both npm 11 array-form and npm 12 package-keyed JSON, with explicit diagnostics for malformed output.","Hosted SDK packaging now parses a bounded JSON file instead of relying on a large shell variable or an obsolete npm output shape."],"0.5.2":["Hosted certification now caps SDK declaration generation at two concurrent entry points and cleans declaration output in isolated bounded-memory workers.","SDK build subprocess failures now report their terminating signal or exit status instead of producing a silent hosted-run failure."],"0.5.1":["Hosted certification now builds the exact SDK candidate in bounded declaration groups, preventing parallel TypeScript declaration generation from exhausting GitHub-hosted runner resources.","Post-freeze readiness now distinguishes exact candidate tags verified at the candidate commit from collisions in release, registry, feed, and service namespaces."],"0.5.0":["Agent Profiles now provide enforceable Assistant, SWE, Reviewer, Writer, Research, Product, CI, DevOps, and Legal Research identities with bounded tools, permissions, skills, hooks, memory, isolation, and external-action authority.","The XENO Artifact Protocol adds durable plans, patches, diffs, reviews, screenshots, recordings, reports, provenance, approvals, and evidence relationships shared across local, hosted, and Hub workflows.","Secure Execution Contracts and capability leases now make filesystem, network, secret, process, device, browser, and external-action authority explicit and auditable.","Skills v2 adds standards-compatible SKILL.md discovery, progressive loading, bundled resources, invocation policy, version identity, and compatibility with XENO, .agents, and Claude skill locations.","MCP now supports current Streamable HTTP sessions and OAuth discovery while retaining compatible stdio and legacy SSE connections.","Browser, computer-use, hosted-agent, semantic-index, production-review, spec-planning, secure-sharing, and provider-onboarding surfaces are integrated through the shared platform contracts.","The retained TUI now presents stable grouped tool activity, live task and subagent status, candidate-bound edit previews, context-pressure and compaction state, and clearer turn completion receipts.","Six-product candidate certification now binds the SDK, XENO Use, XENO Browser, Agents API, CLI, and Hub to exact source identities, versions, tags, evidence, and protected release gates."],"0.4.45":["This transitional release is engineering-tested but not GA-certified: native PTY artifacts are unsigned and remain disabled by default until the Azure signing identity is approved; ordinary CLI and pipe-mode commands remain available.","App Server v2 now provides durable threads and turns, typed clients, permission ownership and expiry, bounded replay and backpressure, authenticated HTTP access, and additive v1 compatibility.","The terminal renderer now uses committed retained frames, bounded coalescing, one normal write per frame, a responsive 50-agent footer, accessibility modes, and a native terminal compatibility matrix.","Release certification now fails closed on six native architectures, platform and manifest signatures, reproducible package payloads, SBOMs, provenance attestations, independent approvals, npm OIDC publication, and public clean-install verification.","Long chat prompts now soft-wrap into a growing six-row composer with Unicode-safe editing, visual Up/Down navigation, file-panel parity, and a temporary XENO_INPUT_SOFT_WRAP=0 rollback switch.","Long-running model-authored shell commands now use managed operations: Ctrl+B promotes the same process, finite background work waits without model polling, and durable continuations resume exactly once after terminal output arrives.","ReadImage now uses Xeno's dependency-free owned raster codec for bounded PNG, BMP, Netpbm, and core-SVG previews; /processes and doctor expose task control, process-tree containment, operation-schema, and codec status.","Dynamic workflows now expose first-class run limits and terminal reducer summaries in run records and inspect JSON.","Background agent sessions now deliver durable completion, failure, stop, and request-keyed needs-input notifications to interactive parent chats and bounded headless runs without clobbering prompt drafts.","Workflow orchestration includes grouped phase/child progress, parent-chat completion notifications, WorkflowWait, /workflows drill-down, watch JSONL snapshots, and ultracode workflow prompts.","Workflow starts now support plan preview and exact-definition approval memory, scheduler ticks are serialized, and workflow lifecycle metrics are available through the OTel usage export.","Tool activity now uses semantic Update and Search labels, contextual line-numbered edit previews, expandable read/search/shell output, and accurate failure rendering.","Interactive chat now blocks repeated inspections and unrequested mutations on short questions, gives explicit research a larger typo-tolerant evidence budget, and reserves a tool-free final-answer turn when work limits are reached."],"0.4.44":["Markdown source links now render as clickable terminal links in supported terminals, with visible URLs preserved when links are disabled."],"0.4.43":["New background agents now appear in the footer immediately after launch, and the footer can show up to eight agent sessions."],"0.4.42":["Background agent footer rows now fit the common three-agent fanout without hiding the first agent on compact terminals.","Completed background agent sessions now close after BackgroundAgentJoin returns their result to the main agent."],"0.4.41":["Completed background agent footer rows now keep a fixed runtime instead of continuing to count upward."],"0.4.40":["One-shot background agent sessions now mark done after returning their result, while user-follow-up sessions stay idle for continued chat."],"0.4.39":["Background agent session activity now uses concise status labels like Thinking instead of showing the full task prompt."],"0.4.38":["Opened background agent sessions now show their own session activity line while keeping main-agent tool progress isolated."],"0.4.37":["Opened background agent sessions no longer show the main agent's active tool progress line."],"0.4.36":["Opened background agent sessions now render the same main-chat transcript surface for user messages, assistant messages, tool calls, and tool results."],"0.4.35":["Background agent session chat now includes tool calls and tool results in its visible history."],"0.4.34":["Opening a footer background agent now switches the main chat surface into that agent session instead of showing a separate info panel.","Child-session input now queues messages to that agent while Esc returns to the main chat."],"0.4.33":["Background agent footer rows now repaint immediately during active turns.","Remembered background-agent approvals now apply to later background-agent launches."],"0.4.32":["Startup release-note hints now sit directly under the note text and render dimmed in the side panel."],"0.4.31":["Unread release notes now render beside the startup XENO AGENT header on wide terminals."],"0.4.30":["BackgroundAgentList now only reports current-chat footer sessions so old workspace agents do not hide missing new deployments."],"0.4.29":["Background agent footer markers now use filled and empty squares.","Opening a background agent from the footer now shows its session chat with transcript and message input."],"0.4.28":["First-run default model is now gpt-5.5 while saved user model choices are preserved.","Number keys in the model picker now type into search instead of selecting by index.","Model selections made with /model now persist as the user's saved default."],"0.4.27":["Background agent footer rows are now scoped to the current chat session."],"0.4.26":["Background agent rows now sit below the status line and inherit the live chat model."],"0.4.25":["Legacy BackgroundAgent calls now create footer-visible interactive background sessions."],"0.4.24":["Model picker support now has a `xeno models --json` command, share export proof, and GitHub review artifact contracts."],"0.4.23":["Model picker and /model listings now refresh Xeno API model availability before switching."],"0.4.22":["Hook review now shows command-hook hashes and supports trust, disable, and explain commands.","Expanded lifecycle hooks now cover permission decisions, stop failures, and delegated subagent start/stop events.","Set XENO_STATUS_LINE_COMMAND to replace the TUI status line with a cached command output.","Rewind now saves the abandoned conversation branch as a manual checkpoint before restoring.","Interactive chat now supports Ctrl+R history search, Ctrl+G prompt editing, /vim input mode, and /copy answer/block/diff clipboard copy.","/theme is now a discoverable alias for /color with user/project custom theme files, and /processes stop-all stops running background tasks."],"0.4.20":["Shell completions now include the current control-plane commands, flags, statuses, scopes, and usage groups.","The local app-server browser page now includes prompt and process controls on top of advanced JSON-RPC.","Published CLI and SDK packages now include GitHub repository metadata.","Docs now call out the temporary GitHub Actions startup_failure blocker while local gates remain authoritative."],"0.1.0":["Persistent shell sessions now preserve cwd and shell state across Bash calls.","Delegated planner, explorer, executor, and reviewer branches now support staged and parallel policies.","MCP now supports stdio and SSE transports, prompt discovery, resource reads, and live tool sync.","Notebook, ask-user, and memory tools are available in the shared agent runtime.","CLI operator workflows now include doctor, bug-report, config editing, cost summaries, and runtime inspection."]};function BKe(e=Pe){return Gwi[e]??[]}function jwi(e=Pe){let t=Rt().lastReleaseNotesSeen;return BKe(e).length>0&&t!==e}function oU(e=Pe){mo({lastReleaseNotesSeen:e})}function Eye(e){let t=e??Pe,r=BKe(t);return r.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...r.map(n=>`- ${n}`)].join(`
|
|
6631
|
+
`)}function Qwi(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function Iye(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${Qwi(e.targetPrompt)}"`,r=await e.checkpointManager.create({trigger:"manual",messages:e.messages,description:t});if(e.sessionManager){let n=[r.id,...e.sessionManager.meta.checkpoints.filter(i=>i!==r.id)];await e.sessionManager.updateMeta({checkpoints:n}),await e.sessionManager.transcript.append({type:"checkpoint",data:{id:r.id,action:"create",name:t,trigger:"manual",messageCount:e.messages.length}})}return r.id}Qo();wo();var Gwi={"0.5.174":["xeno run --machine lets the agent use this Windows PC: real screenshots, clicks and typing. XENO Use downloads itself the first time.","Browser tools work in your own signed-in Chrome or Edge once the extension and its companion are connected."],"0.5.173":["xeno run --mcp and xeno run --image now run on the shared Agent host.","The default model can see images a tool returns: gpt-6-luna and gpt-6.1-sol receive the picture instead of a note saying they cannot."],"0.5.172":["xeno run now goes through the shared Agent host when you are signed in, with its tool lists, fallback models and required JSON answer."],"0.5.171":["Fixed: a chat on the shared Agent host stopped after 10 tool rounds. It now uses your limit, 50 by default.",'--continue no longer fails with "already locked" after a chat on the shared Agent host.',"A chat on the host keeps its web limits and keeps short questions short."],"0.5.170":["MCP servers you approved now work in a chat on the shared Agent host, each started in its own folder.","A chat tells you when a folder's server is waiting for approval."],"0.5.169":["Windows: the helper that runs commands is now one fixed program, so antivirus is far less likely to delete it."],"0.5.168":["A chat with MCP enabled stays in the CLI process again, so its MCP tools are there; the shared Agent host does not load them yet."],"0.5.167":["Windows: commands no longer fail with spawn UNKNOWN when antivirus quarantines the process launcher.","xeno host status now says whether a chat runs on the shared Agent host."],"0.5.166":["Interactive chat now runs on the shared Agent host by default, so conversations appear in the desktop app. XENO_AGENT_ATTACH=0 turns it off."],"0.5.165":["Several CLI jobs can share one sign-in: one renews at a time, and a half-finished renewal recovers by itself instead of asking for xeno login.","On the shared Agent host, a turn now draws its tools and token counts like any other, and Esc stops it and the command it was running.","If the direct route is down, a turn on the shared Agent host takes the Cloudflare route instead of failing."],"0.5.164":["On the shared Agent host, an edit made in the desktop app now reaches the terminal: the turn you edited away stops going to the model, and what you attach or rate there is kept too.","Windows: a scanner briefly holding a file no longer fails a scheduled job or other background write."],"0.5.163":["Conversations you start on the shared Agent host now appear in the XENO Agent desktop app, marked as started in the terminal, and you can carry on from either side."],"0.5.162":["On the shared Agent host, /rewind now puts your files back too: /rewind files shows what would change, /rewind files --confirm restores them. A file you edited since is never overwritten unless you add --overwrite.","Turns on the shared Agent host now remember what earlier turns did, not only what they said, so the model no longer doubts work it already finished."],"0.5.161":["On the shared Agent host, /rewind <n> continues from just before turn n in a new conversation; the original is kept. /rewind lists the turns.","On the shared Agent host, /compact summarises on the host: later turns are sent the summary, and every original turn is kept.","/fork [n] on the shared Agent host branches the host's conversation, all of it or through turn n."],"0.5.160":["In xeno chat on the shared Agent host, the host now keeps the conversation: a turn sends only your new message, and the host supplies the rest from its own record.","Conversations the host did not record from the start keep sending the CLI's own history, so nothing loses context."],"0.5.159":["--security-level process-hardened now runs on the shared Agent host instead of being refused, with the same restricted Windows token as a local run.","--security-level contained and --untrusted are still refused on the host, and say why."],"0.5.158":["An MCP server you signed into with xeno mcp login now works in the XENO Agent app too: the app uses the same stored credentials.","Opening a sign-in or app-server link no longer goes through cmd on Windows, so a crafted URL cannot run a command.","Share bundles now hide credentials found in a prompt or a tool's output, not only under secret-named fields.","xeno org, xeno github, xeno share and xeno mcp run on the same SDK code as the app; their behaviour is unchanged."],"0.5.157":["Chat turns run on the shared Agent host now carry this chat's permission mode and folders. Before, they ran with the host's defaults.","--mode chat can run on the Agent host: its turns ask the host for no tools, and a host that cannot enforce that refuses the turn. Before, a chat-only turn could not attach at all.","A chat turn whose settings the host cannot honour (such as --security-level contained) is refused with the reason, instead of running with weaker settings.","Plan mode works on the Agent host: the host's turn plans without changing anything, and its plan comes to you here for approval.","The agent can make a tool you keep and run again: it publishes a page as a tool on your XENO account. /artifacts publish|promote take --tool [--category <c>], and /artifacts keep-as-tool <id> keeps a hosted page as one."],"0.5.156":["xeno eval now uses the same eval code as the XENO Agent app, from the SDK; the app runs a project's eval suites itself. Nothing about how xeno eval behaves changes."],"0.5.155":["xeno recipes run now starts the recipe's workflow through the XENO Agent host, like xeno workflow run: the host drives it and runs each step, so it keeps going after this terminal closes, and the XENO Agent app's Recipes and Workflows tabs show it."],"0.5.154":["/approved-tools now also shows the folders you always allowed (they were remembered but never listed); remove takes a folder as well as a tool key, and clear forgets both. The XENO Agent app's Approvals tab manages the same list."],"0.5.153":["Your hooks now run in the XENO Agent app as well: the CLI and the app share one hook loader, one trust store and one runtime, from the SDK. A hook you trust with xeno hooks trust runs in both; an untrusted or disabled one runs in neither."],"0.5.152":["xeno ws: when a capability is not granted, the message names Settings \u203A Connected apps once instead of twice.","Scheduled workflows (xeno schedule workflow \u2026) now also run while the XENO Agent app is open, without the CLI daemon. Each schedule is claimed before it starts, so it never starts twice."],"0.5.150":["Scheduled prompts (/loop, the Cron tools and xeno app-server's schedules) now use the same scheduler as the XENO Agent app, from the SDK. The XENO Agent app runs a folder's scheduled jobs itself now, so they run while the app is open even without a terminal; a job is claimed before it runs, so it never runs twice. Schedules you already have keep working unchanged.","Security: built with XENO Agent Interface 0.1.140 (Electron 45.1.0, Node 24.22.1, fixing CVE-2026-111497) and XENO Agent SDK 0.10.92."],"0.5.149":["/artifacts publish (a local page) and adding a comment with /artifacts comments now go through the XENO Agent host, the same pages the app shows. Pages, links and comments work as before."],"0.5.148":["A policy you set with /peers policy now wins over the automatic rule: accept delivers even from a session running with more autonomy than this one. Leave it unset and messages that would move trust upward are still held for you.","Messages between sessions follow the coordination rules everywhere: the same message sent twice in a row is refused, and when a session's queue is full the oldest unread message is dropped and its sender told."],"0.5.147":["Messages between sessions now go through the XENO Agent host: /peers send, accept, refuse and cancel, the peer tool and the peer cockpit. The host checks that a session is really the one it says it is, and every surface sees the change as it happens."],"0.5.146":["xeno workflow run, pause, resume, cancel, retry, skip, rerun, save and create now go through the XENO Agent host, the same one the app's Workflows tab uses. The host runs the workflow, so it keeps going after this terminal closes, and after the host restarts.","Fixed: cancelling a workflow the host was running could stop the host itself. It now cancels only the workflow."],"0.5.145":['xeno run can approve a list of commands: --allowed-tools "Bash(command:python3 *)" lets an unattended run use matching commands without asking, and still refuses anything else, including a listed command that chains on a second one.',"An agent file's permissionMode is now reported as not applied, instead of being ignored silently. Choose the permission mode where the run is started.","xeno run --prompt-file - reads the prompt from standard input."],"0.5.144":["Background runs and workflows now run on the XENO Agent SDK's run store, the same one the XENO Agent app reads, so a workflow you start or pause in either one is the same workflow. Your existing runs and workflows are read as they are."],"0.5.143":["Goals and loops are now changed through the XENO Agent host, the same one the app uses: /goal, xeno goal and /loop send their changes there, so the app shows them as they happen.","Pausing, resuming or clearing a running goal still wins, now through the host as well.","Fixed (--line-input): a line you type while a command or an automatic turn is still running now runs next and its reply stays on screen. Before, the reply could be erased, or the line never ran."],"0.5.142":["Plugins and MCP servers are now managed by the XENO Agent host, the same one the app uses: xeno plugin, /plugin, /mcp and xeno mcp send their changes there, so the CLI and the app follow one set of rules.","Enabling a plugin now records that you trust it, so the app's host keeps it on instead of switching it off.","Fixed: /plugin uninstall no longer deletes the folder of a plugin you installed from your own project.","Fixed: xeno plugin list no longer crashes on an empty plugins.json."],"0.5.141":["Skills are the same in the CLI and the XENO Agent app. /skills and xeno skills now read one shared skill set, the same one the app's new Skills tab shows, so a skill you turn on in one is on in the other.","Turns run in the shared Agent host (XENO_AGENT_ATTACH) now have your skills too; before, they had none."],"0.5.140":["The CLI and the XENO Agent app no longer replace each other's background host. A running Agent host is now replaced only by a newer one; before, whichever started last swapped in its own copy, so an older app could downgrade the host the CLI started."],"0.5.139":["xeno plugin and the XENO Agent app now share one plugin store, ~/.xeno/data/extensions/plugins, so a plugin installed in one shows up in the other. Plugins still in ~/.xeno-agent/plugins keep working until xeno-home migrate copies them across; nothing is moved or deleted for you.","Your XENO files live in ~/.xeno. Installed updates and run logs used to go to the AppData folders; the CLI still reads them there, so nothing is lost, and the next xeno update installs into ~/.xeno.","An Agent-mode session grants the shared host the folders it was given, which you can see and revoke in the XENO Agent app under Settings > Folder Access, and /mcp decisions are recorded in the host too."],"0.5.138":["With XENO_AGENT_ATTACH set, the CLI starts the shared XENO Agent host itself when none is running, the same host the desktop app uses. It keeps running after the CLI exits, and the next CLI or the desktop app joins it.","A turn that fails in the host now fails the run. Before, a provider error could print status ok with an empty answer.","Turns through the host report real token usage and tool calls instead of zeros.","A long shell command collapses with a vertical \u22EE in the gutter, so the card's left rule stays unbroken."],"0.5.137":["XENO Agent turns can run in the shared Agent host, the same one the desktop app uses: set XENO_AGENT_ATTACH=1 (or require) for xeno run, or use /provider use sdk-native in chat. Turns run as your own XENO account; you never sign in twice.","Full Access carries through to the host as its full-access mode: no prompts inside the workspace, and writes outside it are still refused."],"0.5.136":["Security update: the bundled XENO account library moves to 0.4.1 and zod 4.6.7 (fixes a memory-exhaustion advisory that affects every zod 3 release), and undici moves to 6.29.1."],"0.5.135":["A slash command you have typed in full now shows in your accent colour, so you can see it will run, and deleting a letter brings the matching suggestions back.","After /logout, the next start shows the sign-in screen straight away instead of flashing the chat first.",'The sign-in waiting screens keep "Esc or Ctrl+C to cancel" on the bottom row, and the browser page you land on after approving is now a designed XENO page with your alien.'],"0.5.134":["Closing the terminal or ending xeno during a sign-in refresh no longer leaves you signed out: the next start finishes that refresh instead of asking you to sign in again.","The status bar keeps its colours on a narrow terminal, so Ctrl+Down shows which item you are on; long rows drop their least useful parts instead of turning grey.","After xeno login, your alien waves above the XENO name."],"0.5.133":["If your sign-in turns out to be invalid after chat has opened (expired, or a refresh that was cut off), chat now shows the sign-in screen right there and carries on once you sign in, instead of exiting and asking you to run xeno login.","The sign-in screen now animates the whole crew of six aliens, one after another, with its key hints along the bottom of the terminal. Esc on the sign-in screen exits straight away.","A CLI installed with npm no longer hands off to an older version that xeno update activated earlier."],"0.5.132":['New sign-in screen: six animated XENO aliens. Pick yours on first sign-in or any time with /alien; its detail follows your /color. The long browser link is now a clickable "Open the sign-in page" where your terminal supports it, and the device page now also answers at xenosystem.ai/device.',"Escape stops the running turn and clears queued messages; double Escape opens rewind only when the agent is idle and the input box and queue are empty.","/color adds Add color: type a #RRGGBB hex code and it stays in the picker after restarting.","xeno update installs beside running sessions, so an open session no longer makes the update fail with EBUSY. Pairs with @xenosystem/agent-sdk 0.10.77.","xeno run -y no longer overrides a --permission-mode you chose; device sign-in waits through short platform outages; XENO_ACCOUNT_PROFILE keeps a separate sign-in beside your normal one.","Chat draws its screen right away and checks your sign-in in the background; quitting during startup lets an in-progress sign-in refresh finish, so it can no longer leave your sign-in interrupted."],"0.5.131":["Escape interrupts the running turn and clears queued follow-ups without scheduling rewind. Double Escape opens rewind only on an idle, empty composer with no queued prompts; clearing input never counts as a rewind press."],"0.5.130":["/color now offers Add color: enter a #RRGGBB hex code, save it, and select it again after restarting. /theme and direct /color #RRGGBB commands support the same saved colors."],"0.5.129":["Updates install beside running sessions and activate atomically after signature, integrity, dependency and version checks; open sessions keep their loaded runtime."],"0.5.128":["Streamed partial paragraphs now appear before the next newline, with a replaceable preview that becomes formatted Markdown without duplicate text.","Gateway keepalives display Waiting for model output instead of Receiving model response. Fullscreen progress separates each model request's elapsed time from whole-turn elapsed time and labels cumulative turn tokens explicitly."],"0.5.127":["Long fenced code lines now wrap inside the code block: every continuation row repeats the left border and indentation instead of spilling to the terminal's left edge. Blank rows and wide Unicode characters remain aligned."],"0.5.126":["Self-review appears below the Worked for turn divider in fullscreen and line mode, with one Self-review label. Review limitations remain visible.","Shell calls show a readable command block with PowerShell labels, terminal-width wrapping and expandable long scripts instead of truncated multiline parentheses."],"0.5.125":["xeno update now recognizes Linux/macOS npm command symlinks as npm installs, so it installs the latest version instead of incorrectly asking for a native download. Background update eligibility uses the same resolved entry path.","Native checksum links use the correct GitHub Release download URL. Genuine native binaries still retain their own installation channel."],"0.5.124":["Chat now requires XENO account sign-in even with a model API key or local model. A valid account session is reused; signed-out piped chat stops with sign-in guidance. Use xeno run for unattended API-key execution.","SSH sign-in uses a device code in the running terminal. Browser and device sign-in open xenosystem.ai; existing token issuer and credential storage remain unchanged.","Linux without a system keyring keeps account sign-in only for the running process. Sign in inside xeno to use chat, or configure a Secret Service keyring for persistence."],"0.5.123":['After a turn that changed files, the agent now reviews its own work and shows one line after the reply, such as "Self-review: checked the edit; tests pass". Findings, fixes and anything left unverified expand with ctrl+o. A review that failed or ran out of time says so (SDK 0.10.75).',"`xeno run --json` includes the review as a `selfReview` field. Turn it off with `selfReview: false` in config or XENO_SELF_REVIEW=0.","Read-only commands containing JavaScript arrow functions no longer trigger a review by mistake. Windows commands also work when a deeply nested temporary directory would prevent the process launcher from starting."],"0.5.122":["Chat no longer gets a second, confused reply: the check that stops the agent claiming it made a file without verifying it now runs only when the turn actually wrote something (SDK 0.10.73)."],"0.5.121":['Signing in works again. 0.5.117 to 0.5.120 were published without the bundled account module, so `xeno login` reported "XENO sign-in is unavailable". This release is built with the isolated release builder, which refuses a package without it.'],"0.5.120":['`xeno update` works on Windows again: it failed with "spawn EINVAL" because newer Node refuses to start npm.cmd without a shell.',"The background auto-updater uses the same safe launch, so it no longer prints a Node deprecation warning."],"0.5.119":["`/import` turns a Claude Code, Codex or opencode session into a real XENO session, keeping turns, tool calls and results, lists what could not be carried, and offers to resume it. `xeno import <agent> <session> --json` does the same from a script.",'Updates install themselves in the background for global npm installs: at most every 12 hours, never a downgrade, rolled back if the new version does not start. A green "Update installed \xB7 Restart to update" appears above the input. Turn it off with XENO_NO_AUTOUPDATE=1 or `autoUpdates: false`.','Typing `!` shows a pink `!` prompt and "! for shell mode", so a shell command no longer looks like a chat message.',"Pasting or typing the path of an image turns it into an [Image #N] chip, like a clipboard image; Backspace removes the whole chip.",'`/exit` no longer reports "cleanup remains unconfirmed" for harmless steps. When something real is left behind it names the step, with details in ~/.xeno-agent/logs/cli.log.',"Resuming a session whose history has an unfinished tool call or an orphaned tool result repairs it once and saves the repair, so the provider accepts the next turn (`xeno --resume`, `/resume`, `xeno run --resume` and imported sessions).",'When an agent profile asks before an external action (a push, a publish, a deploy), chat asks "Allow <action> <target>?" with Yes / Yes for this session / No. Headless runs deny unless permissions are bypassed (SDK 0.10.72).',"A turn refused for an unfinished tool call shows the SDK's own explanation and what to do, instead of a generic error."],"0.5.118":['A turn no longer dies with "An error occurred while processing your request." after the agent changes directory: a `cd` inside a Bash call moves the session\'s working directory, and that is no longer mistaken for another terminal taking over the conversation.',"Failures now say what went wrong instead of hiding the cause in the session audit log (SDK 0.10.70)."],"0.5.117":["Act as one of your XENO agents: `xeno run --as <agent>` and `/as <agent>` in chat use the agent's identity, instructions, model and tools.","As an agent, xeno sees the tasks delegated to it, claims one while it works and releases it when the run ends. New comments arrive before the turn finishes."],"0.5.116":["Sign in with your XENO account on Linux, including Google Cloud Shell and SSH: `xeno login`, `xeno login --device`, or the chat welcome screen.","On Linux the sign-in is kept in the desktop keyring (Secret Service). Without a keyring it lasts until the process exits, and xeno says so; it is never written to a file."],"0.5.115":["On Linux and macOS, chat says account sign-in is Windows-only for now and names the API-key route, instead of a menu that could only fail.","Long sessions no longer freeze after you send a message: skills are no longer rescanned hundreds of times per request.","Rewind puts the removed message back in the input box. Restore notices disappear instead of staying in the conversation.","Published artifacts return to the tray when you resume a session, with fresh working local links.","Context usage uses the model's real window. The working row says when history is compacting, a model is responding, or a request is retrying; token totals say input+output.","SDK 0.10.66 retries incomplete tool calls instead of ending on a promise. A single denial no longer stops the loop; unattended denials name the allowed commands. Incomplete turns say so."],"0.5.114":["ReadImage shows the model the actual picture instead of text."],"0.5.113":["Overwriting a file shows a diff; Esc Esc opens a redesigned rewind picker; tables and long lines wrap cleanly.","Ctrl+Down moves into the footer; the status row shows context usage in plain words."],"0.5.112":['A long run is no longer refused with "Historical arguments violate schema" after the model sends an invalid tool call.',"A request that reads like a question (for example with a typo) is no longer refused its file changes; the permission mode decides."],"0.5.111":["Headless runs can use the skills they were given: loading a skill no longer asks for permission. What a skill does still asks as usual.","Uses SDK 0.10.61."],"0.5.110":["Acting as one of your XENO agents (`xeno run --as`, `/as`), the agent can also use the platform's image, video, Library and chat services, within its division budget.","`xeno auth status` says when a previous sign-in was interrupted, and that `xeno login` fixes it.","Uses SDK 0.10.60."],"0.5.109":["`xeno login` works without an interactive terminal (from an agent's `!` prompt, a pipe or a script): it uses device sign-in and says so, instead of ending silently.",'A failed sign-in says why (the account error and its code), with anything token-shaped removed, instead of only "could not be completed".',"`xeno auth status` reports whether you are signed in even when an API key pays for model requests."],"0.5.108":['Signing in works again. Since 0.5.95 the npm package was missing the module that holds your XENO sign-in, so `xeno login` said "XENO sign-in is unavailable". The release check now refuses any package that cannot load it.'],"0.5.107":["`/as` in chat: act as one of your XENO agents in the same conversation. `/as` lists them, `/as <name>` switches, `/as me` returns to you. Each switch revokes the previous agent credential, and leaving the chat revokes the last one.","`xeno run --resume` acts as the agent the session acted as before, with a fresh credential. Only the agent id is stored; `--as me` clears it.","Lines piped into `xeno chat` now run in order. Before, a slash command could end the session while later lines were still waiting.","Uses SDK 0.10.59."],"0.5.106":["`xeno run` takes its prompt from standard input (`xeno run -`, or piped with no prompt) or from `--prompt-file <path>`, so a prompt longer than a command line allows reaches the model as the message itself, up to 8 MB.","`xeno run --as <agent>` acts as one of your XENO agents: its instructions, model, effort and tool policy, with the XENO Tasks tools ready. Its credential stays in memory and is revoked when the run ends, however it ends. `--json` reports `acting_as`.","`xeno spawn <args>` hands the rest of the command to XENO Spawn.","Uses SDK 0.10.58."],"0.5.105":["`xeno run` saves every run as a session and prints its `session_id` in `--json` output. `--resume <id>` continues that conversation with a new prompt, and `--continue` picks up this folder's most recent session. Both work for local runs, not with --delegate, --remote or --bg."],"0.5.104":["`xeno run --output-schema <file>`: the final answer must be JSON that matches the given JSON Schema. An answer that does not match is sent back with the errors to fix, and the valid result is returned as `structured_output` in the JSON output. If no valid answer arrives, the run ends incomplete (exit 1).","Uses SDK 0.10.55."],"0.5.103":["A run that produced every output named in XENO_REQUIRED_OUTPUT_PATHS_JSON now reports ok (exit 0) even if one of its tool calls was denied along the way. The denial is still listed in tool_summary and the audit. Without declared outputs, a denial is still the outcome.","`xeno run --allowed-tools` and `--disallowed-tools` (comma-separated) control which tools the agent is offered. The limit also applies to helpers it starts."],"0.5.102":["A research run whose answer is a written document that cites its sources is no longer held open asking for the sources again in chat.","Uses SDK 0.10.54."],"0.5.101":["Skills found by default are named project:<name> or user:<name>, so the Skill tool resolves the name it was given, and the same name in project and user folders is two skills.","Child agents and background workers inherit their parent's skills again; the interactive-child inheritance tests pass.","Uses SDK 0.10.53."],"0.5.100":["You can set how much web research one turn may do. `xeno run` and chat accept --max-web-searches (1 to 200), --max-web-fetches (1 to 500) and --max-web-calls, or the environment variables XENO_MAX_WEB_SEARCHES, XENO_MAX_WEB_FETCHES and XENO_MAX_WEB_CALLS. Without them the limits are unchanged: 5 searches and 12 fetches for a research request, 3 and 4 for a quick question. A value that is not a whole number in range stops the command with a message. Each search can cost provider money, up to the per-request cap.","Uses SDK 0.10.42."],"0.5.99":["Web search uses your account's configured provider allowance when you have not set a limit. Explicit limits still narrow it, including zero: XENO_WEB_CONTEXT_MAX_PROVIDER_COST_USD and --provider-cost-budget-usd never silently authorize additional spending.","WebFetch reports the recorded reason when a page cannot be retrieved, such as site refusal, a missing page, rate limiting or a network error, instead of only saying the scrape failed. Conversational tools preserve the specific error code for the agent. Explicit site refusals are not bypassed.","Uses SDK 0.10.41 and Web Context client 0.1.5. The HTML transcript redesign and /provider picker remain outside this release."],"0.5.98":["Chat draws its composer before loading session state or building the agent. You can type immediately; early submissions wait until restoration, permission state and execution ownership are ready. In five real-terminal runs on our large workspace, the usable frame appeared in 579 ms median. Line-input chat also preserves input received before readiness, including piped input ending at EOF.","Terminal updates repaint only changed lines; typing and in-place tool updates no longer redraw the whole screen. The status command refreshes on changes with a bounded cadence. --version runs from a tiny entry without loading the agent runtime.","Background dispatch helpers report their results back when they settle. The footer separates the agent list from status by one blank row, keeps main and helpers adjacent, shows state on the left and aligns elapsed time and tokens on the right.","Web Context uses your signed-in XENO account by default, with a fresh DPoP proof for each request. XENO_API_KEY also works; explicit Web Context endpoint/token settings still take precedence. Gateway-prefixed search, fetch and artifact reads use Web Context client 0.1.3.","Uses SDK 0.10.40, including faster startup, background reports and the compatible Web Context client peer. The new transcript design and /provider picker are not part of this release."],"0.5.97":["Long sessions stay fast. Adding a line to the conversation no longer redraws the whole history: with 2,000 rows on screen, a new tool row went from about 8.5 seconds to about 5 milliseconds.","Each screen update is sent to the terminal in one piece, wrapped so terminals that support it paint it all at once, which removes flicker and half-drawn frames.","Typing @ to pick a file no longer reads the folder on every key; the listing is reused for two seconds. Set XENO_RENDER_STATS=1 to log frame times and key-to-screen latency to ~/.xeno/render-stats.jsonl."],"0.5.96":['The /model list is the full list the XENO API serves, read live. It shows "Loading models..." while it loads, says so plainly if the list cannot be loaded instead of offering a short built-in list, and keeps models that are temporarily unavailable at the bottom with the reason; picking one is refused with that reason.',"Switching to a model from the live list no longer makes a second network check, so the switch is immediate. Uses @xenosystem/agent-sdk 0.10.38."],"0.5.95":['Messages between sessions are now one line each. A sent message reads "sent to SESSION2: ... \xB7 queued" and its state (queued, held, delivered, running, reported, failed) updates in place; a received one reads "from SESSION1: ...". The full text and message id are behind ctrl+o, and the Send tool no longer prints its own call and JSON result.',"Tool rows no longer wait. A finished tool row settles at once instead of staying for at least 0.7 seconds, and the end of a turn no longer waits for it. Tool results open collapsed (ctrl+o to expand) instead of opening expanded and collapsing 2.2 seconds later."],"0.5.94":["You can save a model API key once with `xeno auth login --api-key`. It is read from a hidden prompt or from standard input, never from the command line, and it is checked with XENO before it is saved. XENO_API_KEY still takes precedence when it is set.","Where the key is kept: on Windows it is protected by Windows DPAPI for your Windows user account, using the native system call, and nothing is saved if that protection is unavailable. On Linux it goes into the desktop keyring (Secret Service, via secret-tool) when one is available, and otherwise into a file only you can read. On macOS it is a file only you can read.","If you used an earlier version, your saved API key moves to the new protected store the first time you start this version, and the old plaintext file loses only that key. Your previous sign-in cannot be carried over: run `xeno login` once to sign in again.","`xeno auth status` shows where the model credential is stored without printing any part of a key. On a machine that has never signed in it says 'not signed in' and how to sign in, rather than reporting a fault. `xeno logout` and `xeno auth logout` remove a saved key.","Account sign-in is available on Windows only for now. On macOS and Linux, `xeno login` says so and points to `xeno auth login --api-key` or XENO_API_KEY. Account sign-in is also bundled inside the CLI, so installing from npm needs nothing from a private registry.","Plan mode now works through the model's own tools: it starts planning by itself when the work calls for it and hands you the plan to approve. You can approve, approve with edits typed in your editor or the input box (your version is what gets carried out), or send it back with feedback. Tools from connected servers that only read keep working while planning. From @xenosystem/agent-sdk 0.10.35.","Stopping a helper at the exact moment it starts a tool no longer crashes the app.","Notification history and dismissal stay within the selected workspace, including isolated helper worktrees and deleted-parent recovery. Control Room actions accept the exact displayed snapshot for 60 seconds and refuse changed state.","MCP authentication failures identify the exact server and its dedicated login command. Repeated failures do not produce duplicate notices, and line-input chat shows the same recovery guidance as fullscreen chat.","Web fetch requests one page instead of exceeding the connected account's page quota. Map and crawl respect the account's page limit. Paid web search supports an explicit per-request USD budget and still defaults to no spending.","A prepared session handoff can now be cancelled from the original fullscreen or line-input chat. The exact offer is withdrawn before the conversation writer resumes; other detached execution stays refused."],"0.5.93":["Plan mode is here. Start with --permission-mode plan, type /plan, or press Shift+Tab: the agent can read and investigate but every change is refused until you approve its plan, including changes a helper agent would make. Plan mode survives a crash and resume, and xeno run returns the plan instead of waiting for an approval.","A session can now move to another enrolled computer with its conversation: the receiving computer downloads it from the execution authority and checks it is exactly the same before taking over. A computer that loses ownership now also stops the background tasks, helper sessions and workflow runs that session started.","Helper agents can be stopped one at a time from the agent list, cancelling a turn stops its helpers, and a helper that ran out of budget is shown as unfinished instead of done.","Every command that takes a prompt now refuses a /command it cannot run instead of sending it to the model, pause and resume on Windows really suspend the work, and slow Windows process queries no longer make commands time out. /goal clear, /goal pause and /loop stop now always win against a running goal loop, and a !command typed during a turn runs as a shell command."],"0.5.92":["A /command the chat does not know is no longer sent to the model as a prompt. Typos like /revew, commands this mode does not support, and commands from another lane now stop with a message naming the command and why, and nothing is sent. This covers the chat, xeno run, background runs and the app server.","Moving a session between computers through an execution authority now recovers safely: a computer that loses contact stops working on the session before another can take it, a failed or abandoned move hands the session back to the computer that offered it, and /handoff cancel withdraws an offer. The receiving computer checks it has exactly the same conversation before taking over.","Helper agents now keep their background tasks private: a helper can no longer read or stop its parent's or another helper's tasks, and the reverse."],"0.5.91":["You can now stop two computers from working on the same session at once. Run xeno app-server --http --execution-authority on one machine, enrol each computer with xeno executors add, and start chats with --execution-authority. While one computer has a session, another is refused until the first lets go or stops responding. Before, each computer only checked its own records, so two could both think they had the session."],"0.5.90":["Forking a conversation now makes you choose, instead of deciding silently: the whole conversation or only up to a checkpoint, and whether the fork shares this folder or gets its own git worktree. Use /fork in the chat, or xeno sessions fork with --history and --working-tree. An isolated fork says how many uncommitted changes it does not carry over. Before, every fork quietly shared the same folder, so both conversations changed the same files."],"0.5.89":["A helper started with dispatch_agent now shows in the agent list below the input while it works. Press Enter on it to open its conversation; what you type there reaches it at its next step, and once it finishes the conversation stays open to read. Before, it was one line in the transcript and its conversation could not be seen.","/agents now lists the agents started from this chat, numbered, so /attach 2 opens the one shown as 2."],"0.5.88":["With helper agents working, pressing Enter on a helper now opens its conversation in the chat, as it happens. While it is still working, what you type there reaches it at its next step. Once it has finished, the conversation stays open to read. Before, Enter showed only a status panel.","A large delegation budget no longer breaks the helpers. Given 200,000 tokens or more, a helper stopped before sending anything, because its whole budget was being reserved as room for one reply. From @xenosystem/agent-sdk 0.10.29."],"0.5.87":["Open a background agent's conversation right in the chat with /attach, by its name, its number in the agent list, or its id. Inside it, /attach opens an agent it started. Esc or /back goes back one level, and /main returns to your own chat. Before, opening an agent's agent lost the way back to the one you came from.","With helper agents working, the Down key now reaches the background agents below them too. Before, it stopped at the helpers."],"0.5.86":["An agent file's max-tokens and deadline now also apply when the agent is called as a helper in the middle of a chat, not only when it runs in the background."],"0.5.85":["xeno agents new now takes --max-tokens and --deadline (for example 30m), so a background run can have its own budget and time limit. They are kept with the run, so relaunching it does not reset them, and a reply in progress is stopped when the time limit passes.","An agent file can set a default budget with max-tokens and deadline at the top. It applies to background work started as that agent, unless you give a budget yourself. From @xenosystem/agent-sdk 0.10.28."],"0.5.84":["A background agent can now be given its own token budget and time limit when it is started. It stops once it has spent the budget, and when the time limit passes it stops, even in the middle of a reply. Both are kept with the session, so restarting the worker does not reset them. Before, a background agent had no limit of its own unless its parent goal had one."],"0.5.83":["With delegation on, each helper agent now stays inside its share of the delegation token budget. Before, the budget only limited each single reply, so a helper given 1,200 tokens could keep calling tools and spend several times that. It now stops once its share is spent and says how much it used. From @xenosystem/agent-sdk 0.10.26."],"0.5.82":["If the CLI closes while the agent is waiting for your answer, the question comes back when you resume the session, with the same choices. Before, the question was lost: the agent was told it had been interrupted and not to repeat it, so it never asked again. Press Esc to skip it and answer in your own words instead."],"0.5.81":["Tools from MCP servers now work with every model. Their names contain dots, and several models refused any request that included one: Claude and DeepSeek failed the whole turn, and gpt-6 answered with nothing. The tool still shows its real name in the terminal and in permission prompts. From @xenosystem/agent-sdk 0.10.23."],"0.5.80":["A tool server that sends a huge reply no longer ties up the agent. A reply over 16 MB is refused as it arrives, and the request fails right away with a clear error. Before, a 200 MB reply was read in full, which took about 48 seconds, and then almost all of it was thrown away. From @xenosystem/agent-sdk 0.10.22."],"0.5.79":["Long sessions stay fast to scroll. In a session of 10,000 messages, one scroll step took about 430 ms and now takes about 24 ms, and a keypress went from about 27 ms to about 4 ms. Resizing and entering scroll mode got faster too.","Images from tools now reach models that accept images even when the name is new, such as gpt-6, because the model list says which models take images. From @xenosystem/agent-sdk 0.10.21.","A reply that ends without the model sending anything now shows as an error instead of an empty, finished turn. From @xenosystem/agent-sdk 0.10.21."],"0.5.78":["When a tool's output is too long and gets shortened, the agent can now read the part that was left out. The full output is kept, and the new ToolOutput tool reads it back. Before, a long shell command lost its middle for good. From @xenosystem/agent-sdk 0.10.19.","ToolOutput reads appear in the compact tool-activity row with the other reads, and the tool line shows which stored output and offset it read."],"0.5.77":["Long sessions no longer slow down as they grow. Adding output used to re-draw the whole conversation every time, so each new line took longer the more was already on screen. Now 10,000 blocks of output take under a second instead of minutes, and memory stays flat.","The spinner on a running tool stays in the right place as output scrolls, including after it scrolls off screen and back."],"0.5.76":["Model endpoints behind a proxy that ignores streaming now work. Their reply is read as one complete answer instead of failing as a broken stream. From @xenosystem/agent-sdk 0.10.18."],"0.5.75":["A model reply cut off in the middle of a tool call no longer runs that tool with empty input. The agent is told the call was not run and nothing was changed.","If you stop the agent after it has sent a change, it is told the change may have happened, and to check before trying again, instead of being told it was cancelled. The same applies to a change that timed out.","The request time limit now covers the whole reply, not just the moment the reply starts. A reply that stalls part-way now ends at the limit instead of hanging. A timed-out request is not repeated automatically, because it may still be running.","`xeno harbor` analysis recognises the new timeout and dropped-stream messages as transport failures, as it did the old wording.","Uses @xenosystem/agent-sdk 0.10.17."],"0.5.74":["New Patch tool: the agent can change several files in one all-or-nothing edit, including adding, moving and deleting files. Nothing is written unless every change matches the files as they are. In accept-edits mode it is approved automatically, like Edit. From @xenosystem/agent-sdk 0.10.16.","Patch is treated as a file write everywhere a write is: it is denied in hosted runs that allow no edits, shown with the files it touches in the tool line and background session details, and counted by the completion checks that look at which files a run wrote."],"0.5.73":["Background and workflow workers that start slowly, for example on a busy machine, now claim their slot reliably. Before, a worker that took more than about 4 seconds to start could lose its slot and exit without a trace, leaving its run stuck as running. A worker that misses the longer start-up window is now refused with a recorded reason.","Stopping all of an agent's background processes now always finishes (from @xenosystem/agent-sdk 0.10.14)."],"0.5.72":['When no approval screen is available and the agent asks for permission in a plain terminal, typing "y" now approves. Before, every answer was recorded as a denial. For a command asking for extra access, the question now lists exactly what it wants and why. Uses @xenosystem/agent-sdk 0.10.13.'],"0.5.71":["Approving or rejecting an agent session's permission request in the Control Room now takes effect. Before, the session ignored the answer and kept waiting until it was stopped.","Control Room approvals and the SDK's built-in approval screens show a command's exact extra access and its reason, the same as the terminal prompt. Uses @xenosystem/agent-sdk 0.10.12."],"0.5.70":['When a command asks for access beyond its sandbox (network or extra folders), the approval prompt lists exactly what it wants and the reason it gave. It offers "Yes, for this call only" instead of "always", because an elevated command needs your approval every time. Uses @xenosystem/agent-sdk 0.10.11.'],"0.5.69":[`The agent can run a command in a specific directory, or through a specific shell (bash, sh, powershell, pwsh or cmd), for that one call, without moving the session's directory. The tool call line shows both, e.g. "npm test (in packages/app, via pwsh)".`,'Approving a command "always" covers only the directory and shell it was approved in, and the approval prompt names both.',"Requires @xenosystem/agent-sdk 0.10.10."],"0.5.68":["New: `xeno ctx-viz --audit` reports tools that are defined but registered by no lane, defined twice, or pointed at by an alias that goes nowhere. Run it from a CLI checkout; it exits 1 when it finds anything.",'Saving artifacts and other local records no longer fails intermittently on Windows with "EPERM: operation not permitted, rename" when another program briefly holds the file.',"Requires @xenosystem/agent-sdk 0.10.9."],"0.5.67":["Auto permission mode no longer asks before ElfAnalyze or ToolSearch, which default mode allows without asking.","The permission audit log labels every tool with the same risk level shown everywhere else.","New generated references: docs/TOOL_CATALOGUE.md (every tool per chat/run/ACP lane) and docs/TOOL_MAPPING.md (the permission decision per mode, how the terminal shows it, and its tests).","Requires @xenosystem/agent-sdk 0.10.8."],"0.5.66":["When a goal token budget runs out, the message now says how many tokens are left and how many the next request needs.",'A goal run no longer fails with "Ownership lease expired" when the process briefly stalls; the session keeps its lease as long as nobody else took it.',"Requires @xenosystem/agent-sdk 0.10.7."],"0.5.65":["Goal token limits now work on the XENO cloud route as a SOFT budget: each request's output is capped to what is left, measured usage is charged, and the goal stops once the limit is spent. One request may overshoot slightly, and the overshoot is recorded.","Local xeno-rt keeps its exact, hard limit. /goal status, xeno run and the chat notice say which kind of limit applies.","Requires @xenosystem/agent-sdk 0.10.5."],"0.5.64":["Removed the direct OpenAI Responses lane for bounded goals that 0.5.63 added. Token-limited goals run on local xeno-rt; other lanes refuse bounded work before inference, as in 0.5.62.","Background runs still refuse inline --api-key arguments, so a credential never reaches a worker's process arguments."],"0.5.63":["Bounded CLI goals can now use the official OpenAI Responses endpoint through an explicit OpenAI base URL and API key. Exact input counting, capped output and durable settlement share the same goal allowance as local xeno-rt.","The Responses lane refuses mutable remote image URLs, invalid counts and unsupported hosts before inference. It is fixture-qualified; live OpenAI and hosted/ACP quota qualification remain open.","Background runs refuse inline API keys before daemon handoff or worker spawn; use an environment or saved credential. Headless quota admission and execution now resolve the same provider endpoint."],"0.5.62":["Goals can use a durable total token limit in the local xeno-rt lane. The allowance survives restarts and is shared with local child agents; unsupported provider lanes refuse bounded work before inference.","TUI commands now execute in order, so renaming a session and immediately preparing a handoff cannot race their transcript and ownership changes.","Automatic goal continuation no longer inserts text into the command you are typing."],"0.5.61":["Goals can now carry an explicit total token limit with /goal set --max-tokens or xeno run --goal-max-tokens. The allowance survives restarts and is shared with local child agents.","Token-limited goals require a local xeno-rt runtime that advertises exact prompt counting and an enforced token ceiling. Other execution lanes report that requirement before starting work.","Automatic goal continuation no longer inserts text into a command you are typing. Human input received during a turn is queued for the next turn."],"0.5.60":[`The four canonical tools \u2014 Send, Receive, ListAgents, ListSessions \u2014 are now the CLI's own, bound to this session's peer runtime. 0.5.58 announced them and shipped the SDK's stock versions, which have no host: they recorded every message as coming from "unknown", so a delegated task's report had no sender to return to, and they forced every message to kind "task", so a note or a question ran a whole turn in the receiving session instead of being injected or asked. Both were silent. The name the release notes told the model to prefer was the one that got this wrong, while the legacy CoordinationSend it replaced got it right.`,"CoordinationSend and CoordinationQuery keep working, and are hidden again. They had been promoted back into the model's tool list beside their own canonical names, so one capability was offered twice.","ListAgents and ListSessions exist for the first time. They answer different questions on purpose \u2014 who you can send to, versus what is running where.","Sending now writes a Sent to row whoever sends. It was rendered only by the /peers command, so a human saw it and the model did not \u2014 the same asymmetry 0.5.59 fixed for arriving messages, in the other direction."],"0.5.59":["Inbound messages from other sessions now land as durable transcript rows on the live path: Received from, including a task waiting until idle and a held message with /peers accept, not a notice that scrolls away."],"0.5.58":["Unified agent architecture: sub-agents are full sessions, docked under the main-agent in the panel beneath the input box or detached as their own window \u2014 one engine, two presentations.","Messages between sessions are now first-class transcript rows in both directions: Sent to / Received from with the message visible, not a transient notice that scrolled away.","Wire vocabulary: the model gets four canonical tools \u2014 Send, Receive, ListAgents, ListSessions. CoordinationSend/CoordinationQuery keep working as hidden aliases.","Picks up SDK 0.10.0, which ships the canonical wire vocabulary and the alias layer."],"0.5.57":["Reliability pass from the goal-reconciliation: one shared projection now turns runtime events into assistant text (run turns and host-delegated branches used to keep separate copies, the class of bug where a tool payload renders as chat text).","Provider cockpit hardening: the host's durable conversation binding is validated before any mode or scope change, a mismatched host can no longer receive your project as a side effect, and the active provider lane is re-read every turn so a selection changed in another window takes effect immediately.","Tool start/end events are now driven by the interface contract's own vocabulary (phase, call id, success) instead of re-parsing raw type strings.","Release plumbing: the packed CLI manifest now records the publishable SDK version rather than the local build reference, and the security-boundary audit resolves file: SDK links through the installed package."],"0.5.56":["Independent sessions can now delegate to each other, the way Claude Code's SendMessage works: /rename names this session (shown on the input border), /peers lists every XENO Agent session on this machine, and /message <session> <task> hands it work that runs INSIDE that session with its own workspace and permissions; the result comes back here automatically.","The model has the same two primitives as the Interface - CoordinationQuery and CoordinationSend - so 'ask my DB - PLUGIN session to audit the auth flow' works in plain language. Delivery and completion are separate states; a task left running by a crashed session is marked recovery-required and never re-run.","Picks up SDK 0.9.39: the durable peer store behind this, a strict /rename commit (a failed disk write is a failed rename), and permission classification of the two coordination tools.","Typing a slash command that takes an argument ghosts its placeholder after the cursor, e.g. /rename [name].","Rendered artifacts, the way Claude Code's Artifact tool works: the model writes an HTML page and publishes it with the Artifact tool; the page appears as a link tray under the status bar (ctrl+] opens it) and is served from a private loopback viewer under a sandboxing CSP. Comments left on the page come back into the conversation as turns, and republishing the same artifact_id keeps the link.","Two homes, your choice: local is private to this machine and needs no account; home cloud (or /artifacts promote <id>) hosts the same revision on your XENO account at xenostudio.ai/a/<id>, private until /artifacts share <id> turns link sharing on. Hosted comments reach the session the same way local ones do."],"0.5.55":["Updated to SDK 0.9.38: app-server retries and permission responses enforce current tenant, workspace, and connection authority.","Fixed standalone startup by bundling the web-context client with the CLI.","Qualified context recovery, schemas, scheduling, subagents, skills, and app-server regression checks on Windows and Linux."],"0.5.54":["Picks up SDK 0.9.37, which corrects the root cause published in 0.9.36: the Linux install failure came from lockfile metadata, not from the dependency itself.","The 0.9.36 fix was correct and is retained; only its explanation was wrong, and a wrong cause is worse than none because the next person reasons from it.","Fixes a crash where a second CLI session in the same workspace killed the first one: listing schedules took a cross-process mutation lock, and the resulting error came from a background timer with no catch, which terminates the process."],"0.5.53":["Picks up SDK 0.9.36: a Windows-only native addon was a hard dependency, so `npm ci` failed outright on Linux - the SDK could not be installed there at all.","The addon is now optional and loaded lazily, which is what its call sites already assumed. Found by running the full suite on a real Linux filesystem rather than a mounted Windows drive."],"0.5.52":["Picks up SDK 0.9.35: a model the gateway cannot route was classified as a retryable server error, so a permanently wrong model id would be retried on a backoff loop forever.","A model that is temporarily unavailable stays retryable, so only the unroutable case changed. Found by a live provider conformance run against the XENO gateway."],"0.5.51":["Picks up SDK 0.9.34, which fixes provider error classification: a bad API key returning HTTP 400 was reported as a missing model capability rather than an authentication failure.","That told you your model lacked a feature when your key was simply wrong. Found by a live provider canary - offline tests prove what we send, never how we read what comes back."],"0.5.50":["Picks up SDK 0.9.33, which fixes a permission-rule wildcard that could span a carriage return: Bash(command:git*) matched 'git status\\rrm -rf /', so a prefix rule an operator wrote as a constraint could authorize a composed command.","On a terminal a carriage return returns the cursor to column zero, so an approval preview could display one command while the shell received a second one. A single * now stops at every line terminator and ** remains strictly broader."],"0.5.49":["Picks up SDK 0.9.32, which fixes a single-writer violation: a live session owner whose heartbeat stalled could be treated as stale and have its lock taken by a second writer.","A long tool call, a paused debugger or a saturated event loop no longer risks losing session ownership; a genuinely dead owner is still reclaimed immediately."],"0.5.48":["xeno handoff status gains --since-revision and --wait-ms: a caller passes the revision it already saw and the command returns when the session actually moves, instead of re-reading the whole session in a loop.","A wait that reaches its deadline exits 2 rather than 1, so an unchanged session reads as a retryable observation rather than a failure."],"0.5.47":["xeno sessions show gains --history and --cursor: recent transcript activity is read in a bounded window with a continuation cursor, instead of loading an entire transcript to display the last few entries.","New xeno agents wait <run-ids...> waits for the first of several background runs to reach a terminal state, or every run with --all. A deadline exits 2 rather than 1, so a caller can tell a timeout from a failure.","New xeno mcp resource-templates lists parameterized resources a connected MCP server offers; servers without template support are unaffected.","AskUser questions can now be cancelled, so an unanswered question no longer holds a turn open indefinitely (via SDK 0.9.31)."],"0.5.46":["Sessions can be branched: xeno sessions fork <id> creates a new session from an existing one without changing the original, carrying its transcript history and linking back to its parent, so both lines of work stay resumable.","Sessions can be titled, pinned and archived: xeno sessions title, pin and archive. Pinned sessions lead every listing regardless of activity, and archiving retains the transcript rather than deleting it.","xeno sessions list gains --archived, and shows titles and pin state inline."],"0.5.45":["The top-level xeno ctx-viz command now exposes the same bounded live tool inventory as the interactive TUI, with cursor paging and permission-safe metadata.","Inventory output clearly separates registered tools from request-loaded schemas and never grants execution authority."],"0.5.44":["File tools now complete reliably in standalone and packaged CLI processes, including guarded Edit and Write results after permission approval.","Durable interrupted-session recovery now preserves receipt-before-status crash ordering and requires explicit respawn for fresh input.","Worker stop, lease revocation, permission approval, workflow recovery, and goal-budget controls are qualified through the unsigned Windows candidate package.","Synced Agent SDK 0.9.28 with the awaited tool-operation liveness repair and recovery contracts."],"0.5.43":["Provider-native Codex and Claude continuations can be attached from the XENO provider cockpit without replacing the XENO TUI; exact provider session identity, workspace, and ownership survive detach, reattach, and Interface handoff.","The native terminal path mirrors user messages into the owning graphical conversation and keeps XENO application system instructions out of provider-visible chat text.","Synced XENO ACP 0.2.13 and Agent Interface 0.1.23 after the earlier immutable candidates were published without moving their npm latest tags."],"0.5.42":["Durable Web Context operations now render the canonical typed evidence progress stream in human and NDJSON modes without inventing counters.","SIGINT and external abort request exactly one service-side cancellation and report whether the durable job reached a confirmed terminal state.","Synced Web Context 0.1.1, Agent SDK 0.9.25, and Agent Interface 0.1.22 for the negotiated ACP v2 evidence contract."],"0.5.41":["Durable compaction now flushes the recoverable session snapshot before mutating resident history, so repeated long-context cycles and crash recovery retain completed turns.","Chat and non-interactive run paths bind the real host parent-session identity before delegating, keeping nested work and results attached to the correct resumable conversation.","Execution handoff preserves writer fencing and live ownership across A-to-B-to-C resume while Loop continuation remains unbounded by default.","Synced the public Agent SDK 0.9.24 and Agent Interface 0.1.21 registry packages for the qualified Goal / Loop / Handoff contract."],"0.5.40":["Added durable Goal records with explicit criteria, milestones, delegated tasks, progress, steering, and evidence-gated completion.","Added distinct scheduled, development, and goal-continuation loops that are unbounded by default, persist every iteration, survive restart, and remain recoverable after an iteration failure.","Added live, heartbeat-backed execution handoff across resumed terminals with atomic A-to-B-to-C transfer and immediate source fencing; one-shot commands cannot impersonate a live owner.","Handoff now flushes and relinquishes the source session-writer lock before printing the resume command, so the target can resume the same transcript without either terminal deleting or rewriting the other's lock state.","Synced Agent SDK 0.9.23 and Agent Interface 0.1.20 for the shared Goal / Loop / Handoff runtime contract."],"0.5.39":["Added XENO Web Context search, fetch, render, map, crawl, extract, job wait/cancel/resume, and Browser handoff commands with canonical evidence metadata.","Preserved Chat and Agent session mode/workspace identity across CLI and Interface resume paths.","Synced Agent SDK 0.9.22 and Agent Interface 0.1.19 for the typed Web Context runtime event contract."],"0.5.38":["Corrective Agent Interface handoff: explicit Chat, Agent, and resume launch intent now wins over restored persisted desktop tabs after session hydration.","`xeno agent --interface` preserves the exact granted workspace even when the desktop has existing Chat history, while `xeno chat --interface` remains Chat-only with no project grant.","Synced the Agent Interface client and contract packages to the installable 0.1.18 release."],"0.5.37":["`xeno chat --interface` opens the canonical desktop surface as XENO Chat with Chat-only authority and no project grant.","`xeno agent --interface` opens the same surface as XENO Agent and grants the exact current local workspace.","Synced the Agent Interface client and contract packages to 0.1.16."],"0.5.36":["`xeno chat` and `xeno agent` now launch the same canonical XENO terminal interface while preserving their invoked identity: Chat is branded XENO CHAT and Agent is branded XENO AGENT.","Chat mode owns a private managed workspace and cannot be promoted to Agent authority by saved settings or `--mode`; Agent mode keeps the explicit local-workspace and full-capability contract.","Windows Terminal multiline paste remains one editable composer item and submits as one persisted user message, including fragmented bracketed-paste frames.","Synced the Agent Interface client and contract packages to 0.1.15 and the Agent SDK to 0.9.21."],"0.5.35":["The provider cockpit now exposes durable provider lanes, exact native attach and detach, explicit stop and reconcile controls, and persists whether each Agent session is Chat mode or Agent mode.","The status bar shows the active provider lane, and non-interactive provider, lane, attach, and reconcile commands expose the same control plane to scripts.","The local release gate now builds the native Windows XENO PTY before integration tests and typechecks the complete test surface from a clean checkout.","Synced the Agent Interface client and contract packages to 0.1.12 and the Agent SDK to 0.9.18."],"0.5.34":["Windows multiline-paste recovery now keys off the actual win32 runtime even when terminal TTY capability probing reports an inconclusive profile.","Input diagnostics now record the runtime platform, terminal profile, and stdin/stdout TTY state so real-terminal evidence explains which paste path ran."],"0.5.33":["Windows Terminal multiline paste now remains one editable composer message even when Windows omits bracketed-paste markers because virtual-terminal input is unavailable.","Real bracketed-paste frames still retain stateful fragmented-stream handling, and an ordinary Enter remains a submit after the short paste-boundary grace period.","Synced the Agent Interface client and contract packages to 0.1.11 and the Agent SDK to 0.9.17."],"0.5.32":["Recent-session state now stays inside XENO_AGENT_HOME and uses durable per-workspace updates, preventing Windows EPERM contention and lost concurrent session entries.","PowerShell command completion now drains the final stdout pipe data before settling, so successful commands cannot intermittently return empty output."],"0.5.31":["Windows Terminal bracketed-paste mode is now explicitly negotiated for the full composer lifetime, correcting 0.5.30's incomplete decoder-only repair.","Native TUI and external-editor handoffs release terminal paste mode before transfer and restore it only after XENO regains terminal ownership.","`--interface` now waits for an exact nonce-bound acknowledgement from the desktop renderer instead of reporting success when an older app merely spawned and ignored the resume request.","Managed finite operations can continue beyond the generic three-turn safety cap, recent-session writes are serialized across processes, and background commands receive privacy-safe semantic fallback labels."],"0.5.30":["Multiline terminal pastes now remain one editable composer message even when Windows Terminal fragments the bracketed-paste frame across multiple input chunks.","Complete bracketed-paste frames are handled before generic Escape sequences, and their terminal markers never leak into the submitted prompt."],"0.5.29":["ACP provider cockpit: resume durable Codex, Claude, and compatible provider lanes without replaying the XENO transcript into a new native session.","Attach, detach, reattach, stop, and reconcile native provider TUIs with one-writer ownership between the XENO TUI, Agent Interface, and provider terminal.","`--interface` handoff now preserves the selected conversation host binding and exact provider continuation identity.","Background work uses semantic task names, and continuation checkpoints retain the original objective instead of ending a live operation at an arbitrary automatic-turn boundary.","Synced Agent Interface client/contract to 0.1.8 and @xenosystem/agent-sdk to 0.9.14."],"0.5.28":["The root `xeno --help` output now exposes `--interface` and `--resume [id]`, so terminal-to-desktop session handoff is discoverable at the exact command surface where it is used."],"0.5.27":["Open the XENO Agent Interface from the terminal with `xeno --interface`, resuming an exact session ID or the latest session in the current workspace.","Long-running background commands now stay alive while active, preserve native PowerShell syntax, and display meaningful task names.","Short follow-through messages such as do it and proceed now retain implementation authority, while nested continuations preserve the original objective.","Synced @xenosystem/agent-sdk to 0.9.13."],"0.5.26":["Terminal bracketed paste & multi-line input: bracketed paste frames are cleanly decoded, collapsed into `[Pasted text #N +N lines]` tokens for large blocks, and submitted with full uncorrupted text without escape code dropouts.","Dynamic terminal reflow: turn receipts, turn dividers, and prompt bubbles adapt smoothly to window resize events without clipping."],"0.5.25":["Interactive `/status`, `/config`, `/usage`, `/stats`, `/settings` multi-tab modal with live search, keyboard cycling, and instant ~/.xeno/config.json persistence.","Live 52-week session activity heatmap, longest/current streak metrics, active days summary, lifetime token metrics, and favorite model analytics.","Real-time git workspace analytics including active branch, ahead/behind counts, working tree diff additions/deletions, and live turn API elapsed times.","Turn receipt visual polish with right-margin padding and formatted recap indentation.","Interactive `/handoff` command: switch seamlessly between specialist agents with prompt context and intent transfer.","Zero-config `.claude/agents/*.md` & `.xeno/agents/*.md` discovery with level-ordered priority shadowing.","Host mid-turn steering (`turn.steer`) and subagent wire payload artifacts integration.","Synced @xenosystem/agent-sdk to 0.9.12 with enhanced offline grace monetization validation.","xeno-rt: resolved Qwen 3.8 / 3.5 MTP NextN architecture prefixes and prevented layer 32 recurrent tensor probe failure."],"0.5.24":["Published with exact matching CLI_VERSION literal, guarded by verify:version in CI.","Synced @xenosystem/agent-sdk to 0.9.11, pulling model-aware context budgets from live gateway `/v1/models` catalog.","`/import` now immediately triggers context reconstruction turns rather than pausing at the input prompt."],"0.5.23":["Model-aware context budget: queries gateway `/v1/models` catalog for authoritative `context_window` limits.","Context compaction request byte budget scaled to prevent false refusals on large toolsets."],"0.5.22":["`/context` divided by a hardcoded 200,000 regardless of which model you are on. That figure is XENO's window and nobody else's: on a 128,000-token OpenAI model the gauge read about 12% where the truth was 19%, and near the limit it said \"Context is healthy\" with compaction imminent; on Google's 1,000,000-token window it pegged at 100% from a fifth of the way in and warned permanently. It now divides by the budget the SDK actually resolved for the run.","The gauge also says how well it knows that number. A configured budget is exact and prints a plain percentage; a provider profile is one window for every model that provider serves, so it prints `~62%` and labels itself approximate. Before any turn has reported, it says the 200,000 is an assumption rather than presenting it as fact.","The numerator was always right and is unchanged: it sums the messages currently in context, so it falls when a compaction drops them. Only the denominator was asserted rather than resolved."],"0.5.21":["Security: undici 6.27.0 -> 6.28.0, closing a cookie-injection advisory. This repo had 12 open alerts and this was the ONLY one that reaches shipped code \u2014 the five rated HIGH are all build and test tooling. Fixing by severity rank would have addressed the wrong thing first.","Worktree cleanup could delete THROUGH a junction. That is the failure that destroyed two repositories on 2026-08-03: on Windows a recursive delete follows a junction and removes the target, and npm creates one for every file: dependency. Cleanup now clears the reparse point itself and never the thing it points at.","Worktree cleanup had also decayed into a no-op \u2014 its filter excluded every orphan it existed to remove, so it ran, reported success, and cleaned nothing. And a reparse-point scan that hits its cap now REFUSES rather than returning a short list, because a truncated scan that looks complete is how the delete above becomes safe-looking.","The control-plane `list()` was not a read: it wrote once per stale record, every time anything listed runs. Listing is now free of side effects.","`/import` brings a session from another agent CLI into XENO and continues it \u2014 including agy stores, where the obvious store turned out not to be the best source. `--imported` shows what is on disk and says plainly that it persists. The source transcript is never touched, and that is enforced rather than intended.","Delegated branches now run on the Agent host under XENO_AGENT_ATTACH, report tool progress while they work, and the CLI reads the HOST's audit rather than only its own. Previously a host-routed branch was silent until it finished, and a refusal blamed a missing stream that in fact existed.","`xeno host status` now reports WHICH lanes the host offers and why a blocked one is blocked \u2014 including whose environment the blockage is about, which was the part that made the old message useless.","Pinned to @xenosystem/agent-sdk 0.9.10. The pin had been two releases stale, so work that shipped in 0.9.9 reached nobody. 0.9.10 also reports how full an agent's context is: turn.completed carries the RESIDENT token count, not the cumulative billing counter, and context.pressure arrives after every model response. The obvious field re-adds the whole prompt each turn \u2014 measured live, three one-word turns reported 3049, 6106 then 9171 tokens while the context grew by about eight.","Budget accounting no longer reads the entire run store when no budget cap is configured."],"0.5.20":["Pinned to @xenosystem/agent-sdk 0.9.8. The SDK's ownership policy still labelled this CLI by a scope retired in 8363d30c, which had failed the release smoke on every run since 2026-08-13 \u2014 the mismatch was never in this repo, so the fix was a repin rather than a workaround.","The release smoke now derives how strict it should be from the release trust policy: while no signing identity is approved it holds the engineering bar, and it tightens by itself the moment one lands. It previously demanded a signature no ordinary CI run could produce, and had failed for long enough to read as background noise.","First test coverage of the native manifest signing path, which had never executed once. Signer and verifier each carry their own copy of the canonical-JSON serializer and cannot import each other, so a drift as small as key ordering would have invalidated every release signature \u2014 and would have surfaced on release day, looking like a key problem.","Windows: temporary-directory cleanup no longer loses a race with exiting child processes, and the certification matrix checks out correctly on Windows ARM. `force: true` suppresses ENOENT, not EPERM, so the previous cleanup looked defensive and was not.","Groundwork for interactive Ctrl+C on Windows: the native addon can now raise a real console interrupt. Writing 0x03 into a ConPTY does not raise a signal, which is why Ctrl+C has never worked there. NOT yet wired \u2014 the console attach succeeds and the event is raised, and a ConPTY client still does not observe it."],"0.5.19":["The CLI did nothing at all on Linux and macOS. Its entry point did not resolve symlinks, so every npx and global install ran the wrong path and exited silently \u2014 the install looked successful and the binary did nothing. Fixed.","Agent permission decisions now reach an actual human on both rails, rather than being resolved without one.","A remote run that is read-only now says so, instead of failing silently and leaving you to work out why nothing changed.","The version the binary REPORTS is now bound to the version npm publishes, and a test enforces it. They had drifted: 0.5.18 was published as a package whose `--version` said 0.5.17.","\u26A0\uFE0F 0.5.18 exists on npm and was published from a branch that was never merged. It is superseded by this release, which is cut from `main`. If you installed 0.5.18, upgrade."],"0.5.17":["The CLI now ships as @xenosystem/agent-cli. The former name @xeno-corporation/xeno-agent-cli is deprecated on npm and receives no further releases; the `xeno`, `xeno-agent` and `xeno-code` binaries are unchanged, so nothing in your shell or scripts has to change.","The exact SDK pin moves with it: the CLI is bound to @xenosystem/agent-sdk 0.8.12. 0.8.11 was never published under either name and cannot be \u2014 GitLab evaluates .gitlab-ci.yml as it exists at the tag, and tag sdk-v0.8.11 predates that pipeline.","This release cannot be installed until @xenosystem/agent-sdk 0.8.12 is live on the registry; the release pipeline fails closed on --require-dependencies-published until it is."],"0.5.16":["Windows 11 ARM64 containment certification now performs architecture-neutral MXC host preparation with the reviewed x64 helper through operating-system emulation while keeping the contained runtime native ARM64.","The CLI is bound exactly to SDK 0.8.11, whose host-preparation reports distinguish the host architecture from the reviewed setup-helper architecture and retain timeout diagnostics."],"0.5.15":["macOS and Linux standalone diagnostics now report their verified POSIX process-group lifecycle independently from the stronger process-hardened sandbox level, preserving truthful security status while certifying full-tree cancellation, timeout, and shutdown behavior.","Generated Harbor benchmark and audit workspaces are excluded from source control, keeping Windows ARM64 checkouts below platform path limits and removing 9,938 generated artifacts from release candidates."],"0.5.14":["Windows 11 24H2 containment admission now uses the authoritative non-server NT client build floor instead of rejecting current Azure and GitHub Windows 11 images whose legacy registry ProductName still says Windows 10.","Windows Server remains fail-closed, pre-26100 clients remain ineligible, and both x64 and ARM64 host identities have regression coverage."],"0.5.13":["Hosted Windows x64 containment certification now fails closed unless the runner is Windows 11 24H2 or newer, the platform supported by Microsoft MXC, instead of treating Windows Server runner failures as product failures.","The certification matrix accepts a protected XENO_WINDOWS_X64_RUNNER label for an ephemeral Windows 11 x64 runner while keeping all other hosted platform rows unchanged.","Containment failure reports preserve bounded head-and-tail diagnostics through SDK 0.8.10 so the actionable trailing Win32 or MXC error is retained."],"0.5.12":["Windows MXC containment now launches its unrestricted host from the prepared system-drive temporary directory, outside directories whose DACLs are mutated by the contained policy, and certification captures official redacted MXC diagnostics.","Internal background session workers no longer start a competing global reconciler, preventing slower macOS hosts from quarantining a healthy turn between transcript append and checkpoint commit.","The interactive attach/input/stop smoke now follows the actual persisted inbox sequence and records worker logs on failure; the CLI is bound exactly to SDK 0.8.9."],"0.5.11":["Windows x64 containment certification now launches the MXC host and contained runtime with working-directory and temporary paths on the prepared system drive, matching split-drive GitHub runners.","The CLI is bound exactly to SDK 0.8.8, preserving the passing Linux, macOS, and Windows ARM64 conformance behavior while repairing Windows x64 ProcessContainer startup."],"0.5.10":["Linux containment certification now keeps disposable fixtures under the OS-private temporary mount instead of GitHub's workspace-projected runner directory, preserving the unlisted-filesystem boundary probe.","Windows certification retains the MXC-prepared system-drive fixture root required by hosted runners whose workspace and default temp directory use another volume."],"0.5.9":["Windows containment certification now creates its disposable fixtures on the MXC-prepared system drive, including hosted runners whose workspace and default temp directory live on another volume.","Standalone Windows certification now performs the same explicit host preparation and temporary-root binding as the native package matrix."],"0.5.8":["Native containment certification now compiles its macOS UI-policy probe against the stable libsystem_sandbox ABI without depending on private SDK headers.","Windows certification now distinguishes MXC's persistent per-policy DACL requirement from its explicit one-time host-preparation warnings."],"0.5.7":["The immutable CLI candidate now binds SDK 0.8.5 to the exact canonical Linux npm tarball bytes used by certification."],"0.5.6":["Windows containment certification now performs Microsoft MXC's explicit idempotent host preparation before AppContainer+DACL conformance.","macOS ARM64 certification now records behavioral Seatbelt evidence for pasteboard, WindowServer, LaunchServices, and HID isolation."],"0.5.5":["Native certification now resolves the SDK candidate artifact from the same workspace path on Bash and PowerShell runners.","SDK containment assets retain executable package modes on Linux and macOS, with a source regression check for every reviewed Unix binary."],"0.5.4":["Native engineering certification jobs now download the exact SDK tarball produced by the successful parent gate before installing dependencies.","The six-platform matrix remains source-bound to one immutable CLI tag and one immutable SDK candidate artifact."],"0.5.3":["Candidate packaging accepts both npm 11 array-form and npm 12 package-keyed JSON, with explicit diagnostics for malformed output.","Hosted SDK packaging now parses a bounded JSON file instead of relying on a large shell variable or an obsolete npm output shape."],"0.5.2":["Hosted certification now caps SDK declaration generation at two concurrent entry points and cleans declaration output in isolated bounded-memory workers.","SDK build subprocess failures now report their terminating signal or exit status instead of producing a silent hosted-run failure."],"0.5.1":["Hosted certification now builds the exact SDK candidate in bounded declaration groups, preventing parallel TypeScript declaration generation from exhausting GitHub-hosted runner resources.","Post-freeze readiness now distinguishes exact candidate tags verified at the candidate commit from collisions in release, registry, feed, and service namespaces."],"0.5.0":["Agent Profiles now provide enforceable Assistant, SWE, Reviewer, Writer, Research, Product, CI, DevOps, and Legal Research identities with bounded tools, permissions, skills, hooks, memory, isolation, and external-action authority.","The XENO Artifact Protocol adds durable plans, patches, diffs, reviews, screenshots, recordings, reports, provenance, approvals, and evidence relationships shared across local, hosted, and Hub workflows.","Secure Execution Contracts and capability leases now make filesystem, network, secret, process, device, browser, and external-action authority explicit and auditable.","Skills v2 adds standards-compatible SKILL.md discovery, progressive loading, bundled resources, invocation policy, version identity, and compatibility with XENO, .agents, and Claude skill locations.","MCP now supports current Streamable HTTP sessions and OAuth discovery while retaining compatible stdio and legacy SSE connections.","Browser, computer-use, hosted-agent, semantic-index, production-review, spec-planning, secure-sharing, and provider-onboarding surfaces are integrated through the shared platform contracts.","The retained TUI now presents stable grouped tool activity, live task and subagent status, candidate-bound edit previews, context-pressure and compaction state, and clearer turn completion receipts.","Six-product candidate certification now binds the SDK, XENO Use, XENO Browser, Agents API, CLI, and Hub to exact source identities, versions, tags, evidence, and protected release gates."],"0.4.45":["This transitional release is engineering-tested but not GA-certified: native PTY artifacts are unsigned and remain disabled by default until the Azure signing identity is approved; ordinary CLI and pipe-mode commands remain available.","App Server v2 now provides durable threads and turns, typed clients, permission ownership and expiry, bounded replay and backpressure, authenticated HTTP access, and additive v1 compatibility.","The terminal renderer now uses committed retained frames, bounded coalescing, one normal write per frame, a responsive 50-agent footer, accessibility modes, and a native terminal compatibility matrix.","Release certification now fails closed on six native architectures, platform and manifest signatures, reproducible package payloads, SBOMs, provenance attestations, independent approvals, npm OIDC publication, and public clean-install verification.","Long chat prompts now soft-wrap into a growing six-row composer with Unicode-safe editing, visual Up/Down navigation, file-panel parity, and a temporary XENO_INPUT_SOFT_WRAP=0 rollback switch.","Long-running model-authored shell commands now use managed operations: Ctrl+B promotes the same process, finite background work waits without model polling, and durable continuations resume exactly once after terminal output arrives.","ReadImage now uses Xeno's dependency-free owned raster codec for bounded PNG, BMP, Netpbm, and core-SVG previews; /processes and doctor expose task control, process-tree containment, operation-schema, and codec status.","Dynamic workflows now expose first-class run limits and terminal reducer summaries in run records and inspect JSON.","Background agent sessions now deliver durable completion, failure, stop, and request-keyed needs-input notifications to interactive parent chats and bounded headless runs without clobbering prompt drafts.","Workflow orchestration includes grouped phase/child progress, parent-chat completion notifications, WorkflowWait, /workflows drill-down, watch JSONL snapshots, and ultracode workflow prompts.","Workflow starts now support plan preview and exact-definition approval memory, scheduler ticks are serialized, and workflow lifecycle metrics are available through the OTel usage export.","Tool activity now uses semantic Update and Search labels, contextual line-numbered edit previews, expandable read/search/shell output, and accurate failure rendering.","Interactive chat now blocks repeated inspections and unrequested mutations on short questions, gives explicit research a larger typo-tolerant evidence budget, and reserves a tool-free final-answer turn when work limits are reached."],"0.4.44":["Markdown source links now render as clickable terminal links in supported terminals, with visible URLs preserved when links are disabled."],"0.4.43":["New background agents now appear in the footer immediately after launch, and the footer can show up to eight agent sessions."],"0.4.42":["Background agent footer rows now fit the common three-agent fanout without hiding the first agent on compact terminals.","Completed background agent sessions now close after BackgroundAgentJoin returns their result to the main agent."],"0.4.41":["Completed background agent footer rows now keep a fixed runtime instead of continuing to count upward."],"0.4.40":["One-shot background agent sessions now mark done after returning their result, while user-follow-up sessions stay idle for continued chat."],"0.4.39":["Background agent session activity now uses concise status labels like Thinking instead of showing the full task prompt."],"0.4.38":["Opened background agent sessions now show their own session activity line while keeping main-agent tool progress isolated."],"0.4.37":["Opened background agent sessions no longer show the main agent's active tool progress line."],"0.4.36":["Opened background agent sessions now render the same main-chat transcript surface for user messages, assistant messages, tool calls, and tool results."],"0.4.35":["Background agent session chat now includes tool calls and tool results in its visible history."],"0.4.34":["Opening a footer background agent now switches the main chat surface into that agent session instead of showing a separate info panel.","Child-session input now queues messages to that agent while Esc returns to the main chat."],"0.4.33":["Background agent footer rows now repaint immediately during active turns.","Remembered background-agent approvals now apply to later background-agent launches."],"0.4.32":["Startup release-note hints now sit directly under the note text and render dimmed in the side panel."],"0.4.31":["Unread release notes now render beside the startup XENO AGENT header on wide terminals."],"0.4.30":["BackgroundAgentList now only reports current-chat footer sessions so old workspace agents do not hide missing new deployments."],"0.4.29":["Background agent footer markers now use filled and empty squares.","Opening a background agent from the footer now shows its session chat with transcript and message input."],"0.4.28":["First-run default model is now gpt-5.5 while saved user model choices are preserved.","Number keys in the model picker now type into search instead of selecting by index.","Model selections made with /model now persist as the user's saved default."],"0.4.27":["Background agent footer rows are now scoped to the current chat session."],"0.4.26":["Background agent rows now sit below the status line and inherit the live chat model."],"0.4.25":["Legacy BackgroundAgent calls now create footer-visible interactive background sessions."],"0.4.24":["Model picker support now has a `xeno models --json` command, share export proof, and GitHub review artifact contracts."],"0.4.23":["Model picker and /model listings now refresh Xeno API model availability before switching."],"0.4.22":["Hook review now shows command-hook hashes and supports trust, disable, and explain commands.","Expanded lifecycle hooks now cover permission decisions, stop failures, and delegated subagent start/stop events.","Set XENO_STATUS_LINE_COMMAND to replace the TUI status line with a cached command output.","Rewind now saves the abandoned conversation branch as a manual checkpoint before restoring.","Interactive chat now supports Ctrl+R history search, Ctrl+G prompt editing, /vim input mode, and /copy answer/block/diff clipboard copy.","/theme is now a discoverable alias for /color with user/project custom theme files, and /processes stop-all stops running background tasks."],"0.4.20":["Shell completions now include the current control-plane commands, flags, statuses, scopes, and usage groups.","The local app-server browser page now includes prompt and process controls on top of advanced JSON-RPC.","Published CLI and SDK packages now include GitHub repository metadata.","Docs now call out the temporary GitHub Actions startup_failure blocker while local gates remain authoritative."],"0.1.0":["Persistent shell sessions now preserve cwd and shell state across Bash calls.","Delegated planner, explorer, executor, and reviewer branches now support staged and parallel policies.","MCP now supports stdio and SSE transports, prompt discovery, resource reads, and live tool sync.","Notebook, ask-user, and memory tools are available in the shared agent runtime.","CLI operator workflows now include doctor, bug-report, config editing, cost summaries, and runtime inspection."]};function BKe(e=Pe){return Gwi[e]??[]}function jwi(e=Pe){let t=Rt().lastReleaseNotesSeen;return BKe(e).length>0&&t!==e}function oU(e=Pe){mo({lastReleaseNotesSeen:e})}function Eye(e){let t=e??Pe,r=BKe(t);return r.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...r.map(n=>`- ${n}`)].join(`
|
|
6632
6632
|
`)}var Hwi=4;function Wur(e=Pe){if(!jwi(e))return;let t=BKe(e),r=t.slice(0,Hwi),n=t.length-r.length;return[`What's new in XENO AGENT v${e}`,...r.map(i=>`- ${i}`),n>0?`...and ${n} more. Run \`xeno release-notes\` to see everything.`:"Run `xeno release-notes` to view this again."].join(`
|
|
6633
6633
|
`)}Zt();Dh();nu();jJ();import{spawn as Wwi}from"node:child_process";import{setTimeout as MKe}from"node:timers/promises";import{resolve as Cye}from"node:path";il();$a();var zur="cancel",wf={name:"WorkflowCancel",command:`workflows ${zur}`,nativeVerb:zur,description:"Request cancellation of a local workflow and stop its child work. Acceptance is not confirmed termination. Inspect or wait on the same workflow while cancellation is pending; do not start replacement work until cancellation is confirmed.",argument:{name:"run_id",type:"string",required:!0,description:"Explicit workflow run ID; never inferred from the selected UI row."},mode:"always",requiresDisplay:!1,reversibility:"irreversible",parity:"exposed",readingTools:["WorkflowInspect","WorkflowWait"],readingCommand:"workflows inspect <run-id> --json",replyFields:{accepted:"True only after the durable cancellation request was read back. False means no workflow target was found.",cancelled:"True only when readback confirms cancellation and no child termination remains pending. False means cancellation is not confirmed, not that work is still running.",pending:"True when the request was accepted but termination or readback remains incomplete. Re-read the same workflow; this is not a new request.",operationId:"Stable cancellation operation ID, or null when no request was accepted. Repeated cancellation requests retain this ID.",run:"Observed cancellation snapshot (workflowRunId, workflowName, status, updatedAt, cancellation), or null if absent/unconfirmed. The native CLI retains its existing full run record; use WorkflowInspect for child details.",warning:"Present when accepted cancellation could not be confirmed or processed. It never grants permission to restart work."},cancellationFields:{schemaVersion:"Cancellation metadata schema version, currently 1.",operationId:"The same durable cancellation operation ID as the top-level reply.",workflowRunId:"Exact workflow targeted by this request.",requestedAt:"UTC timestamp of the durably published request.",pendingChildCount:"Children whose termination remains unconfirmed; absent before the first reconciliation pass.",lastError:"Optional bounded diagnostic about an unconfirmed child; absence does not independently prove completion.",completedAt:"Present only after child termination is confirmed.",notificationEnqueuedAt:"Present after the workflow-cancelled notification was persisted; it does not mean the parent consumed it."}};function sU(e,t){let r=e.run?.workflowName??t;return e.accepted?e.cancelled?`Cancelled ${r}`:`Cancellation pending for ${r}; inspect operation ${e.operationId}`:`Workflow run not found: ${t}`}function Xur(e){let t=e.run;return{...e,run:t?{workflowRunId:t.workflowRunId,workflowName:t.workflowName,status:t.status,updatedAt:t.updatedAt,cancellation:t.cancellation}:null}}var Yur=()=>[wf.description,`Mode: ${wf.mode}; requiresDisplay: ${wf.requiresDisplay}; reversibility: ${wf.reversibility}. Read back with ${wf.readingTools.join(" or ")}.`,"Returns JSON: "+Object.entries(wf.replyFields).map(([e,t])=>`${e}: ${t}`).join(" "),"Cancellation progress: "+Object.entries(wf.cancellationFields).map(([e,t])=>`${e}: ${t}`).join(" ")].join(" ");ZL();var Sye=class extends Error{constructor(r,n){super(r);this.code=n;this.name="WorkflowHostRefusal"}code};function kye(e){throw new Sye(e.error??"The Agent host refused the workflow change.",e.code)}function aU(e){return e.success?e.run??null:e.code==="NOT_FOUND"?null:kye(e)}function Vwi(e){let t=new Set,r=async i=>{if(t.has(i))return;let o=await r_(e,[i]);if(o.granted.length===0&&o.failed.length>0)throw new Sye(`The Agent host did not accept this folder: ${o.failed[0].error}`,"FOLDER_NOT_GRANTED");t.add(i)},n=(i,o)=>e.requestWorkflows(i,o);return{async create(i,o){await r(i);let s=await n("workflows.create",{cwd:i,description:o});return!s.success||!s.definition?kye(s):s.definition},async start(i,o,s,a){await r(i);let l=await n("workflows.start",{cwd:i,ref:o,input:s,...a.model?{model:a.model}:{},...a.sizeGuideline?{sizeGuideline:a.sizeGuideline}:{}});return!l.success||!l.run?kye(l):l.run},pause:async i=>aU(await n("workflows.pause",{workflowRunId:i})),resume:async i=>aU(await n("workflows.resume",{workflowRunId:i})),async cancel(i){let o=await n("workflows.cancel",{workflowRunId:i});if(!o.success&&o.code==="NOT_FOUND")return{accepted:!1,cancelled:!1,pending:!1,operationId:null,run:null};let s=aU(o),a=s?.cancellation?.operationId??null,l=s?.status==="cancelled"&&s.cancellation?.pendingChildCount===0&&!!s.cancellation?.completedAt;return{accepted:!0,cancelled:l,pending:!l,operationId:a,run:s,...a?{}:{warning:"Cancellation was accepted but current state could not be confirmed. Inspect this operation; do not submit new work."}}},retryChild:async(i,o)=>aU(await n("workflows.retryChild",{workflowRunId:i,childRunId:o})),skipChild:async(i,o)=>aU(await n("workflows.skipChild",{workflowRunId:i,childRunId:o})),async rerun(i,o){return await r(o),aU(await n("workflows.rerun",{workflowRunId:i,cwd:o}))},async save(i,o){o.destination==="project"&&await r(o.cwd);let s=await n("workflows.save",{workflowRunId:i,cwd:o.cwd,destination:o.destination,...o.name?{name:o.name}:{}});return s.success?s.definition??null:s.code==="NOT_FOUND"?null:kye(s)}}}function qwi(){return process.env.XENO_TEST_HOOKS==="1"&&process.env.XENO_TEST_WORKFLOWS==="store"}async function xye(e,t){if(qwi())return t(e.local());let{withHostClient:r}=await Promise.resolve().then(()=>(tF(),eF));return r({clientVersion:e.clientVersion,what:"Workflows"},async n=>t(Vwi(n)))}wo();function Zu(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
6634
6634
|
`)}function Jwi(e,t){if(t){Zu(e);return}if(e.ok&&e.definition){process.stdout.write(`Workflow valid: ${e.definition.name}
|
|
@@ -9553,7 +9553,7 @@ $request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
|
9553
9553
|
$result = [XenoProtectedWrite]::Run([string]$request.path, [Convert]::FromBase64String([string]$request.payload), [bool]$request.ifAbsent, [string]$request.operationId, [string]$request.operation, [int]$request.parentPid, [long]$request.parentBirth)
|
|
9554
9554
|
$result | ConvertTo-Json -Compress
|
|
9555
9555
|
`});function $Bi(){if(bbe===void 0)try{let e=(typeof import.meta=="object"?import.meta.url:void 0)??(typeof __filename=="string"?__filename:void 0),t=e?BBi(e):null;bbe=t?t("@primno/dpapi"):null}catch{bbe=null}return bbe??null}var bbe,MBi,OBi=K(()=>{"use strict";ws(),pgr(),pgr(),MBi=$Bi()?.isPlatformSupported===!0}),jrt=K(()=>{"use strict";_0e(),EBi(),fkr(),pkr(),oQ(),pwr(),Jve(),kB(),XY(),Pkr(),kBi(),xBi(),Rtt(),CBi(),Ptt(),_tt(),OBi(),Btt(),Lwr()}),B0e=K(()=>{"use strict"}),NBi,DBi,$0e=K(()=>{"use strict";qve(),B0e(),NBi=2*1024*1024,DBi=64*1024*1024}),LBi,Hrt=K(()=>{"use strict";$0e(),B0e(),LBi=128*1024}),Mkr=K(()=>{"use strict"}),sQ=K(()=>{"use strict";Hrt(),$0e(),$E(),PE(),Frt(),Drt(),kkr(),ws(),Grt(),Mkr(),lc(),r0e(),jrt(),TB()}),Okr=K(()=>{"use strict";Urt(),Qrt(),jrt(),sQ()});Kr();ws();var Gkr=3e3,XBi=Gkr,YBi=4e3,KBi=15e3,jkr=2e3,ZBi=1e4,e$i={platform:process.platform,now:()=>Date.now(),runSync:(e,t,r)=>Vrt(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,stdio:["ignore","pipe","ignore"]}),run:async(e,t,r)=>(await WBi(qBi)(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,maxBuffer:1024*1024,signal:r.signal})).stdout},aQ=e$i,gY=new Map,Wrt=0,QZe;function t$i(e=process.env){if(e===process.env&&QZe)return QZe;let t=e.SystemRoot??e.SYSTEMROOT??e.windir??e.WINDIR,r="powershell.exe";if(t&&/^[a-z]:[\\/]/i.test(t)){let n=`${t.replace(/[\\/]+$/,"")}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;Qkr(n)&&(r=n)}return e===process.env&&(QZe=r),r}function Jrt(e){return Number.isInteger(e)&&e>0}function r$i(e){return JBi("sha256").update(e).digest("hex")}function GY(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${r$i(t)}`:void 0}function Uve(){if(process.platform==="linux")try{return qrt("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function jY(e){if(typeof e!="number"||!Jrt(e))return"dead";try{return process.kill(e,0),"live"}catch(t){return t.code==="ESRCH"?"dead":"unknown"}}function Hkr(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function n$i(e){return["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",["$ErrorActionPreference = 'Stop'",`$items = @(Get-Process -Id @(${e.join(", ")}) -ErrorAction SilentlyContinue)`,"$out = @($items | ForEach-Object { $path = try { [string]$_.Path } catch { '' }; $started = try { $_.StartTime.ToUniversalTime().ToString('o') } catch { '' }; [pscustomobject]@{ pid = [int]$_.Id; startedAt = $started; executable = $path } })","$out | ConvertTo-Json -Compress"].join("; ")]}function i$i(e){let t=new Map;try{if(!e)return t;let r=JSON.parse(e);for(let n of Array.isArray(r)?r:[r]){let i=Number(n.pid),o=Hkr(String(n.startedAt??""));!Jrt(i)||!o||t.set(i,{pid:i,processStartedAt:o,hostname:RB(),...GY(n.executable)?{executableFingerprint:GY(n.executable)}:{},confidence:"observed"})}}catch{return t}return t}function o$i(e,t){let r=new Map;if(t.fresh)return{known:r,pending:e,skip:!1};let n=aQ.now(),i=[];for(let o of e){let s=gY.get(o);s&&n>=s.at&&n-s.at<jkr?s.identity&&r.set(o,s.identity):i.push(o)}return{known:r,pending:i,skip:i.length>0&&n<Wrt}}function s$i(e,t){let r=aQ.now();Wrt=0;for(let n of e)gY.set(n,{identity:t.get(n)??null,at:r});if(gY.size>512)for(let[n,i]of gY)r-i.at>=jkr&&gY.delete(n)}function a$i(){Wrt=aQ.now()+KBi}function l$i(e,t={}){if(!e.length)return new Map;let{known:r,pending:n,skip:i}=o$i(e,t);if(!n.length||i)return r;try{let o=i$i(aQ.runSync(t$i(),n$i(n),{timeoutMs:YBi}).trim());s$i(n,o);for(let[s,a]of o)r.set(s,a)}catch{a$i()}return r}var WX;function c$i(){if(WX)return WX;try{let e=Number.parseInt(Vrt("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);WX=Number.isFinite(e)&&e>0?e:100}catch{WX=100}return WX}function d$i(){try{let e=/^btime\s+(\d+)$/m.exec(qrt("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function u$i(e){try{let t=qrt(`/proc/${e}/stat`,"utf8"),r=t.lastIndexOf(")");if(r<0)return null;let n=t.slice(r+2).trim().split(/\s+/),i=Number(n[19]),o=d$i();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/c$i())*1e3).toISOString(),a;try{a=zBi(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:RB(),...Uve()?{bootId:Uve()}:{},...GY(a)?{executableFingerprint:GY(a)}:{},confidence:"observed"}}catch{return null}}function p$i(e){let t=new Map;if(aQ.platform==="linux"){for(let r of e){let n=u$i(r);n&&t.set(r,n)}return t}for(let r of e)try{let n=Vrt("ps",["-p",String(r),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=Hkr(n);if(!i)continue;t.set(r,{pid:r,processStartedAt:i,hostname:RB(),confidence:"observed"})}catch{continue}return t}function Vkr(e,t={}){let r=[...new Set(e.filter(Jrt))],n=r.includes(process.pid),i=n?r.filter(s=>s!==process.pid):r,o=aQ.platform==="win32"?l$i(i,t):p$i(i);return n&&o.set(process.pid,Xrt()),o}function zrt(e,t={}){return Vkr([e],t).get(e)??null}function f$i(e,t=new Date,r=!1){return(r?zrt(e):null)??{pid:e,processStartedAt:t.toISOString(),hostname:RB(),confidence:"degraded"}}function Xrt(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:RB(),...Uve()?{bootId:Uve()}:{},...Qkr(process.execPath)?{executableFingerprint:GY(process.execPath)}:{},confidence:"self"}}function HY(e,t=zrt){if(e.hostname!==RB())return{status:"remote",expected:e,reason:"Process belongs to another host."};if(jY(e.pid)==="dead")return{status:"dead",expected:e,reason:"Process ID is not live."};let r=t(e.pid);if(!r)return jY(e.pid)==="dead"?{status:"dead",expected:e,reason:"Process ID is not live."}:{status:"degraded",expected:e,reason:"Creation time could not be observed."};let n=Date.parse(e.processStartedAt),i=Date.parse(r.processStartedAt);return!Number.isFinite(n)||!Number.isFinite(i)||Math.abs(n-i)>Gkr?{status:"mismatch",expected:e,observed:r,reason:"Process creation time does not match."}:e.bootId&&r.bootId&&e.bootId!==r.bootId?{status:"mismatch",expected:e,observed:r,reason:"Host boot identity does not match."}:e.executableFingerprint&&r.executableFingerprint&&e.executableFingerprint!==r.executableFingerprint?{status:"mismatch",expected:e,observed:r,reason:"Executable identity does not match."}:{status:"live",expected:e,observed:r}}function h$i(e){return e.hostname===RB()&&jY(e.pid)==="dead"}var m$i=e=>zrt(e,{fresh:!0});function g$i(){return _E()}function ME(){return VBi(g$i(),"daemon")}function Yrt(e){return jY(e)!=="dead"}function S$i(){return new Date().toISOString()}function Zet(e){try{return JSON.parse(b$i(e,"utf8"))}catch{return null}}var Zrt=3e4;function x$i(e){if(e.hostname!==qkr())return!0;let t=Date.parse(e.acquiredAt);if(Number.isFinite(t)&&Date.now()-t<Zrt)return!0;if(!Yrt(e.pid))return!1;if(e.processIdentity){let r=HY(e.processIdentity);return r.status==="live"||r.status==="degraded"||r.status==="remote"}return!0}function Wkr(e,t){y$i(E$i(e),{recursive:!0});let r=`${e}.${process.pid}.${k$i()}.tmp`;I$i(r,JSON.stringify(t,null,2)+`
|
|
9556
|
-
`,{encoding:"utf8",flag:"wx"});try{w$i(r,e)}finally{Krt(r,{force:!0})}}function C$i(e){try{return Date.now()-v$i(e).mtimeMs<Zrt}catch{return!1}}function T$i(e,t){return e?.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}function AY(e,t){return Object.assign(new Error(`${e} is already locked ${t}.`),{code:"CONTROL_PLANE_LOCK_BUSY"})}function nQ(e){return e instanceof Error&&"code"in e&&e.code==="CONTROL_PLANE_LOCK_BUSY"}function R$i(e,t,r){try{Wkr(e,t)}catch(n){throw n.code==="EEXIST"?AY(r,"by another contender"):n}}function P$i(e,t){let r=Zet(e);r?.pid!==t.pid||r.hostname!==t.hostname||r.processStartedAt!==t.processStartedAt||Krt(e,{force:!0})}function Xx(e,t,r){let n=S$i(),i=Xrt(),o={schemaVersion:1,name:t,pid:process.pid,hostname:qkr(),processStartedAt:i.processStartedAt,processIdentity:i,version:r,acquiredAt:n,updatedAt:n};try{Wkr(e,o)}catch(s){if(s.code!=="EEXIST")throw s;let a=Zet(e);if(a&&x$i(a))throw AY(t,`by PID ${a.pid} on ${a.hostname}`);if(a){if(!T$i(Zet(e),a))throw AY(t,"while ownership was changing")}else{if(!A$i(e))throw AY(t,"while ownership was changing");if(C$i(e))throw AY(t,"by an owner whose record is still being published")}Krt(e,{force:!0}),R$i(e,o,t)}return{record:o,release:()=>{P$i(e,o)}}}var Jkr="0.10.
|
|
9556
|
+
`,{encoding:"utf8",flag:"wx"});try{w$i(r,e)}finally{Krt(r,{force:!0})}}function C$i(e){try{return Date.now()-v$i(e).mtimeMs<Zrt}catch{return!1}}function T$i(e,t){return e?.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}function AY(e,t){return Object.assign(new Error(`${e} is already locked ${t}.`),{code:"CONTROL_PLANE_LOCK_BUSY"})}function nQ(e){return e instanceof Error&&"code"in e&&e.code==="CONTROL_PLANE_LOCK_BUSY"}function R$i(e,t,r){try{Wkr(e,t)}catch(n){throw n.code==="EEXIST"?AY(r,"by another contender"):n}}function P$i(e,t){let r=Zet(e);r?.pid!==t.pid||r.hostname!==t.hostname||r.processStartedAt!==t.processStartedAt||Krt(e,{force:!0})}function Xx(e,t,r){let n=S$i(),i=Xrt(),o={schemaVersion:1,name:t,pid:process.pid,hostname:qkr(),processStartedAt:i.processStartedAt,processIdentity:i,version:r,acquiredAt:n,updatedAt:n};try{Wkr(e,o)}catch(s){if(s.code!=="EEXIST")throw s;let a=Zet(e);if(a&&x$i(a))throw AY(t,`by PID ${a.pid} on ${a.hostname}`);if(a){if(!T$i(Zet(e),a))throw AY(t,"while ownership was changing")}else{if(!A$i(e))throw AY(t,"while ownership was changing");if(C$i(e))throw AY(t,"by an owner whose record is still being published")}Krt(e,{force:!0}),R$i(e,o,t)}return{record:o,release:()=>{P$i(e,o)}}}var Jkr="0.10.110";PE();RAr();var _$i={producerVersion:Jkr,defaultModel:()=>yAr,recordCounter:(e,t,r)=>TU(e,t,r),recordHistogram:(e,t,r)=>r7e(e,t,r)},B$i=Symbol.for("xenosystem.agent-sdk.runs.runtime.v1"),$$i=globalThis;function qo(){return $$i[B$i]??_$i}var M$i=class extends Error{code="RUN_WORKER_UNAVAILABLE";constructor(){super("No run worker program is bound in this process, so a background run cannot be started here.")}};function zkr(){let e=qo().workerInvocation;if(!e)throw new M$i;return e()}function Xkr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schedule edit must be an object");let t=e;if(Object.keys(t).some(i=>!["operationId","expectedRevision","cron","prompt"].includes(i)))throw new Error("Unknown schedule edit field");if(typeof t.operationId!="string"||!/^[a-zA-Z0-9_-]{8,200}$/.test(t.operationId))throw new Error("Invalid schedule edit operation identity");if(!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||t.expectedRevision===Number.MAX_SAFE_INTEGER)throw new Error("Invalid expected schedule revision");if(typeof t.cron!="string"||!t.cron.trim()||t.cron.length>256)throw new Error("Invalid cron expression");if(typeof t.prompt!="string"||!t.prompt.trim()||t.prompt.length>16e3)throw new Error("Invalid schedule prompt");let r=t.cron.trim().replace(/\s+/g," "),n=t.prompt.trim();return{operationId:t.operationId,expectedRevision:t.expectedRevision,cron:r,prompt:n,payloadHash:O$i("sha256").update(JSON.stringify({cron:r,prompt:n,expectedRevision:t.expectedRevision})).digest("hex")}}function N$i(e,t,r=new Date){let n=Xkr(t);if(!Number.isFinite(r.getTime()))throw new Error("Invalid schedule edit time");if(e.status==="cancelled")throw new Error("Cancelled schedules cannot be edited");if(e.history?.some(i=>i.status==="running"))throw new Error("Wait for the running occurrence to settle before editing");if(e.revision!==void 0&&(!Number.isSafeInteger(e.revision)||e.revision<0))throw new Error("Stored schedule revision is invalid");if((e.revision??0)!==n.expectedRevision)throw new Error("Schedule changed; refresh before editing");return{...n,nextRevision:n.expectedRevision+1,nextRunAt:fB(n.cron,r).toISOString()}}var L$i=new Int32Array(new SharedArrayBuffer(4)),F$i=6e4;function M0e(e,t,r=D$i,n=F$i){let i=Date.now()+n;for(let o=0;;o++)try{r(e,t);return}catch(s){if(Date.now()>=i||!["EPERM","EACCES","EBUSY"].includes(s.code??""))throw s;Atomics.wait(L$i,0,0,Math.min(100,(o+1)*10))}}var fgr=100,U$i=16e3,Ykr=256,Q$i=10080*60*1e3,G$i=5*366*24*60;function ett(e,t,r){if(typeof e!="string"||!e.trim())throw new Error(`${t} must be a non-empty string`);let n=e.trim();if(n.length>r)throw new Error(`${t} exceeds ${r} characters`);return n}function vbe(e,t,r,n){if(!/^\d+$/.test(e))throw new Error(`Invalid ${t} value: ${e}`);let i=Number(e);if(!Number.isInteger(i)||i<r||i>n)throw new Error(`${t} must be between ${r} and ${n}: ${e}`);return i}function JX(e,t,r,n,i){let o=new Set,s=e==="*";for(let a of e.split(",")){let l=a.trim();if(!l)throw new Error(`Invalid empty ${t} segment`);let[c,d,...u]=l.split("/");if(u.length>0||!c)throw new Error(`Invalid ${t} segment: ${l}`);let p=d===void 0?1:vbe(d,`${t} step`,1,n-r+1),f,h;if(c==="*")f=r,h=n;else if(c.includes("-")){let[m,g,...A]=c.split("-");if(A.length>0||!m||!g)throw new Error(`Invalid ${t} range: ${c}`);if(f=vbe(m,t,r,n),h=vbe(g,t,r,n),f>h)throw new Error(`Invalid descending ${t} range: ${c}`)}else f=vbe(c,t,r,n),h=f;for(let m=f;m<=h;m+=p)o.add(i?i(m):m)}if(o.size===0)throw new Error(`${t} does not select any values`);return{values:o,wildcard:s}}function O0e(e){let t=ett(e,"cron",Ykr).replace(/\s+/g," ").split(" ");if(t.length!==5)throw new Error("cron must contain exactly five fields: minute hour day-of-month month day-of-week");return{minute:JX(t[0],"minute",0,59),hour:JX(t[1],"hour",0,23),dayOfMonth:JX(t[2],"day-of-month",1,31),month:JX(t[3],"month",1,12),dayOfWeek:JX(t[4],"day-of-week",0,7,r=>r===7?0:r)}}function j$i(e,t){if(!e.minute.values.has(t.getMinutes())||!e.hour.values.has(t.getHours())||!e.month.values.has(t.getMonth()+1))return!1;let r=e.dayOfMonth.values.has(t.getDate()),n=e.dayOfWeek.values.has(t.getDay());return!e.dayOfMonth.wildcard&&!e.dayOfWeek.wildcard?r||n:e.dayOfMonth.wildcard?e.dayOfWeek.wildcard?!0:n:r}function fB(e,t){let r=O0e(e),n=new Date(t.getTime());n.setSeconds(0,0),n.setMinutes(n.getMinutes()+1);for(let i=0;i<G$i;i+=1){if(j$i(r,n))return n;n.setMinutes(n.getMinutes()+1)}throw new Error("cron expression has no occurrence within five years")}function Hx(e){return e.toISOString()}function wY(e){let t=Ukr(e);return process.platform==="win32"?t.toLowerCase():t}function H$i(e,t){Lkr(HBi(e),{recursive:!0});let r=`${e}.${process.pid}.${Fve()}.tmp`,n=`${JSON.stringify(t,null,2)}
|
|
9557
9557
|
`;if(nve(r,n,{encoding:"utf8",flag:"wx",mode:384,flush:!0}),M0e(r,e),Fkr(e,"utf8")!==n)throw new Error("Schedule write outcome uncertain; refresh using the same operation identity")}function zX(e){return Nkr("sha256").update(JSON.stringify({cron:e.cron,prompt:e.prompt,recurring:e.recurring,durable:e.durable,cwd:wY(e.cwd),owner:e.owner??null})).digest("hex")}function Ibe(e){let t;try{t=Ket(e,"r");let r=QBi(t).size;if(r>1048576)throw new Error("Schedule record exceeds size limit");let n=Buffer.alloc(r+1),i=0;for(;i<n.length;){let s=UBi(t,n,i,n.length-i,i);if(!s)break;i+=s}if(i!==r)throw new Error("Schedule record changed during read");let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n.subarray(0,i)));if(!o||o.schemaVersion!==1||typeof o.id!="string"||`${o.id}.json`!==MY(e)||typeof o.cwd!="string"||typeof o.cron!="string"||typeof o.prompt!="string")throw new Error("Invalid schedule record");return o}catch(r){if(r.code==="ENOENT")return null;throw new Error(`Stored schedule is unreadable; preserved for recovery: ${MY(e)}`,{cause:r})}finally{t!==void 0&&Dkr(t)}}function V$i(e){return`cron_${e.toISOString().replace(/[^0-9]/g,"").slice(0,14)}_${Fve().slice(0,8)}`}var N0e=class{constructor(e){this.options=e,this.workspace=wY(e.cwd),Lkr(this.storageDir,{recursive:!0})}options;sessionJobs=new Map;workspace;dispatching=!1;mutationDepth=0;get storageDir(){return this.options.storageDir??qX(ME(),"cron")}create(e,t=new Date){return this.withWriteLock(()=>this.createUnlocked(e,t))}createUnlocked(e,t){let r=ett(e.cron,"cron",Ykr).replace(/\s+/g," ");O0e(r);let n=ett(e.prompt,"prompt",U$i),i=e.recurring!==!1,o=e.durable===!0,s=e.operationId;if(s!==void 0&&(!o||!/^[a-zA-Z0-9_-]{8,200}$/.test(s)))throw new Error("Invalid durable schedule operation identity");let a=s?`cron_00000000000000_${Nkr("sha256").update(s).digest("hex")}`:V$i(t),l=()=>{let u=this.recordPath(a);if(!FZe(u))return null;let p=Ibe(u);if(!p||p.operationId!==s||(p.creationFingerprint??zX(p))!==zX({cron:r,prompt:n,recurring:i,durable:o,cwd:this.options.cwd,owner:e.owner}))throw new Error("Schedule operation identity conflicts with prior content or scope");return structuredClone(p)};if(s){let u=l();if(u)return u}if(this.list(t).length>=fgr)throw new Error(`Scheduled prompt limit reached (${fgr})`);let c=Hx(t),d={revision:0,schemaVersion:1,id:a,cron:r,prompt:n,recurring:i,durable:o,cwd:Ukr(this.options.cwd),...this.options.sessionId?{sessionId:this.options.sessionId}:{},...e.owner?{owner:structuredClone(e.owner)}:{},...s?{operationId:s}:{},...e.status?{status:e.status}:{},createdAt:c,updatedAt:c,nextRunAt:fB(r,t).toISOString(),...i?{expiresAt:new Date(t.getTime()+Q$i).toISOString()}:{}};if(d.creationFingerprint=zX(d),s){let u=`${this.recordPath(a)}.${Fve()}.tmp`;try{nve(u,JSON.stringify(d),{flag:"wx",mode:384,flush:!0});try{FBi(u,this.recordPath(a))}catch(p){if(p.code!=="EEXIST")throw p;let f=l();if(!f)throw new Error("Schedule operation publication changed concurrently");return f}}finally{FZe(u)&&UZe(u)}}else this.save(d);return structuredClone(d)}get(e){let t=this.sessionJobs.get(e);if(t)return structuredClone(t);let r=Ibe(this.recordPath(e));return!r||wY(r.cwd)!==this.workspace?null:structuredClone(r)}list(e=new Date){this.removeExpired(e);let t=[...this.sessionJobs.values(),...this.loadDurable()];return[...new Map(t.map(r=>[r.id,r])).values()].filter(r=>!r.deletedAt).sort((r,n)=>Date.parse(r.nextRunAt)-Date.parse(n.nextRunAt)).map(r=>structuredClone(r))}delete(e){return this.withWriteLock(()=>this.deleteUnlocked(e))}deleteUnlocked(e){let t=MY(e.trim()),r=this.sessionJobs.delete(t),n=this.recordPath(t),i=Ibe(n);return i&&wY(i.cwd)===this.workspace?i.deletedAt?!1:(this.mutateRecord(t,o=>({...o,status:"cancelled",deletedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),creationFingerprint:o.creationFingerprint??zX(o)})),!0):r}setStatus(e,t,r=new Date){return this.mutateRecord(e,n=>{if(n.status==="cancelled"&&t!=="cancelled")throw new Error("Cancelled schedules cannot be resumed");return{...n,status:t,updatedAt:Hx(r),...t==="active"?{nextRunAt:fB(n.cron,r).toISOString()}:{}}})}update(e,t,r=new Date){return this.withWriteLock(()=>{let n=this.get(e);if(!n)throw new Error("Schedule not found in this workspace");let i=Xkr(t),o=n.editReceipts?.find(a=>a.operationId===i.operationId);if(o){if(o.payloadHash!==i.payloadHash)throw new Error("Schedule edit operation identity conflicts with prior content");return n}if((n.editReceipts?.length??0)>=128)throw new Error("Schedule edit receipt capacity reached; receipts must not be evicted silently");let s=N$i(n,t,r);return this.mutateRecord(e,a=>({...a,cron:s.cron,prompt:s.prompt,nextRunAt:s.nextRunAt,updatedAt:Hx(r),creationFingerprint:a.creationFingerprint??zX(a),editReceipts:[...a.editReceipts??[],{operationId:s.operationId,payloadHash:s.payloadHash,revision:s.nextRevision}]}))})}withWriteLock(e){if(this.mutationDepth)return e();let t=Xx(qX(this.storageDir,"cron-mutations.lock"),"cron mutation",qo().producerVersion);this.mutationDepth++;try{return e()}finally{this.mutationDepth--,t.release()}}mutateRecord(e,t){return this.withWriteLock(()=>{let r=this.get(e);if(!r)throw new Error("Schedule not found in this workspace");let n=r.revision??0;if(!Number.isSafeInteger(n)||n<0||n>=Number.MAX_SAFE_INTEGER)throw new Error("Stored schedule revision is invalid");let i={...t(r),revision:n+1};this.save(i);let o=this.get(e);if(!o||JSON.stringify(o)!==JSON.stringify(i))throw new Error("Schedule write outcome uncertain; refresh using the same operation identity");return o})}history(e){let t=this.get(e);if(!t)throw new Error("Schedule not found in this workspace");return structuredClone(t.history??[])}async dispatchDue(e){if(this.dispatching||!e.isIdle())return[];this.dispatching=!0;let t=[],r=e.now??new Date;try{let n=this.list(r).filter(i=>(!i.status||i.status==="active")&&Date.parse(i.nextRunAt)<=r.getTime()&&(e.select?.(i)??!0));for(let i of n){if(!e.isIdle())break;let o=i.durable?this.tryClaim(i.id):()=>{};if(o)try{let s=this.withWriteLock(()=>{let u=this.get(i.id);if(!u||u.status&&u.status!=="active"||Date.parse(u.nextRunAt)>r.getTime())return null;if(u.history?.some(f=>f.status==="running"))return this.mutateRecord(u.id,f=>({...f,status:"paused",updatedAt:Hx(r),history:f.history.map(h=>h.status==="running"?{...h,status:"interrupted",completedAt:Hx(r)}:h)})),null;let p={id:Fve(),startedAt:Hx(r),status:"running"};return this.mutateRecord(u.id,f=>({...f,history:[...(f.history??[]).slice(-99),p]})),{current:u,run:p}});if(!s)continue;let{current:a,run:l}=s,c;try{await e.dispatch(a.prompt,a)}catch(u){c=u instanceof Error?u.message:String(u)}let d=Hx(r);c||t.push(a),this.withWriteLock(()=>{if(this.get(a.id)){if(!a.recurring&&!a.durable){this.delete(a.id);return}this.mutateRecord(a.id,u=>({...u,...a.recurring?{}:{status:"cancelled"},lastRunAt:d,updatedAt:d,nextRunAt:fB(a.cron,r).toISOString(),history:(u.history??[]).map(p=>p.id===l.id?{...p,completedAt:Hx(new Date),status:c?"failed":"completed",...c?{error:c.slice(0,2e3)}:{}}:p)}))}})}finally{o()}}}finally{this.dispatching=!1}return t}save(e){e.durable?H$i(this.recordPath(e.id),e):this.sessionJobs.set(e.id,structuredClone(e))}loadDurable(){return FZe(this.storageDir)?GBi(this.storageDir,{withFileTypes:!0}).filter(e=>e.isFile()&&/^cron_[0-9]+_[a-z0-9-]+\.json$/i.test(e.name)).map(e=>Ibe(qX(this.storageDir,e.name))).filter(e=>e!==null&&wY(e.cwd)===this.workspace):[]}removeExpired(e){try{this.withWriteLock(()=>{let t=r=>!r.status&&!!(r.expiresAt&&Date.parse(r.expiresAt)<=e.getTime());for(let r of this.sessionJobs.values())t(r)&&this.sessionJobs.delete(r.id);for(let r of this.loadDurable())t(r)&&this.delete(r.id)})}catch(t){if(!nQ(t))throw t}}tryClaim(e){let t=this.lockPath(e),r;try{r=Ket(t,"wx"),nve(r,`${process.pid}
|
|
9558
9558
|
${new Date().toISOString()}
|
|
9559
9559
|
`,"utf8")}catch{try{let n=Number(Fkr(t,"utf8").split(`
|
|
@@ -12837,7 +12837,7 @@ public static class XenoProtectedWrite {
|
|
|
12837
12837
|
$request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
12838
12838
|
$result = [XenoProtectedWrite]::Run([string]$request.path, [Convert]::FromBase64String([string]$request.payload), [bool]$request.ifAbsent, [string]$request.operationId, [string]$request.operation, [int]$request.parentPid, [long]$request.parentBirth)
|
|
12839
12839
|
$result | ConvertTo-Json -Compress
|
|
12840
|
-
`});function feo(){if(VEe===void 0)try{let e=(typeof import.meta=="object"?import.meta.url:void 0)??(typeof __filename=="string"?__filename:void 0),t=e?peo(e):null;VEe=t?t("@primno/dpapi"):null}catch{VEe=null}return VEe??null}var VEe,heo,meo=Z(()=>{"use strict";xs(),nBr(),nBr(),heo=feo()?.isPlatformSupported===!0}),Pdt=Z(()=>{"use strict";eSe(),neo(),PFr(),RFr(),BG(),R$r(),A1e(),g$(),pZ(),WFr(),ieo(),seo(),gct(),aeo(),Act(),wct(),meo(),yct(),tMr()}),tSe=Z(()=>{"use strict"}),geo,Aeo,rSe=Z(()=>{"use strict";m1e(),tSe(),geo=2*1024*1024,Aeo=64*1024*1024}),weo,_dt=Z(()=>{"use strict";rSe(),tSe(),weo=128*1024}),YFr=Z(()=>{"use strict"}),$G=Z(()=>{"use strict";_dt(),rSe(),uk(),lk(),xdt(),kdt(),QFr(),xs(),Rdt(),YFr(),uc(),S1e(),Pdt(),b$()}),KFr=Z(()=>{"use strict";Cdt(),Tdt(),Pdt(),$G()}),ZFr="0.10.
|
|
12840
|
+
`});function feo(){if(VEe===void 0)try{let e=(typeof import.meta=="object"?import.meta.url:void 0)??(typeof __filename=="string"?__filename:void 0),t=e?peo(e):null;VEe=t?t("@primno/dpapi"):null}catch{VEe=null}return VEe??null}var VEe,heo,meo=Z(()=>{"use strict";xs(),nBr(),nBr(),heo=feo()?.isPlatformSupported===!0}),Pdt=Z(()=>{"use strict";eSe(),neo(),PFr(),RFr(),BG(),R$r(),A1e(),g$(),pZ(),WFr(),ieo(),seo(),gct(),aeo(),Act(),wct(),meo(),yct(),tMr()}),tSe=Z(()=>{"use strict"}),geo,Aeo,rSe=Z(()=>{"use strict";m1e(),tSe(),geo=2*1024*1024,Aeo=64*1024*1024}),weo,_dt=Z(()=>{"use strict";rSe(),tSe(),weo=128*1024}),YFr=Z(()=>{"use strict"}),$G=Z(()=>{"use strict";_dt(),rSe(),uk(),lk(),xdt(),kdt(),QFr(),xs(),Rdt(),YFr(),uc(),S1e(),Pdt(),b$()}),KFr=Z(()=>{"use strict";Cdt(),Tdt(),Pdt(),$G()}),ZFr="0.10.110";lk();BBr();var keo={producerVersion:ZFr,defaultModel:()=>IBr,recordCounter:(e,t,r)=>nG(e,t,r),recordHistogram:(e,t,r)=>Xst(e,t,r)},Seo=Symbol.for("xenosystem.agent-sdk.runs.runtime.v1"),xeo=globalThis;function Ew(){return xeo[Seo]??keo}function Neo(e=Ew().producerVersion){return{createdByCliVersion:e,createdBySdkVersion:ZFr}}var Qeo=1024*1024,Geo=64*1024;function jeo(e,t){let r=Math.max(1,Number.isFinite(t)?Math.trunc(t):80),n;try{n=Feo(e,"r")}catch(i){if(i.code==="ENOENT")return[];throw i}try{let i=Leo(n).size,o=Buffer.allocUnsafe(Math.min(i,Qeo)),s=[],a=i,l=o.length,c=l,d=(u,p)=>{let f=o.toString("utf8",u,p).trim();if(f)try{let h=JSON.parse(f);h!==null&&s.push(h)}catch{}};for(;a>0&&l>0;){let u=Math.min(Geo,l),p=l-u;a-=u;let f=0;for(;f<u;){let h=Ueo(n,o,p+f,u-f,a+f);if(h===0)throw new Error("Event journal changed during tail read; retry.");f+=h}for(let h=l-1;h>=p;h--)if(o[h]===10){if(d(h+1,c),s.length===r)return s.reverse();c=h}l=p}if(a>0)throw new Error("Event tail exceeds the 1 MiB read limit. Request fewer events or inspect the persisted event journal with a bounded file reader.");return d(0,c),s.reverse()}finally{Deo(n)}}var oBr=64*1024;function sBr(e,t){return Heo("sha256").update(JSON.stringify([Jeo(e),t.dev.toString(),t.ino.toString(),t.birthtimeNs.toString(),t.size.toString(),t.mtimeNs.toString(),t.ctimeNs.toString()])).digest("hex")}function zeo(e,t={}){let r=t.maxBytes??oBr;if(!Number.isSafeInteger(r)||r<1||r>oBr)throw new Error("Event page maxBytes must be an integer from 1 to 65536.");let n=0,i;if(t.cursor!==void 0){if(typeof t.cursor!="string"||t.cursor.length>100)throw new Error("Invalid event page cursor.");let s=/^(0|[1-9][0-9]{0,15})\.([a-f0-9]{64})$/.exec(t.cursor);if(!s)throw new Error("Invalid event page cursor.");if(n=Number(s[1]),i=s[2],!Number.isSafeInteger(n))throw new Error("Invalid event page cursor.")}let o;try{o=qeo(e,"r")}catch(s){if(s.code!=="ENOENT")throw s;if(i)throw new Error("Event journal changed; restart pagination without a cursor.");return null}try{let s=iBr(o,{bigint:!0});if(!s.isFile())throw new Error("Event journal is not a regular file.");let a=Number(s.size);if(!Number.isSafeInteger(a))throw new Error("Event journal size exceeds the supported range.");let l=sBr(e,s);if(i&&i!==l||n>a)throw new Error("Event journal changed or cursor is out of range; restart pagination without a cursor.");let c=Buffer.allocUnsafe(Math.min(r,a-n)),d=0;for(;d<c.length;){let p=Weo(o,c,d,c.length-d,n+d);if(p===0)throw new Error("Event journal changed during page read; restart pagination without a cursor.");d+=p}if(sBr(e,iBr(o,{bigint:!0}))!==l)throw new Error("Event journal changed during page read; restart pagination without a cursor.");let u=n+d;return{encoding:"base64",content:c.toString("base64"),offset:n,bytesRead:d,totalBytes:a,journalVersion:l,nextCursor:u<a?`${u}.${l}`:null}}finally{Veo(o)}}dn();xs();var nUr=3e3,cto=nUr,dto=4e3,uto=15e3,iUr=2e3,pto={platform:process.platform,now:()=>Date.now(),runSync:(e,t,r)=>$dt(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,stdio:["ignore","pipe","ignore"]}),run:async(e,t,r)=>(await sto(oto)(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,maxBuffer:1024*1024,signal:r.signal})).stdout},MG=pto,F9=new Map,Odt=0,Gst;function fto(e=process.env){if(e===process.env&&Gst)return Gst;let t=e.SystemRoot??e.SYSTEMROOT??e.windir??e.WINDIR,r="powershell.exe";if(t&&/^[a-z]:[\\/]/i.test(t)){let n=`${t.replace(/[\\/]+$/,"")}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;rUr(n)&&(r=n)}return e===process.env&&(Gst=r),r}function Ndt(e){return Number.isInteger(e)&&e>0}function hto(e){return ato("sha256").update(e).digest("hex")}function sZ(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${hto(t)}`:void 0}function s1e(){if(process.platform==="linux")try{return Mdt("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function Hlt(e){if(typeof e!="number"||!Ndt(e))return"dead";try{return process.kill(e,0),"live"}catch(t){return t.code==="ESRCH"?"dead":"unknown"}}function oUr(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function mto(e){return["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",["$ErrorActionPreference = 'Stop'",`$items = @(Get-Process -Id @(${e.join(", ")}) -ErrorAction SilentlyContinue)`,"$out = @($items | ForEach-Object { $path = try { [string]$_.Path } catch { '' }; $started = try { $_.StartTime.ToUniversalTime().ToString('o') } catch { '' }; [pscustomobject]@{ pid = [int]$_.Id; startedAt = $started; executable = $path } })","$out | ConvertTo-Json -Compress"].join("; ")]}function gto(e){let t=new Map;try{if(!e)return t;let r=JSON.parse(e);for(let n of Array.isArray(r)?r:[r]){let i=Number(n.pid),o=oUr(String(n.startedAt??""));!Ndt(i)||!o||t.set(i,{pid:i,processStartedAt:o,hostname:EZ(),...sZ(n.executable)?{executableFingerprint:sZ(n.executable)}:{},confidence:"observed"})}}catch{return t}return t}function Ato(e,t){let r=new Map;if(t.fresh)return{known:r,pending:e,skip:!1};let n=MG.now(),i=[];for(let o of e){let s=F9.get(o);s&&n>=s.at&&n-s.at<iUr?s.identity&&r.set(o,s.identity):i.push(o)}return{known:r,pending:i,skip:i.length>0&&n<Odt}}function wto(e,t){let r=MG.now();Odt=0;for(let n of e)F9.set(n,{identity:t.get(n)??null,at:r});if(F9.size>512)for(let[n,i]of F9)r-i.at>=iUr&&F9.delete(n)}function yto(){Odt=MG.now()+uto}function bto(e,t={}){if(!e.length)return new Map;let{known:r,pending:n,skip:i}=Ato(e,t);if(!n.length||i)return r;try{let o=gto(MG.runSync(fto(),mto(n),{timeoutMs:dto}).trim());wto(n,o);for(let[s,a]of o)r.set(s,a)}catch{yto()}return r}var v9;function vto(){if(v9)return v9;try{let e=Number.parseInt($dt("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);v9=Number.isFinite(e)&&e>0?e:100}catch{v9=100}return v9}function Ito(){try{let e=/^btime\s+(\d+)$/m.exec(Mdt("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function Eto(e){try{let t=Mdt(`/proc/${e}/stat`,"utf8"),r=t.lastIndexOf(")");if(r<0)return null;let n=t.slice(r+2).trim().split(/\s+/),i=Number(n[19]),o=Ito();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/vto())*1e3).toISOString(),a;try{a=lto(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:EZ(),...s1e()?{bootId:s1e()}:{},...sZ(a)?{executableFingerprint:sZ(a)}:{},confidence:"observed"}}catch{return null}}function kto(e){let t=new Map;if(MG.platform==="linux"){for(let r of e){let n=Eto(r);n&&t.set(r,n)}return t}for(let r of e)try{let n=$dt("ps",["-p",String(r),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=oUr(n);if(!i)continue;t.set(r,{pid:r,processStartedAt:i,hostname:EZ(),confidence:"observed"})}catch{continue}return t}function sUr(e,t={}){let r=[...new Set(e.filter(Ndt))],n=r.includes(process.pid),i=n?r.filter(s=>s!==process.pid):r,o=MG.platform==="win32"?bto(i,t):kto(i);return n&&o.set(process.pid,Ddt()),o}function Sto(e,t={}){return sUr([e],t).get(e)??null}function Ddt(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:EZ(),...s1e()?{bootId:s1e()}:{},...rUr(process.execPath)?{executableFingerprint:sZ(process.execPath)}:{},confidence:"self"}}function Ldt(e,t=Sto){if(e.hostname!==EZ())return{status:"remote",expected:e,reason:"Process belongs to another host."};if(Hlt(e.pid)==="dead")return{status:"dead",expected:e,reason:"Process ID is not live."};let r=t(e.pid);if(!r)return Hlt(e.pid)==="dead"?{status:"dead",expected:e,reason:"Process ID is not live."}:{status:"degraded",expected:e,reason:"Creation time could not be observed."};let n=Date.parse(e.processStartedAt),i=Date.parse(r.processStartedAt);return!Number.isFinite(n)||!Number.isFinite(i)||Math.abs(n-i)>nUr?{status:"mismatch",expected:e,observed:r,reason:"Process creation time does not match."}:e.bootId&&r.bootId&&e.bootId!==r.bootId?{status:"mismatch",expected:e,observed:r,reason:"Host boot identity does not match."}:e.executableFingerprint&&r.executableFingerprint&&e.executableFingerprint!==r.executableFingerprint?{status:"mismatch",expected:e,observed:r,reason:"Executable identity does not match."}:{status:"live",expected:e,observed:r}}function xto(){return ck()}function Fdt(){return ito(xto(),"daemon")}function Udt(e){return Hlt(e)!=="dead"}function Cto(){return new Date().toISOString()}function Vlt(e){try{return JSON.parse(Zeo(e,"utf8"))}catch{return null}}var Qdt=3e4;function Tto(e){if(e.hostname!==tUr())return!0;let t=Date.parse(e.acquiredAt);if(Number.isFinite(t)&&Date.now()-t<Qdt)return!0;if(!Udt(e.pid))return!1;if(e.processIdentity){let r=Ldt(e.processIdentity);return r.status==="live"||r.status==="degraded"||r.status==="remote"}return!0}function aUr(e,t){Keo(rto(e),{recursive:!0});let r=`${e}.${process.pid}.${nto()}.tmp`;tto(r,JSON.stringify(t,null,2)+`
|
|
12841
12841
|
`,{encoding:"utf8",flag:"wx"});try{Yeo(r,e)}finally{Bdt(r,{force:!0})}}function Rto(e){try{return Date.now()-eto(e).mtimeMs<Qdt}catch{return!1}}function Pto(e,t){return e?.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}function U9(e,t){return Object.assign(new Error(`${e} is already locked ${t}.`),{code:"CONTROL_PLANE_LOCK_BUSY"})}function lUr(e){return e instanceof Error&&"code"in e&&e.code==="CONTROL_PLANE_LOCK_BUSY"}function _to(e,t,r){try{aUr(e,t)}catch(n){throw n.code==="EEXIST"?U9(r,"by another contender"):n}}function Bto(e,t){let r=Vlt(e);r?.pid!==t.pid||r.hostname!==t.hostname||r.processStartedAt!==t.processStartedAt||Bdt(e,{force:!0})}function cUr(e,t,r){let n=Cto(),i=Ddt(),o={schemaVersion:1,name:t,pid:process.pid,hostname:tUr(),processStartedAt:i.processStartedAt,processIdentity:i,version:r,acquiredAt:n,updatedAt:n};try{aUr(e,o)}catch(s){if(s.code!=="EEXIST")throw s;let a=Vlt(e);if(a&&Tto(a))throw U9(t,`by PID ${a.pid} on ${a.hostname}`);if(a){if(!Pto(Vlt(e),a))throw U9(t,"while ownership was changing")}else{if(!Xeo(e))throw U9(t,"while ownership was changing");if(Rto(e))throw U9(t,"by an owner whose record is still being published")}Bdt(e,{force:!0}),_to(e,o,t)}return{record:o,release:()=>{Bto(e,o)}}}dn();var jst=64,Gto=16,aBr=16*1024*1024,lBr=15*6e4,Mf=class extends Error{constructor(e,t,r){super(t,r),this.code=e,this.name="WorkflowResourceError"}code},jto={control:1e3,foreground:900,reconciliation:850,terminal:800,"app-server":700,workflow:500,background:400,scheduled:300};function eZ(e,t,r=1,n=Number.MAX_SAFE_INTEGER){let i=typeof e=="number"?e:Number.parseInt(String(e??""),10);return Number.isFinite(i)?Math.min(n,Math.max(r,Math.trunc(i))):t}function Hto(e,t,r=0,n=Number.MAX_SAFE_INTEGER){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.min(n,Math.max(r,i)):t}function dG(e,t){return t===void 0?e:Math.min(e,t)}function Q9(e,t){return{maxConcurrency:dG(e.maxConcurrency,t?.maxConcurrency),maxCredentialConcurrency:dG(e.maxCredentialConcurrency,t?.maxCredentialConcurrency),maxRequestsPerWindow:dG(e.maxRequestsPerWindow,t?.maxRequestsPerWindow),maxTokensPerWindow:dG(e.maxTokensPerWindow,t?.maxTokensPerWindow),windowMs:t?.windowMs===void 0?e.windowMs:Math.max(1e3,t.windowMs)}}function Vto(e={}){let t=e.env??process.env,r=Math.max(1,e.cpuCount??Fto().length),n=Math.min(Math.max(1,r-2),Gto),i=eZ(t.XENO_WORKFLOW_GLOBAL_CONCURRENCY,n,1,jst),o=t.XENO_WORKFLOW_TRUSTED_CONCURRENCY_OVERRIDE==="1"?i:Math.min(n,i);o=dG(o,e.user?.globalConcurrency),o=dG(o,e.managed?.globalConcurrency),o=eZ(o,n,1,jst);let s={maxConcurrency:Math.min(o,8),maxCredentialConcurrency:Math.min(o,4),maxRequestsPerWindow:120,maxTokensPerWindow:2e6,windowMs:6e4},a=Q9(s,e.user?.providerDefault),l=Q9(a,e.managed?.providerDefault),c=new Set([...Object.keys(e.user?.providers??{}),...Object.keys(e.managed?.providers??{})]),d=Object.fromEntries([...c].map(p=>[p,Q9(Q9(l,e.user?.providers?.[p]),e.managed?.providers?.[p])])),u=(p,f,h=1,m=Number.MAX_SAFE_INTEGER)=>{let g=f,A=e.user?.[p],w=e.managed?.[p];return typeof A=="number"&&(g=Math.min(g,A)),typeof w=="number"&&(g=Math.min(g,w)),eZ(g,f,h,m)};return{schemaVersion:1,productHardConcurrency:jst,globalConcurrency:o,perRunConcurrency:u("perRunConcurrency",o,1,o),perParentConcurrency:u("perParentConcurrency",o,1,o),reservedPrioritySlots:Math.min(2,Math.max(0,o-1)),maxQueueLength:u("maxQueueLength",4096,1,65536),maxQueueWaitMs:u("maxQueueWaitMs",5*6e4,1e3,1440*6e4),maxAttemptsPerLogicalChild:u("maxAttemptsPerLogicalChild",3,1,100),maxAttemptsPerRun:u("maxAttemptsPerRun",1e3,1,1e4),maxReservedTokens:u("maxReservedTokens",4e6,1,Number.MAX_SAFE_INTEGER),maxReservedCostUsd:Hto(Math.min(e.user?.maxReservedCostUsd??500,e.managed?.maxReservedCostUsd??500),500,.01,1e6),leaseTtlMs:u("leaseTtlMs",4e3,2e3,5*6e4),handoffTtlMs:Math.max(u("leaseTtlMs",4e3,2e3,5*6e4),u("handoffTtlMs",6e4,2e3,10*6e4)),heartbeatIntervalMs:u("heartbeatIntervalMs",1e3,250,6e4),maxStarvationMs:u("maxStarvationMs",3e4,1e3,60*6e4),providerDefault:l,providers:d}}function cBr(e,t){if(!pUr(e)){if(t)throw new Mf("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy file not found: ${e}`);return}try{let r=JSON.parse(Nto(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("policy root must be an object");return r}catch(r){throw new Mf("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy is invalid: ${e}: ${r instanceof Error?r.message:String(r)}`)}}function qto(e=process.env){let t=mUr(Fdt()),r=e.XENO_WORKFLOW_RESOURCE_POLICY?.trim(),n=e.XENO_MANAGED_WORKFLOW_RESOURCE_POLICY?.trim(),i=a=>Uto(a)?a:Qto(a),o=cBr(r?i(r):Ske(t,"resource-policy.json"),!!r),s=n?cBr(i(n),!0):void 0;return Vto({env:e,user:o,managed:s})}function Es(e){return new Date(e).toISOString()}function Wto(e){return{schemaVersion:1,revision:0,nextFencingToken:1,updatedAt:Es(e),permits:[],queue:[],attempts:[],usage:[],providerRates:[],effects:[]}}function Jto(e){let t=e,r=p=>!!(p&&typeof p=="object"&&!Array.isArray(p)),n=p=>typeof p=="string"&&p.length>0&&p.length<=512,i=p=>typeof p=="string"&&Number.isFinite(Date.parse(p)),o=p=>r(p)&&Number.isInteger(p.pid)&&Number(p.pid)>0&&n(p.hostname)&&i(p.processStartedAt),s=p=>r(p)&&n(p.permitId)&&n(p.requestId)&&n(p.operationId)&&n(p.runId)&&n(p.providerId)&&n(p.logicalChildId)&&n(p.attemptId)&&n(p.idempotencyKey)&&Number.isInteger(p.fencingToken)&&Number(p.fencingToken)>0&&o(p.owner)&&i(p.acquiredAt)&&i(p.heartbeatAt)&&i(p.expiresAt)&&Number.isFinite(p.reservedTokens)&&Number(p.reservedTokens)>=0&&Number.isFinite(p.reservedCostUsd)&&Number(p.reservedCostUsd)>=0&&(p.handoff===void 0||r(p.handoff)&&o(p.handoff.target)&&i(p.handoff.startedAt)&&i(p.handoff.deadlineAt))&&(p.claimedAt===void 0||i(p.claimedAt)),a=p=>r(p)&&n(p.requestId)&&n(p.operationId)&&n(p.runId)&&n(p.providerId)&&n(p.logicalChildId)&&n(p.attemptId)&&n(p.idempotencyKey)&&o(p.owner)&&i(p.enqueuedAt)&&i(p.updatedAt),l=p=>r(p)&&n(p.runId)&&n(p.logicalChildId)&&n(p.attemptId)&&n(p.idempotencyKey)&&n(p.state)&&i(p.startedAt),c=p=>r(p)&&n(p.runId)&&Number.isFinite(p.tokens)&&Number(p.tokens)>=0&&Number.isFinite(p.costUsd)&&Number(p.costUsd)>=0&&Number.isInteger(p.attempts)&&Number(p.attempts)>=0&&i(p.updatedAt),d=p=>r(p)&&n(p.providerId)&&i(p.timestamp)&&Number.isFinite(p.tokens)&&Number(p.tokens)>=0,u=p=>r(p)&&n(p.effectKey)&&n(p.idempotencyKey)&&n(p.permitId)&&Number.isInteger(p.fencingToken)&&Number(p.fencingToken)>0&&n(p.state)&&i(p.claimedAt);return!!(t&&t.schemaVersion===1&&Number.isInteger(t.revision)&&Number(t.revision)>=0&&Number.isInteger(t.nextFencingToken)&&Number(t.nextFencingToken)>0&&i(t.updatedAt)&&Array.isArray(t.permits)&&t.permits.every(s)&&Array.isArray(t.queue)&&t.queue.every(a)&&Array.isArray(t.attempts)&&t.attempts.every(l)&&Array.isArray(t.usage)&&t.usage.every(c)&&Array.isArray(t.providerRates)&&t.providerRates.every(d)&&Array.isArray(t.effects)&&t.effects.every(u))}function zto(e,t){fUr(mUr(e),{recursive:!0});let r=`${e}.${process.pid}.${dUr()}.tmp`,n=hUr(r,"wx",384);try{Lto(n,JSON.stringify(t,null,2)+`
|
|
12842
12842
|
`,"utf8"),Oto(n)}finally{uUr(n)}aZ(r,e)}function Xto(e,t,r){let n=Date.parse(e.requestedAt??""),i=Number.isFinite(n)?n:t,o=Date.parse(e.queueDeadlineAt??"");return{requestedAt:Es(i),deadlineAt:Es(Number.isFinite(o)?Math.min(o,i+r):i+r)}}function gUr(e,t){return Q9(e.providerDefault,e.providers[t])}function dBr(e,t,r){let n=Math.max(0,t-Date.parse(e.enqueuedAt));return jto[e.priorityClass]+Math.floor(n/r.maxStarvationMs)*1001}function Yto(e,t,r){return[...e].sort((n,i)=>dBr(i,t,r)-dBr(n,t,r)||Date.parse(n.enqueuedAt)-Date.parse(i.enqueuedAt)||n.requestId.localeCompare(i.requestId))}function uBr(e,t){return e.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt}function uG(e){return Number.isFinite(e)?Math.max(0,Number(e)):0}function pBr(e,t,r,n){let i=e.permits;if(i.length>=r.globalConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"global_concurrency"};if(!(t.priorityClass==="control"||t.priorityClass==="foreground"||t.priorityClass==="reconciliation"||t.priorityClass==="terminal")&&i.length>=Math.max(0,r.globalConcurrency-r.reservedPrioritySlots))return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"reserved_priority_capacity"};let o=Math.min(r.perRunConcurrency,eZ(t.runConcurrencyLimit,r.perRunConcurrency,1,r.globalConcurrency));if(i.filter(A=>A.runId===t.runId).length>=o)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"run_concurrency"};if(t.parentId&&i.filter(A=>A.parentId===t.parentId).length>=r.perParentConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"parent_concurrency"};let s=gUr(r,t.providerId);if(i.filter(A=>A.providerId===t.providerId).length>=s.maxConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"provider_concurrency"};if(t.credentialFingerprint&&i.filter(A=>A.providerId===t.providerId&&A.credentialFingerprint===t.credentialFingerprint).length>=s.maxCredentialConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"credential_concurrency"};if(i.some(A=>A.logicalChildId===t.logicalChildId))return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"logical_child_active"};let a=new Set(e.attempts.filter(A=>A.logicalChildId===t.logicalChildId).map(A=>A.attemptId));if(!a.has(t.attemptId)&&a.size>=r.maxAttemptsPerLogicalChild)return{code:"WORKFLOW_ATTEMPT_LIMIT",reason:"logical_child_attempt_limit"};let l=new Set(e.attempts.filter(A=>A.runId===t.runId).map(A=>A.attemptId)),c=Math.min(r.maxAttemptsPerRun,eZ(t.runAttemptLimit,r.maxAttemptsPerRun,1,r.maxAttemptsPerRun));if(!l.has(t.attemptId)&&l.size>=c)return{code:"WORKFLOW_ATTEMPT_LIMIT",reason:"run_attempt_limit"};let d=uG(t.reservedTokens);if(i.reduce((A,w)=>A+w.reservedTokens,0)+d>r.maxReservedTokens)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"global_token_reservation"};let u=uG(t.reservedCostUsd);if(i.reduce((A,w)=>A+w.reservedCostUsd,0)+u>r.maxReservedCostUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"global_cost_reservation"};let p=e.usage.find(A=>A.runId===t.runId),f=i.filter(A=>A.runId===t.runId).reduce((A,w)=>A+w.reservedTokens,0);if(t.runTokenLimit!==void 0&&(p?.tokens??0)+f+d>t.runTokenLimit)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"run_token_limit"};let h=i.filter(A=>A.runId===t.runId).reduce((A,w)=>A+w.reservedCostUsd,0);if(t.runCostLimitUsd!==void 0&&(p?.costUsd??0)+h+u>t.runCostLimitUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"run_cost_limit"};let m=n-s.windowMs,g=e.providerRates.filter(A=>A.providerId===t.providerId&&Date.parse(A.timestamp)>=m&&(!t.credentialFingerprint||A.credentialFingerprint===t.credentialFingerprint));return g.length>=s.maxRequestsPerWindow?{reason:"provider_request_rate"}:g.reduce((A,w)=>A+w.tokens,0)+d>s.maxTokensPerWindow?{reason:"provider_token_rate"}:{}}function Kto(e){for(let[t,r]of Object.entries({requestId:e.requestId,operationId:e.operationId,runId:e.runId,providerId:e.providerId,logicalChildId:e.logicalChildId,attemptId:e.attemptId,idempotencyKey:e.idempotencyKey}))if(typeof r!="string"||!r.trim()||r.length>512)throw new Mf("WORKFLOW_GOVERNOR_UNAVAILABLE",`Invalid resource request field: ${t}.`);if(e.credentialFingerprint&&!/^(?:cred_)?sha256_[a-f0-9]{32,64}$/i.test(e.credentialFingerprint))throw new Mf("WORKFLOW_GOVERNOR_UNAVAILABLE","credentialFingerprint must be a scoped SHA-256 fingerprint.")}function Zto(e,t){let r=String(e??"default").trim().toLowerCase().split(/[/:]/,1)[0]||"default",n=t?.trim()?$to("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16):"default";return`${r}@${n}`}var ero=class{policy;rootDir;ledgerPath;lockPath;now;owner;fault;constructor(e={}){this.rootDir=e.rootDir??Ske(Fdt(),"governor"),this.ledgerPath=Ske(this.rootDir,"resource-ledger.json"),this.lockPath=Ske(this.rootDir,"resource-ledger.lock"),this.policy=e.policy??qto(),this.now=e.now??Date.now,this.owner=e.owner??Ddt,this.fault=e.fault,fUr(this.rootDir,{recursive:!0})}acquire(e){Kto(e);let t=0,r=this.withLedger((s,a)=>{this.cleanupExpired(s,a);let l=s.permits.find(b=>b.requestId===e.requestId||b.attemptId===e.attemptId);if(l)return t=s.permits.length,{value:{status:"active",permit:l,reason:"attempt_already_active"},changed:!0};let c=Xto(e,a,this.policy.maxQueueWaitMs);if(a>Date.parse(c.deadlineAt))return{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!1};let d=s.queue.find(b=>b.requestId===e.requestId);if(d&&a>Date.parse(d.queueDeadlineAt??c.deadlineAt))return s.queue=s.queue.filter(b=>b.requestId!==e.requestId),{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!0};if(!d&&s.queue.length>=this.policy.maxQueueLength)return{value:{status:"rejected",code:"WORKFLOW_QUEUE_FULL",reason:"The host workflow queue is full."},changed:!1};let u=e.owner??this.owner(),p=d?{...d,...e,owner:d.owner,updatedAt:Es(a)}:{...e,owner:u,requestedAt:c.requestedAt,queueDeadlineAt:c.deadlineAt,enqueuedAt:Es(a),updatedAt:Es(a)};d?s.queue=s.queue.map(b=>b.requestId===p.requestId?p:b):s.queue.push(p);let f=Yto(s.queue,a,this.policy),h,m={};for(let b of f){let I=pBr(s,b,this.policy,a);if(b.requestId===p.requestId&&(m=I),!I.reason){h=b;break}}if(m.code==="WORKFLOW_ATTEMPT_LIMIT"||m.code==="WORKFLOW_TOKEN_LIMIT"||m.code==="WORKFLOW_COST_LIMIT")return s.queue=s.queue.filter(b=>b.requestId!==p.requestId),{value:{status:"rejected",code:m.code,reason:m.reason??"resource_limit"},changed:!0};if(!h||h.requestId!==p.requestId){let b=s.permits.map(S=>Date.parse(S.expiresAt)).filter(Number.isFinite).sort((S,x)=>S-x)[0],I=gUr(this.policy,p.providerId),v=s.providerRates.filter(S=>S.providerId===p.providerId&&(!p.credentialFingerprint||S.credentialFingerprint===p.credentialFingerprint)).map(S=>Date.parse(S.timestamp)+I.windowMs).filter(S=>Number.isFinite(S)&&S>a).sort((S,x)=>S-x)[0],E=[b,v].filter(S=>typeof S=="number").sort((S,x)=>S-x)[0];return{value:{status:"queued",request:p,reason:m.reason??"waiting_for_fair_turn",...E?{estimatedEligibleAt:Es(E)}:{}},changed:!0}}let g=pBr(s,p,this.policy,a);if(g.reason)return g.code==="WORKFLOW_ATTEMPT_LIMIT"||g.code==="WORKFLOW_TOKEN_LIMIT"||g.code==="WORKFLOW_COST_LIMIT"?(s.queue=s.queue.filter(b=>b.requestId!==p.requestId),{value:{status:"rejected",code:g.code,reason:g.reason},changed:!0}):{value:{status:"queued",request:p,reason:g.reason},changed:!0};let A=Es(a),w={permitId:`permit_${dUr()}`,requestId:p.requestId,operationId:p.operationId,surface:p.surface,priorityClass:p.priorityClass,runId:p.runId,...p.parentId?{parentId:p.parentId}:{},providerId:p.providerId,...p.credentialFingerprint?{credentialFingerprint:p.credentialFingerprint}:{},logicalChildId:p.logicalChildId,attemptId:p.attemptId,idempotencyKey:p.idempotencyKey,fencingToken:s.nextFencingToken++,owner:p.owner,acquiredAt:A,heartbeatAt:A,expiresAt:Es(a+this.policy.leaseTtlMs),reservedTokens:uG(p.reservedTokens),reservedCostUsd:uG(p.reservedCostUsd),lastDurableSequence:0};s.queue=s.queue.filter(b=>b.requestId!==p.requestId),s.permits.push(w),t=s.permits.length;let y=s.attempts.find(b=>b.attemptId===p.attemptId);return y?Object.assign(y,{state:"active",permitId:w.permitId,operationId:p.operationId,endedAt:void 0,outcome:void 0,refusedClaim:void 0}):s.attempts.push({runId:p.runId,operationId:p.operationId,logicalChildId:p.logicalChildId,attemptId:p.attemptId,idempotencyKey:p.idempotencyKey,state:"active",permitId:w.permitId,startedAt:A}),s.providerRates.push({providerId:p.providerId,...p.credentialFingerprint?{credentialFingerprint:p.credentialFingerprint}:{},timestamp:A,tokens:w.reservedTokens}),this.fault?.("acquire.before_commit"),{value:{status:"acquired",permit:w},changed:!0,afterCommit:()=>this.fault?.("acquire.after_commit")}}),n=r.status==="rejected"?r.code:r.status==="acquired"?"admitted":r.reason;Ew().recordCounter("xeno.workflow.admission_results",1,{component:"resource_governor",provider:e.providerId,state:r.status,reason:n,...r.status==="rejected"?{error_code:r.code}:{}}),(n==="provider_request_rate"||n==="provider_token_rate"||n==="provider_concurrency"||n==="credential_concurrency")&&Ew().recordCounter("xeno.workflow.provider_throttles",1,{component:"resource_governor",provider:e.providerId,reason:n});let i=Date.parse((r.status==="queued"?r.request.requestedAt:e.requestedAt)??""),o=r.status==="acquired"||r.status==="active"?Date.parse(r.permit.acquiredAt):this.now();return Number.isFinite(i)&&Number.isFinite(o)&&Ew().recordHistogram("xeno.workflow.queue_wait_ms",Math.max(0,o-i),{component:"resource_governor",provider:e.providerId,state:r.status}),t>0&&Ew().recordHistogram("xeno.workflow.active_concurrency",t,{component:"resource_governor",provider:e.providerId}),r}heartbeat(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r),i=e.owner??this.owner();if(!uBr(n.owner,i))throw new Mf("WORKER_IDENTITY_MISMATCH","Permit heartbeat came from a different worker identity.");return n.heartbeatAt=Es(r),n.expiresAt=Es(r+this.policy.leaseTtlMs),n.lastDurableSequence=Math.max(n.lastDurableSequence,Math.max(0,e.lastDurableSequence??0)),{value:{...n},changed:!0}})}assertFence(e,t){return this.withLedger((r,n)=>({value:{...this.currentPermit(r,e,t,n)},changed:!1}))}beginHandoff(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r);if(n.claimedAt)return{value:{...n},changed:!1};let i=Math.max(Date.parse(n.expiresAt),r+this.policy.handoffTtlMs);return n.handoff={target:{...e.target},startedAt:Es(r),deadlineAt:Es(i)},n.owner={...e.target},n.expiresAt=Es(i),{value:{...n},changed:!0}})}transfer(e,t,r){let n=this.withLedger((i,o)=>{this.cleanupExpired(i,o);let s=l=>{let c=i.attempts.find(d=>d.permitId===e);return c?(c.refusedClaim={pid:r.pid,code:l.code,at:Es(o)},{value:{error:l},changed:!0}):{value:{error:l},changed:!1}},a=i.permits.find(l=>l.permitId===e);if(!a||a.fencingToken!==t){let l=i.attempts.find(c=>c.permitId===e);return s(l?.outcome==="WORKER_HANDOFF_EXPIRED"||l?.outcome==="WORKER_HANDOFF_ABANDONED"?new Mf("WORKER_HANDOFF_EXPIRED",`The worker hand-off window closed (${l.outcome} at ${l.endedAt??"unknown"}) before this worker claimed its permit.`):new Mf("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out."))}if(a.handoff){let l=a.handoff.target;if(l.pid!==r.pid||l.hostname!==r.hostname)return s(new Mf("WORKER_IDENTITY_MISMATCH","The permit hand-off is bound to a different worker process."))}else if(a.claimedAt&&!uBr(a.owner,r))return s(new Mf("WORKER_IDENTITY_MISMATCH","The permit is already claimed by another worker process."));return a.owner=r,delete a.handoff,a.claimedAt??=Es(o),a.heartbeatAt=Es(o),a.expiresAt=Es(o+this.policy.leaseTtlMs),{value:{permit:{...a}},changed:!0}});if("error"in n)throw n.error;return n.permit}settle(e){return this.withLedger((t,r)=>{let n=t.permits.find(a=>a.permitId===e.permitId);if(!n)return{value:!1,changed:!1};if(n.fencingToken!==e.fencingToken||Date.parse(n.expiresAt)<=r)throw new Mf("WORKER_LEASE_EXPIRED","The worker fencing token is stale.");t.permits=t.permits.filter(a=>a.permitId!==n.permitId);let i=t.attempts.find(a=>a.attemptId===n.attemptId);i&&Object.assign(i,{state:"settled",endedAt:Es(r),outcome:e.outcome});let o=t.usage.find(a=>a.runId===n.runId),s={runId:n.runId,tokens:(o?.tokens??0)+uG(e.actualTokens),costUsd:(o?.costUsd??0)+uG(e.actualCostUsd),attempts:(o?.attempts??0)+1,updatedAt:Es(r)};return t.usage=[...t.usage.filter(a=>a.runId!==n.runId),s],{value:!0,changed:!0}})}settleOperation(e,t,r=0,n=0){let i=this.snapshot().permits.find(o=>o.operationId===e);return i?this.settle({permitId:i.permitId,fencingToken:i.fencingToken,outcome:t,actualTokens:r,actualCostUsd:n}):!1}cancelQueued(e){return this.withLedger(t=>{let r=t.queue.some(n=>n.requestId===e);return t.queue=t.queue.filter(n=>n.requestId!==e),{value:r,changed:r}})}claimEffect(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r),i=t.effects.find(o=>o.effectKey===e.effectKey||o.idempotencyKey===n.idempotencyKey);return i?{value:i.permitId===n.permitId&&i.fencingToken===n.fencingToken&&i.state==="claimed",changed:!1}:(t.effects.push({effectKey:e.effectKey,idempotencyKey:n.idempotencyKey,permitId:n.permitId,fencingToken:n.fencingToken,state:"claimed",claimedAt:Es(r)}),{value:!0,changed:!0})})}commitEffect(e){return this.withLedger((t,r)=>{this.currentPermit(t,e.permitId,e.fencingToken,r);let n=t.effects.find(i=>i.effectKey===e.effectKey);return!n||n.permitId!==e.permitId||n.fencingToken!==e.fencingToken?{value:!1,changed:!1}:n.state==="committed"?{value:!0,changed:!1}:(n.state="committed",n.committedAt=Es(r),{value:!0,changed:!0})})}reconcile(e){let t=this.withLedger((r,n)=>{let i=[...r.permits],o=[...r.queue],s=e??sUr(i.map(A=>A.owner.pid)),a=new Set,l=new Set,c=new Set;for(let A of i){let w=Ldt(A.owner,y=>s.get(y)??null);if(A.handoff){let y=w.status==="mismatch"&&w.observed&&Date.parse(w.observed.processStartedAt)>Date.parse(A.owner.processStartedAt);w.status==="dead"||y?c.add(A.permitId):w.status!=="live"&&l.add(A.permitId);continue}w.status==="mismatch"&&a.add(A.permitId),(w.status==="degraded"||w.status==="remote")&&l.add(A.permitId)}this.cleanupExpired(r,n,a,c);let d=new Set(r.permits.map(A=>A.permitId)),u=i.filter(A=>!d.has(A.permitId)&&!a.has(A.permitId)),p=i.filter(A=>a.has(A.permitId)),f=new Set(r.queue.map(A=>A.requestId)),h=o.filter(A=>!f.has(A.requestId)),m=new Map(r.effects.map(A=>[A.permitId,A.fencingToken]));for(let A of i)m.set(A.permitId,A.fencingToken);let g=new Map(r.attempts.filter(A=>A.state==="expired"&&A.permitId&&(A.outcome==="WORKER_HANDOFF_EXPIRED"||A.outcome==="WORKER_HANDOFF_ABANDONED")&&n-Date.parse(A.endedAt??"")<=lBr).map(A=>[A.attemptId,{...A.operationId?{operationId:A.operationId}:{},permitId:A.permitId,fencingToken:m.get(A.permitId)??0,outcome:A.outcome,...A.endedAt?{endedAt:A.endedAt}:{},...A.refusedClaim?{refusedClaim:{...A.refusedClaim}}:{}}]));return{value:{expiredPermits:u,handoffFailures:g,identityMismatches:p,expiredQueue:h,livePermits:r.permits.length,degradedPermits:r.permits.filter(A=>l.has(A.permitId)).length},changed:u.length>0||p.length>0||h.length>0}});return Ew().recordHistogram("xeno.worker.live_leases",t.livePermits,{component:"resource_governor",operation:"reconcile"}),Ew().recordHistogram("xeno.worker.degraded_leases",t.degradedPermits,{component:"resource_governor",operation:"reconcile"}),t.expiredPermits.length>0&&Ew().recordCounter("xeno.worker.lease_expirations",t.expiredPermits.length,{component:"resource_governor",operation:"reconcile"}),t.identityMismatches.length>0&&Ew().recordCounter("xeno.worker.identity_mismatches",t.identityMismatches.length,{component:"resource_governor",operation:"reconcile"}),t}snapshot(){return this.withLedger(e=>({value:structuredClone(e),changed:!1}))}recentHandoffFailureOperations(){return this.withLedger((e,t)=>({value:[...new Set(e.attempts.filter(r=>r.operationId&&r.state==="expired"&&(r.outcome==="WORKER_HANDOFF_EXPIRED"||r.outcome==="WORKER_HANDOFF_ABANDONED")&&t-Date.parse(r.endedAt??"")<=lBr).map(r=>r.operationId))],changed:!1}))}cleanupExpired(e,t,r=new Set,n=new Set){let i=new Map(e.permits.filter(s=>Date.parse(s.expiresAt)<=t||r.has(s.permitId)||n.has(s.permitId)).map(s=>[s.permitId,s]));if(i.size>0){e.permits=e.permits.filter(s=>!i.has(s.permitId));for(let s of e.attempts)s.permitId&&i.has(s.permitId)&&s.state==="active"&&(s.state="expired",s.endedAt=Es(t),s.outcome=r.has(s.permitId)?"WORKER_IDENTITY_MISMATCH":n.has(s.permitId)?"WORKER_HANDOFF_ABANDONED":i.get(s.permitId)?.handoff?"WORKER_HANDOFF_EXPIRED":"WORKER_LEASE_EXPIRED")}e.queue=e.queue.filter(s=>Date.parse(s.queueDeadlineAt??s.updatedAt)>t);let o=Math.max(this.policy.providerDefault.windowMs,...Object.values(this.policy.providers).map(s=>s.windowMs??0));if(e.providerRates=e.providerRates.filter(s=>Date.parse(s.timestamp)>t-o),e.attempts.length>2e4){let s=e.attempts.filter(l=>l.state==="active"),a=e.attempts.filter(l=>l.state!=="active").slice(-Math.max(0,2e4-s.length));e.attempts=[...a,...s]}e.effects.length>2e4&&(e.effects=e.effects.slice(-2e4)),e.usage.length>1e4&&(e.usage=e.usage.slice(-1e4))}currentPermit(e,t,r,n){let i=e.permits.find(o=>o.permitId===t);if(!i||Date.parse(i.expiresAt)<=n||i.fencingToken!==r)throw new Mf("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out.");return i}readLedger(e){if(!pUr(this.ledgerPath))return Wto(e);let t;try{t=hUr(this.ledgerPath,"r");let r=Mto(t).size;if(!Number.isSafeInteger(r)||r>aBr)throw new Error(`ledger exceeds the ${aBr} byte limit`);let n=Buffer.alloc(r),i=0;for(;i<r;){let a=Dto(t,n,i,r-i,i);if(a===0)throw new Error("Resource ledger changed during read");i+=a}let o=n.toString("utf8"),s=JSON.parse(o);if(!Jto(s))throw new Error("Unsupported resource ledger schema.");return s}catch(r){throw new Mf("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource ledger is unreadable and was not overwritten: ${r instanceof Error?r.message:String(r)}`)}finally{t!==void 0&&uUr(t)}}withLedger(e){let t=Date.now()+Qdt+5e3,r=new Int32Array(new SharedArrayBuffer(4)),n,i;for(;!n&&Date.now()<=t;)try{n=cUr(this.lockPath,"workflow-resource-governor",Ew().producerVersion)}catch(o){if(i=o,!(o instanceof Error)||!o.message.includes("is already locked"))break;Atomics.wait(r,0,0,10)}if(!n)throw new Mf("WORKFLOW_GOVERNOR_UNAVAILABLE",i instanceof Error?i.message:String(i??"Resource governor lock unavailable."),{cause:i});try{let o=this.now(),s=this.readLedger(o),a=e(s,o);return a.changed&&(s.revision+=1,s.updatedAt=Es(o),zto(this.ledgerPath,s)),a.afterCommit?.(),a.value}finally{n.release()}}};function tro(e=process.env){let t=e.XENO_RESOURCE_PERMIT_ID?.trim(),r=Number.parseInt(e.XENO_RESOURCE_FENCING_TOKEN??"",10);return t&&Number.isInteger(r)&&r>0?{permitId:t,fencingToken:r}:null}function Hst(e,t,r=process.env){if(r.XENO_RESOURCE_OPERATION_ID?.trim()!==e)return;let n=tro(r);if(!t||!n||t.permitId!==n.permitId||t.fencingToken!==n.fencingToken)throw new Mf("WORKER_LEASE_EXPIRED","Worker state write rejected because its fencing token is stale.");new ero().assertFence(n.permitId,n.fencingToken)}var nro=new Int32Array(new SharedArrayBuffer(4)),iro=6e4;function oro(e,t,r=rro,n=iro){let i=Date.now()+n;for(let o=0;;o++)try{r(e,t);return}catch(s){if(Date.now()>=i||!["EPERM","EACCES","EBUSY"].includes(s.code??""))throw s;Atomics.wait(nro,0,0,Math.min(100,(o+1)*10))}}dk();dk();jC();jC();lk();n$r();dk();cZ();sct();act();cZ();var sro=1,YB={streaming:!0,textInput:!0,imageInput:!0,tools:!0,parallelToolCalls:!0,structuredOutput:!1,reasoningMetadata:!0,usageAccounting:!0,promptCaching:!1,modelDiscovery:!0},WEe={...YB,reasoningMetadata:!1},uOs=[Zb("xeno","XENO hosted","xeno","openai-compatible","https://api.xenosystem.ai","public-https","bearer-env","XENO_API_KEY","/v1/models",YB),Zb("openai","OpenAI","direct","openai-responses","https://api.openai.com","public-https","bearer-env","OPENAI_API_KEY","/v1/models",YB),Zb("anthropic","Anthropic","direct","anthropic","https://api.anthropic.com","public-https","header-env","ANTHROPIC_API_KEY","/v1/models",{...YB,structuredOutput:!1}),Zb("google","Google AI Studio","direct","google","https://generativelanguage.googleapis.com","public-https","header-env","GOOGLE_API_KEY","/v1beta/models",YB),Zb("openrouter","OpenRouter","gateway","openai-compatible","https://openrouter.ai/api","public-https","bearer-env","OPENROUTER_API_KEY","/v1/models",WEe),Zb("xeno-rt","xeno-rt","local","openai-compatible","http://127.0.0.1:3338","local-network","none",void 0,"/v1/models",WEe,["running xeno-rt endpoint"]),Zb("ollama","Ollama","local","openai-compatible","http://127.0.0.1:11434","local-network","none",void 0,"/v1/models",WEe,["Ollama OpenAI compatibility endpoint"]),Zb("azure-openai","Azure OpenAI","cloud","openai-compatible",void 0,"public-https","header-env","AZURE_OPENAI_API_KEY",void 0,WEe,["resource endpoint","deployment","API version","host adapter for deployment-shaped requests"]),Zb("aws-bedrock","Amazon Bedrock","cloud","aws-bedrock",void 0,"public-https","cloud-chain",void 0,void 0,{...YB,modelDiscovery:!1},["AWS credential chain","region","Bedrock host adapter"]),Zb("vertex-ai","Google Vertex AI","cloud","vertex-ai",void 0,"public-https","cloud-chain",void 0,void 0,{...YB,modelDiscovery:!1},["Google application-default credentials","project","region","Vertex host adapter"])];function Zb(e,t,r,n,i,o,s,a,l,c,d=[]){return{schemaVersion:sro,id:e,displayName:t,family:r,adapterKind:n,...i?{defaultBaseUrl:i}:{},endpointProfile:o,...i?{allowedHosts:[new URL(i).hostname]}:{},auth:{mode:s,...a?{defaultSecretRef:a}:{},...s==="header-env"?{header:aro(e)}:{},description:s==="none"?"No credential required":s==="cloud-chain"?"Provider-owned cloud credential chain":`Environment/credential reference ${a}`},capabilities:c,...l?{discoveryPath:l}:{},requires:d}}function aro(e){return e==="anthropic"?"x-api-key":e==="google"?"x-goog-api-key":e==="azure-openai"?"api-key":"authorization"}dn();h$();IG();IG();m$();f1e();dn();Vc();cct();g1e();var AUr=new Set(["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read"]),wUr=new Set(["browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download","browser.record.start","browser.record.stop"]),yUr=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),bUr=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),Gdt=[...AUr,...wUr,...yUr,...bUr];function lro(e){if(AUr.has(e))return{operation:e,surface:"browser",effect:"observe",evidence:{before:"disabled",after:e==="browser.wait"||e==="browser.tabs.list"?"optional":"required",recording:"optional"}};if(wUr.has(e)){let t=e==="browser.record.start"||e==="browser.record.stop";return{operation:e,surface:"browser",effect:"act",evidence:{before:"required",after:"required",recording:e==="browser.record.stop"?"required":"optional"}}}if(yUr.has(e))return{operation:e,surface:"computer",effect:"observe",evidence:{before:"disabled",after:e==="computer.wait"?"optional":"required",recording:"optional"}};if(bUr.has(e))return{operation:e,surface:"computer",effect:"act",evidence:{before:"required",after:"required",recording:"optional"}};throw new TypeError(`Unsupported XENO automation operation: ${e}`)}xd();var pOs=new Set(["Read","Glob","Grep","LS","GitStatus","GitDiff","GitLog","WebFetch","WebSearch","MemoryRead","NotebookRead","ReadImage","SqliteAnalyze","ElfAnalyze","GcodeAnalyze","HtmlSanitizerAudit","ArtifactCompare","Think","ToolSearch","Skill",...Gdt.filter(e=>lro(e).effect==="observe")]);wct();var cro=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation","page"],dro=["draft","pending_review","approved","rejected","superseded","archived"],uro=["public","internal","confidential","restricted"],pro=["agent","tool","user","system","integration"],vUr=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],IUr=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];y1e();var fro="[\\u0000-\\u001f\\u007f]",fOs=new RegExp(fro),hOs=new Set(dro),mOs=new Set(uro),gOs=new Set(pro),AOs=new Set(cro),wOs=new Set(vUr),yOs=new Set(IUr),bOs=32*1024*1024,vOs=1024*1024*1024,IOs=16*1024*1024,EOs=48*1024*1024;pZ();var kOs=4*1024*1024;dn();h$();var SOs=64*1024*1024;pZ();wct();var xOs=8*1024*1024;yct();var COs=Gdt.filter(e=>e.startsWith("browser.")),TOs=Gdt.filter(e=>e.startsWith("computer."));y1e();var ROs=new Set(vUr),POs=new Set(IUr),_Os=16*1024*1024;y1e();dn();var BOs=16*1024*1024,$Os=1024*1024,MOs=["default-src 'none'","script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net/npm/ https://cdn.tailwindcss.com https://code.jquery.com","style-src 'self' 'unsafe-inline' https://fonts.googleapis.com","font-src 'self' data: https://fonts.gstatic.com","img-src 'self' data: blob:","media-src 'self' data: blob:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; "),OOs=128*1024*1024,NOs=new TextDecoder().decode(new Uint8Array([239,191,189]));b1e();Z$r();eMr();bct();xs();bct();g$();uk();uk();lk();uk();Vc();Vc();uk();Vc();v1e();$ke();xdt();LFr();FFr();UFr();BFr();Sdt();OFr();NFr();DFr();CFr();b$();QFr();$Fr();MFr();uZ();w$();hZ();Cdt();qct();kdt();GFr();Tdt();Rdt();S1e();RDr();qFr();Tct();Tct();Pdt();tSe();rSe();_dt();dn();xs();m1e();rSe();_dt();tSe();b$();Mct();mZ();nOr();yFr();Oct();cOr();uOr();qC();SOr();BOr();INr();_Nr();BNr();MNr();FNr();jct();N1e();GLr();DNr();VNr();WNr();VDr();JDr();sLr();uLr();gLr();ELr();_Lr();NLr();YLr();oFr();lFr();dFr();mFr();gFr();kFr();xd();Xo();var hro=["completed","partial","failed","cancelled"],DOs=["queued","running",...hro];Z1e();uv();dn();h$();h$();xs();var mro=EUr(ck(),"daemon"),GOs=EUr(mro,"runs");dn();xs();xs();h$();EFr();Idt();var gro=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,jOs=new RegExp(String.raw`${gro}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i");Idt();dn();var HOs=512*1024*1024,VOs=10080*60*1e3,qOs=365*24*60*60*1e3;dn();h$();xs();IG();var WOs=8*1024*1024,JOs=64*1024*1024,zOs=744*60*60*1e3;m$();var XOs=Object.freeze({"thread.run":"prompt","turn.start":"input","turn.steer":"input","schedule.create":"prompt","schedule.update":"prompt"}),Aro=["Read","Write","Edit","Glob","Grep","WebFetch"],YOs=new Set(Aro),KOs=64*1024;Vc();p$();var ZOs=String.raw`
|
|
12843
12843
|
using System;
|
|
@@ -15577,7 +15577,7 @@ public static class XenoProtectedWrite {
|
|
|
15577
15577
|
$request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
15578
15578
|
$result = [XenoProtectedWrite]::Run([string]$request.path, [Convert]::FromBase64String([string]$request.payload), [bool]$request.ifAbsent, [string]$request.operationId, [string]$request.operation, [int]$request.parentPid, [long]$request.parentBirth)
|
|
15579
15579
|
$result | ConvertTo-Json -Compress
|
|
15580
|
-
`});function UNo(){if(OTe===void 0)try{let e=(typeof import.meta=="object"?import.meta.url:void 0)??(typeof __filename=="string"?__filename:void 0),t=e?FNo(e):null;OTe=t?t("@primno/dpapi"):null}catch{OTe=null}return OTe??null}var OTe,QNo,GNo=ee(()=>{"use strict";Bs(),WKr(),WKr(),QNo=UNo()?.isPlatformSupported===!0}),lvt=ee(()=>{"use strict";YRe(),PNo(),isn(),nsn(),G4(),e7r(),mRe(),FM(),fte(),vsn(),_No(),$No(),Jyt(),MNo(),zyt(),Xyt(),GNo(),Yyt(),R7r()}),KRe=ee(()=>{"use strict"}),jNo,HNo,ZRe=ee(()=>{"use strict";pRe(),KRe(),jNo=2*1024*1024,HNo=64*1024*1024}),VNo,cvt=ee(()=>{"use strict";ZRe(),KRe(),VNo=128*1024}),Ssn=ee(()=>{"use strict"}),j4=ee(()=>{"use strict";cvt(),ZRe(),Yk(),zk(),ivt(),rvt(),msn(),Bs(),avt(),Ssn(),wc(),IRe(),lvt(),jM()}),xsn=ee(()=>{"use strict";ovt(),svt(),lvt(),j4()}),qNo=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation","page"],WNo=["draft","pending_review","approved","rejected","superseded","archived"],JNo=["public","internal","confidential","restricted"],zNo=["agent","tool","user","system","integration"],Csn=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],Tsn=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];function YNo(e){return{algorithm:"sha256",value:XNo("sha256").update(e).digest("hex")}}function KNo(e){return JSON.stringify(yyt(e,new Set))}function ZNo(e){return YNo(KNo(e))}function yyt(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 n=e.map(i=>yyt(i,t));return t.delete(e),n}let r={};for(let n of Object.keys(e).sort((i,o)=>i.localeCompare(o))){let i=e[n];if(i===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);r[n]=yyt(i,t)}return t.delete(e),r}cRe();var e5o="[\\u0000-\\u001f\\u007f]",GHs=new RegExp(e5o),jHs=new Set(WNo),HHs=new Set(JNo),VHs=new Set(zNo),qHs=new Set(qNo),WHs=new Set(Csn),JHs=new Set(Tsn);cRe();var zHs=new Set(Csn),XHs=new Set(Tsn);yn();MM();var Rsn="0.10.109",YHs=64*1024*1024,KHs=16*1024*1024;cRe();yn();var ZHs=16*1024*1024,eVs=1024*1024,tVs=["default-src 'none'","script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net/npm/ https://cdn.tailwindcss.com https://code.jquery.com","style-src 'self' 'unsafe-inline' https://fonts.googleapis.com","font-src 'self' data: https://fonts.gstatic.com","img-src 'self' data: blob:","media-src 'self' data: blob:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; "),rVs=128*1024*1024,nVs=new TextDecoder().decode(new Uint8Array([239,191,189]));function Psn(e,t={}){for(let r of e){let n=r.codePointAt(0);if(n===127||!(n>31)&&!(n===9&&t.allowTab===!0)&&!((n===10||n===13)&&t.allowLineBreaks===!0))return!0}return!1}var t5o="xeno.recipe.v1",Tp=class extends Error{constructor(e){super(`XENO recipe is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoRecipeValidationError"}issues;code="XENO_RECIPE_INVALID"};function r5o(e){let t=RM(e,"recipe",["schemaVersion","recipeId","name","description","version","modes","inputs","requiredSecretRefs","authority","budget","steps","provenance"]),r=RM(t.authority,"authority",["permissionMode","externalActions","network"]),n=RM(t.budget,"budget",["maxAgents","maxConcurrency","maxTotalTokens","timeoutMs"]),i={schemaVersion:t.schemaVersion,recipeId:gc(t.recipeId,"recipeId"),name:gc(t.name,"name"),description:gc(t.description,"description"),version:uee(t.version,"version"),modes:EM(t.modes,"modes").map(o=>o),inputs:EM(t.inputs,"inputs").map((o,s)=>i5o(o,s)),requiredSecretRefs:EM(t.requiredSecretRefs,"requiredSecretRefs").map(o=>gc(o,"secret ref")),authority:{permissionMode:r.permissionMode,externalActions:r.externalActions,network:r.network},budget:{maxAgents:uee(n.maxAgents,"budget.maxAgents"),maxConcurrency:uee(n.maxConcurrency,"budget.maxConcurrency"),maxTotalTokens:uee(n.maxTotalTokens,"budget.maxTotalTokens"),timeoutMs:uee(n.timeoutMs,"budget.timeoutMs")},steps:EM(t.steps,"steps").map((o,s)=>o5o(o,s)),...t.provenance!==void 0?{provenance:s5o(t.provenance)}:{}};return dvt(i),i}function dvt(e){let t=[];e?.schemaVersion!==t5o&&t.push("schemaVersion must be xeno.recipe.v1"),NTe(e?.recipeId,"recipeId",t),$k(e?.name,"name",t,256),$k(e?.description,"description",t,8e3),(!Number.isSafeInteger(e?.version)||e.version<1||e.version>1e6)&&t.push("version must be a positive bounded integer"),(!Array.isArray(e?.modes)||e.modes.length<1)&&t.push("modes must contain at least one execution mode");let r=new Set;for(let s of e?.modes??[])s!=="interactive"&&s!=="headless"&&s!=="ci"&&t.push(`unsupported recipe mode ${String(s)}`),r.has(s)&&t.push(`duplicate recipe mode ${s}`),r.add(s);g5o(e?.authority?.permissionMode)||t.push("authority.permissionMode is invalid"),e?.authority?.externalActions!=="deny"&&e?.authority?.externalActions!=="approval-required"&&t.push("authority.externalActions is invalid"),e?.authority?.network!=="deny"&&e?.authority?.network!=="environment-policy"&&t.push("authority.network is invalid"),a5o(e?.budget,t);let n=new Set;for(let s of e?.inputs??[]){if(h5o(s?.name,t),n.has(s.name)&&t.push(`duplicate input ${s.name}`),n.add(s.name),$k(s?.description,`input ${s.name} description`,t,2e3),typeof s?.required!="boolean"&&t.push(`input ${s.name} required must be boolean`),s?.default!==void 0&&$k(s.default,`input ${s.name} default`,t,32e3),s?.required&&s?.default!==void 0&&t.push(`required input ${s.name} cannot define a default`),s?.enum!==void 0){(!Array.isArray(s.enum)||s.enum.length<1||s.enum.length>256)&&t.push(`input ${s.name} enum is invalid`);for(let a of s.enum??[])$k(a,`input ${s.name} enum value`,t,2e3);s.default!==void 0&&!s.enum.includes(s.default)&&t.push(`input ${s.name} default is outside its enum`)}if(s?.pattern!==void 0){$k(s.pattern,`input ${s.name} pattern`,t,1e3);try{new RegExp(s.pattern,"u")}catch{t.push(`input ${s.name} pattern is invalid`)}}}let i=new Set;for(let s of e?.requiredSecretRefs??[])/^[A-Z_][A-Z0-9_]{0,127}$/u.test(s)||t.push(`required secret ref ${s} is invalid`),i.has(s)&&t.push(`duplicate secret ref ${s}`),i.add(s);(!Array.isArray(e?.steps)||e.steps.length<1||e.steps.length>256)&&t.push("steps must contain 1 through 256 records"),Array.isArray(e?.steps)&&e.steps.length>(e?.budget?.maxAgents??0)&&t.push("budget.maxAgents must cover every recipe step");let o=new Map;for(let s of e?.steps??[]){NTe(s?.id,"step id",t),o.has(s.id)&&t.push(`duplicate step ${s.id}`),o.set(s.id,s),$k(s?.title,`step ${s.id} title`,t,2e3),s?.kind!=="agent"&&s?.kind!=="verification"&&t.push(`step ${s.id} kind is invalid`),$k(s?.prompt,`step ${s.id} prompt`,t,128e3),s?.agentProfile!==void 0&&NTe(s.agentProfile,`step ${s.id} agentProfile`,t);for(let a of s?.dependsOn??[])NTe(a,`step ${s.id} dependency`,t);s?.approval&&$k(s.approval.message,`step ${s.id} approval message`,t,8e3);for(let a of s?.expectedArtifacts??[])m5o(a,`step ${s.id} expected artifact`,t);for(let a of p5o(s?.prompt??""))n.has(a)||t.push(`step ${s.id} references unknown input ${a}`);/\{\{\s*(?:secret|env)[.:]/iu.test(s?.prompt??"")&&t.push(`step ${s.id} cannot interpolate secrets into prompts`)}for(let s of e?.steps??[])for(let a of s.dependsOn??[])o.has(a)||t.push(`step ${s.id} depends on unknown step ${a}`),a===s.id&&t.push(`step ${s.id} cannot depend on itself`);if(l5o(e?.steps??[],t),t.length>0)throw new Tp([...new Set(t)])}function n5o(e,t){if(dvt(e),!e.modes.includes(t.mode))throw new Tp([`recipe does not allow ${t.mode} mode`]);let r=t.inputs??{},n=new Map(e.inputs.map(a=>[a.name,a])),i=Object.keys(r).filter(a=>!n.has(a));if(i.length>0)throw new Tp(i.map(a=>`unknown recipe input ${a}`));let o={};for(let a of e.inputs){let l=r[a.name]??a.default;if(l===void 0){if(a.required)throw new Tp([`required recipe input ${a.name} is missing`]);o[a.name]="";continue}o[a.name]=d5o(a,l)}let s=e.requiredSecretRefs.filter(a=>t.hasSecretRef&&!t.hasSecretRef(a));if(s.length>0)throw new Tp(s.map(a=>`required secret reference is unavailable: ${a}`));return{schemaVersion:1,recipeId:e.recipeId,recipeVersion:e.version,recipeFingerprint:_sn(e),mode:t.mode,inputs:o,requiredSecretRefs:[...e.requiredSecretRefs],authority:structuredClone(e.authority),budget:structuredClone(e.budget),steps:c5o(e.steps).map(a=>({...structuredClone(a),prompt:u5o(a.prompt,o)}))}}function _sn(e){return dvt(e),{algorithm:"sha256",value:ZNo(e).value}}function i5o(e,t){let r=RM(e,`inputs[${t}]`,["name","description","required","default","enum","pattern"]);return{name:gc(r.name,`inputs[${t}].name`),description:gc(r.description,`inputs[${t}].description`),required:f5o(r.required,`inputs[${t}].required`),...r.default!==void 0?{default:gc(r.default,`inputs[${t}].default`)}:{},...r.enum!==void 0?{enum:EM(r.enum,`inputs[${t}].enum`).map(n=>gc(n,"enum value"))}:{},...r.pattern!==void 0?{pattern:gc(r.pattern,`inputs[${t}].pattern`)}:{}}}function o5o(e,t){let r=RM(e,`steps[${t}]`,["id","title","kind","prompt","dependsOn","agentProfile","approval","expectedArtifacts"]),n=r.approval===void 0?void 0:RM(r.approval,`steps[${t}].approval`,["message"]);return{id:gc(r.id,`steps[${t}].id`),title:gc(r.title,`steps[${t}].title`),kind:r.kind,prompt:gc(r.prompt,`steps[${t}].prompt`),...r.dependsOn!==void 0?{dependsOn:EM(r.dependsOn,"dependsOn").map(i=>gc(i,"dependency"))}:{},...r.agentProfile!==void 0?{agentProfile:gc(r.agentProfile,"agentProfile")}:{},...n?{approval:{message:gc(n.message,"approval message")}}:{},...r.expectedArtifacts!==void 0?{expectedArtifacts:EM(r.expectedArtifacts,"expectedArtifacts").map(i=>gc(i,"expected artifact"))}:{}}}function s5o(e){let t=RM(e,"provenance",["publisherId","source","revision"]);return{publisherId:gc(t.publisherId,"provenance.publisherId"),...t.source!==void 0?{source:gc(t.source,"provenance.source")}:{},...t.revision!==void 0?{revision:gc(t.revision,"provenance.revision")}:{}}}function a5o(e,t){(!Number.isSafeInteger(e?.maxAgents)||e.maxAgents<1||e.maxAgents>256)&&t.push("budget.maxAgents is invalid"),(!Number.isSafeInteger(e?.maxConcurrency)||e.maxConcurrency<1||e.maxConcurrency>64)&&t.push("budget.maxConcurrency is invalid"),e?.maxConcurrency>e?.maxAgents&&t.push("budget.maxConcurrency cannot exceed maxAgents"),(!Number.isSafeInteger(e?.maxTotalTokens)||e.maxTotalTokens<1||e.maxTotalTokens>1e8)&&t.push("budget.maxTotalTokens is invalid"),(!Number.isSafeInteger(e?.timeoutMs)||e.timeoutMs<1e3||e.timeoutMs>10080*60*1e3)&&t.push("budget.timeoutMs is invalid")}function l5o(e,t){let r=new Map(e.map(s=>[s.id,s])),n=new Set,i=new Set,o=s=>{if(!(i.has(s)||!r.has(s))){if(n.has(s)){t.push(`recipe step dependency cycle includes ${s}`);return}n.add(s);for(let a of r.get(s)?.dependsOn??[])o(a);n.delete(s),i.add(s)}};for(let s of e)o(s.id)}function c5o(e){let t=new Map(e.map(i=>[i.id,i])),r=new Map(e.map((i,o)=>[i.id,{step:i,index:o,dependencies:new Set(i.dependsOn??[])}])),n=[];for(;r.size>0;){let i=[...r.values()].filter(({dependencies:o})=>[...o].every(s=>!r.has(s))).sort((o,s)=>o.index-s.index);if(i.length===0)throw new Tp(["recipe step dependency graph is cyclic"]);for(let o of i)n.push(t.get(o.step.id)),r.delete(o.step.id)}return n}function d5o(e,t){let r=t.trim();if(r.length>32e3||Psn(r,{allowTab:!0,allowLineBreaks:!0}))throw new Tp([`input ${e.name} is invalid`]);if(e.enum&&!e.enum.includes(r))throw new Tp([`input ${e.name} is outside its enum`]);if(e.pattern&&!new RegExp(e.pattern,"u").test(r))throw new Tp([`input ${e.name} does not match its pattern`]);return r}function u5o(e,t){return e.replace(/\{\{\s*input\.([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/gu,(r,n)=>t[n]??"")}function p5o(e){return[...e.matchAll(/\{\{\s*input\.([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/gu)].map(t=>t[1])}function RM(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Tp([`${t} must be an object`]);let n=e,i=Object.keys(n).filter(o=>!r.includes(o));if(i.length>0)throw new Tp(i.map(o=>`${t} contains unsupported field ${o}`));return n}function EM(e,t){if(!Array.isArray(e))throw new Tp([`${t} must be an array`]);return e}function gc(e,t){if(typeof e!="string")throw new Tp([`${t} must be text`]);return e}function f5o(e,t){if(typeof e!="boolean")throw new Tp([`${t} must be boolean`]);return e}function uee(e,t){if(!Number.isSafeInteger(e))throw new Tp([`${t} must be an integer`]);return e}function NTe(e,t,r){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u.test(e))&&r.push(`${t} is invalid`)}function h5o(e,t){(typeof e!="string"||!/^[A-Za-z_][A-Za-z0-9_-]{0,127}$/u.test(e))&&t.push(`input name ${String(e)} is invalid`)}function $k(e,t,r,n){(typeof e!="string"||!e.trim()||e.length>n||Psn(e,{allowTab:!0,allowLineBreaks:!0}))&&r.push(`${t} must be non-empty bounded text`)}function m5o(e,t,r){(typeof e!="string"||!e||e.startsWith("/")||/^[A-Za-z]:[\\/]/u.test(e)||e.includes("\\")||e.split("/").some(n=>!n||n==="."||n===".."))&&r.push(`${t} must be workflow-relative`)}function g5o(e){return e==="default"||e==="plan"||e==="acceptEdits"||e==="auto"||e==="dontAsk"}yn();Bs();var Fsn=3e3,N5o=Fsn,D5o=4e3,L5o=15e3,Usn=2e3,F5o=1e4,U5o={platform:process.platform,now:()=>Date.now(),runSync:(e,t,r)=>pvt(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,stdio:["ignore","pipe","ignore"]}),run:async(e,t,r)=>(await $5o(B5o)(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,maxBuffer:1024*1024,signal:r.signal})).stdout},H4=U5o,$ee=new Map,hvt=0,lAt;function Q5o(e=process.env){if(e===process.env&&lAt)return lAt;let t=e.SystemRoot??e.SYSTEMROOT??e.windir??e.WINDIR,r="powershell.exe";if(t&&/^[a-z]:[\\/]/i.test(t)){let n=`${t.replace(/[\\/]+$/,"")}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;Lsn(n)&&(r=n)}return e===process.env&&(lAt=r),r}function mvt(e){return Number.isInteger(e)&&e>0}function G5o(e){return M5o("sha256").update(e).digest("hex")}function ite(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${G5o(t)}`:void 0}function iRe(){if(process.platform==="linux")try{return fvt("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function ote(e){if(typeof e!="number"||!mvt(e))return"dead";try{return process.kill(e,0),"live"}catch(t){return t.code==="ESRCH"?"dead":"unknown"}}function Qsn(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function j5o(e){return["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",["$ErrorActionPreference = 'Stop'",`$items = @(Get-Process -Id @(${e.join(", ")}) -ErrorAction SilentlyContinue)`,"$out = @($items | ForEach-Object { $path = try { [string]$_.Path } catch { '' }; $started = try { $_.StartTime.ToUniversalTime().ToString('o') } catch { '' }; [pscustomobject]@{ pid = [int]$_.Id; startedAt = $started; executable = $path } })","$out | ConvertTo-Json -Compress"].join("; ")]}function H5o(e){let t=new Map;try{if(!e)return t;let r=JSON.parse(e);for(let n of Array.isArray(r)?r:[r]){let i=Number(n.pid),o=Qsn(String(n.startedAt??""));!mvt(i)||!o||t.set(i,{pid:i,processStartedAt:o,hostname:HM(),...ite(n.executable)?{executableFingerprint:ite(n.executable)}:{},confidence:"observed"})}}catch{return t}return t}function V5o(e,t){let r=new Map;if(t.fresh)return{known:r,pending:e,skip:!1};let n=H4.now(),i=[];for(let o of e){let s=$ee.get(o);s&&n>=s.at&&n-s.at<Usn?s.identity&&r.set(o,s.identity):i.push(o)}return{known:r,pending:i,skip:i.length>0&&n<hvt}}function q5o(e,t){let r=H4.now();hvt=0;for(let n of e)$ee.set(n,{identity:t.get(n)??null,at:r});if($ee.size>512)for(let[n,i]of $ee)r-i.at>=Usn&&$ee.delete(n)}function W5o(){hvt=H4.now()+L5o}function J5o(e,t={}){if(!e.length)return new Map;let{known:r,pending:n,skip:i}=V5o(e,t);if(!n.length||i)return r;try{let o=H5o(H4.runSync(Q5o(),j5o(n),{timeoutMs:D5o}).trim());q5o(n,o);for(let[s,a]of o)r.set(s,a)}catch{W5o()}return r}var fee;function z5o(){if(fee)return fee;try{let e=Number.parseInt(pvt("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);fee=Number.isFinite(e)&&e>0?e:100}catch{fee=100}return fee}function X5o(){try{let e=/^btime\s+(\d+)$/m.exec(fvt("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function Y5o(e){try{let t=fvt(`/proc/${e}/stat`,"utf8"),r=t.lastIndexOf(")");if(r<0)return null;let n=t.slice(r+2).trim().split(/\s+/),i=Number(n[19]),o=X5o();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/z5o())*1e3).toISOString(),a;try{a=O5o(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:HM(),...iRe()?{bootId:iRe()}:{},...ite(a)?{executableFingerprint:ite(a)}:{},confidence:"observed"}}catch{return null}}function K5o(e){let t=new Map;if(H4.platform==="linux"){for(let r of e){let n=Y5o(r);n&&t.set(r,n)}return t}for(let r of e)try{let n=pvt("ps",["-p",String(r),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=Qsn(n);if(!i)continue;t.set(r,{pid:r,processStartedAt:i,hostname:HM(),confidence:"observed"})}catch{continue}return t}function Gsn(e,t={}){let r=[...new Set(e.filter(mvt))],n=r.includes(process.pid),i=n?r.filter(s=>s!==process.pid):r,o=H4.platform==="win32"?J5o(i,t):K5o(i);return n&&o.set(process.pid,Avt()),o}function gvt(e,t={}){return Gsn([e],t).get(e)??null}function Z5o(e,t=new Date,r=!1){return(r?gvt(e):null)??{pid:e,processStartedAt:t.toISOString(),hostname:HM(),confidence:"degraded"}}function Avt(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:HM(),...iRe()?{bootId:iRe()}:{},...Lsn(process.execPath)?{executableFingerprint:ite(process.execPath)}:{},confidence:"self"}}function ste(e,t=gvt){if(e.hostname!==HM())return{status:"remote",expected:e,reason:"Process belongs to another host."};if(ote(e.pid)==="dead")return{status:"dead",expected:e,reason:"Process ID is not live."};let r=t(e.pid);if(!r)return ote(e.pid)==="dead"?{status:"dead",expected:e,reason:"Process ID is not live."}:{status:"degraded",expected:e,reason:"Creation time could not be observed."};let n=Date.parse(e.processStartedAt),i=Date.parse(r.processStartedAt);return!Number.isFinite(n)||!Number.isFinite(i)||Math.abs(n-i)>Fsn?{status:"mismatch",expected:e,observed:r,reason:"Process creation time does not match."}:e.bootId&&r.bootId&&e.bootId!==r.bootId?{status:"mismatch",expected:e,observed:r,reason:"Host boot identity does not match."}:e.executableFingerprint&&r.executableFingerprint&&e.executableFingerprint!==r.executableFingerprint?{status:"mismatch",expected:e,observed:r,reason:"Executable identity does not match."}:{status:"live",expected:e,observed:r}}function eDo(e){return e.hostname===HM()&&ote(e.pid)==="dead"}var tDo=e=>gvt(e,{fresh:!0});function rDo(){return qw()}function VM(){return _5o(rDo(),"daemon")}function wvt(e){return ote(e)!=="dead"}var iDo=new Int32Array(new SharedArrayBuffer(4)),oDo=6e4;function yvt(e,t,r=nDo,n=oDo){let i=Date.now()+n;for(let o=0;;o++)try{r(e,t);return}catch(s){if(Date.now()>=i||!["EPERM","EACCES","EBUSY"].includes(s.code??""))throw s;Atomics.wait(iDo,0,0,Math.min(100,(o+1)*10))}}var dDo=64*1024;function uDo(e){let t;try{t=lDo(e,"r")}catch(r){if(r.code==="ENOENT")return{text:"",startOffset:0,endOffset:0,totalBytes:0};throw r}try{let r=aDo(t);if(!r.isFile()||!Number.isSafeInteger(r.size))throw new Error("Output preview requires a regular file of supported size.");let n=r.size,i=Math.max(0,n-dDo),o=Buffer.allocUnsafe(n-i),s=0;for(;s<o.length;){let d=cDo(t,o,s,o.length-s,i+s);if(d===0)throw new Error("Output changed during preview; retry.");s+=d}let a=0;if(i>0)for(;a<Math.min(3,o.length)&&(o[a]&192)===128;)a++;let l=i+a,c;try{c=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(o.subarray(a),{stream:!0})}catch{throw new Error("Output preview contains invalid UTF-8; inspect the persisted output as bytes.")}return{text:c,startOffset:l,endOffset:l+Buffer.byteLength(c,"utf8"),totalBytes:n}}finally{sDo(t)}}Xc();function Hsn(e,t){if(!e||wDo(e)!==e)throw new Error("Invalid workflow cancellation target");return jsn(t,e,"cancellation-request.json")}function kM(e,t=jsn(VM(),"workflows","runs")){let r;try{r=hDo(Hsn(e,t),"r")}catch(o){if(o.code==="ENOENT")return null;throw o}let n;try{let o=YKr(r).size;if(o>8192)throw new Error("Workflow cancellation state exceeds its 8 KiB bound; it was preserved and execution is held.");let s=Buffer.alloc(o),a=0;for(;a<o;){let l=mDo(r,s,a,o-a,a);if(!l)throw new Error("Workflow cancellation state changed during read; execution is held.");a+=l}if(YKr(r).size!==o)throw new Error("Workflow cancellation state changed during read; execution is held.");n=s.toString("utf8")}finally{pDo(r)}let i=$g(n,null);if(i?.schemaVersion!==1||i.workflowRunId!==e||typeof i.operationId!="string"||!/^[a-f0-9-]{36}$/.test(i.operationId)||typeof i.requestedAt!="string"||!Number.isFinite(Date.parse(i.requestedAt)))throw new Error("Workflow cancellation state is invalid; it was preserved and execution is held.");return i}function yDo(e,t){let r=kM(e,t);if(r)return r;let n=Hsn(e,t),i={schemaVersion:1,operationId:XKr(),workflowRunId:e,requestedAt:new Date().toISOString()},o=`${n}.${process.pid}.${XKr()}.tmp`;ADo(o,JSON.stringify(i)+`
|
|
15580
|
+
`});function UNo(){if(OTe===void 0)try{let e=(typeof import.meta=="object"?import.meta.url:void 0)??(typeof __filename=="string"?__filename:void 0),t=e?FNo(e):null;OTe=t?t("@primno/dpapi"):null}catch{OTe=null}return OTe??null}var OTe,QNo,GNo=ee(()=>{"use strict";Bs(),WKr(),WKr(),QNo=UNo()?.isPlatformSupported===!0}),lvt=ee(()=>{"use strict";YRe(),PNo(),isn(),nsn(),G4(),e7r(),mRe(),FM(),fte(),vsn(),_No(),$No(),Jyt(),MNo(),zyt(),Xyt(),GNo(),Yyt(),R7r()}),KRe=ee(()=>{"use strict"}),jNo,HNo,ZRe=ee(()=>{"use strict";pRe(),KRe(),jNo=2*1024*1024,HNo=64*1024*1024}),VNo,cvt=ee(()=>{"use strict";ZRe(),KRe(),VNo=128*1024}),Ssn=ee(()=>{"use strict"}),j4=ee(()=>{"use strict";cvt(),ZRe(),Yk(),zk(),ivt(),rvt(),msn(),Bs(),avt(),Ssn(),wc(),IRe(),lvt(),jM()}),xsn=ee(()=>{"use strict";ovt(),svt(),lvt(),j4()}),qNo=["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation","page"],WNo=["draft","pending_review","approved","rejected","superseded","archived"],JNo=["public","internal","confidential","restricted"],zNo=["agent","tool","user","system","integration"],Csn=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],Tsn=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];function YNo(e){return{algorithm:"sha256",value:XNo("sha256").update(e).digest("hex")}}function KNo(e){return JSON.stringify(yyt(e,new Set))}function ZNo(e){return YNo(KNo(e))}function yyt(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 n=e.map(i=>yyt(i,t));return t.delete(e),n}let r={};for(let n of Object.keys(e).sort((i,o)=>i.localeCompare(o))){let i=e[n];if(i===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);r[n]=yyt(i,t)}return t.delete(e),r}cRe();var e5o="[\\u0000-\\u001f\\u007f]",GHs=new RegExp(e5o),jHs=new Set(WNo),HHs=new Set(JNo),VHs=new Set(zNo),qHs=new Set(qNo),WHs=new Set(Csn),JHs=new Set(Tsn);cRe();var zHs=new Set(Csn),XHs=new Set(Tsn);yn();MM();var Rsn="0.10.110",YHs=64*1024*1024,KHs=16*1024*1024;cRe();yn();var ZHs=16*1024*1024,eVs=1024*1024,tVs=["default-src 'none'","script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net/npm/ https://cdn.tailwindcss.com https://code.jquery.com","style-src 'self' 'unsafe-inline' https://fonts.googleapis.com","font-src 'self' data: https://fonts.gstatic.com","img-src 'self' data: blob:","media-src 'self' data: blob:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; "),rVs=128*1024*1024,nVs=new TextDecoder().decode(new Uint8Array([239,191,189]));function Psn(e,t={}){for(let r of e){let n=r.codePointAt(0);if(n===127||!(n>31)&&!(n===9&&t.allowTab===!0)&&!((n===10||n===13)&&t.allowLineBreaks===!0))return!0}return!1}var t5o="xeno.recipe.v1",Tp=class extends Error{constructor(e){super(`XENO recipe is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoRecipeValidationError"}issues;code="XENO_RECIPE_INVALID"};function r5o(e){let t=RM(e,"recipe",["schemaVersion","recipeId","name","description","version","modes","inputs","requiredSecretRefs","authority","budget","steps","provenance"]),r=RM(t.authority,"authority",["permissionMode","externalActions","network"]),n=RM(t.budget,"budget",["maxAgents","maxConcurrency","maxTotalTokens","timeoutMs"]),i={schemaVersion:t.schemaVersion,recipeId:gc(t.recipeId,"recipeId"),name:gc(t.name,"name"),description:gc(t.description,"description"),version:uee(t.version,"version"),modes:EM(t.modes,"modes").map(o=>o),inputs:EM(t.inputs,"inputs").map((o,s)=>i5o(o,s)),requiredSecretRefs:EM(t.requiredSecretRefs,"requiredSecretRefs").map(o=>gc(o,"secret ref")),authority:{permissionMode:r.permissionMode,externalActions:r.externalActions,network:r.network},budget:{maxAgents:uee(n.maxAgents,"budget.maxAgents"),maxConcurrency:uee(n.maxConcurrency,"budget.maxConcurrency"),maxTotalTokens:uee(n.maxTotalTokens,"budget.maxTotalTokens"),timeoutMs:uee(n.timeoutMs,"budget.timeoutMs")},steps:EM(t.steps,"steps").map((o,s)=>o5o(o,s)),...t.provenance!==void 0?{provenance:s5o(t.provenance)}:{}};return dvt(i),i}function dvt(e){let t=[];e?.schemaVersion!==t5o&&t.push("schemaVersion must be xeno.recipe.v1"),NTe(e?.recipeId,"recipeId",t),$k(e?.name,"name",t,256),$k(e?.description,"description",t,8e3),(!Number.isSafeInteger(e?.version)||e.version<1||e.version>1e6)&&t.push("version must be a positive bounded integer"),(!Array.isArray(e?.modes)||e.modes.length<1)&&t.push("modes must contain at least one execution mode");let r=new Set;for(let s of e?.modes??[])s!=="interactive"&&s!=="headless"&&s!=="ci"&&t.push(`unsupported recipe mode ${String(s)}`),r.has(s)&&t.push(`duplicate recipe mode ${s}`),r.add(s);g5o(e?.authority?.permissionMode)||t.push("authority.permissionMode is invalid"),e?.authority?.externalActions!=="deny"&&e?.authority?.externalActions!=="approval-required"&&t.push("authority.externalActions is invalid"),e?.authority?.network!=="deny"&&e?.authority?.network!=="environment-policy"&&t.push("authority.network is invalid"),a5o(e?.budget,t);let n=new Set;for(let s of e?.inputs??[]){if(h5o(s?.name,t),n.has(s.name)&&t.push(`duplicate input ${s.name}`),n.add(s.name),$k(s?.description,`input ${s.name} description`,t,2e3),typeof s?.required!="boolean"&&t.push(`input ${s.name} required must be boolean`),s?.default!==void 0&&$k(s.default,`input ${s.name} default`,t,32e3),s?.required&&s?.default!==void 0&&t.push(`required input ${s.name} cannot define a default`),s?.enum!==void 0){(!Array.isArray(s.enum)||s.enum.length<1||s.enum.length>256)&&t.push(`input ${s.name} enum is invalid`);for(let a of s.enum??[])$k(a,`input ${s.name} enum value`,t,2e3);s.default!==void 0&&!s.enum.includes(s.default)&&t.push(`input ${s.name} default is outside its enum`)}if(s?.pattern!==void 0){$k(s.pattern,`input ${s.name} pattern`,t,1e3);try{new RegExp(s.pattern,"u")}catch{t.push(`input ${s.name} pattern is invalid`)}}}let i=new Set;for(let s of e?.requiredSecretRefs??[])/^[A-Z_][A-Z0-9_]{0,127}$/u.test(s)||t.push(`required secret ref ${s} is invalid`),i.has(s)&&t.push(`duplicate secret ref ${s}`),i.add(s);(!Array.isArray(e?.steps)||e.steps.length<1||e.steps.length>256)&&t.push("steps must contain 1 through 256 records"),Array.isArray(e?.steps)&&e.steps.length>(e?.budget?.maxAgents??0)&&t.push("budget.maxAgents must cover every recipe step");let o=new Map;for(let s of e?.steps??[]){NTe(s?.id,"step id",t),o.has(s.id)&&t.push(`duplicate step ${s.id}`),o.set(s.id,s),$k(s?.title,`step ${s.id} title`,t,2e3),s?.kind!=="agent"&&s?.kind!=="verification"&&t.push(`step ${s.id} kind is invalid`),$k(s?.prompt,`step ${s.id} prompt`,t,128e3),s?.agentProfile!==void 0&&NTe(s.agentProfile,`step ${s.id} agentProfile`,t);for(let a of s?.dependsOn??[])NTe(a,`step ${s.id} dependency`,t);s?.approval&&$k(s.approval.message,`step ${s.id} approval message`,t,8e3);for(let a of s?.expectedArtifacts??[])m5o(a,`step ${s.id} expected artifact`,t);for(let a of p5o(s?.prompt??""))n.has(a)||t.push(`step ${s.id} references unknown input ${a}`);/\{\{\s*(?:secret|env)[.:]/iu.test(s?.prompt??"")&&t.push(`step ${s.id} cannot interpolate secrets into prompts`)}for(let s of e?.steps??[])for(let a of s.dependsOn??[])o.has(a)||t.push(`step ${s.id} depends on unknown step ${a}`),a===s.id&&t.push(`step ${s.id} cannot depend on itself`);if(l5o(e?.steps??[],t),t.length>0)throw new Tp([...new Set(t)])}function n5o(e,t){if(dvt(e),!e.modes.includes(t.mode))throw new Tp([`recipe does not allow ${t.mode} mode`]);let r=t.inputs??{},n=new Map(e.inputs.map(a=>[a.name,a])),i=Object.keys(r).filter(a=>!n.has(a));if(i.length>0)throw new Tp(i.map(a=>`unknown recipe input ${a}`));let o={};for(let a of e.inputs){let l=r[a.name]??a.default;if(l===void 0){if(a.required)throw new Tp([`required recipe input ${a.name} is missing`]);o[a.name]="";continue}o[a.name]=d5o(a,l)}let s=e.requiredSecretRefs.filter(a=>t.hasSecretRef&&!t.hasSecretRef(a));if(s.length>0)throw new Tp(s.map(a=>`required secret reference is unavailable: ${a}`));return{schemaVersion:1,recipeId:e.recipeId,recipeVersion:e.version,recipeFingerprint:_sn(e),mode:t.mode,inputs:o,requiredSecretRefs:[...e.requiredSecretRefs],authority:structuredClone(e.authority),budget:structuredClone(e.budget),steps:c5o(e.steps).map(a=>({...structuredClone(a),prompt:u5o(a.prompt,o)}))}}function _sn(e){return dvt(e),{algorithm:"sha256",value:ZNo(e).value}}function i5o(e,t){let r=RM(e,`inputs[${t}]`,["name","description","required","default","enum","pattern"]);return{name:gc(r.name,`inputs[${t}].name`),description:gc(r.description,`inputs[${t}].description`),required:f5o(r.required,`inputs[${t}].required`),...r.default!==void 0?{default:gc(r.default,`inputs[${t}].default`)}:{},...r.enum!==void 0?{enum:EM(r.enum,`inputs[${t}].enum`).map(n=>gc(n,"enum value"))}:{},...r.pattern!==void 0?{pattern:gc(r.pattern,`inputs[${t}].pattern`)}:{}}}function o5o(e,t){let r=RM(e,`steps[${t}]`,["id","title","kind","prompt","dependsOn","agentProfile","approval","expectedArtifacts"]),n=r.approval===void 0?void 0:RM(r.approval,`steps[${t}].approval`,["message"]);return{id:gc(r.id,`steps[${t}].id`),title:gc(r.title,`steps[${t}].title`),kind:r.kind,prompt:gc(r.prompt,`steps[${t}].prompt`),...r.dependsOn!==void 0?{dependsOn:EM(r.dependsOn,"dependsOn").map(i=>gc(i,"dependency"))}:{},...r.agentProfile!==void 0?{agentProfile:gc(r.agentProfile,"agentProfile")}:{},...n?{approval:{message:gc(n.message,"approval message")}}:{},...r.expectedArtifacts!==void 0?{expectedArtifacts:EM(r.expectedArtifacts,"expectedArtifacts").map(i=>gc(i,"expected artifact"))}:{}}}function s5o(e){let t=RM(e,"provenance",["publisherId","source","revision"]);return{publisherId:gc(t.publisherId,"provenance.publisherId"),...t.source!==void 0?{source:gc(t.source,"provenance.source")}:{},...t.revision!==void 0?{revision:gc(t.revision,"provenance.revision")}:{}}}function a5o(e,t){(!Number.isSafeInteger(e?.maxAgents)||e.maxAgents<1||e.maxAgents>256)&&t.push("budget.maxAgents is invalid"),(!Number.isSafeInteger(e?.maxConcurrency)||e.maxConcurrency<1||e.maxConcurrency>64)&&t.push("budget.maxConcurrency is invalid"),e?.maxConcurrency>e?.maxAgents&&t.push("budget.maxConcurrency cannot exceed maxAgents"),(!Number.isSafeInteger(e?.maxTotalTokens)||e.maxTotalTokens<1||e.maxTotalTokens>1e8)&&t.push("budget.maxTotalTokens is invalid"),(!Number.isSafeInteger(e?.timeoutMs)||e.timeoutMs<1e3||e.timeoutMs>10080*60*1e3)&&t.push("budget.timeoutMs is invalid")}function l5o(e,t){let r=new Map(e.map(s=>[s.id,s])),n=new Set,i=new Set,o=s=>{if(!(i.has(s)||!r.has(s))){if(n.has(s)){t.push(`recipe step dependency cycle includes ${s}`);return}n.add(s);for(let a of r.get(s)?.dependsOn??[])o(a);n.delete(s),i.add(s)}};for(let s of e)o(s.id)}function c5o(e){let t=new Map(e.map(i=>[i.id,i])),r=new Map(e.map((i,o)=>[i.id,{step:i,index:o,dependencies:new Set(i.dependsOn??[])}])),n=[];for(;r.size>0;){let i=[...r.values()].filter(({dependencies:o})=>[...o].every(s=>!r.has(s))).sort((o,s)=>o.index-s.index);if(i.length===0)throw new Tp(["recipe step dependency graph is cyclic"]);for(let o of i)n.push(t.get(o.step.id)),r.delete(o.step.id)}return n}function d5o(e,t){let r=t.trim();if(r.length>32e3||Psn(r,{allowTab:!0,allowLineBreaks:!0}))throw new Tp([`input ${e.name} is invalid`]);if(e.enum&&!e.enum.includes(r))throw new Tp([`input ${e.name} is outside its enum`]);if(e.pattern&&!new RegExp(e.pattern,"u").test(r))throw new Tp([`input ${e.name} does not match its pattern`]);return r}function u5o(e,t){return e.replace(/\{\{\s*input\.([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/gu,(r,n)=>t[n]??"")}function p5o(e){return[...e.matchAll(/\{\{\s*input\.([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/gu)].map(t=>t[1])}function RM(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Tp([`${t} must be an object`]);let n=e,i=Object.keys(n).filter(o=>!r.includes(o));if(i.length>0)throw new Tp(i.map(o=>`${t} contains unsupported field ${o}`));return n}function EM(e,t){if(!Array.isArray(e))throw new Tp([`${t} must be an array`]);return e}function gc(e,t){if(typeof e!="string")throw new Tp([`${t} must be text`]);return e}function f5o(e,t){if(typeof e!="boolean")throw new Tp([`${t} must be boolean`]);return e}function uee(e,t){if(!Number.isSafeInteger(e))throw new Tp([`${t} must be an integer`]);return e}function NTe(e,t,r){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u.test(e))&&r.push(`${t} is invalid`)}function h5o(e,t){(typeof e!="string"||!/^[A-Za-z_][A-Za-z0-9_-]{0,127}$/u.test(e))&&t.push(`input name ${String(e)} is invalid`)}function $k(e,t,r,n){(typeof e!="string"||!e.trim()||e.length>n||Psn(e,{allowTab:!0,allowLineBreaks:!0}))&&r.push(`${t} must be non-empty bounded text`)}function m5o(e,t,r){(typeof e!="string"||!e||e.startsWith("/")||/^[A-Za-z]:[\\/]/u.test(e)||e.includes("\\")||e.split("/").some(n=>!n||n==="."||n===".."))&&r.push(`${t} must be workflow-relative`)}function g5o(e){return e==="default"||e==="plan"||e==="acceptEdits"||e==="auto"||e==="dontAsk"}yn();Bs();var Fsn=3e3,N5o=Fsn,D5o=4e3,L5o=15e3,Usn=2e3,F5o=1e4,U5o={platform:process.platform,now:()=>Date.now(),runSync:(e,t,r)=>pvt(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,stdio:["ignore","pipe","ignore"]}),run:async(e,t,r)=>(await $5o(B5o)(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeoutMs,maxBuffer:1024*1024,signal:r.signal})).stdout},H4=U5o,$ee=new Map,hvt=0,lAt;function Q5o(e=process.env){if(e===process.env&&lAt)return lAt;let t=e.SystemRoot??e.SYSTEMROOT??e.windir??e.WINDIR,r="powershell.exe";if(t&&/^[a-z]:[\\/]/i.test(t)){let n=`${t.replace(/[\\/]+$/,"")}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;Lsn(n)&&(r=n)}return e===process.env&&(lAt=r),r}function mvt(e){return Number.isInteger(e)&&e>0}function G5o(e){return M5o("sha256").update(e).digest("hex")}function ite(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${G5o(t)}`:void 0}function iRe(){if(process.platform==="linux")try{return fvt("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function ote(e){if(typeof e!="number"||!mvt(e))return"dead";try{return process.kill(e,0),"live"}catch(t){return t.code==="ESRCH"?"dead":"unknown"}}function Qsn(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function j5o(e){return["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",["$ErrorActionPreference = 'Stop'",`$items = @(Get-Process -Id @(${e.join(", ")}) -ErrorAction SilentlyContinue)`,"$out = @($items | ForEach-Object { $path = try { [string]$_.Path } catch { '' }; $started = try { $_.StartTime.ToUniversalTime().ToString('o') } catch { '' }; [pscustomobject]@{ pid = [int]$_.Id; startedAt = $started; executable = $path } })","$out | ConvertTo-Json -Compress"].join("; ")]}function H5o(e){let t=new Map;try{if(!e)return t;let r=JSON.parse(e);for(let n of Array.isArray(r)?r:[r]){let i=Number(n.pid),o=Qsn(String(n.startedAt??""));!mvt(i)||!o||t.set(i,{pid:i,processStartedAt:o,hostname:HM(),...ite(n.executable)?{executableFingerprint:ite(n.executable)}:{},confidence:"observed"})}}catch{return t}return t}function V5o(e,t){let r=new Map;if(t.fresh)return{known:r,pending:e,skip:!1};let n=H4.now(),i=[];for(let o of e){let s=$ee.get(o);s&&n>=s.at&&n-s.at<Usn?s.identity&&r.set(o,s.identity):i.push(o)}return{known:r,pending:i,skip:i.length>0&&n<hvt}}function q5o(e,t){let r=H4.now();hvt=0;for(let n of e)$ee.set(n,{identity:t.get(n)??null,at:r});if($ee.size>512)for(let[n,i]of $ee)r-i.at>=Usn&&$ee.delete(n)}function W5o(){hvt=H4.now()+L5o}function J5o(e,t={}){if(!e.length)return new Map;let{known:r,pending:n,skip:i}=V5o(e,t);if(!n.length||i)return r;try{let o=H5o(H4.runSync(Q5o(),j5o(n),{timeoutMs:D5o}).trim());q5o(n,o);for(let[s,a]of o)r.set(s,a)}catch{W5o()}return r}var fee;function z5o(){if(fee)return fee;try{let e=Number.parseInt(pvt("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);fee=Number.isFinite(e)&&e>0?e:100}catch{fee=100}return fee}function X5o(){try{let e=/^btime\s+(\d+)$/m.exec(fvt("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function Y5o(e){try{let t=fvt(`/proc/${e}/stat`,"utf8"),r=t.lastIndexOf(")");if(r<0)return null;let n=t.slice(r+2).trim().split(/\s+/),i=Number(n[19]),o=X5o();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/z5o())*1e3).toISOString(),a;try{a=O5o(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:HM(),...iRe()?{bootId:iRe()}:{},...ite(a)?{executableFingerprint:ite(a)}:{},confidence:"observed"}}catch{return null}}function K5o(e){let t=new Map;if(H4.platform==="linux"){for(let r of e){let n=Y5o(r);n&&t.set(r,n)}return t}for(let r of e)try{let n=pvt("ps",["-p",String(r),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=Qsn(n);if(!i)continue;t.set(r,{pid:r,processStartedAt:i,hostname:HM(),confidence:"observed"})}catch{continue}return t}function Gsn(e,t={}){let r=[...new Set(e.filter(mvt))],n=r.includes(process.pid),i=n?r.filter(s=>s!==process.pid):r,o=H4.platform==="win32"?J5o(i,t):K5o(i);return n&&o.set(process.pid,Avt()),o}function gvt(e,t={}){return Gsn([e],t).get(e)??null}function Z5o(e,t=new Date,r=!1){return(r?gvt(e):null)??{pid:e,processStartedAt:t.toISOString(),hostname:HM(),confidence:"degraded"}}function Avt(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:HM(),...iRe()?{bootId:iRe()}:{},...Lsn(process.execPath)?{executableFingerprint:ite(process.execPath)}:{},confidence:"self"}}function ste(e,t=gvt){if(e.hostname!==HM())return{status:"remote",expected:e,reason:"Process belongs to another host."};if(ote(e.pid)==="dead")return{status:"dead",expected:e,reason:"Process ID is not live."};let r=t(e.pid);if(!r)return ote(e.pid)==="dead"?{status:"dead",expected:e,reason:"Process ID is not live."}:{status:"degraded",expected:e,reason:"Creation time could not be observed."};let n=Date.parse(e.processStartedAt),i=Date.parse(r.processStartedAt);return!Number.isFinite(n)||!Number.isFinite(i)||Math.abs(n-i)>Fsn?{status:"mismatch",expected:e,observed:r,reason:"Process creation time does not match."}:e.bootId&&r.bootId&&e.bootId!==r.bootId?{status:"mismatch",expected:e,observed:r,reason:"Host boot identity does not match."}:e.executableFingerprint&&r.executableFingerprint&&e.executableFingerprint!==r.executableFingerprint?{status:"mismatch",expected:e,observed:r,reason:"Executable identity does not match."}:{status:"live",expected:e,observed:r}}function eDo(e){return e.hostname===HM()&&ote(e.pid)==="dead"}var tDo=e=>gvt(e,{fresh:!0});function rDo(){return qw()}function VM(){return _5o(rDo(),"daemon")}function wvt(e){return ote(e)!=="dead"}var iDo=new Int32Array(new SharedArrayBuffer(4)),oDo=6e4;function yvt(e,t,r=nDo,n=oDo){let i=Date.now()+n;for(let o=0;;o++)try{r(e,t);return}catch(s){if(Date.now()>=i||!["EPERM","EACCES","EBUSY"].includes(s.code??""))throw s;Atomics.wait(iDo,0,0,Math.min(100,(o+1)*10))}}var dDo=64*1024;function uDo(e){let t;try{t=lDo(e,"r")}catch(r){if(r.code==="ENOENT")return{text:"",startOffset:0,endOffset:0,totalBytes:0};throw r}try{let r=aDo(t);if(!r.isFile()||!Number.isSafeInteger(r.size))throw new Error("Output preview requires a regular file of supported size.");let n=r.size,i=Math.max(0,n-dDo),o=Buffer.allocUnsafe(n-i),s=0;for(;s<o.length;){let d=cDo(t,o,s,o.length-s,i+s);if(d===0)throw new Error("Output changed during preview; retry.");s+=d}let a=0;if(i>0)for(;a<Math.min(3,o.length)&&(o[a]&192)===128;)a++;let l=i+a,c;try{c=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(o.subarray(a),{stream:!0})}catch{throw new Error("Output preview contains invalid UTF-8; inspect the persisted output as bytes.")}return{text:c,startOffset:l,endOffset:l+Buffer.byteLength(c,"utf8"),totalBytes:n}}finally{sDo(t)}}Xc();function Hsn(e,t){if(!e||wDo(e)!==e)throw new Error("Invalid workflow cancellation target");return jsn(t,e,"cancellation-request.json")}function kM(e,t=jsn(VM(),"workflows","runs")){let r;try{r=hDo(Hsn(e,t),"r")}catch(o){if(o.code==="ENOENT")return null;throw o}let n;try{let o=YKr(r).size;if(o>8192)throw new Error("Workflow cancellation state exceeds its 8 KiB bound; it was preserved and execution is held.");let s=Buffer.alloc(o),a=0;for(;a<o;){let l=mDo(r,s,a,o-a,a);if(!l)throw new Error("Workflow cancellation state changed during read; execution is held.");a+=l}if(YKr(r).size!==o)throw new Error("Workflow cancellation state changed during read; execution is held.");n=s.toString("utf8")}finally{pDo(r)}let i=$g(n,null);if(i?.schemaVersion!==1||i.workflowRunId!==e||typeof i.operationId!="string"||!/^[a-f0-9-]{36}$/.test(i.operationId)||typeof i.requestedAt!="string"||!Number.isFinite(Date.parse(i.requestedAt)))throw new Error("Workflow cancellation state is invalid; it was preserved and execution is held.");return i}function yDo(e,t){let r=kM(e,t);if(r)return r;let n=Hsn(e,t),i={schemaVersion:1,operationId:XKr(),workflowRunId:e,requestedAt:new Date().toISOString()},o=`${n}.${process.pid}.${XKr()}.tmp`;ADo(o,JSON.stringify(i)+`
|
|
15581
15581
|
`,{encoding:"utf8",flag:"wx",mode:384});try{try{fDo(o,n)}catch(a){if(a.code!=="EEXIST")throw a}}finally{gDo(o)}let s=kM(e,t);if(!s)throw new Error("Workflow cancellation request is unconfirmed; inspect state before retrying.");return s}function KKr(e){return e.tags.includes("workflow")&&kM(e.rootRunId)!==null}zk();dZr();var bDo={producerVersion:Rsn,defaultModel:()=>eZr,recordCounter:(e,t,r)=>c4(e,t,r),recordHistogram:(e,t,r)=>IAt(e,t,r)},vDo=Symbol.for("xenosystem.agent-sdk.runs.runtime.v1"),IDo=globalThis;function pa(){return IDo[vDo]??bDo}var EDo=class extends Error{code="RUN_WORKER_UNAVAILABLE";constructor(){super("No run worker program is bound in this process, so a background run cannot be started here.")}};function Vsn(){let e=pa().workerInvocation;if(!e)throw new EDo;return e()}function Wsn(e=pa().producerVersion){return{createdByCliVersion:e,createdBySdkVersion:Rsn}}var LDo=1024*1024,FDo=64*1024;function UDo(e,t){let r=Math.max(1,Number.isFinite(t)?Math.trunc(t):80),n;try{n=NDo(e,"r")}catch(i){if(i.code==="ENOENT")return[];throw i}try{let i=ODo(n).size,o=Buffer.allocUnsafe(Math.min(i,LDo)),s=[],a=i,l=o.length,c=l,d=(u,p)=>{let f=o.toString("utf8",u,p).trim();if(f)try{let h=JSON.parse(f);h!==null&&s.push(h)}catch{}};for(;a>0&&l>0;){let u=Math.min(FDo,l),p=l-u;a-=u;let f=0;for(;f<u;){let h=DDo(n,o,p+f,u-f,a+f);if(h===0)throw new Error("Event journal changed during tail read; retry.");f+=h}for(let h=l-1;h>=p;h--)if(o[h]===10){if(d(h+1,c),s.length===r)return s.reverse();c=h}l=p}if(a>0)throw new Error("Event tail exceeds the 1 MiB read limit. Request fewer events or inspect the persisted event journal with a bounded file reader.");return d(0,c),s.reverse()}finally{MDo(n)}}var r9r=64*1024;function n9r(e,t){return QDo("sha256").update(JSON.stringify([VDo(e),t.dev.toString(),t.ino.toString(),t.birthtimeNs.toString(),t.size.toString(),t.mtimeNs.toString(),t.ctimeNs.toString()])).digest("hex")}function qDo(e,t={}){let r=t.maxBytes??r9r;if(!Number.isSafeInteger(r)||r<1||r>r9r)throw new Error("Event page maxBytes must be an integer from 1 to 65536.");let n=0,i;if(t.cursor!==void 0){if(typeof t.cursor!="string"||t.cursor.length>100)throw new Error("Invalid event page cursor.");let s=/^(0|[1-9][0-9]{0,15})\.([a-f0-9]{64})$/.exec(t.cursor);if(!s)throw new Error("Invalid event page cursor.");if(n=Number(s[1]),i=s[2],!Number.isSafeInteger(n))throw new Error("Invalid event page cursor.")}let o;try{o=jDo(e,"r")}catch(s){if(s.code!=="ENOENT")throw s;if(i)throw new Error("Event journal changed; restart pagination without a cursor.");return null}try{let s=t9r(o,{bigint:!0});if(!s.isFile())throw new Error("Event journal is not a regular file.");let a=Number(s.size);if(!Number.isSafeInteger(a))throw new Error("Event journal size exceeds the supported range.");let l=n9r(e,s);if(i&&i!==l||n>a)throw new Error("Event journal changed or cursor is out of range; restart pagination without a cursor.");let c=Buffer.allocUnsafe(Math.min(r,a-n)),d=0;for(;d<c.length;){let p=HDo(o,c,d,c.length-d,n+d);if(p===0)throw new Error("Event journal changed during page read; restart pagination without a cursor.");d+=p}if(n9r(e,t9r(o,{bigint:!0}))!==l)throw new Error("Event journal changed during page read; restart pagination without a cursor.");let u=n+d;return{encoding:"base64",content:c.toString("base64"),offset:n,bytesRead:d,totalBytes:a,journalVersion:l,nextCursor:u<a?`${u}.${l}`:null}}finally{GDo(o)}}function tLo(){return new Date().toISOString()}function Iyt(e){try{return JSON.parse(XDo(e,"utf8"))}catch{return null}}var vvt=3e4;function rLo(e){if(e.hostname!==Jsn())return!0;let t=Date.parse(e.acquiredAt);if(Number.isFinite(t)&&Date.now()-t<vvt)return!0;if(!wvt(e.pid))return!1;if(e.processIdentity){let r=ste(e.processIdentity);return r.status==="live"||r.status==="degraded"||r.status==="remote"}return!0}function zsn(e,t){zDo(ZDo(e),{recursive:!0});let r=`${e}.${process.pid}.${eLo()}.tmp`;KDo(r,JSON.stringify(t,null,2)+`
|
|
15582
15582
|
`,{encoding:"utf8",flag:"wx"});try{JDo(r,e)}finally{bvt(r,{force:!0})}}function nLo(e){try{return Date.now()-YDo(e).mtimeMs<vvt}catch{return!1}}function iLo(e,t){return e?.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}function Oee(e,t){return Object.assign(new Error(`${e} is already locked ${t}.`),{code:"CONTROL_PLANE_LOCK_BUSY"})}function oRe(e){return e instanceof Error&&"code"in e&&e.code==="CONTROL_PLANE_LOCK_BUSY"}function oLo(e,t,r){try{zsn(e,t)}catch(n){throw n.code==="EEXIST"?Oee(r,"by another contender"):n}}function sLo(e,t){let r=Iyt(e);r?.pid!==t.pid||r.hostname!==t.hostname||r.processStartedAt!==t.processStartedAt||bvt(e,{force:!0})}function w4(e,t,r){let n=tLo(),i=Avt(),o={schemaVersion:1,name:t,pid:process.pid,hostname:Jsn(),processStartedAt:i.processStartedAt,processIdentity:i,version:r,acquiredAt:n,updatedAt:n};try{zsn(e,o)}catch(s){if(s.code!=="EEXIST")throw s;let a=Iyt(e);if(a&&rLo(a))throw Oee(t,`by PID ${a.pid} on ${a.hostname}`);if(a){if(!iLo(Iyt(e),a))throw Oee(t,"while ownership was changing")}else{if(!WDo(e))throw Oee(t,"while ownership was changing");if(nLo(e))throw Oee(t,"by an owner whose record is still being published")}bvt(e,{force:!0}),oLo(e,o,t)}return{record:o,release:()=>{sLo(e,o)}}}yn();var dAt=64,hLo=16,i9r=16*1024*1024,o9r=15*6e4,hu=class extends Error{constructor(e,t,r){super(t,r),this.code=e,this.name="WorkflowResourceError"}code},mLo={control:1e3,foreground:900,reconciliation:850,terminal:800,"app-server":700,workflow:500,background:400,scheduled:300};function Kee(e,t,r=1,n=Number.MAX_SAFE_INTEGER){let i=typeof e=="number"?e:Number.parseInt(String(e??""),10);return Number.isFinite(i)?Math.min(n,Math.max(r,Math.trunc(i))):t}function gLo(e,t,r=0,n=Number.MAX_SAFE_INTEGER){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.min(n,Math.max(r,i)):t}function y4(e,t){return t===void 0?e:Math.min(e,t)}function Nee(e,t){return{maxConcurrency:y4(e.maxConcurrency,t?.maxConcurrency),maxCredentialConcurrency:y4(e.maxCredentialConcurrency,t?.maxCredentialConcurrency),maxRequestsPerWindow:y4(e.maxRequestsPerWindow,t?.maxRequestsPerWindow),maxTokensPerWindow:y4(e.maxTokensPerWindow,t?.maxTokensPerWindow),windowMs:t?.windowMs===void 0?e.windowMs:Math.max(1e3,t.windowMs)}}function ALo(e={}){let t=e.env??process.env,r=Math.max(1,e.cpuCount??uLo().length),n=Math.min(Math.max(1,r-2),hLo),i=Kee(t.XENO_WORKFLOW_GLOBAL_CONCURRENCY,n,1,dAt),o=t.XENO_WORKFLOW_TRUSTED_CONCURRENCY_OVERRIDE==="1"?i:Math.min(n,i);o=y4(o,e.user?.globalConcurrency),o=y4(o,e.managed?.globalConcurrency),o=Kee(o,n,1,dAt);let s={maxConcurrency:Math.min(o,8),maxCredentialConcurrency:Math.min(o,4),maxRequestsPerWindow:120,maxTokensPerWindow:2e6,windowMs:6e4},a=Nee(s,e.user?.providerDefault),l=Nee(a,e.managed?.providerDefault),c=new Set([...Object.keys(e.user?.providers??{}),...Object.keys(e.managed?.providers??{})]),d=Object.fromEntries([...c].map(p=>[p,Nee(Nee(l,e.user?.providers?.[p]),e.managed?.providers?.[p])])),u=(p,f,h=1,m=Number.MAX_SAFE_INTEGER)=>{let g=f,A=e.user?.[p],w=e.managed?.[p];return typeof A=="number"&&(g=Math.min(g,A)),typeof w=="number"&&(g=Math.min(g,w)),Kee(g,f,h,m)};return{schemaVersion:1,productHardConcurrency:dAt,globalConcurrency:o,perRunConcurrency:u("perRunConcurrency",o,1,o),perParentConcurrency:u("perParentConcurrency",o,1,o),reservedPrioritySlots:Math.min(2,Math.max(0,o-1)),maxQueueLength:u("maxQueueLength",4096,1,65536),maxQueueWaitMs:u("maxQueueWaitMs",5*6e4,1e3,1440*6e4),maxAttemptsPerLogicalChild:u("maxAttemptsPerLogicalChild",3,1,100),maxAttemptsPerRun:u("maxAttemptsPerRun",1e3,1,1e4),maxReservedTokens:u("maxReservedTokens",4e6,1,Number.MAX_SAFE_INTEGER),maxReservedCostUsd:gLo(Math.min(e.user?.maxReservedCostUsd??500,e.managed?.maxReservedCostUsd??500),500,.01,1e6),leaseTtlMs:u("leaseTtlMs",4e3,2e3,5*6e4),handoffTtlMs:Math.max(u("leaseTtlMs",4e3,2e3,5*6e4),u("handoffTtlMs",6e4,2e3,10*6e4)),heartbeatIntervalMs:u("heartbeatIntervalMs",1e3,250,6e4),maxStarvationMs:u("maxStarvationMs",3e4,1e3,60*6e4),providerDefault:l,providers:d}}function s9r(e,t){if(!Ivt(e)){if(t)throw new hu("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy file not found: ${e}`);return}try{let r=JSON.parse(Eyt(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("policy root must be an object");return r}catch(r){throw new hu("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy is invalid: ${e}: ${r instanceof Error?r.message:String(r)}`)}}function wLo(e=process.env){let t=tan(VM()),r=e.XENO_WORKFLOW_RESOURCE_POLICY?.trim(),n=e.XENO_MANAGED_WORKFLOW_RESOURCE_POLICY?.trim(),i=a=>pLo(a)?a:fLo(a),o=s9r(r?i(r):R4(t,"resource-policy.json"),!!r),s=n?s9r(i(n),!0):void 0;return ALo({env:e,user:o,managed:s})}function Ps(e){return new Date(e).toISOString()}function yLo(e){return{schemaVersion:1,revision:0,nextFencingToken:1,updatedAt:Ps(e),permits:[],queue:[],attempts:[],usage:[],providerRates:[],effects:[]}}function bLo(e){let t=e,r=p=>!!(p&&typeof p=="object"&&!Array.isArray(p)),n=p=>typeof p=="string"&&p.length>0&&p.length<=512,i=p=>typeof p=="string"&&Number.isFinite(Date.parse(p)),o=p=>r(p)&&Number.isInteger(p.pid)&&Number(p.pid)>0&&n(p.hostname)&&i(p.processStartedAt),s=p=>r(p)&&n(p.permitId)&&n(p.requestId)&&n(p.operationId)&&n(p.runId)&&n(p.providerId)&&n(p.logicalChildId)&&n(p.attemptId)&&n(p.idempotencyKey)&&Number.isInteger(p.fencingToken)&&Number(p.fencingToken)>0&&o(p.owner)&&i(p.acquiredAt)&&i(p.heartbeatAt)&&i(p.expiresAt)&&Number.isFinite(p.reservedTokens)&&Number(p.reservedTokens)>=0&&Number.isFinite(p.reservedCostUsd)&&Number(p.reservedCostUsd)>=0&&(p.handoff===void 0||r(p.handoff)&&o(p.handoff.target)&&i(p.handoff.startedAt)&&i(p.handoff.deadlineAt))&&(p.claimedAt===void 0||i(p.claimedAt)),a=p=>r(p)&&n(p.requestId)&&n(p.operationId)&&n(p.runId)&&n(p.providerId)&&n(p.logicalChildId)&&n(p.attemptId)&&n(p.idempotencyKey)&&o(p.owner)&&i(p.enqueuedAt)&&i(p.updatedAt),l=p=>r(p)&&n(p.runId)&&n(p.logicalChildId)&&n(p.attemptId)&&n(p.idempotencyKey)&&n(p.state)&&i(p.startedAt),c=p=>r(p)&&n(p.runId)&&Number.isFinite(p.tokens)&&Number(p.tokens)>=0&&Number.isFinite(p.costUsd)&&Number(p.costUsd)>=0&&Number.isInteger(p.attempts)&&Number(p.attempts)>=0&&i(p.updatedAt),d=p=>r(p)&&n(p.providerId)&&i(p.timestamp)&&Number.isFinite(p.tokens)&&Number(p.tokens)>=0,u=p=>r(p)&&n(p.effectKey)&&n(p.idempotencyKey)&&n(p.permitId)&&Number.isInteger(p.fencingToken)&&Number(p.fencingToken)>0&&n(p.state)&&i(p.claimedAt);return!!(t&&t.schemaVersion===1&&Number.isInteger(t.revision)&&Number(t.revision)>=0&&Number.isInteger(t.nextFencingToken)&&Number(t.nextFencingToken)>0&&i(t.updatedAt)&&Array.isArray(t.permits)&&t.permits.every(s)&&Array.isArray(t.queue)&&t.queue.every(a)&&Array.isArray(t.attempts)&&t.attempts.every(l)&&Array.isArray(t.usage)&&t.usage.every(c)&&Array.isArray(t.providerRates)&&t.providerRates.every(d)&&Array.isArray(t.effects)&&t.effects.every(u))}function vLo(e,t){Evt(tan(e),{recursive:!0});let r=`${e}.${process.pid}.${Ysn()}.tmp`,n=Zsn(r,"wx",384);try{ean(n,JSON.stringify(t,null,2)+`
|
|
15583
15583
|
`,"utf8"),cLo(n)}finally{Ksn(n)}lte(r,e)}function ILo(e,t,r){let n=Date.parse(e.requestedAt??""),i=Number.isFinite(n)?n:t,o=Date.parse(e.queueDeadlineAt??"");return{requestedAt:Ps(i),deadlineAt:Ps(Number.isFinite(o)?Math.min(o,i+r):i+r)}}function ran(e,t){return Nee(e.providerDefault,e.providers[t])}function a9r(e,t,r){let n=Math.max(0,t-Date.parse(e.enqueuedAt));return mLo[e.priorityClass]+Math.floor(n/r.maxStarvationMs)*1001}function ELo(e,t,r){return[...e].sort((n,i)=>a9r(i,t,r)-a9r(n,t,r)||Date.parse(n.enqueuedAt)-Date.parse(i.enqueuedAt)||n.requestId.localeCompare(i.requestId))}function l9r(e,t){return e.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt}function b4(e){return Number.isFinite(e)?Math.max(0,Number(e)):0}function c9r(e,t,r,n){let i=e.permits;if(i.length>=r.globalConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"global_concurrency"};if(!(t.priorityClass==="control"||t.priorityClass==="foreground"||t.priorityClass==="reconciliation"||t.priorityClass==="terminal")&&i.length>=Math.max(0,r.globalConcurrency-r.reservedPrioritySlots))return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"reserved_priority_capacity"};let o=Math.min(r.perRunConcurrency,Kee(t.runConcurrencyLimit,r.perRunConcurrency,1,r.globalConcurrency));if(i.filter(A=>A.runId===t.runId).length>=o)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"run_concurrency"};if(t.parentId&&i.filter(A=>A.parentId===t.parentId).length>=r.perParentConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"parent_concurrency"};let s=ran(r,t.providerId);if(i.filter(A=>A.providerId===t.providerId).length>=s.maxConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"provider_concurrency"};if(t.credentialFingerprint&&i.filter(A=>A.providerId===t.providerId&&A.credentialFingerprint===t.credentialFingerprint).length>=s.maxCredentialConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"credential_concurrency"};if(i.some(A=>A.logicalChildId===t.logicalChildId))return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"logical_child_active"};let a=new Set(e.attempts.filter(A=>A.logicalChildId===t.logicalChildId).map(A=>A.attemptId));if(!a.has(t.attemptId)&&a.size>=r.maxAttemptsPerLogicalChild)return{code:"WORKFLOW_ATTEMPT_LIMIT",reason:"logical_child_attempt_limit"};let l=new Set(e.attempts.filter(A=>A.runId===t.runId).map(A=>A.attemptId)),c=Math.min(r.maxAttemptsPerRun,Kee(t.runAttemptLimit,r.maxAttemptsPerRun,1,r.maxAttemptsPerRun));if(!l.has(t.attemptId)&&l.size>=c)return{code:"WORKFLOW_ATTEMPT_LIMIT",reason:"run_attempt_limit"};let d=b4(t.reservedTokens);if(i.reduce((A,w)=>A+w.reservedTokens,0)+d>r.maxReservedTokens)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"global_token_reservation"};let u=b4(t.reservedCostUsd);if(i.reduce((A,w)=>A+w.reservedCostUsd,0)+u>r.maxReservedCostUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"global_cost_reservation"};let p=e.usage.find(A=>A.runId===t.runId),f=i.filter(A=>A.runId===t.runId).reduce((A,w)=>A+w.reservedTokens,0);if(t.runTokenLimit!==void 0&&(p?.tokens??0)+f+d>t.runTokenLimit)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"run_token_limit"};let h=i.filter(A=>A.runId===t.runId).reduce((A,w)=>A+w.reservedCostUsd,0);if(t.runCostLimitUsd!==void 0&&(p?.costUsd??0)+h+u>t.runCostLimitUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"run_cost_limit"};let m=n-s.windowMs,g=e.providerRates.filter(A=>A.providerId===t.providerId&&Date.parse(A.timestamp)>=m&&(!t.credentialFingerprint||A.credentialFingerprint===t.credentialFingerprint));return g.length>=s.maxRequestsPerWindow?{reason:"provider_request_rate"}:g.reduce((A,w)=>A+w.tokens,0)+d>s.maxTokensPerWindow?{reason:"provider_token_rate"}:{}}function kLo(e){for(let[t,r]of Object.entries({requestId:e.requestId,operationId:e.operationId,runId:e.runId,providerId:e.providerId,logicalChildId:e.logicalChildId,attemptId:e.attemptId,idempotencyKey:e.idempotencyKey}))if(typeof r!="string"||!r.trim()||r.length>512)throw new hu("WORKFLOW_GOVERNOR_UNAVAILABLE",`Invalid resource request field: ${t}.`);if(e.credentialFingerprint&&!/^(?:cred_)?sha256_[a-f0-9]{32,64}$/i.test(e.credentialFingerprint))throw new hu("WORKFLOW_GOVERNOR_UNAVAILABLE","credentialFingerprint must be a scoped SHA-256 fingerprint.")}function nan(e,t){let r=String(e??"default").trim().toLowerCase().split(/[/:]/,1)[0]||"default",n=t?.trim()?Xsn("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16):"default";return`${r}@${n}`}function SLo(e){let t=Xsn("sha256");return t.update(e.salt),t.update("\0"),t.update(e.providerId),t.update("\0"),t.update(e.endpoint?.trim().toLowerCase()??""),t.update("\0"),t.update(e.credential),`cred_sha256_${t.digest("hex")}`}function xLo(e=R4(VM(),"governor")){let t=R4(e,"credential-salt.bin");if(Evt(e,{recursive:!0}),Ivt(t))return Eyt(t);let r=aLo(32);try{return ean(t,r,{flag:"wx",mode:384}),r}catch{return Eyt(t)}}function CLo(e,t=process.env,r){let n=e.split("@",1)[0]?.toLowerCase(),i=(n==="anthropic"||n==="claude"?["ANTHROPIC_API_KEY","XENO_API_KEY"]:n==="openai"||n==="gpt"?["OPENAI_API_KEY","XENO_API_KEY"]:n==="google"||n==="gemini"?["GOOGLE_API_KEY","GEMINI_API_KEY","XENO_API_KEY"]:["XENO_API_KEY","ANTHROPIC_API_KEY","OPENAI_API_KEY","GOOGLE_API_KEY","GEMINI_API_KEY"]).map(o=>t[o]?.trim()).find(Boolean);return i?SLo({providerId:e,endpoint:r,credential:i,salt:xLo()}):void 0}var $T=class{policy;rootDir;ledgerPath;lockPath;now;owner;fault;constructor(e={}){this.rootDir=e.rootDir??R4(VM(),"governor"),this.ledgerPath=R4(this.rootDir,"resource-ledger.json"),this.lockPath=R4(this.rootDir,"resource-ledger.lock"),this.policy=e.policy??wLo(),this.now=e.now??Date.now,this.owner=e.owner??Avt,this.fault=e.fault,Evt(this.rootDir,{recursive:!0})}acquire(e){kLo(e);let t=0,r=this.withLedger((s,a)=>{this.cleanupExpired(s,a);let l=s.permits.find(b=>b.requestId===e.requestId||b.attemptId===e.attemptId);if(l)return t=s.permits.length,{value:{status:"active",permit:l,reason:"attempt_already_active"},changed:!0};let c=ILo(e,a,this.policy.maxQueueWaitMs);if(a>Date.parse(c.deadlineAt))return{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!1};let d=s.queue.find(b=>b.requestId===e.requestId);if(d&&a>Date.parse(d.queueDeadlineAt??c.deadlineAt))return s.queue=s.queue.filter(b=>b.requestId!==e.requestId),{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!0};if(!d&&s.queue.length>=this.policy.maxQueueLength)return{value:{status:"rejected",code:"WORKFLOW_QUEUE_FULL",reason:"The host workflow queue is full."},changed:!1};let u=e.owner??this.owner(),p=d?{...d,...e,owner:d.owner,updatedAt:Ps(a)}:{...e,owner:u,requestedAt:c.requestedAt,queueDeadlineAt:c.deadlineAt,enqueuedAt:Ps(a),updatedAt:Ps(a)};d?s.queue=s.queue.map(b=>b.requestId===p.requestId?p:b):s.queue.push(p);let f=ELo(s.queue,a,this.policy),h,m={};for(let b of f){let I=c9r(s,b,this.policy,a);if(b.requestId===p.requestId&&(m=I),!I.reason){h=b;break}}if(m.code==="WORKFLOW_ATTEMPT_LIMIT"||m.code==="WORKFLOW_TOKEN_LIMIT"||m.code==="WORKFLOW_COST_LIMIT")return s.queue=s.queue.filter(b=>b.requestId!==p.requestId),{value:{status:"rejected",code:m.code,reason:m.reason??"resource_limit"},changed:!0};if(!h||h.requestId!==p.requestId){let b=s.permits.map(S=>Date.parse(S.expiresAt)).filter(Number.isFinite).sort((S,x)=>S-x)[0],I=ran(this.policy,p.providerId),v=s.providerRates.filter(S=>S.providerId===p.providerId&&(!p.credentialFingerprint||S.credentialFingerprint===p.credentialFingerprint)).map(S=>Date.parse(S.timestamp)+I.windowMs).filter(S=>Number.isFinite(S)&&S>a).sort((S,x)=>S-x)[0],E=[b,v].filter(S=>typeof S=="number").sort((S,x)=>S-x)[0];return{value:{status:"queued",request:p,reason:m.reason??"waiting_for_fair_turn",...E?{estimatedEligibleAt:Ps(E)}:{}},changed:!0}}let g=c9r(s,p,this.policy,a);if(g.reason)return g.code==="WORKFLOW_ATTEMPT_LIMIT"||g.code==="WORKFLOW_TOKEN_LIMIT"||g.code==="WORKFLOW_COST_LIMIT"?(s.queue=s.queue.filter(b=>b.requestId!==p.requestId),{value:{status:"rejected",code:g.code,reason:g.reason},changed:!0}):{value:{status:"queued",request:p,reason:g.reason},changed:!0};let A=Ps(a),w={permitId:`permit_${Ysn()}`,requestId:p.requestId,operationId:p.operationId,surface:p.surface,priorityClass:p.priorityClass,runId:p.runId,...p.parentId?{parentId:p.parentId}:{},providerId:p.providerId,...p.credentialFingerprint?{credentialFingerprint:p.credentialFingerprint}:{},logicalChildId:p.logicalChildId,attemptId:p.attemptId,idempotencyKey:p.idempotencyKey,fencingToken:s.nextFencingToken++,owner:p.owner,acquiredAt:A,heartbeatAt:A,expiresAt:Ps(a+this.policy.leaseTtlMs),reservedTokens:b4(p.reservedTokens),reservedCostUsd:b4(p.reservedCostUsd),lastDurableSequence:0};s.queue=s.queue.filter(b=>b.requestId!==p.requestId),s.permits.push(w),t=s.permits.length;let y=s.attempts.find(b=>b.attemptId===p.attemptId);return y?Object.assign(y,{state:"active",permitId:w.permitId,operationId:p.operationId,endedAt:void 0,outcome:void 0,refusedClaim:void 0}):s.attempts.push({runId:p.runId,operationId:p.operationId,logicalChildId:p.logicalChildId,attemptId:p.attemptId,idempotencyKey:p.idempotencyKey,state:"active",permitId:w.permitId,startedAt:A}),s.providerRates.push({providerId:p.providerId,...p.credentialFingerprint?{credentialFingerprint:p.credentialFingerprint}:{},timestamp:A,tokens:w.reservedTokens}),this.fault?.("acquire.before_commit"),{value:{status:"acquired",permit:w},changed:!0,afterCommit:()=>this.fault?.("acquire.after_commit")}}),n=r.status==="rejected"?r.code:r.status==="acquired"?"admitted":r.reason;pa().recordCounter("xeno.workflow.admission_results",1,{component:"resource_governor",provider:e.providerId,state:r.status,reason:n,...r.status==="rejected"?{error_code:r.code}:{}}),(n==="provider_request_rate"||n==="provider_token_rate"||n==="provider_concurrency"||n==="credential_concurrency")&&pa().recordCounter("xeno.workflow.provider_throttles",1,{component:"resource_governor",provider:e.providerId,reason:n});let i=Date.parse((r.status==="queued"?r.request.requestedAt:e.requestedAt)??""),o=r.status==="acquired"||r.status==="active"?Date.parse(r.permit.acquiredAt):this.now();return Number.isFinite(i)&&Number.isFinite(o)&&pa().recordHistogram("xeno.workflow.queue_wait_ms",Math.max(0,o-i),{component:"resource_governor",provider:e.providerId,state:r.status}),t>0&&pa().recordHistogram("xeno.workflow.active_concurrency",t,{component:"resource_governor",provider:e.providerId}),r}heartbeat(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r),i=e.owner??this.owner();if(!l9r(n.owner,i))throw new hu("WORKER_IDENTITY_MISMATCH","Permit heartbeat came from a different worker identity.");return n.heartbeatAt=Ps(r),n.expiresAt=Ps(r+this.policy.leaseTtlMs),n.lastDurableSequence=Math.max(n.lastDurableSequence,Math.max(0,e.lastDurableSequence??0)),{value:{...n},changed:!0}})}assertFence(e,t){return this.withLedger((r,n)=>({value:{...this.currentPermit(r,e,t,n)},changed:!1}))}beginHandoff(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r);if(n.claimedAt)return{value:{...n},changed:!1};let i=Math.max(Date.parse(n.expiresAt),r+this.policy.handoffTtlMs);return n.handoff={target:{...e.target},startedAt:Ps(r),deadlineAt:Ps(i)},n.owner={...e.target},n.expiresAt=Ps(i),{value:{...n},changed:!0}})}transfer(e,t,r){let n=this.withLedger((i,o)=>{this.cleanupExpired(i,o);let s=l=>{let c=i.attempts.find(d=>d.permitId===e);return c?(c.refusedClaim={pid:r.pid,code:l.code,at:Ps(o)},{value:{error:l},changed:!0}):{value:{error:l},changed:!1}},a=i.permits.find(l=>l.permitId===e);if(!a||a.fencingToken!==t){let l=i.attempts.find(c=>c.permitId===e);return s(l?.outcome==="WORKER_HANDOFF_EXPIRED"||l?.outcome==="WORKER_HANDOFF_ABANDONED"?new hu("WORKER_HANDOFF_EXPIRED",`The worker hand-off window closed (${l.outcome} at ${l.endedAt??"unknown"}) before this worker claimed its permit.`):new hu("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out."))}if(a.handoff){let l=a.handoff.target;if(l.pid!==r.pid||l.hostname!==r.hostname)return s(new hu("WORKER_IDENTITY_MISMATCH","The permit hand-off is bound to a different worker process."))}else if(a.claimedAt&&!l9r(a.owner,r))return s(new hu("WORKER_IDENTITY_MISMATCH","The permit is already claimed by another worker process."));return a.owner=r,delete a.handoff,a.claimedAt??=Ps(o),a.heartbeatAt=Ps(o),a.expiresAt=Ps(o+this.policy.leaseTtlMs),{value:{permit:{...a}},changed:!0}});if("error"in n)throw n.error;return n.permit}settle(e){return this.withLedger((t,r)=>{let n=t.permits.find(a=>a.permitId===e.permitId);if(!n)return{value:!1,changed:!1};if(n.fencingToken!==e.fencingToken||Date.parse(n.expiresAt)<=r)throw new hu("WORKER_LEASE_EXPIRED","The worker fencing token is stale.");t.permits=t.permits.filter(a=>a.permitId!==n.permitId);let i=t.attempts.find(a=>a.attemptId===n.attemptId);i&&Object.assign(i,{state:"settled",endedAt:Ps(r),outcome:e.outcome});let o=t.usage.find(a=>a.runId===n.runId),s={runId:n.runId,tokens:(o?.tokens??0)+b4(e.actualTokens),costUsd:(o?.costUsd??0)+b4(e.actualCostUsd),attempts:(o?.attempts??0)+1,updatedAt:Ps(r)};return t.usage=[...t.usage.filter(a=>a.runId!==n.runId),s],{value:!0,changed:!0}})}settleOperation(e,t,r=0,n=0){let i=this.snapshot().permits.find(o=>o.operationId===e);return i?this.settle({permitId:i.permitId,fencingToken:i.fencingToken,outcome:t,actualTokens:r,actualCostUsd:n}):!1}cancelQueued(e){return this.withLedger(t=>{let r=t.queue.some(n=>n.requestId===e);return t.queue=t.queue.filter(n=>n.requestId!==e),{value:r,changed:r}})}claimEffect(e){return this.withLedger((t,r)=>{let n=this.currentPermit(t,e.permitId,e.fencingToken,r),i=t.effects.find(o=>o.effectKey===e.effectKey||o.idempotencyKey===n.idempotencyKey);return i?{value:i.permitId===n.permitId&&i.fencingToken===n.fencingToken&&i.state==="claimed",changed:!1}:(t.effects.push({effectKey:e.effectKey,idempotencyKey:n.idempotencyKey,permitId:n.permitId,fencingToken:n.fencingToken,state:"claimed",claimedAt:Ps(r)}),{value:!0,changed:!0})})}commitEffect(e){return this.withLedger((t,r)=>{this.currentPermit(t,e.permitId,e.fencingToken,r);let n=t.effects.find(i=>i.effectKey===e.effectKey);return!n||n.permitId!==e.permitId||n.fencingToken!==e.fencingToken?{value:!1,changed:!1}:n.state==="committed"?{value:!0,changed:!1}:(n.state="committed",n.committedAt=Ps(r),{value:!0,changed:!0})})}reconcile(e){let t=this.withLedger((r,n)=>{let i=[...r.permits],o=[...r.queue],s=e??Gsn(i.map(A=>A.owner.pid)),a=new Set,l=new Set,c=new Set;for(let A of i){let w=ste(A.owner,y=>s.get(y)??null);if(A.handoff){let y=w.status==="mismatch"&&w.observed&&Date.parse(w.observed.processStartedAt)>Date.parse(A.owner.processStartedAt);w.status==="dead"||y?c.add(A.permitId):w.status!=="live"&&l.add(A.permitId);continue}w.status==="mismatch"&&a.add(A.permitId),(w.status==="degraded"||w.status==="remote")&&l.add(A.permitId)}this.cleanupExpired(r,n,a,c);let d=new Set(r.permits.map(A=>A.permitId)),u=i.filter(A=>!d.has(A.permitId)&&!a.has(A.permitId)),p=i.filter(A=>a.has(A.permitId)),f=new Set(r.queue.map(A=>A.requestId)),h=o.filter(A=>!f.has(A.requestId)),m=new Map(r.effects.map(A=>[A.permitId,A.fencingToken]));for(let A of i)m.set(A.permitId,A.fencingToken);let g=new Map(r.attempts.filter(A=>A.state==="expired"&&A.permitId&&(A.outcome==="WORKER_HANDOFF_EXPIRED"||A.outcome==="WORKER_HANDOFF_ABANDONED")&&n-Date.parse(A.endedAt??"")<=o9r).map(A=>[A.attemptId,{...A.operationId?{operationId:A.operationId}:{},permitId:A.permitId,fencingToken:m.get(A.permitId)??0,outcome:A.outcome,...A.endedAt?{endedAt:A.endedAt}:{},...A.refusedClaim?{refusedClaim:{...A.refusedClaim}}:{}}]));return{value:{expiredPermits:u,handoffFailures:g,identityMismatches:p,expiredQueue:h,livePermits:r.permits.length,degradedPermits:r.permits.filter(A=>l.has(A.permitId)).length},changed:u.length>0||p.length>0||h.length>0}});return pa().recordHistogram("xeno.worker.live_leases",t.livePermits,{component:"resource_governor",operation:"reconcile"}),pa().recordHistogram("xeno.worker.degraded_leases",t.degradedPermits,{component:"resource_governor",operation:"reconcile"}),t.expiredPermits.length>0&&pa().recordCounter("xeno.worker.lease_expirations",t.expiredPermits.length,{component:"resource_governor",operation:"reconcile"}),t.identityMismatches.length>0&&pa().recordCounter("xeno.worker.identity_mismatches",t.identityMismatches.length,{component:"resource_governor",operation:"reconcile"}),t}snapshot(){return this.withLedger(e=>({value:structuredClone(e),changed:!1}))}recentHandoffFailureOperations(){return this.withLedger((e,t)=>({value:[...new Set(e.attempts.filter(r=>r.operationId&&r.state==="expired"&&(r.outcome==="WORKER_HANDOFF_EXPIRED"||r.outcome==="WORKER_HANDOFF_ABANDONED")&&t-Date.parse(r.endedAt??"")<=o9r).map(r=>r.operationId))],changed:!1}))}cleanupExpired(e,t,r=new Set,n=new Set){let i=new Map(e.permits.filter(s=>Date.parse(s.expiresAt)<=t||r.has(s.permitId)||n.has(s.permitId)).map(s=>[s.permitId,s]));if(i.size>0){e.permits=e.permits.filter(s=>!i.has(s.permitId));for(let s of e.attempts)s.permitId&&i.has(s.permitId)&&s.state==="active"&&(s.state="expired",s.endedAt=Ps(t),s.outcome=r.has(s.permitId)?"WORKER_IDENTITY_MISMATCH":n.has(s.permitId)?"WORKER_HANDOFF_ABANDONED":i.get(s.permitId)?.handoff?"WORKER_HANDOFF_EXPIRED":"WORKER_LEASE_EXPIRED")}e.queue=e.queue.filter(s=>Date.parse(s.queueDeadlineAt??s.updatedAt)>t);let o=Math.max(this.policy.providerDefault.windowMs,...Object.values(this.policy.providers).map(s=>s.windowMs??0));if(e.providerRates=e.providerRates.filter(s=>Date.parse(s.timestamp)>t-o),e.attempts.length>2e4){let s=e.attempts.filter(l=>l.state==="active"),a=e.attempts.filter(l=>l.state!=="active").slice(-Math.max(0,2e4-s.length));e.attempts=[...a,...s]}e.effects.length>2e4&&(e.effects=e.effects.slice(-2e4)),e.usage.length>1e4&&(e.usage=e.usage.slice(-1e4))}currentPermit(e,t,r,n){let i=e.permits.find(o=>o.permitId===t);if(!i||Date.parse(i.expiresAt)<=n||i.fencingToken!==r)throw new hu("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out.");return i}readLedger(e){if(!Ivt(this.ledgerPath))return yLo(e);let t;try{t=Zsn(this.ledgerPath,"r");let r=lLo(t).size;if(!Number.isSafeInteger(r)||r>i9r)throw new Error(`ledger exceeds the ${i9r} byte limit`);let n=Buffer.alloc(r),i=0;for(;i<r;){let a=dLo(t,n,i,r-i,i);if(a===0)throw new Error("Resource ledger changed during read");i+=a}let o=n.toString("utf8"),s=JSON.parse(o);if(!bLo(s))throw new Error("Unsupported resource ledger schema.");return s}catch(r){throw new hu("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource ledger is unreadable and was not overwritten: ${r instanceof Error?r.message:String(r)}`)}finally{t!==void 0&&Ksn(t)}}withLedger(e){let t=Date.now()+vvt+5e3,r=new Int32Array(new SharedArrayBuffer(4)),n,i;for(;!n&&Date.now()<=t;)try{n=w4(this.lockPath,"workflow-resource-governor",pa().producerVersion)}catch(o){if(i=o,!(o instanceof Error)||!o.message.includes("is already locked"))break;Atomics.wait(r,0,0,10)}if(!n)throw new hu("WORKFLOW_GOVERNOR_UNAVAILABLE",i instanceof Error?i.message:String(i??"Resource governor lock unavailable."),{cause:i});try{let o=this.now(),s=this.readLedger(o),a=e(s,o);return a.changed&&(s.revision+=1,s.updatedAt=Ps(o),vLo(this.ledgerPath,s)),a.afterCommit?.(),a.value}finally{n.release()}}};function TLo(e){return{XENO_RESOURCE_PERMIT_ID:e.permitId,XENO_RESOURCE_FENCING_TOKEN:String(e.fencingToken),XENO_RESOURCE_OPERATION_ID:e.operationId,XENO_RESOURCE_IDEMPOTENCY_KEY:e.idempotencyKey}}function RLo(e=process.env){let t=e.XENO_RESOURCE_PERMIT_ID?.trim(),r=Number.parseInt(e.XENO_RESOURCE_FENCING_TOKEN??"",10);return t&&Number.isInteger(r)&&r>0?{permitId:t,fencingToken:r}:null}function uAt(e,t,r=process.env){if(r.XENO_RESOURCE_OPERATION_ID?.trim()!==e)return;let n=RLo(r);if(!t||!n||t.permitId!==n.permitId||t.fencingToken!==n.fencingToken)throw new hu("WORKER_LEASE_EXPIRED","Worker state write rejected because its fencing token is stale.");new $T().assertFence(n.permitId,n.fencingToken)}Xk();Xk();NM();NM();zk();vZr();Xk();dte();Lyt();Fyt();dte();var PLo=1,hM={streaming:!0,textInput:!0,imageInput:!0,tools:!0,parallelToolCalls:!0,structuredOutput:!1,reasoningMetadata:!0,usageAccounting:!0,promptCaching:!1,modelDiscovery:!0},LTe={...hM,reasoningMetadata:!1},GVs=[Tv("xeno","XENO hosted","xeno","openai-compatible","https://api.xenosystem.ai","public-https","bearer-env","XENO_API_KEY","/v1/models",hM),Tv("openai","OpenAI","direct","openai-responses","https://api.openai.com","public-https","bearer-env","OPENAI_API_KEY","/v1/models",hM),Tv("anthropic","Anthropic","direct","anthropic","https://api.anthropic.com","public-https","header-env","ANTHROPIC_API_KEY","/v1/models",{...hM,structuredOutput:!1}),Tv("google","Google AI Studio","direct","google","https://generativelanguage.googleapis.com","public-https","header-env","GOOGLE_API_KEY","/v1beta/models",hM),Tv("openrouter","OpenRouter","gateway","openai-compatible","https://openrouter.ai/api","public-https","bearer-env","OPENROUTER_API_KEY","/v1/models",LTe),Tv("xeno-rt","xeno-rt","local","openai-compatible","http://127.0.0.1:3338","local-network","none",void 0,"/v1/models",LTe,["running xeno-rt endpoint"]),Tv("ollama","Ollama","local","openai-compatible","http://127.0.0.1:11434","local-network","none",void 0,"/v1/models",LTe,["Ollama OpenAI compatibility endpoint"]),Tv("azure-openai","Azure OpenAI","cloud","openai-compatible",void 0,"public-https","header-env","AZURE_OPENAI_API_KEY",void 0,LTe,["resource endpoint","deployment","API version","host adapter for deployment-shaped requests"]),Tv("aws-bedrock","Amazon Bedrock","cloud","aws-bedrock",void 0,"public-https","cloud-chain",void 0,void 0,{...hM,modelDiscovery:!1},["AWS credential chain","region","Bedrock host adapter"]),Tv("vertex-ai","Google Vertex AI","cloud","vertex-ai",void 0,"public-https","cloud-chain",void 0,void 0,{...hM,modelDiscovery:!1},["Google application-default credentials","project","region","Vertex host adapter"])];function Tv(e,t,r,n,i,o,s,a,l,c,d=[]){return{schemaVersion:PLo,id:e,displayName:t,family:r,adapterKind:n,...i?{defaultBaseUrl:i}:{},endpointProfile:o,...i?{allowedHosts:[new URL(i).hostname]}:{},auth:{mode:s,...a?{defaultSecretRef:a}:{},...s==="header-env"?{header:_Lo(e)}:{},description:s==="none"?"No credential required":s==="cloud-chain"?"Provider-owned cloud credential chain":`Environment/credential reference ${a}`},capabilities:c,...l?{discoveryPath:l}:{},requires:d}}function _Lo(e){return e==="anthropic"?"x-api-key":e==="google"?"x-goog-api-key":e==="azure-openai"?"api-key":"authorization"}yn();MM();B4();B4();LM();uRe();yn();Xc();Qyt();hRe();var ian=new Set(["browser.navigate","browser.back","browser.forward","browser.reload","browser.wait","browser.snapshot","browser.screenshot","browser.locate","browser.tabs.list","browser.tabs.open","browser.console.read","browser.network.read","browser.storage.read","browser.page-errors.read"]),oan=new Set(["browser.click","browser.type","browser.key","browser.select","browser.scroll","browser.tabs.close","browser.upload","browser.download","browser.record.start","browser.record.stop"]),san=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),aan=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),kvt=[...ian,...oan,...san,...aan];function BLo(e){if(ian.has(e))return{operation:e,surface:"browser",effect:"observe",evidence:{before:"disabled",after:e==="browser.wait"||e==="browser.tabs.list"?"optional":"required",recording:"optional"}};if(oan.has(e)){let t=e==="browser.record.start"||e==="browser.record.stop";return{operation:e,surface:"browser",effect:"act",evidence:{before:"required",after:"required",recording:e==="browser.record.stop"?"required":"optional"}}}if(san.has(e))return{operation:e,surface:"computer",effect:"observe",evidence:{before:"disabled",after:e==="computer.wait"?"optional":"required",recording:"optional"}};if(aan.has(e))return{operation:e,surface:"computer",effect:"act",evidence:{before:"required",after:"required",recording:"optional"}};throw new TypeError(`Unsupported XENO automation operation: ${e}`)}$d();var jVs=new Set(["Read","Glob","Grep","LS","GitStatus","GitDiff","GitLog","WebFetch","WebSearch","MemoryRead","NotebookRead","ReadImage","SqliteAnalyze","ElfAnalyze","GcodeAnalyze","HtmlSanitizerAudit","ArtifactCompare","Think","ToolSearch","Skill",...kvt.filter(e=>BLo(e).effect==="observe")]);Xyt();var HVs=32*1024*1024,VVs=1024*1024*1024,qVs=16*1024*1024,WVs=48*1024*1024;fte();var JVs=4*1024*1024;fte();Xyt();var zVs=8*1024*1024;Yyt();var XVs=kvt.filter(e=>e.startsWith("browser.")),YVs=kvt.filter(e=>e.startsWith("computer."));ARe();k7r();S7r();Kyt();Bs();Kyt();FM();Yk();Yk();zk();Yk();Xc();Xc();Yk();Xc();wRe();B2e();ivt();psn();fsn();hsn();ssn();nvt();csn();dsn();usn();tsn();jM();msn();asn();lsn();pte();QM();mte();ovt();kbt();rvt();gsn();svt();avt();IRe();nin();bsn();sbt();sbt();lvt();KRe();ZRe();cvt();yn();Bs();pRe();ZRe();cvt();KRe();jM();pbt();gte();_en();Won();fbt();Den();Fen();FT();Zen();stn();Xtn();orn();srn();lrn();frn();vbt();$Re();gon();urn();yrn();vrn();yin();Iin();Min();Fin();Hin();Yin();oon();don();Son();$on();Non();Lon();jon();Hon();Kon();$d();es();var $Lo=["completed","partial","failed","cancelled"],KVs=["queued","running",...$Lo];XRe();Fv();yn();MM();MM();Bs();var MLo=lan(qw(),"daemon"),nqs=lan(MLo,"runs");yn();Bs();Bs();MM();Yon();evt();var OLo=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,iqs=new RegExp(String.raw`${OLo}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i");evt();yn();var oqs=512*1024*1024,sqs=10080*60*1e3,aqs=365*24*60*60*1e3;yn();MM();Bs();B4();var lqs=8*1024*1024,cqs=64*1024*1024,dqs=744*60*60*1e3;LM();var uqs=Object.freeze({"thread.run":"prompt","turn.start":"input","turn.steer":"input","schedule.create":"prompt","schedule.update":"prompt"}),NLo=["Read","Write","Edit","Glob","Grep","WebFetch"],pqs=new Set(NLo);j4();XRe();XRe();yn();U4();Fv();yn();var DLo=["initialize","capabilities.get","thread.start","thread.get","thread.list","thread.resume","thread.archive","thread.delete","turn.start","turn.get","turn.lookup","turn.steer","turn.interrupt","events.subscribe","events.unsubscribe","events.poll","events.replay","permission.respond","integrations.list","execution.acquire","execution.renew","execution.release","handoff.prepare","handoff.claim","handoff.complete","handoff.status","handoff.cancel"];Bs();var fqs=new Set(DLo);wRe();vRe();mte();yn();Xc();wc();yte();var d9r=new Map;function LLo(e,t){return e!=null&&e.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}function FLo(){for(let[e,t]of d9r)try{let r=$g(ePe.readFileSync(e,"utf8"),null);LLo(r,t)&&ePe.unlinkSync(e)}catch{}d9r.clear()}BRe(FLo);obt();yn();Xc();vRe();mte();obt();wRe();LM();bRe();wc();mte();vRe();$Re();Q7r();bRe();z7r();$d();Va();var hqs=64*1024*1024,ULo=8*1024*1024,mqs=4*Math.ceil(ULo/3);wc();ivt();jM();YRe();var gqs=300*1e3;wc();ute();j4();xsn();QM();kbt();svt();xsn();j4();U4();j4();jM();Xc();Yk();YRe();FM();$d();DT();wc();Ssn();Yk();avt();IRe();Xc();Xc();Yk();Bs();var Aqs=1024*1024;FM();wc();FT();wc();var bqs={enabled:!0,executionTimeout:3e4,maxMemory:50*1024*1024,allowedHosts:[],blockedPaths:[]};yn();wc();var vqs=GLo(QLo);wc();var Iqs=1024*1024;yn();wc();j4();jM();Xk();zk();B2e();ute();var u9r=1e8,p9r=10080*60*1e3,pAt=class extends Error{constructor(e,t){super(t),this.code=e,this.name="SessionBudgetError"}code};function jLo(e,t){if(e===void 0)return;let{maxTokens:r,deadlineMs:n}=e;if(r!==void 0&&(!Number.isSafeInteger(r)||r<1||r>u9r))throw new pAt("SESSION_BUDGET_INVALID",`A session token budget must be a whole number from 1 to ${u9r}.`);if(n!==void 0&&(!Number.isSafeInteger(n)||n<1||n>p9r))throw new pAt("SESSION_BUDGET_INVALID",`A session deadline must be from 1 ms to ${p9r} ms (7 days).`);if(!(r===void 0&&n===void 0)){if(!Number.isFinite(t))throw new pAt("SESSION_BUDGET_INVALID","The session creation time is unavailable.");return{schemaVersion:1,...r!==void 0?{maxTokens:r}:{},...n!==void 0?{deadlineAt:new Date(t+n).toISOString()}:{}}}}var f9r=1,fAt=1,HLo=512,VLo=128,h9r=4*1024*1024;function da(){return new Date().toISOString()}function qLo(e=new Date){return e.toISOString().replace(/[^0-9]/g,"").slice(0,14)}function hAt(e){return e.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)}function Svt(e){return $Do(e)}function sRe(e){return Svt(e).toLowerCase()}function m9r(e,t){let r=sRe(e),n=sRe(t);return r===n||r.startsWith(`${n}\\`)||r.startsWith(`${n}/`)}function mAt(e,t){return!!(sRe(e.cwd)===sRe(t)||e.git?.root&&m9r(t,e.git.root)||e.git?.worktree&&m9r(t,e.git.worktree))}function WLo(e){let t=Svt(e);return`workspace_${SDo("sha256").update(process.platform==="win32"?t.toLowerCase():t).digest("hex")}`}function JLo(){return{input:0,output:0,total:0}}function Mk(e){try{return JSON.parse(_Do(e,"utf8"))}catch{return null}}function zLo(e){return oRe(e)}function i4(e,t){Mee(qsn(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;b2e(r,JSON.stringify(t,null,2)+`
|
|
@@ -17438,7 +17438,7 @@ ${d===0?"No reachability findings.":`${d} finding(s).`}
|
|
|
17438
17438
|
`),process.stdout.write(`Open: xeno attach ${Te.record.sessionId} --no-follow
|
|
17439
17439
|
`);return}if(e.interface){try{let ne=await uGr({cwd:process.cwd(),mode:y==="chatOnly"?"chat":"agent",resume:e.resume??!0});process.stdout.write(ne.sessionId?`Opened XENO Agent Interface; the desktop accepted the resume request for session ${ne.sessionId}.
|
|
17440
17440
|
`:`Opened XENO Agent Interface. No resumable session exists in this workspace yet.
|
|
17441
|
-
`)}catch(ne){console.error(ne instanceof Error?ne.message:String(ne)),process.exitCode=1}return}await tRr({peerLaunch:{entry:A0t[1]??process.argv[1],args:A0t.slice(2)},webResearchBudget:mPe(e),model:n,fallbackModels:i,effort:o,orchestrationMode:s,apiKey:a,authBypassSource:u,baseURL:p,maxTokens:f,maxIterations:h,executionMode:y,delegationEnabled:b,delegationMaxTotalTokens:I,delegationTimeoutMs:v,delegationMode:E,delegationTeamPreset:S,delegationRoles:x,delegationRolePrecedence:P,delegationMaxConcurrentBranches:k,delegationRemoteMcpByRole:C,mcpEnabled:_,permissionMode:R,executionSecurity:B.selection,executionSecurityStatus:B.status,securityPolicy:B.policy,memoryContextSessions:m,memoryContextTokens:g,memoryContextChars:A,resume:e.resume,claimHandoffId:e.claimHandoff,executionOwnerId:e.executionOwner,...typeof e.executionAuthority=="string"?{executionAuthority:e.executionAuthority}:{},role:e.role,checkpoint:e.checkpoint,lineInput:!!e.lineInput,rawTui:!!e.tui,accessibilityMode:e.accessibility,promptSections:Q?[Q]:void 0,agentName:O.name,agentProfile:O.profile,agentModelManaged:N,agentToolPolicy:O.profile?.capabilities.tools,safeMode:r})});$e.command("run [prompt]").description("Run a task non-interactively").option("-m, --model <model>","AI model to use").option("--fallback-models <models>","Comma-separated fallback models for retryable provider failures").option("--effort <level>","Reasoning effort: low, medium, high, xhigh, max, or ultracode").option("-k, --api-key <key>","API key (optional for Xeno API)").option("--base-url <url>","API base URL").option("--max-tokens <n>","Max response tokens").option("--max-iterations <n>","Max agentic loop iterations").option("--max-web-searches <n>","Web searches allowed per turn, 1-200 (default 5 for research, 3 otherwise; env XENO_MAX_WEB_SEARCHES)").option("--max-web-fetches <n>","Page fetches allowed per turn, 1-500 (default 12 for research, 4 otherwise; env XENO_MAX_WEB_FETCHES)").option("--max-web-calls <n>","Searches plus fetches allowed per turn (default: the sum of the two; env XENO_MAX_WEB_CALLS)").option("--memory-context-sessions <n>","Prior-session context entries for prompt memory (1-10)").option("--memory-context-tokens <n>","Token budget for prior-session prompt memory context").option("--memory-context-chars <n>","Per-session char budget for prior-session prompt memory context").option("--mode <mode>","Execution mode: agent, chat").option("--color <color>","UI color/theme name").option("--json","Emit machine-readable JSON output").option("--ndjson","Emit newline-delimited JSON events during execution").option("--bg","Start the run in the background and return a run ID").option("--remote","Request remote/cloud execution; fails fast until a backend is configured").option("--environment <id>","Remote environment ID for --remote runs").option("--attempts <n>","Hosted remote attempt count; requires backend support").option("--playbook <id>","Hosted playbook reference for --remote runs (repeatable)",d0t,[]).option("--knowledge <id>","Hosted knowledge collection reference for --remote runs (repeatable)",d0t,[]).option("--secret <name>","Hosted secret reference for --remote runs (repeatable)",d0t,[]).option("--image <path...>","Attach image file paths by asking the agent to inspect them with ReadImage").option("--title <title>","Human-readable title for a background run").option("--pin","Keep the background run pinned in the agents list").option("--worktree","Run the background task in an isolated git worktree").option("--worktree-base-ref <ref>","Git ref used when creating a background worktree").option("--worktree-root <path>","Directory for Xeno-managed background worktrees").option("--agent <name>","Use a built-in specialist profile or custom .xeno/agents definition").option("--mcp","Enable MCP server loading from config").option("--delegate","Enable planner/explorer/executor/reviewer delegation mode").option("--delegate-max-total-tokens <n>","Total token budget for delegated branches").option("--delegate-timeout-ms <n>","Wall-clock budget for delegated run (ms)").option("--delegate-mode <mode>","Delegation workflow mode: staged or parallel").option("--delegate-team <team>","Delegation team preset: balanced, explore, build, or review").option("--delegate-roles <csv>","Delegated branch roles (comma-separated)").option("--delegate-concurrency <n|auto>","Max concurrent delegated branches").option("--delegate-role-precedence <csv>","Reducer precedence list (comma-separated roles)").option("--delegate-remote <policy>","Delegated branch remote MCP policy: none, prompts, resources, context, all, or role=policy,...").option("--goal <condition>","Set a persistent goal condition for this run").option("--goal-max-turns <n>","Optional explicit goal iteration limit (unbounded by default)").option("--goal-max-tokens <n>","Durable total input and output token budget for this goal").option("--goal-verifier <mode>","Goal verifier mode: deterministic, llm, or auto","deterministic").option("-y, --yes","Accept file edits without asking (acceptEdits); never weakens a --permission-mode you chose").option("--permission-mode <mode>","Permission mode: default, plan, auto, acceptEdits, bypassPermissions").option("--prompt-file <path>","Read the prompt from a file (for prompts too long for a command line); `-` as the prompt reads standard input").option("--as <agent>","Act as one of your XENO agents (name or agt_ id): its instructions, model, tools and XENO Tasks identity").option("--resume [id]","Continue a saved session: by ID, or this folder's most recent one; prints session_id in --json output").option("--continue","Continue this folder's most recent session").option("--output-schema <file>","Require the final answer to be JSON matching this JSON Schema; returned as structured_output").option("--allowed-tools <names>",'Offer only these tools to the agent (comma-separated); children inherit the limit. "Bash(command:<pattern>)" also approves matching commands without a prompt, e.g. "Bash(command:python3 *)"; a command line that chains or redirects is still refused').option("--disallowed-tools <names>","Never offer these tools to the agent (comma-separated); children inherit the limit").option("--bypass-permissions","UNSAFE: Bypass permission checks entirely").option("--security-level <level>","Execution security: policy-only, process-hardened, or contained","policy-only").option("--untrusted","Require certified contained execution; never downgrades").option("--allow-network","Acknowledge network access for trusted process-hardened execution").option("--allow-directory <path...>","Additional policy directory allowlist for secured execution").option("--safe-mode","Disable user/project customizations for troubleshooting").action(async(e,t)=>{let r;try{r=await dcn(e,{...t.promptFile!==void 0?{promptFile:String(t.promptFile)}:{}})}catch(se){console.error(se.message),process.exit(2)}let n=pd(String(r),{surface:"run"});n&&(console.error(n.message),process.exit(2));let i=Bte(t),o=null,s=null,a=t.continue===!0?!0:t.resume===void 0?void 0:t.resume===!0?!0:String(t.resume),l=t.as!==void 0?String(t.as):void 0,c=!1;if(l===void 0&&a!==void 0){let se=typeof a=="string"?await et.find(a):await FG({workingDirectory:process.cwd()});if(se?.platformAgent){if(se.platformAgent.issuer.replace(/\/+$/,"")!==XK())throw new Error(`Session ${se.id} acted as an agent on ${se.platformAgent.issuer}, not ${XK()}. Pass --as me to continue it as yourself.`);l=se.platformAgent.agentId,c=!0}}if(l!==void 0){if(t.delegate||t.remote||t.bg)throw new Error("--as runs a local turn as one agent; it cannot be combined with --delegate, --remote or --bg.");o=rot({onWarning:Ve=>process.stderr.write(`[xeno] ${Ve.message}
|
|
17441
|
+
`)}catch(ne){console.error(ne instanceof Error?ne.message:String(ne)),process.exitCode=1}return}await tRr({peerLaunch:{entry:A0t[1]??process.argv[1],args:A0t.slice(2)},webResearchBudget:mPe(e),model:n,fallbackModels:i,effort:o,orchestrationMode:s,apiKey:a,authBypassSource:u,baseURL:p,maxTokens:f,maxIterations:h,executionMode:y,delegationEnabled:b,delegationMaxTotalTokens:I,delegationTimeoutMs:v,delegationMode:E,delegationTeamPreset:S,delegationRoles:x,delegationRolePrecedence:P,delegationMaxConcurrentBranches:k,delegationRemoteMcpByRole:C,mcpEnabled:_,permissionMode:R,executionSecurity:B.selection,executionSecurityStatus:B.status,securityPolicy:B.policy,memoryContextSessions:m,memoryContextTokens:g,memoryContextChars:A,resume:e.resume,claimHandoffId:e.claimHandoff,executionOwnerId:e.executionOwner,...typeof e.executionAuthority=="string"?{executionAuthority:e.executionAuthority}:{},role:e.role,checkpoint:e.checkpoint,lineInput:!!e.lineInput,rawTui:!!e.tui,accessibilityMode:e.accessibility,promptSections:Q?[Q]:void 0,agentName:O.name,agentProfile:O.profile,agentModelManaged:N,agentToolPolicy:O.profile?.capabilities.tools,safeMode:r})});$e.command("run [prompt]").description("Run a task non-interactively").option("-m, --model <model>","AI model to use").option("--fallback-models <models>","Comma-separated fallback models for retryable provider failures").option("--effort <level>","Reasoning effort: low, medium, high, xhigh, max, or ultracode").option("-k, --api-key <key>","API key (optional for Xeno API)").option("--base-url <url>","API base URL").option("--max-tokens <n>","Max response tokens").option("--max-iterations <n>","Max agentic loop iterations").option("--max-web-searches <n>","Web searches allowed per turn, 1-200 (default 5 for research, 3 otherwise; env XENO_MAX_WEB_SEARCHES)").option("--max-web-fetches <n>","Page fetches allowed per turn, 1-500 (default 12 for research, 4 otherwise; env XENO_MAX_WEB_FETCHES)").option("--max-web-calls <n>","Searches plus fetches allowed per turn (default: the sum of the two; env XENO_MAX_WEB_CALLS)").option("--memory-context-sessions <n>","Prior-session context entries for prompt memory (1-10)").option("--memory-context-tokens <n>","Token budget for prior-session prompt memory context").option("--memory-context-chars <n>","Per-session char budget for prior-session prompt memory context").option("--mode <mode>","Execution mode: agent, chat").option("--color <color>","UI color/theme name").option("--json","Emit machine-readable JSON output").option("--ndjson","Emit newline-delimited JSON events during execution").option("--bg","Start the run in the background and return a run ID").option("--remote","Request remote/cloud execution; fails fast until a backend is configured").option("--environment <id>","Remote environment ID for --remote runs").option("--attempts <n>","Hosted remote attempt count; requires backend support").option("--playbook <id>","Hosted playbook reference for --remote runs (repeatable)",d0t,[]).option("--knowledge <id>","Hosted knowledge collection reference for --remote runs (repeatable)",d0t,[]).option("--secret <name>","Hosted secret reference for --remote runs (repeatable)",d0t,[]).option("--image <path...>","Attach image file paths by asking the agent to inspect them with ReadImage").option("--title <title>","Human-readable title for a background run").option("--pin","Keep the background run pinned in the agents list").option("--worktree","Run the background task in an isolated git worktree").option("--worktree-base-ref <ref>","Git ref used when creating a background worktree").option("--worktree-root <path>","Directory for Xeno-managed background worktrees").option("--agent <name>","Use a built-in specialist profile or custom .xeno/agents definition").option("--mcp","Enable MCP server loading from config").option("--delegate","Enable planner/explorer/executor/reviewer delegation mode").option("--delegate-max-total-tokens <n>","Total token budget for delegated branches").option("--delegate-timeout-ms <n>","Wall-clock budget for delegated run (ms)").option("--delegate-mode <mode>","Delegation workflow mode: staged or parallel").option("--delegate-team <team>","Delegation team preset: balanced, explore, build, or review").option("--delegate-roles <csv>","Delegated branch roles (comma-separated)").option("--delegate-concurrency <n|auto>","Max concurrent delegated branches").option("--delegate-role-precedence <csv>","Reducer precedence list (comma-separated roles)").option("--delegate-remote <policy>","Delegated branch remote MCP policy: none, prompts, resources, context, all, or role=policy,...").option("--goal <condition>","Set a persistent goal condition for this run").option("--goal-max-turns <n>","Optional explicit goal iteration limit (unbounded by default)").option("--goal-max-tokens <n>","Durable total input and output token budget for this goal").option("--goal-verifier <mode>","Goal verifier mode: deterministic, llm, or auto","deterministic").option("-y, --yes","Accept file edits without asking (acceptEdits); never weakens a --permission-mode you chose").option("--permission-mode <mode>","Permission mode: default, plan, auto, acceptEdits, bypassPermissions").option("--prompt-file <path>","Read the prompt from a file (for prompts too long for a command line); `-` as the prompt reads standard input").option("--as <agent>","Act as one of your XENO agents (name or agt_ id): its instructions, model, tools and XENO Tasks identity").option("--resume [id]","Continue a saved session: by ID, or this folder's most recent one; prints session_id in --json output").option("--continue","Continue this folder's most recent session").option("--output-schema <file>","Require the final answer to be JSON matching this JSON Schema; returned as structured_output").option("--machine","Let the agent use this computer's real screen, mouse and keyboard (Windows)").option("--allowed-tools <names>",'Offer only these tools to the agent (comma-separated); children inherit the limit. "Bash(command:<pattern>)" also approves matching commands without a prompt, e.g. "Bash(command:python3 *)"; a command line that chains or redirects is still refused').option("--disallowed-tools <names>","Never offer these tools to the agent (comma-separated); children inherit the limit").option("--bypass-permissions","UNSAFE: Bypass permission checks entirely").option("--security-level <level>","Execution security: policy-only, process-hardened, or contained","policy-only").option("--untrusted","Require certified contained execution; never downgrades").option("--allow-network","Acknowledge network access for trusted process-hardened execution").option("--allow-directory <path...>","Additional policy directory allowlist for secured execution").option("--safe-mode","Disable user/project customizations for troubleshooting").action(async(e,t)=>{let r;try{r=await dcn(e,{...t.promptFile!==void 0?{promptFile:String(t.promptFile)}:{}})}catch(se){console.error(se.message),process.exit(2)}let n=pd(String(r),{surface:"run"});n&&(console.error(n.message),process.exit(2));let i=Bte(t),o=null,s=null,a=t.continue===!0?!0:t.resume===void 0?void 0:t.resume===!0?!0:String(t.resume),l=t.as!==void 0?String(t.as):void 0,c=!1;if(l===void 0&&a!==void 0){let se=typeof a=="string"?await et.find(a):await FG({workingDirectory:process.cwd()});if(se?.platformAgent){if(se.platformAgent.issuer.replace(/\/+$/,"")!==XK())throw new Error(`Session ${se.id} acted as an agent on ${se.platformAgent.issuer}, not ${XK()}. Pass --as me to continue it as yourself.`);l=se.platformAgent.agentId,c=!0}}if(l!==void 0){if(t.delegate||t.remote||t.bg)throw new Error("--as runs a local turn as one agent; it cannot be combined with --delegate, --remote or --bg.");o=rot({onWarning:Ve=>process.stderr.write(`[xeno] ${Ve.message}
|
|
17442
17442
|
`)});let se;try{se=await o.listAgents()}catch(Ve){let st=Ve.code,Nr=c?"This session acts as one of your XENO agents, which":"--as";throw new Error(st==="not_signed_in"?`${Nr} needs you to be signed in. Run \`xeno login\` first.`:`Your XENO agents could not be listed: ${Ve.message}`)}let Ke=not(l,se);if(Ke.kind==="ambiguous")throw new Error(`More than one of your agents is named "${l}". Use its id:
|
|
17443
17443
|
${QB(Ke.matches)}`);if(Ke.kind==="unknown")throw new Error(c?`This session acted as ${l}, which is no longer one of your agents. Pass --as me to continue it as yourself, or --as <agent>. Your agents:
|
|
17444
17444
|
${QB(Ke.agents)}`:`No agent of yours matches "${Ke.ref}". Your agents:
|
|
@@ -17465,9 +17465,9 @@ ${QB(Ke.agents)}`);Ke.kind==="agent"&&(s=await o.useAgent(Ke.agent.id))}let d=[]
|
|
|
17465
17465
|
`)},Yw=!process.stdin.isTTY||process.env.XENO_FORCE_AUTO_DENY_PROMPTS==="1",Kw=Yw?async()=>"deny":void 0;Yw&&Ci!=="bypassPermissions"&&!D&&process.stderr.write(`[permissions] Non-interactive mode: prompt-required actions are auto-denied.
|
|
17466
17466
|
`);let Os=Ie({mode:Ci,cwd:We,...he.length>0?{rules:he}:{},...Se?{permissionProfile:Se}:{},promptFn:Kw,auditLogger:co,fallbackTraceId:`run-${Dg}`,decisionHook:async se=>{await lF(Yn,se)}});XP(Os);let XM=Dge(Os),vc=PX({cwd:()=>We,profile:()=>U.profile,runId:nr,agentId:"agent-main",sessionId:nr,surface:"cli",securityPolicy:()=>Pr.policy,securityStatus:Pr.status,safeMode:i,onAudit:gS(co)}),vu="",Wv=new Hb,Li=async(se,Ke)=>{if(xt?.maxTokens===void 0)return;let Ve=await Wv.prepare(xt,{cwd:We,model:Ke,maxOutputTokens:Math.max(512,Math.min(x,4096)),agent:se});se.configureModelExecution({provider:Ve.provider})},Kc=eI();Kc.onSettled(se=>{Di("child_agent_settled",{child_id:se.id,kind:se.kind,...se.label?{label:se.label}:{},outcome:se.outcome,duration_ms:se.durationMs,...se.tokenUsage?{token_usage:se.tokenUsage}:{},...se.reason?{reason:se.reason}:{}})});let bm=r,o1=(se=0,Ke="agent-main",Ve=()=>pb(U.profile,We),st=()=>Fr?.active()??[])=>async({agent:Nr,prompt:Kt,signal:bt})=>{let Ut=Ve();if(se>=2)throw new Error("Nested dispatch_agent depth limit reached.");if(Nr?.trim()){if(i)throw new Error("Custom agents are disabled in safe mode.");let Ur=e_(Nr,We,Ut),Il=Ur.definition,Hn=Cf(nr,"dispatch",Il.name),Zw=ux(Ur.compiled,Hn),po=await fb.create({profile:Ur.compiled,cwd:We,...Zw?{sessionDir:Zw.sessionDir}:{}}).catch(()=>null);if(po)try{await po.prepare(Kt)}catch{po.clear()}let Im=Hv({cwd:We,sandbox:Pr.policy,ownerSessionId:Hn,dispatchAgent:o1(se+1,Il.name,()=>pb(Ur.compiled,We,Ve()),()=>zv.active()),childController:Kc}),zv=Yu({cwd:We,policy:Ur.compiled.capabilities.skills,outerExternalActions:Ur.compiled.capabilities.externalActions.default,classifyExternalActions:wd,isExternalActionApproved:sh=>yd(sh,bm),onAudit:sh=>rh(sh,"branch"),inheritedActivations:st()});Im.register(zv.tool),og(Im,We,{runId:nr,agentId:Il.name}),ui(Im,Ur.compiled.capabilities.tools),ui(Im,ne);let Mte=Ea(Ur.compiled.capabilities.tools),Ote=Zd({profile:()=>Ur.compiled,currentUserPrompt:()=>bm}),Nte=Np(Il.name,Ke,g0t(Il),Ur.compiled.capabilities.hooks),qT=KA({cwd:We,registry:Im,mcpManager:Ns,profile:Ur.compiled,beforeStep:()=>s1(),getParentProfile:Ve,hooks:bu(Il.name,Ke,g0t(Il),Ur.compiled.capabilities.hooks)}),t3=Ycn(Kt,We),{agent:YM}=await Am({cwd:We,sandbox:Pr.policy,apiKey:y,baseURL:ha,model:bPe(Il,h),...t3.length?{identity:{targetPaths:t3}}:{},...m?{fallbackModels:m}:{},effort:A,maxTokens:Math.max(512,Math.min(x,4096)),maxIterations:Math.max(10,Math.min(k,100)),...Il.budget?.maxTokens!==void 0?{turnTokenBudget:Il.budget.maxTokens}:{},requesterLabel:`Agent:${Il.name}`,role:Ur.compiled.memory.role,executionMode:B,permissionEngine:Os,memory:Zw,session:{auditLogger:co},promptSections:[Ur.compiled.promptSection,...po?[po.promptSection]:[],...Oc(We,Ur.compiled.capabilities.skills).promptSections,...nh.promptSections,AC(),...qv?[qv]:[]],toolMiddleware:[zv.middleware,qT.middleware,...nh.toolMiddleware,Nte,Ote,...Mte?[Mte]:[]],toolRegistry:Im,runAuthority:qT.runAuthority,continuationCheckpoints:!1});if(bt?.aborted)throw po?.clear(),new Ft;let Dte="",KM="success";try{await Li(YM,bPe(Il,h));let sh=await qy({agent:YM,prompt:Kt,signal:bt,ownerSessionId:Hn,lifecycle:qT,run:()=>nx(YM,Il.budget?.deadlineMs,()=>YM.run(Kt))});return Dte=sh.output,bI(sh.termination)||(KM="partial"),sh}catch(sh){throw KM=bt?.aborted?"partial":"failure",sh}finally{if(po)try{await po.complete({task:Kt,transcript:Dte||(KM==="partial"?"The delegated run was interrupted before a final answer.":"The delegated run failed before a final answer."),outcome:KM})}catch{}finally{po.clear()}}}vu||(vu=(await Am({cwd:We,sandbox:Pr.policy,apiKey:y,baseURL:ha,model:h,...Lg.length?{identity:{targetPaths:Lg}}:{},...m?{fallbackModels:m}:{},effort:A,maxTokens:x,maxIterations:k,requesterLabel:"Agent",...Ae?{role:Ae}:{},executionMode:B,permissionEngine:Os,memory:Te,session:{auditLogger:co},...ym})).systemPrompt);let jt=Cf(nr,"dispatch"),cr=i?null:Yu({cwd:We,policy:Ut.capabilities.skills,outerExternalActions:Ut.capabilities.externalActions.default,classifyExternalActions:wd,isExternalActionApproved:Ur=>yd(Ur,bm),onAudit:Ur=>rh(Ur,"branch"),inheritedActivations:st()}),uo=Hv({cwd:We,sandbox:Pr.policy,ownerSessionId:jt});cr&&uo.register(cr.tool),ui(uo,Ut.capabilities.tools),ui(uo,ne);let ir=Ea(Ut.capabilities.tools),zr=Zd({profile:()=>Ut,currentUserPrompt:()=>bm}),Tn=KA({cwd:We,registry:uo,mcpManager:Ns,profile:Ut,beforeStep:()=>s1(),getParentProfile:Ve,hooks:bu("explorer",Ke,void 0,Ut.capabilities.hooks)}),Fi=(await gu({cwd:We,sandbox:Pr.policy,apiKey:y,baseURL:ha,model:h,...m?{fallbackModels:m}:{},effort:A,maxTokens:Math.max(512,Math.min(x,4096)),maxIterations:Math.max(10,Math.min(k,100)),parentSystemPrompt:await ZA({cwd:We,model:h,executionMode:B,profile:Ut,ownerSessionId:jt}),parentExecutionMode:B,subagentRole:"explorer",permissionEngine:Os,ownerSessionId:jt,childController:Kc,toolRegistry:uo,runAuthority:Tn.runAuthority,toolMiddleware:[Tn.middleware,...cr?[cr.middleware]:[],Np("explorer",Ke,void 0,Ut.capabilities.hooks),zr,...ir?[ir]:[]]})).agent;return await Li(Fi,h),qy({agent:Fi,prompt:Kt,signal:bt,ownerSessionId:jt,lifecycle:Tn})},si=o1(),Ns,s1=async()=>{Ns&&(await cz(Ns,{cwd:We,allowedServers:U.profile.capabilities.mcpServers}),await l_(Ns,{cwd:We,filter:se=>U.profile.capabilities.mcpServers===void 0||U.profile.capabilities.mcpServers.includes(se.name)}))},VT=!1,vm,Iu=await aK(vc,new IA),e3=()=>{let se=Hv({cwd:We,dispatchAgent:si,childController:Kc,sandbox:Pr.policy,ownerSessionId:nr,...Se?{permissionProfile:Se}:{}});if(Iu>0&&vc.register(se),Fr&&se.register(Fr.tool),xQr(se),og(se,We,{runId:nr,agentId:"agent-main"}),yX(se,{cwd:We,model:h,getOrchestrationMode:()=>w??"workflow",cliVersion:Pe,getParentOrigin:()=>vm}),LB(se,{cwd:We,model:h,...A?{effort:A}:{},permissionMode:Ci,cliVersion:Pe,parentSessionId:nr,getParentOrigin:()=>vm,getParentProfile:()=>U.profile,getExecutionSecurity:()=>Pr.selection,getParentSkills:()=>Fr?.active()??[],safeMode:i,onSessionStarted:()=>{VT=!0}}),Ns&&Kf(Ns,se),Ng(se,XM.options),ui(se,ie),o&&s){for(let Ke of XIe(o,{runId:u}))se.register(Ke);for(let Ke of d)se.has(Ke.definition.name)||se.register(Ke);ui(se,f?.agentTools)}if(ui(se,ne),s){for(let Ke of FTr)se.has(Ke)&&se.activateMatchingDefinitions(Ke,1);for(let Ke of d)se.has(Ke.definition.name)&&se.activateMatchingDefinitions(Ke.definition.name,1)}return se},Jv=(se,Ke)=>{let Ve=Cf(nr,"delegate",se),st=Hv({cwd:We,sandbox:Pr.policy,ownerSessionId:Ve});if(og(st,We,{runId:nr,agentId:se}),Ns){let Nr=Au(Ke,se);Kf(Ns,st,[],Kt=>r1(Kt,Nr)&&(U.profile.capabilities.mcpServers===void 0||U.profile.capabilities.mcpServers.includes(Kt.server)))}return{...a_({registry:st,cwd:We,safeMode:i,profile:U.profile,currentUserPrompt:()=>bm,hookMiddleware:Np(`branch-${se}`,"agent-main",void 0,U.profile.capabilities.hooks),onSkillAudit:Nr=>rh(Nr,"branch"),inheritedActivations:Fr?.active()}),ownerSessionId:Ve}},je=e3(),Nd=i?void 0:await iF({toolRegistry:je}),zt=i?void 0:Oc(We,U.profile?.capabilities.skills),Qg=F_(qt.outputStyle,Nd?.outputStyles??[]);ym.promptSections.push(...Qg?[Qg]:[],...Nd?.promptSections??[],...zt?.promptSections??[]),Di("run_start",{cwd:We,model:h,fallback_models:m??[],effort:A,prompt:r,safe_mode:i,...re?{agent:re}:{},execution_mode:B,delegation_enabled:ke,mcp_enabled:Ye,plugin_count:Nd?.activePlugins.length??0,plugin_tool_count:Nd?.registeredTools.length??0,skill_count:zt?.skills.length??0,enabled_skill_count:zt?.enabledSkills.length??0});let j=async()=>{if(!Ye)return;Ns=fE({permissionProfile:Se??void 0});let se=await cz(Ns,{cwd:We,allowedServers:U.profile.capabilities.mcpServers}),Ke=await l_(Ns,{cwd:We,filter:st=>U.profile.capabilities.mcpServers===void 0||U.profile.capabilities.mcpServers.includes(st.name)}),Ve=uF(se,Ke);if(Kf(Ns,je),ui(je,ie),s&&ui(je,f?.agentTools),ui(je,ne),Di("mcp_connect",{connected:Ve.connected.length,skipped:Ve.skipped.length,denied:Ve.denied.length,errors:Ve.errors.length}),!D){let st=[];Ve.connected.length>0&&st.push(`connected ${Ve.connected.length}`),Ve.skipped.length>0&&st.push(`skipped ${Ve.skipped.length}`),Ve.denied.length>0&&st.push(`denied ${Ve.denied.length}`),Ve.errors.length>0&&st.push(`errors ${Ve.errors.length}`),st.length>0&&process.stderr.write(`[mcp] ${st.join(", ")}
|
|
17467
17467
|
`)}},ae="",pe,de=!1,Ue=!1,Je=!1,Xt,gr=null,Kn=null,Jr={input:0,output:0,total:0},en,Ic,Ar,jn,xn=`run-${Dg}-${Pte().slice(0,8)}`,Cn=new hs,Bo=new nt,Ec=wPe("XENO_BACKGROUND_AGENT_NOTIFICATION_WAIT_MS",3e5,0),ge=Math.max(1,Math.min(16,k)),me=async se=>{if(!VT||!yF())return{timedOut:!1,turnLimitReached:!1,activeChildren:0};let Ke=Date.now(),Ve=0;for(;;){let st=Cn.listPending(nr);if(st.length>0){if(Ve>=ge)return{timedOut:!1,turnLimitReached:!0,activeChildren:Bo.list({all:!0}).filter(Ut=>Ut.parentSessionId===nr).filter(Ut=>!["completed","failed","stopped"].includes(Ut.status)).length};let Kt=st.slice(0,l4o);for(let bt of Kt){Cn.markDeliveryAttempt(bt.notificationId);let Ut=Ez(bt);Di("agent_notification",{notification_id:bt.notificationId,parent_session_id:bt.parentSessionId,child_session_id:bt.childSessionId,status:bt.status,name:bt.name,summary:bt.summary,remaining_queued:Math.max(0,st.length-Kt.length)}),D||process.stderr.write(`${Ut}
|
|
17468
|
-
`)}ae=await se.run(kz(Kt),{messageId:DAe(Kt)}),Kn=se.lastTraceId,Jr=se.tokenUsage,Ar=se.messages.length,Ic=nh.getExecutionGovernanceSummary()??void 0;for(let bt of Kt)Cn.markDelivered(bt.notificationId);Ve+=1;continue}let Nr=Bo.list({all:!0}).filter(Kt=>Kt.parentSessionId===nr).filter(Kt=>!["completed","failed","stopped"].includes(Kt.status));if(Nr.length===0)return{timedOut:!1,turnLimitReached:!1,activeChildren:0};if(Date.now()-Ke>=Ec)return{timedOut:!0,turnLimitReached:!1,activeChildren:Nr.length};await f0t(200)}},Be=n1({mode:qe,teamPreset:ot,roles:ze,rolePrecedence:fa,remoteMcpByRole:$s,...qr!==void 0?{maxConcurrentBranches:qr}:{}}),tt=xt?new ri:void 0,ur=xt?Ki():void 0,jr=xt?.maxTokens!==void 0?new Hb:void 0,Lp=new UJ,ga=null,Eu=async(se,Ke,Ve)=>{if(!(!Jt||!ur)){for(;;){let st=await ur.getLoop(nr,Jt.id);if(!st)throw new Error(`Goal continuation loop ${Jt.id} disappeared`);if(Jt=st,st.status==="running")break;if(st.status==="paused"||st.status==="waiting"){await f0t(250);continue}throw new Error(`Goal continuation loop ${st.id} is ${st.status}`)}if(await yu?.assertOwned(),xt?.maxTokens!==void 0){if(!tt||!jr)throw new Error("Bounded goal quota runtime is unavailable.");if(!Ve)throw new Error("A bounded goal turn requires the agent that will run it.");let st=await jr.prepare(xt,{cwd:We,model:h,maxOutputTokens:x,agent:Ve}),Nr=await tt.admitTurn(nr,Ke,`goal-turn-${Pte()}`,xt,"local-sdk",await yu?.assertOwned(),st);if(!Nr?.admitted)throw new Error("Bounded goal turn was already admitted; replay is not authorized.");return ga=Nr,xt=Nr.goal,Jt=await ur.getLoop(nr,Jt.id)??Jt,st}Jt=await ur.beginLoopIteration(nr,Jt.id,Jt.version,`Goal turn ${se}: ${Ke.replace(/\s+/g," ").trim().slice(0,512)}`)}},oh=async(se,Ke="ok")=>{if(!xt||!tt)return{shouldContinue:!1};await co.flush();let Ve=await Txr({goal:xt,answer:ae,auditEvents:await co.read(),runStatus:Ke,...pe?{error:pe}:{}},{mode:Yf,model:h,...m?{fallbackModels:m}:{},effort:A,apiKey:y,baseURL:ha}),st=xt.maxTurns!==void 0&&se>=xt.maxTurns;if(xt=await tt.updateVerifierResult(xt,Ve,{maxTurnsReached:st,accountedTurns:Math.max(xt.accountedTurns??0,se)})??xt,Jt&&ur){let Nr=await ur.getLoop(nr,Jt.id);if(!Nr)throw new Error(`Goal continuation loop ${Jt.id} disappeared`);Jt=Nr,ga&&tt?(await tt.finishTurn(ga,"completed"),ga=null,Jt=await ur.getLoop(nr,Jt.id)??Jt):Jt=await ur.finishLoopIteration(nr,Jt.id,Jt.version,{status:"completed"}),xt.status==="complete"&&Jt.status!=="completed"?Jt=await ur.setLoopStatus(nr,Jt.id,Jt.version,"completed","Goal verification passed"):(xt.status==="blocked"||xt.status==="failed")&&Jt.status!=="failed"&&(Jt=await ur.setLoopStatus(nr,Jt.id,Jt.version,"failed",`Goal became ${xt.status}`))}return Di("goal_verifier",{goal_id:xt.goalId,goal_status:xt.status,turn:se,max_turns:xt.maxTurns??null,result:Ve}),xt.status==="complete"?{shouldContinue:!1}:xt.status==="blocked"||xt.status==="failed"?(Je=!0,pe=`Goal ${xt.status}: ${Ve.reason}`,{shouldContinue:!1}):{shouldContinue:!0,nextPrompt:IQ(xt,Ve,se+1)}};try{if(Op)throw Op;let se=!1,Ke=!!(ke||t.agent||t.as!==void 0||s||Ms!==void 0||qa!==void 0||t.remote||t.bg||Ti||t.memoryContextSessions||t.memoryContextTokens||t.memoryContextChars||String(h).startsWith("local:")),Ve=WA(process.env[eu],Ke?void 0:{baseURL:ha,authBypassSource:E,...i?{safeMode:!0}:{}});if(Ms!==void 0&&Ve==="required")throw new Error(`${eu}=require cannot be combined with --resume or --continue yet.`);let st=Ve==="off"||ke||Ms!==void 0?void 0:JIe({cwd:We,allowedDirectories:Pr.selection.allowedDirectories,executionMode:String(B),permissionMode:Ci,securityLevel:Pr.selection.level,effectiveSecurityLevel:Pr.selection.effectiveLevel,trustMode:Pr.selection.trustMode,allowNetwork:Pr.selection.allowNetwork});if(st&&!st.carried){if(Ve==="required")throw new Error(`${eu}=require, but this run's authority cannot be carried to the Agent host. ${st.reason}`);!D&&process.env[eu]?.trim()&&process.stderr.write(`[attach] ${st.reason} Running the embedded loop instead.
|
|
17468
|
+
`)}ae=await se.run(kz(Kt),{messageId:DAe(Kt)}),Kn=se.lastTraceId,Jr=se.tokenUsage,Ar=se.messages.length,Ic=nh.getExecutionGovernanceSummary()??void 0;for(let bt of Kt)Cn.markDelivered(bt.notificationId);Ve+=1;continue}let Nr=Bo.list({all:!0}).filter(Kt=>Kt.parentSessionId===nr).filter(Kt=>!["completed","failed","stopped"].includes(Kt.status));if(Nr.length===0)return{timedOut:!1,turnLimitReached:!1,activeChildren:0};if(Date.now()-Ke>=Ec)return{timedOut:!0,turnLimitReached:!1,activeChildren:Nr.length};await f0t(200)}},Be=n1({mode:qe,teamPreset:ot,roles:ze,rolePrecedence:fa,remoteMcpByRole:$s,...qr!==void 0?{maxConcurrentBranches:qr}:{}}),tt=xt?new ri:void 0,ur=xt?Ki():void 0,jr=xt?.maxTokens!==void 0?new Hb:void 0,Lp=new UJ,ga=null,Eu=async(se,Ke,Ve)=>{if(!(!Jt||!ur)){for(;;){let st=await ur.getLoop(nr,Jt.id);if(!st)throw new Error(`Goal continuation loop ${Jt.id} disappeared`);if(Jt=st,st.status==="running")break;if(st.status==="paused"||st.status==="waiting"){await f0t(250);continue}throw new Error(`Goal continuation loop ${st.id} is ${st.status}`)}if(await yu?.assertOwned(),xt?.maxTokens!==void 0){if(!tt||!jr)throw new Error("Bounded goal quota runtime is unavailable.");if(!Ve)throw new Error("A bounded goal turn requires the agent that will run it.");let st=await jr.prepare(xt,{cwd:We,model:h,maxOutputTokens:x,agent:Ve}),Nr=await tt.admitTurn(nr,Ke,`goal-turn-${Pte()}`,xt,"local-sdk",await yu?.assertOwned(),st);if(!Nr?.admitted)throw new Error("Bounded goal turn was already admitted; replay is not authorized.");return ga=Nr,xt=Nr.goal,Jt=await ur.getLoop(nr,Jt.id)??Jt,st}Jt=await ur.beginLoopIteration(nr,Jt.id,Jt.version,`Goal turn ${se}: ${Ke.replace(/\s+/g," ").trim().slice(0,512)}`)}},oh=async(se,Ke="ok")=>{if(!xt||!tt)return{shouldContinue:!1};await co.flush();let Ve=await Txr({goal:xt,answer:ae,auditEvents:await co.read(),runStatus:Ke,...pe?{error:pe}:{}},{mode:Yf,model:h,...m?{fallbackModels:m}:{},effort:A,apiKey:y,baseURL:ha}),st=xt.maxTurns!==void 0&&se>=xt.maxTurns;if(xt=await tt.updateVerifierResult(xt,Ve,{maxTurnsReached:st,accountedTurns:Math.max(xt.accountedTurns??0,se)})??xt,Jt&&ur){let Nr=await ur.getLoop(nr,Jt.id);if(!Nr)throw new Error(`Goal continuation loop ${Jt.id} disappeared`);Jt=Nr,ga&&tt?(await tt.finishTurn(ga,"completed"),ga=null,Jt=await ur.getLoop(nr,Jt.id)??Jt):Jt=await ur.finishLoopIteration(nr,Jt.id,Jt.version,{status:"completed"}),xt.status==="complete"&&Jt.status!=="completed"?Jt=await ur.setLoopStatus(nr,Jt.id,Jt.version,"completed","Goal verification passed"):(xt.status==="blocked"||xt.status==="failed")&&Jt.status!=="failed"&&(Jt=await ur.setLoopStatus(nr,Jt.id,Jt.version,"failed",`Goal became ${xt.status}`))}return Di("goal_verifier",{goal_id:xt.goalId,goal_status:xt.status,turn:se,max_turns:xt.maxTurns??null,result:Ve}),xt.status==="complete"?{shouldContinue:!1}:xt.status==="blocked"||xt.status==="failed"?(Je=!0,pe=`Goal ${xt.status}: ${Ve.reason}`,{shouldContinue:!1}):{shouldContinue:!0,nextPrompt:IQ(xt,Ve,se+1)}};try{if(Op)throw Op;let se=!1,Ke=!!(ke||t.agent||t.as!==void 0||s||Ms!==void 0||qa!==void 0||t.remote||t.bg||Ti||t.memoryContextSessions||t.memoryContextTokens||t.memoryContextChars||String(h).startsWith("local:"));if(t.machine&&Ke)throw new Error("--machine runs on the shared Agent host, which this run's other options keep it from using. Remove them and try again.");let Ve=t.machine?"required":WA(process.env[eu],Ke?void 0:{baseURL:ha,authBypassSource:E,...i?{safeMode:!0}:{}});if(Ms!==void 0&&Ve==="required")throw new Error(`${eu}=require cannot be combined with --resume or --continue yet.`);let st=Ve==="off"||ke||Ms!==void 0?void 0:JIe({cwd:We,allowedDirectories:Pr.selection.allowedDirectories,executionMode:String(B),permissionMode:Ci,securityLevel:Pr.selection.level,effectiveSecurityLevel:Pr.selection.effectiveLevel,trustMode:Pr.selection.trustMode,allowNetwork:Pr.selection.allowNetwork});if(st&&!st.carried){if(Ve==="required")throw new Error(`${eu}=require, but this run's authority cannot be carried to the Agent host. ${st.reason}`);!D&&process.env[eu]?.trim()&&process.stderr.write(`[attach] ${st.reason} Running the embedded loop instead.
|
|
17469
17469
|
`)}if(Ve!=="off"&&!ke&&st?.carried){let{attachAsHeadlessClient:Nr,describeAttachRefusal:Kt}=await Promise.resolve().then(()=>(sx(),hAe)),{runTurnThroughHost:bt}=await Promise.resolve().then(()=>(LKe(),wpr)),{cliSurfaceAccount:Ut}=await Promise.resolve().then(()=>(Zit(),NTr)),jt=await Nr({clientVersion:Pe,account:Ut(),startIfAbsent:!0,...process.env.XENO_AGENT_HOST_ROOT?{hostRootDirectory:process.env.XENO_AGENT_HOST_ROOT}:{}});if(jt.attached){let cr=jt.host,uo=Pte();try{if(await cr.client.connect(),st.authority.mode==="development"){let{grantTerminalFolders:Tn}=await Promise.resolve().then(()=>(ZL(),fze)),Fi=await Tn(cr.client,[st.authority.workspace.primaryDirectory,...st.authority.workspace.additionalDirectories??[]]);Fi.failed.length>0&&!D&&process.stderr.write(`[attach] The Agent host did not record access to ${Fi.failed.map(Ur=>Ur.path).join(", ")}: ${Fi.failed[0].error}
|
|
17470
|
-
`)}let ir=cr.client;if(ir.openConversation){let Tn=await ir.openConversation({mode:st.authority.mode,...st.authority.mode==="development"&&st.authority.workspace.primaryDirectory?{workingDirectory:st.authority.workspace.primaryDirectory}:{}});if(!Tn.success)throw new Error(`Agent host conversation open failed: ${Tn.code?`${Tn.code}: `:""}`+(Tn.error??"the host returned no safe error"));if(!Tn.conversationId||!Tn.hostStorageIdentity)throw new Error("Agent host omitted its durable conversation binding.");uo=Tn.conversationId}Di("attach_connected",{root_directory:cr.rootDirectory}),await co.append({trace_id:`attach-${uo.slice(0,16)}`,event_type:"agent_turn_delegated_to_host",actor:"system",risk_level:"medium",status:"ok",metadata:{surface:"run",attach_mode:Ve,host_root_directory:cr.rootDirectory,conversation_id:uo,local_permission_engine_applies:!1,can_answer_prompts:cr.canAnswerPrompts,carried_mode:st.authority.mode,carried_primary_directory:st.authority.workspace.primaryDirectory,carried_additional_directories:st.authority.workspace.additionalDirectories??[]}});let zr=r;for(let Tn=1;;Tn+=1){Tn>1&&(Je=!1,Ue=!1,pe=void 0),await Eu(Tn,zr);let Fi=Promise.resolve(),Ur=po=>{Fi=Fi.then(()=>co.append(po)).catch(()=>{})},Il=`attach-${uo.slice(0,16)}`,Hn=await bt(cr,{prompt:zr,conversationId:uo,...h?{modelId:h}:{},mode:st.authority.mode,workspace:st.authority.workspace,execution:{...st.authority.execution,maxIterations:k,maxOutputTokens:Math.min(x,mfe),run:{...ne?{toolPolicy:ne}:{},...m?{fallbackModels:m}:{},governance:{kind:"run",...mPe(t),...th.length?{requiredOutputPaths:th}:{}},...Ug&&Ug!==!0?{outputSchema:Ug}:{}}},...D?{}:{onText:po=>process.stdout.write(po)},onToolStart:po=>{Ur({trace_id:Il,event_type:"tool_call",actor:"assistant",risk_level:"low",status:"ok",tool_name:po,metadata:{surface:"run",executed_by:"agent-host"}}),D||process.stderr.write(`[tool] ${po}
|
|
17470
|
+
`)}let ir=cr.client;if(ir.openConversation){let Tn=await ir.openConversation({mode:st.authority.mode,...st.authority.mode==="development"&&st.authority.workspace.primaryDirectory?{workingDirectory:st.authority.workspace.primaryDirectory}:{}});if(!Tn.success)throw new Error(`Agent host conversation open failed: ${Tn.code?`${Tn.code}: `:""}`+(Tn.error??"the host returned no safe error"));if(!Tn.conversationId||!Tn.hostStorageIdentity)throw new Error("Agent host omitted its durable conversation binding.");uo=Tn.conversationId}Di("attach_connected",{root_directory:cr.rootDirectory}),await co.append({trace_id:`attach-${uo.slice(0,16)}`,event_type:"agent_turn_delegated_to_host",actor:"system",risk_level:"medium",status:"ok",metadata:{surface:"run",attach_mode:Ve,host_root_directory:cr.rootDirectory,conversation_id:uo,local_permission_engine_applies:!1,can_answer_prompts:cr.canAnswerPrompts,carried_mode:st.authority.mode,carried_primary_directory:st.authority.workspace.primaryDirectory,carried_additional_directories:st.authority.workspace.additionalDirectories??[]}});let zr=r;for(let Tn=1;;Tn+=1){Tn>1&&(Je=!1,Ue=!1,pe=void 0),await Eu(Tn,zr);let Fi=Promise.resolve(),Ur=po=>{Fi=Fi.then(()=>co.append(po)).catch(()=>{})},Il=`attach-${uo.slice(0,16)}`,Hn=await bt(cr,{prompt:zr,conversationId:uo,...h?{modelId:h}:{},mode:st.authority.mode,workspace:st.authority.workspace,execution:{...st.authority.execution,maxIterations:k,...t.machine?{machine:!0}:{},maxOutputTokens:Math.min(x,mfe),run:{...ne?{toolPolicy:ne}:{},...m?{fallbackModels:m}:{},governance:{kind:"run",...mPe(t),...th.length?{requiredOutputPaths:th}:{}},...Ug&&Ug!==!0?{outputSchema:Ug}:{}}},...D?{}:{onText:po=>process.stdout.write(po)},onToolStart:po=>{Ur({trace_id:Il,event_type:"tool_call",actor:"assistant",risk_level:"low",status:"ok",tool_name:po,metadata:{surface:"run",executed_by:"agent-host"}}),D||process.stderr.write(`[tool] ${po}
|
|
17471
17471
|
`)},onToolEnd:(po,Im)=>{Ur({trace_id:Il,event_type:"tool_result",actor:"assistant",risk_level:"low",status:Im?"ok":"error",tool_name:po,metadata:{surface:"run",executed_by:"agent-host"}}),D||process.stderr.write(`[tool] ${po}: ${Im?"ok":"error"}
|
|
17472
17472
|
`)}});if(await Fi,se=!0,Hn.ok&&Hn.tokenUsage&&(Jr={input:Jr.input+Hn.tokenUsage.input,output:Jr.output+Hn.tokenUsage.output,total:Jr.total+Hn.tokenUsage.total}),Hn.ok?(ae=Hn.finalText||Hn.text,bc&&await bc.completionGuard.evaluate({finalText:ae}),Ja&&(await Ja.transcript.append({type:"user_message",data:{role:"user",content:zr}}),await Ja.transcript.append({type:"assistant_message",data:{role:"assistant",content:ae}})),Kn=null):(Je=!0,Ue=Hn.reason!=="abandoned",pe=`Agent host ${Hn.reason}: ${Hn.detail}`,D||process.stderr.write(`[attach] ${pe}
|
|
17473
17473
|
`)),Di("attach_turn_result",{ok:Hn.ok,request_id:Hn.requestId,goal_turn:xt?Tn:void 0,...Hn.ok?{adapter_id:Hn.adapterId}:{reason:Hn.reason}}),await co.append({trace_id:`attach-${uo.slice(0,16)}`,event_type:"agent_turn_delegated_result",actor:"system",risk_level:"low",status:Hn.ok?"ok":"error",...Hn.ok?{}:{reason:Hn.detail},metadata:{surface:"run",request_id:Hn.requestId,goal_turn:xt?Tn:void 0,...Hn.ok?{adapter_id:Hn.adapterId}:{failure:Hn.reason}}}),!Hn.ok&&Hn.reason==="rejected"&&Ve==="optional"&&!xt){se=!1,Je=!1,Ue=!1,pe=void 0;break}if(!xt||!Hn.ok)break;let Zw=await oh(Tn,Je?"incomplete":"ok");if(!Zw.shouldContinue)break;if(!Zw.nextPrompt)throw new Error("Goal verifier requested continuation without a continuation prompt");zr=Zw.nextPrompt}}finally{cr.stopRespondingToElicitations(),await cr.session.close()}}else{let cr=Kt(jt.reason,jt.detail);if(Ve==="required")throw new Error(`${eu}=require, but the CLI could not attach. ${cr}`);D||process.stderr.write(`[attach] ${cr} Running the embedded loop instead.
|