@xenosystem/agent-cli 0.5.48 → 0.5.49
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/index.js +5 -5
- package/dist/metafile-esm.json +1 -1
- package/dist/sdk-build-identity.json +4 -4
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -2657,7 +2657,7 @@ public static class XenoProtectedWrite {
|
|
|
2657
2657
|
$request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
2658
2658
|
$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)
|
|
2659
2659
|
$result | ConvertTo-Json -Compress
|
|
2660
|
-
`});Ygt=z(()=>{"use strict";is(),Ome(),Ome(),kL="ai.xenostudio.xeno-agent.mcp",EL="xeno.host.state.encryption-key.v1",SC="aes-256-gcm",dm=32,oM=12,PX=16,Ab="b64:",sN="dpapi:v1:"}),MY=z(()=>{"use strict";gL(),sgt(),YSe(),zSe(),G0(),wwe(),sO(),wv(),fO(),s0e(),pgt(),Agt(),Fz(),Fgt(),Jz(),Zz(),Ygt()}),E0e={};jnt(E0e,{createDelegatedXenoAgent:()=>ql});NY=z(()=>{"use strict";cY(),hY(),MY(),Tx(),S0e=[{tool:"Write",decision:"deny"},{tool:"Edit",decision:"deny"},{tool:"MemoryWrite",decision:"deny"},{tool:"Bash",decision:"deny"},{tool:"dispatch_agent",decision:"deny"}]});Tx=z(()=>{"use strict";EA(),Cm(),iY(),$Ce(),gY(),FO(),MY(),BA(),S0=8192,C0=50});pv();Tp="0.9.31";ka();rs();DA=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=tAt(),n={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 _B(this.filePath,JSON.stringify(n))}),await this.writeQueue,t}async read(e){let t=await fi(this.filePath);if(!t)return[];let n=lC(t);return e?.eventType&&(n=n.filter(r=>r.event_type===e.eventType)),e?.traceId&&(n=n.filter(r=>r.trace_id===e.traceId)),e?.limit!==void 0&&(n=n.slice(-Math.max(0,e.limit))),n}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 Li(e,JSON.stringify(t,null,2)),t.length}async flush(){await this.writeQueue}};ewe();owe();T0e=1,DY=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"]),LY=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"]),QY=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),FY=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),QA=[...DY,...LY,...QY,...FY];Ue=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoAutomationError"}code;detail};Zz();oAt=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,Fme=1048576;_0e=1,$0e=1,VY=["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"],HY=["draft","pending_review","approved","rejected","superseded","archived"],WY=["public","internal","confidential","restricted"],GY=["agent","tool","user","system","integration"],TL=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],PL=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];dO();Px=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(n=>({...n}))}},JY=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"},fAt={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},mAt="[\\u0000-\\u001f\\u007f]",hAt=new RegExp(mAt),B0e=/^[a-f0-9]{64}$/,gAt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,AAt=new Set(HY),wAt=new Set(WY),yAt=new Set(GY),bAt=new Set(VY),vAt=new Set(TL),IAt=new Set(PL);At=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoArtifactRepositoryError"}code;detail},BL=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(Wme).map(t=>({artifact:GC(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(Rs(e),this.assertInitialState(e),e.revision!==1)throw new At("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 At("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=GC(e),n=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),r={artifact:t,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,r]])),this.currentRevisions.set(t.artifactId,t.revision),$g(r)}async createRevision(e,t={}){Rs(e),this.assertInitialState(e);let n=this.getMutable(e.artifactId);this.assertVersion(n,t.expectedRecordVersion);let r=n.artifact.revision+1;if(e.revision!==r||e.predecessorRevision!==n.artifact.revision)throw new At("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:e.artifactId,currentRevision:n.artifact.revision,requestedRevision:e.revision});if(EAt(e,n.artifact))throw new At("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(n.artifact.state==="archived")throw new At("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){x0(n.artifact.state,"superseded");let a=this.now(),c=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});n.artifact.state="superseded",n.artifact.updatedAt=a,n.lifecycleEvents.push(c),n.recordVersion+=1}let i=GC(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-${n.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),$g(s)}async get(e,t){let n=this.records.get(e);if(!n)return;let r=t??this.currentRevisions.get(e);if(r===void 0)return;let i=n.get(r);return i?$g(i):void 0}async require(e,t){let n=await this.get(e,t);if(!n)throw new At("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return n}async list(e={}){let t=[];for(let[n,r]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(n)))if(e.includeSuperseded)t.push(...r.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let o=r.get(i);o&&t.push(o)}}return t.filter(n=>SAt(n.artifact,e)).sort(Wme).map($g)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((n,r)=>n.artifact.revision-r.artifact.revision).map($g):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),x0(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=$L(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new At("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 At("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let n=this.now(),r=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:r,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:n});return t.artifact.state=e.toState,t.artifact.updatedAt=n,t.lifecycleEvents.push(i),t.recordVersion+=1,$g(t)}async appendReviewEvent(e){let t=e.event,n=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(n,e.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new At("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(n,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new At("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let r={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=_L(r,n.artifact);if(i.length>0)throw new Px("XENO artifact review event validation failed",i);return n.reviewEvents.push(r),n.recordVersion+=1,$g(n)}getMutable(e,t){let n=this.records.get(e),r=t??this.currentRevisions.get(e),i=r===void 0?void 0:n?.get(r);if(!i)throw new At("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 At("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 At("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(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.parentCommentId))throw new At("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(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let n=CAt(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&n.resolved)throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!n.resolved)throw new At("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 At("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 At("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((n,r)=>n.artifact.artifactId.localeCompare(r.artifact.artifactId)||n.artifact.revision-r.artifact.revision);for(let n of t){let r=kAt(n,this.eventIds),i=this.records.get(r.artifact.artifactId);if(i||(i=new Map,this.records.set(r.artifact.artifactId,i)),i.has(r.artifact.revision))throw new At("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${r.artifact.artifactId}:${r.artifact.revision}`);i.set(r.artifact.revision,r),this.currentRevisions.set(r.artifact.artifactId,r.artifact.revision)}for(let[n,r]of this.records){let i=[...r.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 At("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new At("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new At("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new At("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${a} must be superseded`)}}}};BX=32*1024*1024,xAt=1024*1024*1024,RAt=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;Jme=16*1024*1024;zme=3e4,Yme=1e3,KY=class{adapter;leaseAuthority;durable;artifactRepository;now;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())}execute(e,t){e=structuredClone(e);let n=QAt(e),r=this.executions.get(e.operationId);if(r){if(r.fingerprint!==n)throw new Ue("AUTOMATION_OPERATION_CONFLICT",`Operation ${e.operationId} was already submitted with different authority or parameters`);if(this.durable){let a=this.durable;return a.assertCurrent(e).then(()=>r.promise).then(async c=>(await a.assertCurrent(e),structuredClone(c)))}return r.promise}if(this.active.size>=Yme)throw new Ue("AUTOMATION_OPERATION_CONFLICT","Automation active-operation capacity reached");let i=new AbortController,o=FAt(t,i);this.active.set(e.operationId,i);let s=(this.durable?YY(this.durable,e,n,a=>this.executeFresh(e,i.signal,a)):this.executeFresh(e,i.signal)).finally(()=>{o(),this.active.delete(e.operationId)});return this.executions.set(e.operationId,{fingerprint:n,promise:s}),this.durable&&s.then(()=>this.executions.delete(e.operationId),()=>this.executions.delete(e.operationId)),this.trimIdempotencyRecords(),s}async stop(e,t="human-stop"){let n=this.active.get(e);return n?(n.abort(new Error(t)),await this.adapter.stop?.(e,t),!0):!1}async executeFresh(e,t,n){UY(e),eB(t);let r=await this.adapter.manifest();RL(r);let i=zc(e.operation),o=jY(e),s=this.now(),a=await this.adapter.preflight(e,t);NAt(a,this.now()),aN(e,r,a.observedTarget),eB(t);let c=a.evidence??[];JC(c,o,"before");let l=await R0(this.artifactRepository,cN({request:e,manifest:r,policy:o,evidence:c,now:this.now}));if(eB(t),Date.parse(a.expiresAt)<=Date.parse(this.now()))throw new Ue("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let u=qY(e,a.observedTarget),d;if(this.durable){await this.durable.assertCurrent(e);let b=await this.durable.consume(n,e.capabilityLeaseId,e.expectedLeaseVersion,u);if(b.executionDisposition!=="dispatch-once"||b.replayed)throw vp();d=b.lease,await this.durable.assertCurrent(e)}else d=await this.leaseAuthority.consume(e.capabilityLeaseId,e.expectedLeaseVersion,u);let p={contractFingerprint:e.executionContract.fingerprint,lease:d,capabilityUse:u},f;try{eB(t),f=await this.adapter.execute(e,a,p,t)}catch(b){return o4({request:e,manifest:r,descriptorEffect:i.effect,target:a.observedTarget,lease:d,artifacts:l,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":UAt(b)})}if(OAt(f),f.operationId!==void 0&&f.operationId!==e.operationId)throw new Ue("AUTOMATION_RESPONSE_INVALID","Adapter returned another operation identity");let m=DAt(a.observedTarget,f.observedTarget),h;try{aN(e,r,f.observedTarget)}catch(b){h=b instanceof Error?b:new Error(String(b))}let g=f.evidence??[];LAt(c,g);let A=[],y;try{JC(g,o,"after"),JC([...c,...g],o,"recording"),A=await R0(this.artifactRepository,cN({request:e,manifest:r,policy:o,evidence:g,now:this.now}))}catch(b){y=b instanceof Error?b:new Error(String(b))}let w=[...l,...A];return m||h?o4({request:e,manifest:r,descriptorEffect:i.effect,target:f.observedTarget,lease:d,artifacts:w,startedAt:f.startedAt,completedAt:f.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:m??h.message}):y?o4({request:e,manifest:r,descriptorEffect:i.effect,target:f.observedTarget,lease:d,artifacts:w,startedAt:f.startedAt,completedAt:f.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:y.message}):{operationId:e.operationId,status:f.status,effect:i.effect,startedAt:f.startedAt,completedAt:f.completedAt,adapter:N0e(r),target:structuredClone(f.observedTarget),...f.data!==void 0?{data:structuredClone(f.data)}:{},artifacts:w,lease:O0e(d),...f.error?{error:{...f.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>Yme;){let e=this.executions.keys().next().value;if(!e||this.active.has(e))break;this.executions.delete(e)}}};ZY=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),NX(e),Eb(e,["operationId","fingerprint","ownerToken"]),this.transaction(()=>{let t=this.read(e.operationId);if(t){if(t.fingerprint!==e.fingerprint)throw tB();return{claimed:!1,record:t}}let n=this.database.prepare("SELECT COUNT(*) AS count FROM automation_executions").get()?.count;if(typeof n!="number"||n>=1e5)throw Error("Automation journal capacity reached; explicit archival required");let r={schemaVersion:1,...e,outcome:{kind:"pending"}};return this.database.prepare("INSERT INTO automation_executions(id,body) VALUES(?,?)").run(e.operationId,Kme(r)),{claimed:!0,record:r}})}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),NX(e),Eb(e,["operationId","fingerprint","ownerToken"]);let n={schemaVersion:1,...e,outcome:t};return OX(n),this.transaction(()=>{let r=this.read(e.operationId);if(!r||r.fingerprint!==e.fingerprint||r.ownerToken!==e.ownerToken)throw tB();if(r.outcome.kind!=="pending"){if(JSON.stringify(r.outcome)!==JSON.stringify(t))throw tB();return}this.database.prepare("UPDATE automation_executions SET body=? WHERE id=?").run(Kme(n),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 n=JSON.parse(t.body);if(OX(n),n.operationId!==e)throw tB();return n}async transaction(e){let t=Date.now()+1e3;for(;;){if(this.closed)throw Error("Automation journal closed");let n=!1;try{this.database.exec("BEGIN IMMEDIATE"),n=!0;let r=e();return this.database.exec("COMMIT"),r}catch(r){if(n)try{this.database.exec("ROLLBACK")}catch{}if(Date.now()>=t||!/SQLITE_BUSY|database is locked/.test(String(r)))throw r;await new Promise(i=>setTimeout(i,10))}}}};VAt=6e4,HAt=48*1024*1024,Q0e=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(e){if(this.endpoint=WAt(e.baseUrl),this.token=GAt(e.token),this.timeoutMs=Zme(e.timeoutMs??VAt,1e3,3e5,"timeoutMs"),this.maxResponseBytes=Zme(e.maxResponseBytes??HAt,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=e.fetch??globalThis.fetch,typeof this.fetchImpl!="function")throw new Ue("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}preflight(e,t){return this.request("preflight","POST",e,t)}execute(e,t,n,r){return this.request("execute","POST",{request:e,preflight:t,grant:n},r)}async stop(e,t){await this.request("stop","POST",{operationId:e,reason:t.slice(0,512)})}async request(e,t,n,r){let i=new AbortController,o=zAt(r,i),s=setTimeout(()=>i.abort(new Error("automation transport timeout")),this.timeoutMs);s.unref?.();try{let a=new URL(e,this.endpoint),c=await 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(n??{})}:{},signal:i.signal}),l=await JAt(c,this.maxResponseBytes);if(!c.ok){let u=XAt(l);throw new Ue("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${e}: ${u.message}`,{status:c.status,route:e,adapterCode:u.code})}if(!DX(l)||l.ok!==!0||!("result"in l))throw new Ue("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${e} envelope`);return l.result}catch(a){if(a instanceof Ue)throw a;let c=r?.aborted;throw new Ue(c?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",c?"Automation transport was stopped":`XENO Browser ${e} transport failed`,{route:e},{cause:a})}finally{clearTimeout(s),o()}}};_x=["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"],ML=class{constructor(e){if(this.options=e,this.base=ewt(e.baseUrl),this.fetchImpl=e.fetch??globalThis.fetch,this.timeoutMs=e.timeoutMs??6e4,!twt(e.token))throw new Error("XENO browser control-plane token is invalid")}options;base;fetchImpl;timeoutMs;async manifest(){let e=await this.call("health",void 0),t=_x.filter(n=>e.verbs?.includes(ehe(n))??!1);return{protocolVersion:1,adapterId:this.options.driver==="extension"?"xeno-extension-native":"xeno-browser-native",adapterVersion:e.version??"unknown",platform:process.platform,architecture:process.arch,operations:t,targetBinding:"atomic-preflight",profileIsolation:this.options.driver==="browser"?"both":"none",supports:{accessibilitySnapshots:!0,screenshots:!0,recordings:!1,consoleInspection:!0,networkInspection:!0,storageInspection:t.includes("browser.storage.read"),pageErrorInspection:!0,visibleCoControl:!0,deterministicHandback:!0,immediateStop:!0,sensitiveRegionRedaction:!1},policyEnforcement:{domain:!0,scheme:!0,port:!0,redirect:!0,upload:t.includes("browser.upload"),download:t.includes("browser.download")},certified:!1,limitations:[`${this.options.driver==="extension"?"Extension":"Browser"} transport is policy-enforced but not release-certified`,"sensitive-region screenshot redaction is not available"]}}async preflight(e,t){ZAt(e.operation);let n=await this.call("health",void 0,t);if(!n.verbs?.includes(ehe(e.operation)))throw new Error(`${this.options.driver} driver does not support ${e.operation}`);let r=ihe(n.activeTab),i=Sb(e.parameters.tabId)??e.declaredTarget?.tabId;if(i&&r&&i!==r)throw new Error(`Requested tab ${i} is not the active browser tab ${r}`);let o=the(e,r);nhe(e,o);let s=new Date;return{token:`${e.operationId}:${r??"unbound"}:${YAt()}`,preparedAt:s.toISOString(),expiresAt:new Date(s.getTime()+2e4).toISOString(),observedTarget:o,...U0e(e.operation)?{evidence:[await this.snapshotEvidence(e,"before",t)]}:{},adapterState:{activeTab:r??null,driver:this.options.driver}}}async execute(e,t,n,r){let i=new Date().toISOString(),o=await this.call("health",void 0,r),s=ihe(o.activeTab);if(t.observedTarget.tabId&&s!==t.observedTarget.tabId)throw new Error("Active browser tab changed after atomic preflight");nhe(e,t.observedTarget);try{let a=F0e(e.operation,e.parameters),c=await this.call(a.verb,a.params,r),l=the(e,s),u=e.operation==="browser.wait"||e.operation==="browser.tabs.list"?[]:[await this.resultEvidence(e,c,r)];return{status:"ok",startedAt:i,completedAt:new Date().toISOString(),observedTarget:l,data:rwt(c),...u.length?{evidence:u}:{}}}catch(a){let c={code:owt(a),message:iwt(a),retryable:!1};return{status:swt(a),startedAt:i,completedAt:new Date().toISOString(),observedTarget:t.observedTarget,error:c,evidence:[{evidenceId:`${e.operationId}-after-failure`,phase:"after",kind:"browser-snapshot",title:`${e.operation} failed attempt`,mediaType:"application/json",content:{type:"text",text:JSON.stringify({error:c})},sensitivity:"restricted"}]}}}async stop(e,t){await this.call("stop",{})}async resultEvidence(e,t,n){return e.operation==="browser.screenshot"?KAt(e,"after",t):this.snapshotEvidence(e,"after",n)}async snapshotEvidence(e,t,n){let r=await this.call("observe",{limit:1e3},n);return{evidenceId:`${e.operationId}-${t}`,phase:t,kind:"browser-snapshot",title:`${e.operation} ${t} state`,mediaType:"application/json",content:{type:"text",text:JSON.stringify(r)},sensitivity:"restricted"}}async call(e,t,n){let r=new AbortController,i=()=>r.abort(n?.reason);n?.aborted?i():n?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>r.abort(new Error("browser control-plane timeout")),this.timeoutMs);o.unref?.();try{let s=await this.fetchImpl(new URL(`/v1/browser/${e}`,this.base),{method:e==="health"?"GET":"POST",redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.options.token}`,accept:"application/json",...e==="health"?{}:{"content-type":"application/json"}},...e==="health"?{}:{body:JSON.stringify(t??{})},signal:r.signal}),a=await s.json();if(!s.ok||a.ok!==!0)throw Object.assign(new Error(a.error?.message??`Browser ${e} failed with HTTP ${s.status}`),{code:a.error?.code??`HTTP_${s.status}`,status:s.status});return a.result}finally{clearTimeout(o),n?.removeEventListener("abort",i)}}};NL=1,Iwt="repository.v1.json",kwt=5e3,Ewt=20,Swt=64*1024*1024,tK=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??Iwt;if(ahe(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=pwt(e.directory),this.snapshotPath=dwt(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=s4(e.lockTimeoutMs,kwt,100,6e4,"lockTimeoutMs"),this.lockRetryMs=s4(e.lockRetryMs,Ewt,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=s4(e.maxSnapshotBytes,Swt,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(n=>n.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 n=await this.load(),r=await e(n.repository);return await this.persist(n),r}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 FA(this.lockPath,`artifact-repository:${ahe(this.snapshotPath)}`,Tp)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;t=n,await Pwt(this.lockRetryMs)}throw new At("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,n=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=uN(i)}if(!t&&(e||await Twt(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,n=!0)}catch(i){throw e?new At("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,uN(i)])}):i}if(!t&&e)throw e;let r=t?.state??{schemaVersion:1,records:[]};return{repository:new BL({now:this.now,idFactory:i=>`${i}_${V0e()}`,initialState:r}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:n,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),n={schemaVersion:NL,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},r=xwt(n),i=`${JSON.stringify(r,null,2)}
|
|
2660
|
+
`});Ygt=z(()=>{"use strict";is(),Ome(),Ome(),kL="ai.xenostudio.xeno-agent.mcp",EL="xeno.host.state.encryption-key.v1",SC="aes-256-gcm",dm=32,oM=12,PX=16,Ab="b64:",sN="dpapi:v1:"}),MY=z(()=>{"use strict";gL(),sgt(),YSe(),zSe(),G0(),wwe(),sO(),wv(),fO(),s0e(),pgt(),Agt(),Fz(),Fgt(),Jz(),Zz(),Ygt()}),E0e={};jnt(E0e,{createDelegatedXenoAgent:()=>ql});NY=z(()=>{"use strict";cY(),hY(),MY(),Tx(),S0e=[{tool:"Write",decision:"deny"},{tool:"Edit",decision:"deny"},{tool:"MemoryWrite",decision:"deny"},{tool:"Bash",decision:"deny"},{tool:"dispatch_agent",decision:"deny"}]});Tx=z(()=>{"use strict";EA(),Cm(),iY(),$Ce(),gY(),FO(),MY(),BA(),S0=8192,C0=50});pv();Tp="0.9.32";ka();rs();DA=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=tAt(),n={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 _B(this.filePath,JSON.stringify(n))}),await this.writeQueue,t}async read(e){let t=await fi(this.filePath);if(!t)return[];let n=lC(t);return e?.eventType&&(n=n.filter(r=>r.event_type===e.eventType)),e?.traceId&&(n=n.filter(r=>r.trace_id===e.traceId)),e?.limit!==void 0&&(n=n.slice(-Math.max(0,e.limit))),n}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 Li(e,JSON.stringify(t,null,2)),t.length}async flush(){await this.writeQueue}};ewe();owe();T0e=1,DY=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"]),LY=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"]),QY=new Set(["computer.observe","computer.screenshot","computer.window-state","computer.wait"]),FY=new Set(["computer.point","computer.click","computer.double-click","computer.right-click","computer.drag","computer.type","computer.key","computer.scroll","computer.launch"]),QA=[...DY,...LY,...QY,...FY];Ue=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoAutomationError"}code;detail};Zz();oAt=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/,Fme=1048576;_0e=1,$0e=1,VY=["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"],HY=["draft","pending_review","approved","rejected","superseded","archived"],WY=["public","internal","confidential","restricted"],GY=["agent","tool","user","system","integration"],TL=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],PL=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];dO();Px=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(n=>({...n}))}},JY=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"},fAt={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},mAt="[\\u0000-\\u001f\\u007f]",hAt=new RegExp(mAt),B0e=/^[a-f0-9]{64}$/,gAt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,AAt=new Set(HY),wAt=new Set(WY),yAt=new Set(GY),bAt=new Set(VY),vAt=new Set(TL),IAt=new Set(PL);At=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoArtifactRepositoryError"}code;detail},BL=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(Wme).map(t=>({artifact:GC(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(Rs(e),this.assertInitialState(e),e.revision!==1)throw new At("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 At("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=GC(e),n=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),r={artifact:t,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,r]])),this.currentRevisions.set(t.artifactId,t.revision),$g(r)}async createRevision(e,t={}){Rs(e),this.assertInitialState(e);let n=this.getMutable(e.artifactId);this.assertVersion(n,t.expectedRecordVersion);let r=n.artifact.revision+1;if(e.revision!==r||e.predecessorRevision!==n.artifact.revision)throw new At("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:e.artifactId,currentRevision:n.artifact.revision,requestedRevision:e.revision});if(EAt(e,n.artifact))throw new At("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(n.artifact.state==="archived")throw new At("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){x0(n.artifact.state,"superseded");let a=this.now(),c=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});n.artifact.state="superseded",n.artifact.updatedAt=a,n.lifecycleEvents.push(c),n.recordVersion+=1}let i=GC(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-${n.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),$g(s)}async get(e,t){let n=this.records.get(e);if(!n)return;let r=t??this.currentRevisions.get(e);if(r===void 0)return;let i=n.get(r);return i?$g(i):void 0}async require(e,t){let n=await this.get(e,t);if(!n)throw new At("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return n}async list(e={}){let t=[];for(let[n,r]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(n)))if(e.includeSuperseded)t.push(...r.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let o=r.get(i);o&&t.push(o)}}return t.filter(n=>SAt(n.artifact,e)).sort(Wme).map($g)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((n,r)=>n.artifact.revision-r.artifact.revision).map($g):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),x0(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=$L(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new At("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 At("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let n=this.now(),r=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:r,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:n});return t.artifact.state=e.toState,t.artifact.updatedAt=n,t.lifecycleEvents.push(i),t.recordVersion+=1,$g(t)}async appendReviewEvent(e){let t=e.event,n=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(n,e.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new At("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(n,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new At("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let r={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=_L(r,n.artifact);if(i.length>0)throw new Px("XENO artifact review event validation failed",i);return n.reviewEvents.push(r),n.recordVersion+=1,$g(n)}getMutable(e,t){let n=this.records.get(e),r=t??this.currentRevisions.get(e),i=r===void 0?void 0:n?.get(r);if(!i)throw new At("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 At("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 At("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(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.parentCommentId))throw new At("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(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let n=CAt(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&n.resolved)throw new At("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!n.resolved)throw new At("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 At("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 At("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((n,r)=>n.artifact.artifactId.localeCompare(r.artifact.artifactId)||n.artifact.revision-r.artifact.revision);for(let n of t){let r=kAt(n,this.eventIds),i=this.records.get(r.artifact.artifactId);if(i||(i=new Map,this.records.set(r.artifact.artifactId,i)),i.has(r.artifact.revision))throw new At("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${r.artifact.artifactId}:${r.artifact.revision}`);i.set(r.artifact.revision,r),this.currentRevisions.set(r.artifact.artifactId,r.artifact.revision)}for(let[n,r]of this.records){let i=[...r.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 At("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new At("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new At("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new At("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${a} must be superseded`)}}}};BX=32*1024*1024,xAt=1024*1024*1024,RAt=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;Jme=16*1024*1024;zme=3e4,Yme=1e3,KY=class{adapter;leaseAuthority;durable;artifactRepository;now;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())}execute(e,t){e=structuredClone(e);let n=QAt(e),r=this.executions.get(e.operationId);if(r){if(r.fingerprint!==n)throw new Ue("AUTOMATION_OPERATION_CONFLICT",`Operation ${e.operationId} was already submitted with different authority or parameters`);if(this.durable){let a=this.durable;return a.assertCurrent(e).then(()=>r.promise).then(async c=>(await a.assertCurrent(e),structuredClone(c)))}return r.promise}if(this.active.size>=Yme)throw new Ue("AUTOMATION_OPERATION_CONFLICT","Automation active-operation capacity reached");let i=new AbortController,o=FAt(t,i);this.active.set(e.operationId,i);let s=(this.durable?YY(this.durable,e,n,a=>this.executeFresh(e,i.signal,a)):this.executeFresh(e,i.signal)).finally(()=>{o(),this.active.delete(e.operationId)});return this.executions.set(e.operationId,{fingerprint:n,promise:s}),this.durable&&s.then(()=>this.executions.delete(e.operationId),()=>this.executions.delete(e.operationId)),this.trimIdempotencyRecords(),s}async stop(e,t="human-stop"){let n=this.active.get(e);return n?(n.abort(new Error(t)),await this.adapter.stop?.(e,t),!0):!1}async executeFresh(e,t,n){UY(e),eB(t);let r=await this.adapter.manifest();RL(r);let i=zc(e.operation),o=jY(e),s=this.now(),a=await this.adapter.preflight(e,t);NAt(a,this.now()),aN(e,r,a.observedTarget),eB(t);let c=a.evidence??[];JC(c,o,"before");let l=await R0(this.artifactRepository,cN({request:e,manifest:r,policy:o,evidence:c,now:this.now}));if(eB(t),Date.parse(a.expiresAt)<=Date.parse(this.now()))throw new Ue("AUTOMATION_PREFLIGHT_INVALID","Automation preflight expired before authority consumption");let u=qY(e,a.observedTarget),d;if(this.durable){await this.durable.assertCurrent(e);let b=await this.durable.consume(n,e.capabilityLeaseId,e.expectedLeaseVersion,u);if(b.executionDisposition!=="dispatch-once"||b.replayed)throw vp();d=b.lease,await this.durable.assertCurrent(e)}else d=await this.leaseAuthority.consume(e.capabilityLeaseId,e.expectedLeaseVersion,u);let p={contractFingerprint:e.executionContract.fingerprint,lease:d,capabilityUse:u},f;try{eB(t),f=await this.adapter.execute(e,a,p,t)}catch(b){return o4({request:e,manifest:r,descriptorEffect:i.effect,target:a.observedTarget,lease:d,artifacts:l,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":UAt(b)})}if(OAt(f),f.operationId!==void 0&&f.operationId!==e.operationId)throw new Ue("AUTOMATION_RESPONSE_INVALID","Adapter returned another operation identity");let m=DAt(a.observedTarget,f.observedTarget),h;try{aN(e,r,f.observedTarget)}catch(b){h=b instanceof Error?b:new Error(String(b))}let g=f.evidence??[];LAt(c,g);let A=[],y;try{JC(g,o,"after"),JC([...c,...g],o,"recording"),A=await R0(this.artifactRepository,cN({request:e,manifest:r,policy:o,evidence:g,now:this.now}))}catch(b){y=b instanceof Error?b:new Error(String(b))}let w=[...l,...A];return m||h?o4({request:e,manifest:r,descriptorEffect:i.effect,target:f.observedTarget,lease:d,artifacts:w,startedAt:f.startedAt,completedAt:f.completedAt,status:"error",code:"AUTOMATION_TARGET_CHANGED",message:m??h.message}):y?o4({request:e,manifest:r,descriptorEffect:i.effect,target:f.observedTarget,lease:d,artifacts:w,startedAt:f.startedAt,completedAt:f.completedAt,status:"evidence-incomplete",code:"AUTOMATION_EVIDENCE_INCOMPLETE",message:y.message}):{operationId:e.operationId,status:f.status,effect:i.effect,startedAt:f.startedAt,completedAt:f.completedAt,adapter:N0e(r),target:structuredClone(f.observedTarget),...f.data!==void 0?{data:structuredClone(f.data)}:{},artifacts:w,lease:O0e(d),...f.error?{error:{...f.error}}:{}}}trimIdempotencyRecords(){for(;this.executions.size>Yme;){let e=this.executions.keys().next().value;if(!e||this.active.has(e))break;this.executions.delete(e)}}};ZY=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),NX(e),Eb(e,["operationId","fingerprint","ownerToken"]),this.transaction(()=>{let t=this.read(e.operationId);if(t){if(t.fingerprint!==e.fingerprint)throw tB();return{claimed:!1,record:t}}let n=this.database.prepare("SELECT COUNT(*) AS count FROM automation_executions").get()?.count;if(typeof n!="number"||n>=1e5)throw Error("Automation journal capacity reached; explicit archival required");let r={schemaVersion:1,...e,outcome:{kind:"pending"}};return this.database.prepare("INSERT INTO automation_executions(id,body) VALUES(?,?)").run(e.operationId,Kme(r)),{claimed:!0,record:r}})}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),NX(e),Eb(e,["operationId","fingerprint","ownerToken"]);let n={schemaVersion:1,...e,outcome:t};return OX(n),this.transaction(()=>{let r=this.read(e.operationId);if(!r||r.fingerprint!==e.fingerprint||r.ownerToken!==e.ownerToken)throw tB();if(r.outcome.kind!=="pending"){if(JSON.stringify(r.outcome)!==JSON.stringify(t))throw tB();return}this.database.prepare("UPDATE automation_executions SET body=? WHERE id=?").run(Kme(n),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 n=JSON.parse(t.body);if(OX(n),n.operationId!==e)throw tB();return n}async transaction(e){let t=Date.now()+1e3;for(;;){if(this.closed)throw Error("Automation journal closed");let n=!1;try{this.database.exec("BEGIN IMMEDIATE"),n=!0;let r=e();return this.database.exec("COMMIT"),r}catch(r){if(n)try{this.database.exec("ROLLBACK")}catch{}if(Date.now()>=t||!/SQLITE_BUSY|database is locked/.test(String(r)))throw r;await new Promise(i=>setTimeout(i,10))}}}};VAt=6e4,HAt=48*1024*1024,Q0e=class{endpoint;token;timeoutMs;maxResponseBytes;fetchImpl;constructor(e){if(this.endpoint=WAt(e.baseUrl),this.token=GAt(e.token),this.timeoutMs=Zme(e.timeoutMs??VAt,1e3,3e5,"timeoutMs"),this.maxResponseBytes=Zme(e.maxResponseBytes??HAt,1024,128*1024*1024,"maxResponseBytes"),this.fetchImpl=e.fetch??globalThis.fetch,typeof this.fetchImpl!="function")throw new Ue("AUTOMATION_TRANSPORT_ERROR","A Fetch API implementation is required")}manifest(){return this.request("manifest","GET")}preflight(e,t){return this.request("preflight","POST",e,t)}execute(e,t,n,r){return this.request("execute","POST",{request:e,preflight:t,grant:n},r)}async stop(e,t){await this.request("stop","POST",{operationId:e,reason:t.slice(0,512)})}async request(e,t,n,r){let i=new AbortController,o=zAt(r,i),s=setTimeout(()=>i.abort(new Error("automation transport timeout")),this.timeoutMs);s.unref?.();try{let a=new URL(e,this.endpoint),c=await 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(n??{})}:{},signal:i.signal}),l=await JAt(c,this.maxResponseBytes);if(!c.ok){let u=XAt(l);throw new Ue("AUTOMATION_TRANSPORT_ERROR",`XENO Browser rejected ${e}: ${u.message}`,{status:c.status,route:e,adapterCode:u.code})}if(!DX(l)||l.ok!==!0||!("result"in l))throw new Ue("AUTOMATION_RESPONSE_INVALID",`XENO Browser returned an invalid ${e} envelope`);return l.result}catch(a){if(a instanceof Ue)throw a;let c=r?.aborted;throw new Ue(c?"AUTOMATION_CANCELLED":"AUTOMATION_TRANSPORT_ERROR",c?"Automation transport was stopped":`XENO Browser ${e} transport failed`,{route:e},{cause:a})}finally{clearTimeout(s),o()}}};_x=["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"],ML=class{constructor(e){if(this.options=e,this.base=ewt(e.baseUrl),this.fetchImpl=e.fetch??globalThis.fetch,this.timeoutMs=e.timeoutMs??6e4,!twt(e.token))throw new Error("XENO browser control-plane token is invalid")}options;base;fetchImpl;timeoutMs;async manifest(){let e=await this.call("health",void 0),t=_x.filter(n=>e.verbs?.includes(ehe(n))??!1);return{protocolVersion:1,adapterId:this.options.driver==="extension"?"xeno-extension-native":"xeno-browser-native",adapterVersion:e.version??"unknown",platform:process.platform,architecture:process.arch,operations:t,targetBinding:"atomic-preflight",profileIsolation:this.options.driver==="browser"?"both":"none",supports:{accessibilitySnapshots:!0,screenshots:!0,recordings:!1,consoleInspection:!0,networkInspection:!0,storageInspection:t.includes("browser.storage.read"),pageErrorInspection:!0,visibleCoControl:!0,deterministicHandback:!0,immediateStop:!0,sensitiveRegionRedaction:!1},policyEnforcement:{domain:!0,scheme:!0,port:!0,redirect:!0,upload:t.includes("browser.upload"),download:t.includes("browser.download")},certified:!1,limitations:[`${this.options.driver==="extension"?"Extension":"Browser"} transport is policy-enforced but not release-certified`,"sensitive-region screenshot redaction is not available"]}}async preflight(e,t){ZAt(e.operation);let n=await this.call("health",void 0,t);if(!n.verbs?.includes(ehe(e.operation)))throw new Error(`${this.options.driver} driver does not support ${e.operation}`);let r=ihe(n.activeTab),i=Sb(e.parameters.tabId)??e.declaredTarget?.tabId;if(i&&r&&i!==r)throw new Error(`Requested tab ${i} is not the active browser tab ${r}`);let o=the(e,r);nhe(e,o);let s=new Date;return{token:`${e.operationId}:${r??"unbound"}:${YAt()}`,preparedAt:s.toISOString(),expiresAt:new Date(s.getTime()+2e4).toISOString(),observedTarget:o,...U0e(e.operation)?{evidence:[await this.snapshotEvidence(e,"before",t)]}:{},adapterState:{activeTab:r??null,driver:this.options.driver}}}async execute(e,t,n,r){let i=new Date().toISOString(),o=await this.call("health",void 0,r),s=ihe(o.activeTab);if(t.observedTarget.tabId&&s!==t.observedTarget.tabId)throw new Error("Active browser tab changed after atomic preflight");nhe(e,t.observedTarget);try{let a=F0e(e.operation,e.parameters),c=await this.call(a.verb,a.params,r),l=the(e,s),u=e.operation==="browser.wait"||e.operation==="browser.tabs.list"?[]:[await this.resultEvidence(e,c,r)];return{status:"ok",startedAt:i,completedAt:new Date().toISOString(),observedTarget:l,data:rwt(c),...u.length?{evidence:u}:{}}}catch(a){let c={code:owt(a),message:iwt(a),retryable:!1};return{status:swt(a),startedAt:i,completedAt:new Date().toISOString(),observedTarget:t.observedTarget,error:c,evidence:[{evidenceId:`${e.operationId}-after-failure`,phase:"after",kind:"browser-snapshot",title:`${e.operation} failed attempt`,mediaType:"application/json",content:{type:"text",text:JSON.stringify({error:c})},sensitivity:"restricted"}]}}}async stop(e,t){await this.call("stop",{})}async resultEvidence(e,t,n){return e.operation==="browser.screenshot"?KAt(e,"after",t):this.snapshotEvidence(e,"after",n)}async snapshotEvidence(e,t,n){let r=await this.call("observe",{limit:1e3},n);return{evidenceId:`${e.operationId}-${t}`,phase:t,kind:"browser-snapshot",title:`${e.operation} ${t} state`,mediaType:"application/json",content:{type:"text",text:JSON.stringify(r)},sensitivity:"restricted"}}async call(e,t,n){let r=new AbortController,i=()=>r.abort(n?.reason);n?.aborted?i():n?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>r.abort(new Error("browser control-plane timeout")),this.timeoutMs);o.unref?.();try{let s=await this.fetchImpl(new URL(`/v1/browser/${e}`,this.base),{method:e==="health"?"GET":"POST",redirect:"error",cache:"no-store",credentials:"omit",headers:{authorization:`Bearer ${this.options.token}`,accept:"application/json",...e==="health"?{}:{"content-type":"application/json"}},...e==="health"?{}:{body:JSON.stringify(t??{})},signal:r.signal}),a=await s.json();if(!s.ok||a.ok!==!0)throw Object.assign(new Error(a.error?.message??`Browser ${e} failed with HTTP ${s.status}`),{code:a.error?.code??`HTTP_${s.status}`,status:s.status});return a.result}finally{clearTimeout(o),n?.removeEventListener("abort",i)}}};NL=1,Iwt="repository.v1.json",kwt=5e3,Ewt=20,Swt=64*1024*1024,tK=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??Iwt;if(ahe(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=pwt(e.directory),this.snapshotPath=dwt(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=s4(e.lockTimeoutMs,kwt,100,6e4,"lockTimeoutMs"),this.lockRetryMs=s4(e.lockRetryMs,Ewt,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=s4(e.maxSnapshotBytes,Swt,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(n=>n.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 n=await this.load(),r=await e(n.repository);return await this.persist(n),r}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 FA(this.lockPath,`artifact-repository:${ahe(this.snapshotPath)}`,Tp)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;t=n,await Pwt(this.lockRetryMs)}throw new At("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,n=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=uN(i)}if(!t&&(e||await Twt(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,n=!0)}catch(i){throw e?new At("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,uN(i)])}):i}if(!t&&e)throw e;let r=t?.state??{schemaVersion:1,records:[]};return{repository:new BL({now:this.now,idFactory:i=>`${i}_${V0e()}`,initialState:r}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:n,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),n={schemaVersion:NL,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},r=xwt(n),i=`${JSON.stringify(r,null,2)}
|
|
2661
2661
|
`;if(Buffer.byteLength(i,"utf8")>this.maxSnapshotBytes)throw new At("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await H0e(this.directory,{recursive:!0,mode:448}),e.hasSnapshot&&!e.recoveredFromBackup&&e.sourceSnapshot&&await uhe(this.backupPath,`${JSON.stringify(e.sourceSnapshot,null,2)}
|
|
2662
2662
|
`),await uhe(this.snapshotPath,i)}async readSnapshot(e,t){let n;try{n=await W0e(e)}catch(r){if(!t&&LX(r,"ENOENT")||t&&LX(r,"ENOENT"))return;throw QX("Unable to inspect artifact repository snapshot",e,r)}if(!n.isFile()||n.size>this.maxSnapshotBytes)throw new At("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:e,sizeBytes:n.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let r=await cwt(e);if(r.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return Cwt(JSON.parse(r.toString("utf8")),e)}catch(r){throw r instanceof At?r:QX("Unable to parse artifact repository snapshot",e,r,!0)}}};fO();Zz();Bwt=8*1024*1024,Mwt=4;K0e=[..._x],Ywt=K0e.filter(e=>!["browser.storage.read","browser.upload","browser.download"].includes(e)),Kwt=QA.filter(e=>e.startsWith("computer.")),c4=6e4,OL=class{constructor(e){this.options=e,this.environment=e.environment??Bx()}options;leases=new wm({maximumDurationMs:c4,maximumUses:1});activeExecutors=new Map;environment;browserAdapter;computerAdapter;register(e){if(this.options.safeMode)return 0;let t=[];return UX(this.environment.browser)&&t.push(...nyt(this.environment.browser.driver)),qX(this.environment.computer)&&t.push(...Kwt),t.length===0?0:(e.registerAll(nK({runtime:this,operations:t})),t.length)}async execute(e){if(this.options.safeMode)throw new Error("Governed automation is disabled in safe mode");dyt(e);let t=zc(e.operation),n=this.options.profile(),r={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}:{}},i=cyt(e.operation,e.declaredTarget,this.environment),o=t.surface==="browser"?t.effect==="act"?"browser-act":"browser-read":t.effect==="act"?"computer-act":"computer-observe",s=t.effect==="act"?"external":"read",a=lyt(i),c=uyt(i),l=this.leases.request({subject:{...r,toolName:e.governingToolName,operationId:e.operationId},scope:{kind:o,effect:s,operations:[e.operation],...a?{resources:[a]}:{},...c?{destinations:[c]}:{},governingToolName:e.governingToolName},reason:`${e.operation} authorized by the CLI policy and permission layers`,requestedBy:{kind:"agent",id:r.agentId,profileFingerprint:n.fingerprint},durationMs:c4,requestTtlMs:3e4,maxUses:1,childInheritance:"none",policyFingerprints:[n.fingerprint]},n),u=this.leases.approve({leaseId:l.leaseId,expectedVersion:l.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}}),d=await this.adapterFor(t.surface),p=zz({contractId:`contract-${e.operationId}`,identity:r,policy:this.securityPolicy(),profile:n,...this.options.securityStatus?{adapterStatus:this.options.securityStatus}:{},filesystem:{readRoots:[KS(this.options.cwd())],writeRoots:[KS(this.options.cwd())],executeRoots:[KS(this.options.cwd())]},network:ayt(i,this.environment),browser:t.surface==="browser"?oyt(t.effect,i,this.environment):{mode:"none"},computer:t.surface==="computer"?syt(t.effect,this.environment):{mode:"none"},capabilityLeaseIds:[u.leaseId],expiresAt:new Date(Date.now()+c4).toISOString()});await this.audit({eventType:"automation_lease_approved",traceId:e.authorization.turnId,operation:e.operation,operationId:e.operationId,leaseId:u.leaseId,contractFingerprint:p.fingerprint,permissionReason:e.authorization.permission.reason});let f=new KY({adapter:d,leaseAuthority:this.leases,artifactRepository:new tK({directory:KS(this.options.cwd(),".xeno","artifacts")})});this.activeExecutors.set(e.operationId,f),e.reportProgress?.({activity:"state",message:`Executing governed ${e.operation}`});try{let m=await f.execute({protocolVersion:1,operationId:e.operationId,idempotencyKey:e.idempotencyKey,requestedAt:new Date().toISOString(),identity:r,governingToolName:e.governingToolName,operation:e.operation,parameters:pyt(e.parameters),...i?{declaredTarget:i}:{},executionContract:p,capabilityLeaseId:u.leaseId,expectedLeaseVersion:u.version},e.signal);return await this.audit({eventType:m.status==="ok"?"automation_completed":"automation_failed",traceId:e.authorization.turnId,operation:e.operation,operationId:e.operationId,leaseId:u.leaseId,contractFingerprint:p.fingerprint,status:m.status,artifactIds:m.artifacts.map(h=>h.artifactId)}),m}catch(m){throw await this.audit({eventType:"automation_failed",traceId:e.authorization.turnId,operation:e.operation,operationId:e.operationId,leaseId:u.leaseId,contractFingerprint:p.fingerprint,status:m instanceof Error?m.name:"error"}),m}finally{this.activeExecutors.delete(e.operationId)}}async stop(e,t="human-stop"){let n=this.activeExecutors.get(e);return n?n.stop(e,t):!1}securityPolicy(){let e=this.options.securityPolicy?.();if(e)return e;let t=KS(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 n=this.environment.browser;if(!UX(n))throw new Error(exe(n));return this.browserAdapter??=new ML({baseUrl:n.baseUrl,token:n.token,driver:n.driver}),this.browserAdapter}let t=this.environment.computer;if(!qX(t))throw new Error(txe(t));return this.computerAdapter??=Z0e(t),this.computerAdapter}async audit(e){try{await this.options.onAudit?.(e)}catch{}}};dO();oK=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}))}},gyt=new Set(["depends_on","decomposes","supersedes"]),Ayt=new Set(TL),wyt=new Set(PL);oxe=class{now;graph;constructor(e){if("schemaVersion"in e)Xg(e),this.now=()=>new Date().toISOString(),this.graph=rB(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:[]},Xg(this.graph)}}addNode(e){let t=rB(this.graph);return t.nodes.push(sxe(e)),this.touch(t),Xg(t),this.graph=t,this}addEdge(e){let t=rB(this.graph);return t.edges.push(axe(e)),this.touch(t),Xg(t),this.graph=t,this}build(){return Xg(this.graph),rB(this.graph)}touch(e){e.version+=1,e.updatedAt=this.now()}};yyt=16*1024*1024,byt=5e3,vyt=1e5,Iyt=1e6,kyt=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,Es=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"};pN=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_${Tyt()}`)}async addComment(e){let t=LL(e.body,"Review comment body",65536),n=await this.repository.require(e.artifactId,e.revision),r=fN(n,e),i=mN(this.idFactory(),"Comment ID"),o=Pyt(e.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:"comment-added",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,commentId:i,body:t,...r?{anchor:r}:{},...o?{parentCommentId:o}:{}}})}async setCommentResolution(e){let t=mN(e.commentId,"Review comment ID"),n=whe(e.reason,"Resolution reason",16*1024),r=await this.repository.require(e.artifactId,e.revision);return this.repository.appendReviewEvent({expectedRecordVersion:r.recordVersion,event:{type:e.resolved?"comment-resolved":"comment-reopened",artifactId:r.artifact.artifactId,artifactRevision:r.artifact.revision,artifactHash:r.artifact.content.hash,actor:this.actor,commentId:t,...n?{reason:n}:{}}})}async decide(e){let t=await this.repository.require(e.artifactId,e.revision);if(t.artifact.state!=="pending_review")throw new At("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${t.artifact.state}`);let n=fN(t,e),r=whe(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,...r?{rationale:r}:{},...n?{scope:n}:{}}});if(n||e.decision==="changes_requested")return i;let o=i.reviewEvents.at(-1);if(!o||o.type!=="decision-recorded")throw new At("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,...r?{reason:r}:{}})}};lA="xeno.spec.v1",sv="xeno.spec-execution.v1",Zo=class extends Error{constructor(e){super(`XENO spec is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},uxe=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??(()=>_yt())}async create(e,t){if(e.revision!==1||e.predecessorRevision!==void 0)throw new Zo(["A new spec must begin at revision 1 without a predecessor"]);let n=hN(e,t);return await this.repository.create(n.requirements),await this.repository.create(n.design),await this.repository.create(n.taskGraph),await this.repository.create(n.plan),n}async revise(e,t){let n=tA(e.specId),r=await this.repository.require(n.plan);if(e.revision!==r.artifact.revision+1||e.predecessorRevision!==r.artifact.revision)throw new Zo([`Revision ${e.revision} must follow approved or reviewed revision ${r.artifact.revision}`]);let i=hN(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,n){return new pN({repository:this.repository,actor:t}).decide({artifactId:tA(e).plan,decision:"approved",...n?{rationale:n}:{}})}async reject(e,t,n){return new pN({repository:this.repository,actor:t}).decide({artifactId:tA(e).plan,decision:"rejected",rationale:n})}async startExecution(e,t){let n=await this.repository.require(tA(e).plan);if(n.artifact.state!=="approved")throw new Zo([`Spec ${e} must be approved before execution`]);let r=gN(n.artifact),i=this.now(),o={schemaVersion:sv,executionId:`spec_execution_${this.idFactory()}`,specId:r.specId,specRevision:r.revision,planArtifactId:n.artifact.artifactId,planHash:{...n.artifact.content.hash},state:"ready",createdAt:i,updatedAt:i,observedPaths:[],tasks:r.tasks.map(s=>({taskId:s.id,status:"pending",evidence:[],acceptanceEvidence:Object.fromEntries(s.acceptanceCriterionIds.map(a=>[a,[]]))}))};return this.repository.create(AN(o,{producer:t,identity:n.artifact.identity,sensitivity:n.artifact.sensitivity,accessPolicyId:n.artifact.accessPolicyId}))}async updateExecution(e,t,n){let r=await this.repository.require(e),i=uK(r.artifact),o=await this.repository.require(i.planArtifactId,i.specRevision);if(o.artifact.state!=="approved"||!T0(o.artifact.content.hash,i.planHash))throw new Zo(["Execution is no longer bound to the approved plan revision"]);let s=t(structuredClone(i));s.schemaVersion=sv,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(),QL(s,gN(o.artifact));let a=AN(s,{producer:n,identity:r.artifact.identity,sensitivity:r.artifact.sensitivity,accessPolicyId:r.artifact.accessPolicyId},r.artifact.revision+1,r.artifact.revision);return this.repository.createRevision(a,{actor:n,reason:"spec-execution-updated"})}};dO();FL="xeno.review-report.v1",dK=["correctness","security","performance","api","tests","documentation"],pK=["source","test","trace","artifact","reproduction","benchmark"],es=class extends Error{constructor(e){super(`XENO review is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},mxe=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}_${Dyt()}`)}async run(e){UL(e.pack),qL(e.target),yN(e.runId,"runId");let t=this.now(),n=await Promise.all(e.pack.dimensions.map(async(a,c)=>{let l=await this.reviewer({...e,dimension:a,reviewerSlot:c});return Fyt(l,a,e.pack.maxFindings),structuredClone(l)})),r=n.flatMap(a=>a.findings.map(c=>({finding:c,reviewerAgentId:a.reviewerAgentId})));if(r.length>e.pack.maxFindings)throw new es([`Reviewers returned ${r.length} findings, exceeding maxFindings ${e.pack.maxFindings}`]);let i=Lyt(r,this.idFactory);for(let a of i){let c=this.verifier?await Promise.all(Array.from({length:e.pack.verifierCount},async(f,m)=>{let h=await this.verifier({...e,finding:structuredClone(a),verifierSlot:m});return Uyt(h),structuredClone(h)})):[];a.verifications=qyt(c),a.evidence=bxe([...a.evidence,...a.verifications.flatMap(f=>f.evidence)]);let l=new Set(a.verifications.filter(f=>f.outcome==="reproduced").map(f=>f.verifierAgentId)).size,u=a.verifications.length>0&&a.verifications.every(f=>f.outcome==="rejected"),d=new Set(a.evidence.map(f=>f.producerId)).size;l>=e.pack.minimumVerifierReproductions?(a.state="verified",a.verificationBasis="verifier"):e.pack.allowIndependentEvidenceVerification&&d>=e.pack.minimumIndependentEvidenceProducers?(a.state="verified",a.verificationBasis="independent-evidence"):u?(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=Cxe(Math.min(a.confidence,...p)))}i.sort(jyt);let o=this.now(),s={schemaVersion:FL,reportId:yN(this.idFactory("report"),"reportId"),runId:e.runId,pack:structuredClone(e.pack),target:structuredClone(e.target),startedAt:t,completedAt:o,reviewers:n.map(a=>({agentId:a.reviewerAgentId,dimension:a.dimension,findingCount:a.findings.length})),findings:i,summary:kxe(i)};return Wv(s),s}};zyt=3e4,Yyt=64*1024,Kyt=/(^|_)(TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|COOKIE|AUTH|AUTHORIZATION)(_|$)/i,Zyt=new Set(["PATH","Path","PATHEXT","SystemRoot","WINDIR","ComSpec","TMP","TEMP","HOME","USERPROFILE"]);wv();nbt=3e4,rbt=64*1024;Oxe=class{constructor(e,t={}){this.executor=e,this.options=t}executor;options;run(e,t){return WL(e,t,{...this.options,promptExecutor:this.executor})}},Dxe=class{constructor(e,t={}){this.executor=e,this.options=t}executor;options;run(e,t){return GL(e,t,{...this.options,agentExecutor:this.executor})}};Lxe=class{constructor(e,t={}){this.hooks=e,this.options=t}hooks;options;run(e){return JL(this.hooks,e,this.options)}},Qxe=class{constructor(e,t={}){this.config=e,this.options=t}config;options;run(e){let t=[...this.config.hooks??[],...this.config.events?.[e.event]??[]];return JL([...new Set(t)],e,this.options)}},Fxe=class{constructor(e={}){this.options=e}options;run(e,t){return VL(e,t,this.options)}},Uxe=class{constructor(e={}){this.options=e}options;run(e,t){return HL(e,t,this.options)}};EA();zC=class extends Error{code;expiresAt;constructor(e,t,n={}){super(e),this.name="XenoAuthError",this.code=t,n.expiresAt&&(this.expiresAt=n.expiresAt)}},pbt="XENO_API_KEY",gK=6e4;Cm();EA();rs();bbt="profiles.json",d4="default",Fx=class{data;filePath;constructor(){this.filePath=ybt(rr(),bbt),this.data=this.load()}listProfiles(){return[...this.data.profiles]}getActiveProfile(){let e=this.data.activeProfile??d4,t=this.data.profiles.find(n=>n.name===e);return t?{...t}:{name:d4}}getActiveProfileName(){return this.data.activeProfile??d4}switchProfile(e){if(!this.data.profiles.some(t=>t.name===e))throw new Error(`Profile "${e}" does not exist. Use listProfiles() to see available profiles.`);this.data.activeProfile=e,this.save()}createProfile(e){if(!e.name||!e.name.trim())throw new Error("Profile name cannot be empty.");let t=e.name.trim();if(t.length>64)throw new Error("Profile name too long (max 64 characters).");if(/[/\\:\0]/.test(t))throw new Error("Profile name cannot contain path separators (/ \\), colons, or null bytes.");if(t.startsWith(".")||t.startsWith("-"))throw new Error('Profile name cannot start with "." or "-".');let n={...e,name:t};if(this.data.profiles.some(r=>r.name===n.name))throw new Error(`Profile "${n.name}" already exists. Use updateProfile() to modify it.`);this.data.profiles.push(n),this.save()}deleteProfile(e){let t=this.data.profiles.findIndex(n=>n.name===e);if(t===-1)throw new Error(`Profile "${e}" does not exist.`);this.data.profiles.splice(t,1),this.data.activeProfile===e&&(this.data.activeProfile=null),this.save()}updateProfile(e,t){let n=this.data.profiles.findIndex(s=>s.name===e);if(n===-1)throw new Error(`Profile "${e}" does not exist.`);let r=this.data.profiles[n],{name:i,...o}=t;this.data.profiles[n]={...r,...o,name:r.name},this.save()}getProfile(e){let t=this.data.profiles.find(n=>n.name===e);return t?{...t}:void 0}reload(){this.data=this.load()}load(){if(!khe(this.filePath))return{activeProfile:null,profiles:[]};try{let e=Abt(this.filePath,"utf-8"),t=Er(e,{activeProfile:null,profiles:[]});return Array.isArray(t.profiles)?{activeProfile:typeof t.activeProfile=="string"?t.activeProfile:null,profiles:t.profiles.filter(n=>typeof n=="object"&&n!==null&&typeof n.name=="string")}:{activeProfile:null,profiles:[]}}catch{return{activeProfile:null,profiles:[]}}}save(){ex();let e=rr();khe(e)||gbt(e,{recursive:!0}),wbt(this.filePath,JSON.stringify(this.data,null,2)+`
|
|
2663
2663
|
`,"utf-8")}};rs();Sbt=[".xenocode",".xenocode.json"];EA();rs();SO();A8();iY();SCe();CCe();xCe();hCe();vCe();ICe();ECe();BA();Nbt={Read:{avgMs:500,p95Ms:900},Glob:{avgMs:1800,p95Ms:3200},Grep:{avgMs:2200,p95Ms:4e3},LS:{avgMs:900,p95Ms:1600},Edit:{avgMs:450,p95Ms:900},Write:{avgMs:450,p95Ms:900}},Che=.7;$Ce();wCe();yCe();Bv();cx();UA=class{checkpointManager;lastCheckpointAt=0;constructor(e){this.checkpointManager=e}async checkInterval(e){return e.length-this.lastCheckpointAt>=10?(await this.checkpointManager.create({trigger:"auto",messages:e,description:`Auto-checkpoint at ${e.length} messages`}),this.lastCheckpointAt=e.length,!0):!1}async checkBeforeDangerous(e,t,n){return Jc.isDangerousOperation(e,t)?(await this.checkpointManager.create({trigger:"pre_dangerous",messages:n,description:`Before ${e}`}),!0):!1}};cY();BCe();hY();gY();FO();Jke();KCe();M8();bK=class zxe{index;byId=new Map;constructor(t={}){this.index=new lx({maxDocuments:t.maxEpisodes??5e3})}async add(t){this.byId.set(t.id,t),await this.index.addDocument(t.id,qbt(t),{kind:"episode",outcome:t.outcome})}async recall(t,n=5,r=.1){let i=await this.index.search(t,n,r),o=[];for(let s of i){let a=this.byId.get(s.id);a&&o.push({episode:a,score:s.score})}return o}get(t){return this.byId.get(t)}all(){return[...this.byId.values()]}get size(){return this.byId.size}toJSON(){return this.all()}static async fromEpisodes(t,n={}){let r=new zxe(n);for(let i of t)await r.add(i);return r}};M8();vK=class Yxe{index;byId=new Map;constructor(t={}){this.index=new lx({maxDocuments:t.maxSkills??5e3})}async add(t){this.byId.set(t.id,t),await this.index.addDocument(t.id,jbt(t),{kind:"skill",name:t.name})}async recall(t,n=5,r=.1){let i=await this.index.search(t,n,r),o=[];for(let s of i){let a=this.byId.get(s.id);a&&o.push({skill:a,score:s.score})}return o}nextVersion(t){let n=0;for(let r of this.byId.values())r.name===t&&r.version>n&&(n=r.version);return n+1}get(t){return this.byId.get(t)}all(){return[...this.byId.values()]}get size(){return this.byId.size}toJSON(){return this.all()}static async fromSkills(t,n={}){let r=new Yxe(n);for(let i of t)await r.add(i);return r}};Hbt=`You distill REUSABLE SKILLS from a completed agent task.
|
|
@@ -2707,7 +2707,7 @@ ${e.result.error??""}`;if(!YIt(e.toolName,e.input,t))return[];let n=KIt(e.toolNa
|
|
|
2707
2707
|
`),i}finally{t.release()}}};bTe=1,vTe=2,ITe=3,kTe=4,we=class extends Error{constructor(e,t,n={}){super(t),this.code=e,this.details=n,this.name="XenoCoordinationError"}code;details};is();dSt=3e4,pSt=3e4,fSt=6e4,mSt=2e4,AB=new Set(["EACCES","EBUSY","EPERM"]),pge=[5,10,20,40,80,160,320],hSt=[5,10,20,40,80,160,320],fge=[1,2,3,4];HK=class{get goalTurnAdmissionVersion(){return 1}rootDirectory;now;idFactory;ownerLeaseMs;lockTimeoutMs;lockStaleMs;maximumEventsPerSession;constructor(e={}){this.rootDirectory=e.rootDirectory??Rl.join(Ea(),"coordination"),this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${gB()}`),this.ownerLeaseMs=e.ownerLeaseMs??dSt,this.lockTimeoutMs=e.lockTimeoutMs??pSt,this.lockStaleMs=e.lockStaleMs??fSt,this.maximumEventsPerSession=e.maximumEventsPerSession??mSt}async getSessionState(e){let t=Jt(e,"sessionId",1024);return ks(await this.readState(t))}async fenceAdmission(e,t,n){let r=Jt(n.authorityId,"authorityId",512),i=Jt(n.operationId,"operationId",512);if(!Number.isSafeInteger(t)||t<0)throw new we("INVALID","Expected session version must be a nonnegative safe integer");if(n.action!=="archive"&&n.action!=="delete")throw new we("INVALID","Unsupported admission fence action");return this.mutate(e,o=>{let s=o.admissionFence;if(s?.authorityId===r&&s.operationId===i&&s.action===n.action)return s;if(o.version!==t)throw new we("CONFLICT","Session version changed before lifecycle fencing",{expected:t,actual:o.version});if(s?.authorityId===r&&s.action==="archive"&&n.action==="archive")return s;if(s&&!(s.authorityId===r&&s.action==="archive"&&n.action==="delete"))throw new we("CONFLICT","Another lifecycle fence already owns this session");let a={schemaVersion:1,authorityId:r,operationId:i,action:n.action,createdAt:this.now()};return o.admissionFence=a,o.schemaVersion===1&&(o.schemaVersion=2),this.appendEvent(o,"admission.fenced",{data:{authorityId:r,operationId:i,action:n.action}}),a},!0)}async clearAdmissionFence(e,t,n,r){await this.mutate(e,i=>{this.assertVersion(e,i.version,t);let o=i.admissionFence;if(!o||o.authorityId!==n||o.operationId!==r)throw new we("CONFLICT","Lifecycle fence identity does not match");if(o.action==="delete")throw new we("CONFLICT","Deleted session admission cannot be restored");if(i.owner)throw new we("CONFLICT","Execution ownership must settle before restoration");i.admissionFence=void 0,this.appendEvent(i,"admission.restored",{data:{authorityId:n,operationId:r}})},!0)}async releaseDeadLifecycleOwner(e,t,n,r){await this.mutate(e,i=>{this.assertVersion(e,i.version,t);let o=i.admissionFence;if(!o||o.authorityId!==n||o.operationId!==r)throw new we("CONFLICT","Lifecycle fence identity does not match");let s=i.owner;if(s){if(s.host!==Hg.hostname()||!Number.isInteger(s.processId)||(s.processId??0)<=0||A4(s.processId))throw new we("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=Rl.join(this.rootDirectory,"sessions"),t;try{t=await Xn.readdir(e)}catch(n){if(n.code==="ENOENT")return[];throw n}return(await Promise.all(t.filter(n=>n.endsWith(".json")).map(async n=>{try{let r=JSON.parse(await Xn.readFile(Rl.join(e,n),"utf8"));return!fge.includes(r.schemaVersion)||typeof r.sessionId!="string"?void 0:((!Number.isSafeInteger(r.ownershipEpoch)||r.ownershipEpoch<0)&&(r.ownershipEpoch=Math.max(r.owner?.epoch??0,...r.handoffs.map(i=>i.targetLeaseEpoch??i.sourceLeaseEpoch??0))),r)}catch{return}}))).filter(n=>n!==void 0).sort((n,r)=>db(r.updatedAt)-db(n.updatedAt)).map(n=>ks(n))}async createGoal(e){let t=Jt(e.sessionId,"sessionId",1024),n=mge(e.limits);return this.mutate(t,r=>{let i=r.goals.find(c=>["active","paused","waiting","blocked"].includes(c.status));if(i)throw new we("CONFLICT",`Session ${t} already has active goal ${i.id}`);let o=this.now(),s=(e.successCriteria??[]).map(c=>typeof c=="string"?{id:this.idFactory("criterion"),description:Jt(c,"successCriteria"),required:!0}:{id:c.id?Jt(c.id,"successCriteria.id",512):this.idFactory("criterion"),description:Jt(c.description,"successCriteria.description"),required:c.required}),a={schemaVersion:1,id:this.idFactory("goal"),version:1,sessionId:t,objective:Jt(e.objective,"objective"),...e.why?{why:Jt(e.why,"why")}:{},successCriteria:s,constraints:wB(e.constraints,"constraints"),...n?{limits:n}:{},metadata:ks(e.metadata??{}),status:"active",milestones:[],tasks:[],progress:ASt(o),verification:wSt(),steering:[],createdAt:o,updatedAt:o};return r.goals.push(a),this.appendEvent(r,"goal.created",{goalId:a.id,data:{objective:a.objective}}),a})}async getGoal(e,t){let n=await this.getSessionState(e),r=t?n.goals.find(i=>i.id===t):[...n.goals].reverse().find(i=>["active","paused","waiting","blocked"].includes(i.status));return r?ks(r):void 0}async updateGoal(e,t,n,r){return this.mutate(e,i=>{let o=this.requireGoal(i,t);if(this.assertVersion(o.id,o.version,n),["completed","cancelled","failed"].includes(o.status))throw new we("CONFLICT",`Goal ${o.id} is terminal (${o.status})`);let s=o.status!=="active";if(r.status==="active"&&o.status==="blocked"?o.status="active":r.status&&(o.status=r.status),r.objective!==void 0&&(o.objective=Jt(r.objective,"objective")),r.why!==void 0&&(o.why=Jt(r.why,"why")),r.constraints&&(o.constraints=wB(r.constraints,"constraints")),r.successCriteria&&(o.successCriteria=ks(r.successCriteria)),r.progress&&(o.progress={...o.progress,...ks(r.progress),outstanding:wB(r.progress.outstanding??o.progress.outstanding,"progress.outstanding"),decisions:wB(r.progress.decisions??o.progress.decisions,"progress.decisions"),updatedAt:this.now()}),r.verification&&(o.verification=ks(r.verification)),r.metadata&&(o.metadata=ks(r.metadata)),s&&o.status==="active")for(let a of i.loops.filter(c=>c.goalId===t&&c.kind==="goal-continuation"&&c.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},r.status!==void 0&&["paused","cancelled","failed"].includes(r.status))}async addMilestone(e,t,n,r){return this.mutateGoal(e,t,n,(i,o)=>{let s={id:this.idFactory("milestone"),title:Jt(r.title,"milestone.title"),...r.description?{description:Jt(r.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,n,r){return this.mutateGoal(e,t,n,(i,o)=>{let s=i.milestones.find(l=>l.id===r.milestoneId);if(!s)throw new we("NOT_FOUND",`Milestone ${r.milestoneId} was not found`);if(r.parentTaskId&&!i.tasks.some(l=>l.id===r.parentTaskId))throw new we("NOT_FOUND",`Parent task ${r.parentTaskId} was not found`);let a=[...new Set(r.dependsOn??[])];for(let l of a)if(!i.tasks.some(u=>u.id===l))throw new we("NOT_FOUND",`Task dependency ${l} was not found`);let c={id:this.idFactory("task"),milestoneId:s.id,...r.parentTaskId?{parentTaskId:r.parentTaskId}:{},title:Jt(r.title,"task.title"),...r.description?{description:Jt(r.description,"task.description")}:{},status:a.length===0?"ready":"pending",...r.assignedAgentId?{assignedAgentId:Jt(r.assignedAgentId,"task.assignedAgentId",512)}:{},...a.length?{dependsOn:a}:{},createdAt:o,updatedAt:o};i.tasks.push(c),s.taskIds.push(c.id),s.updatedAt=o,i.progress.totalTaskCount=i.tasks.length,i.progress.outstanding=i.tasks.filter(l=>l.status!=="completed").map(l=>l.title),i.progress.updatedAt=o})}async updateTask(e,t,n,r,i){return this.mutateGoal(e,t,r,(o,s)=>{let a=o.tasks.find(l=>l.id===n);if(!a)throw new we("NOT_FOUND",`Task ${n} was not found`);a.status=i.status,i.progress!==void 0&&(a.progress=Jt(i.progress,"task.progress")),i.resultEventId!==void 0&&(a.resultEventId=Jt(i.resultEventId,"task.resultEventId",512)),i.assignedAgentId!==void 0&&(a.assignedAgentId=Jt(i.assignedAgentId,"task.assignedAgentId",512)),a.updatedAt=s,a.status==="completed"&&(a.completedAt=s);let c=o.milestones.find(l=>l.id===a.milestoneId);if(c){let l=o.tasks.filter(u=>u.milestoneId===c.id);l.length>0&&l.every(u=>u.status==="completed")?(c.status="completed",c.completedAt=s):l.some(u=>u.status==="running")?c.status="active":l.some(u=>u.status==="blocked")&&(c.status="blocked"),c.updatedAt=s}for(let l of o.tasks)l.status!=="pending"||!l.dependsOn?.length||l.dependsOn.every(u=>o.tasks.find(d=>d.id===u)?.status==="completed")&&(l.status="ready",l.updatedAt=s);this.recalculateProgress(o,s)})}async steerGoal(e,t,n,r){return this.mutateGoal(e,t,n,(i,o,s)=>{let a=this.idFactory("steer");i.steering.push({id:a,instruction:Jt(r,"instruction"),createdAt:o}),this.appendEvent(s,"goal.steered",{goalId:t,data:{steeringId:a}})},!1)}async consumeGoalSteering(e,t,n){let r=[];return{goal:await this.mutateGoal(e,t,n,(i,o)=>{r=i.steering.filter(s=>!s.consumedAt).map(({id:s,instruction:a,createdAt:c})=>({id:s,instruction:a,createdAt:c}));for(let s of i.steering)s.consumedAt||(s.consumedAt=o)}),instructions:r}}async completeGoal(e,t,n,r){if(r.status!=="passed")throw new we("VERIFICATION_REQUIRED","Goal completion requires passed verification");return this.mutate(e,i=>{let o=this.requireGoal(i,t);this.assertVersion(o.id,o.version,n);let s=o.successCriteria.filter(l=>l.required),a=s.filter(l=>{let u=r.criteria.find(d=>d.criterionId===l.id);return!u?.satisfied||u.evidence.length===0});if(a.length>0)throw new we("VERIFICATION_REQUIRED","Required success criteria lack passing evidence",{unmetCriteria:a.map(l=>l.id)});if(s.length===0&&r.evidence.length===0)throw new we("VERIFICATION_REQUIRED","Goal completion requires at least one durable evidence reference");let c=this.now();return o.status="completed",o.verification=ks(r),o.verification.verifiedAt??=c,o.completedAt=c,o.updatedAt=c,o.version+=1,this.appendEvent(i,"goal.completed",{goalId:t,data:{evidence:o.verification.evidence}}),o},!0)}async cancelGoal(e,t,n,r){return this.mutate(e,i=>{let o=this.requireGoal(i,t);if(this.assertVersion(o.id,o.version,n),["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:Jt(r,"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: ${r}`,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 we("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 we("CONFLICT",`Cannot start a loop for terminal goal ${s.id}`)}if(t.kind==="scheduled"&&!t.schedule)throw new we("INVALID","Scheduled loops require schedule metadata");if(t.kind!=="scheduled"&&t.schedule)throw new we("INVALID","Only scheduled loops may carry schedule metadata");let n=gSt(t.schedule),r=e.loops.find(s=>s.goalId===t.goalId&&s.kind===t.kind&&["running","paused","waiting"].includes(s.status));if(r)throw new we("CONFLICT",`Loop ${r.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:Jt(t.activity,"activity")}:{},iterations:[],...n?{schedule:n}:{},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 n=await this.getSessionState(e),r=t?n.loops.find(i=>i.id===t):[...n.loops].reverse().find(i=>["running","paused","waiting"].includes(i.status));return r?ks(r):void 0}async beginLoopIteration(e,t,n,r,i){return this.mutateLoop(e,t,n,(o,s,a)=>{this.appendLoopIteration(a,o,s,r,i)},!1)}appendLoopIteration(e,t,n,r,i){if(t.status!=="running")throw new we("CONFLICT",`Loop ${t.id} is ${t.status}`);if(t.goalId){let a=this.requireGoal(e,t.goalId);this.isCliGoal(a)&&this.initializeGoalTurnAccounting(e,a)}if(this.assertGoalIterationAdmission(e,t,n),t.iterations.some(a=>a.status==="running"))throw new we("CONFLICT",`Loop ${t.id} already has a running iteration`);let o=(t.iterations.at(-1)?.number??0)+1;t.currentActivity=Jt(r,"activity");let s={number:o,startedAt:n,status:"running",activity:t.currentActivity,...t.goalId&&e.goalTurnAccounting?.[t.goalId]?{goalAccountingVersion:1}:{},...i?{taskId:Jt(i,"taskId",512)}:{}};return t.iterations.push(s),t.resumeRequested!==void 0&&(t.resumeRequested=!1),this.appendEvent(e,"loop.iteration",{loopId:t.id,goalId:t.goalId,data:{number:o,phase:"started",activity:t.currentActivity}}),s}async admitGoalTurn(e){let t=Jt(e.requestId,"requestId",512),n=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,r=>{let i=this.requireGoal(r,e.goalId);for(let c of r.loops.filter(l=>l.goalId===i.id)){let l=c.iterations.find(u=>u.goalTurn?.requestId===t);if(l){if(l.goalTurn?.requestHash!==n)throw new we("CONFLICT","Goal turn identity was reused for different work");return{...this.goalTurnState(r,i,c,l),admitted:!1}}}if(this.assertVersion(i.id,i.version,e.expectedGoalVersion),i.status!=="active")throw new we("CONFLICT",`Goal ${i.id} is ${i.status}`);let o=[...r.loops].reverse().find(c=>c.goalId===i.id&&c.kind==="goal-continuation");if(e.expectedLoopId!==void 0){if(!o||o.id!==e.expectedLoopId)throw new we("CONFLICT","Goal continuation loop changed before admission");this.assertVersion(o.id,o.version,e.expectedLoopVersion??-1)}else if(e.expectedLoopVersion!==void 0)throw new we("INVALID","A goal turn loop version requires its exact loop ID");if(o&&o.status!=="running")throw new we("CONFLICT",`Goal loop ${o.id} is ${o.status}; resume or start it explicitly`);this.initializeGoalTurnAccounting(r,i),o??=this.createLoopRecord(r,{sessionId:r.sessionId,goalId:i.id,kind:"goal-continuation"});let s=this.now(),a=this.appendLoopIteration(r,o,s,"Interactive goal turn");if(e.executionKind!==void 0&&e.executionKind!=="local-sdk"&&e.executionKind!=="external")throw new we("INVALID","Unknown goal execution lane");return a.goalTurn={requestId:t,requestHash:n,executor:e.executionKind==="local-sdk"?{kind:"local-sdk",processId:process.pid,host:Hg.hostname()}:{kind:"external"}},o.version+=1,o.updatedAt=s,{...this.goalTurnState(r,i,o,a),admitted:!0}},!1,r=>r.admitted)}async getGoalTurnState(e,t,n){let r=await this.getSessionState(e),i=t?r.goals.find(c=>c.id===t):[...r.goals].reverse().find(c=>["active","paused","waiting","blocked"].includes(c.status));if(!i)return;let o=r.loops.filter(c=>c.goalId===i.id),s=n?o.find(c=>c.iterations.some(l=>l.goalTurn?.requestId===n)):[...o].reverse().find(c=>c.kind==="goal-continuation"),a=n?s?.iterations.find(c=>c.goalTurn?.requestId===n):s?.iterations.at(-1);if(n&&!a)throw new we("NOT_FOUND","Goal turn was not found");return this.goalTurnState(r,i,s,a)}async finishGoalTurn(e){if(!["completed","failed","interrupted"].includes(e.status))throw new we("INVALID","Invalid goal turn outcome");let t=this.goalTurnHash(e.requestHash);return this.mutate(e.sessionId,n=>{let r=this.requireGoal(n,e.goalId),i=n.loops.find(s=>s.goalId===r.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 we("NOT_FOUND","Goal turn was not found");if(o.goalTurn?.requestHash!==t)throw new we("CONFLICT","Goal turn settlement identity does not match");return o.status==="running"&&(this.settleLoopIteration(n,i,o,this.now(),{status:r.status==="cancelled"||["stopped","failed"].includes(i.status)?"interrupted":e.status}),i.version+=1,i.updatedAt=this.now()),this.goalTurnState(n,r,i,o)},!0)}async recoverGoalTurn(e,t,n){return this.mutate(e,r=>{let i=this.requireGoal(r,t),o=r.loops.find(a=>a.goalId===t&&a.iterations.some(c=>c.goalTurn?.requestId===n)),s=o?.iterations.find(a=>a.goalTurn?.requestId===n);if(!o||!s)throw new we("NOT_FOUND","Goal turn was not found");if(s.status==="running"){if(!this.goalTurnOwnerExited(s))throw new we("NOT_OWNER","The original local goal executor has not been proved exited; external execution requires reconciliation");this.settleLoopIteration(r,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(r,i,o,s)},!0)}async finishLoopIteration(e,t,n,r){return this.mutateLoop(e,t,n,(i,o,s)=>{let a=[...i.iterations].reverse().find(c=>c.status==="running");if(!a)throw new we("CONFLICT",`Loop ${i.id} has no running iteration`);this.settleLoopIteration(s,i,a,o,r)},!1,!0)}settleLoopIteration(e,t,n,r,i){n.status=i.status,n.completedAt=r,i.verificationEventId&&(n.verificationEventId=Jt(i.verificationEventId,"verificationEventId",512)),i.error&&(n.error=Jt(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:n.number,phase:"finished",status:i.status}})}async setLoopStatus(e,t,n,r,i){return this.mutateLoop(e,t,n,(o,s,a)=>{let c=o.status;if(["stopped","completed","failed"].includes(c))throw new we("CONFLICT",`Loop ${o.id} is terminal (${c})`);let l=[...o.iterations].reverse().find(d=>d.status==="running");if(l&&r==="completed")throw new we("CONFLICT",`Loop ${o.id} cannot complete while iteration ${l.number} is running`);l&&(r==="stopped"||r==="failed")&&(l.status=r==="failed"?"failed":"interrupted",l.completedAt=s,l.error=Jt(i??r,"reason")),o.status=r,o.kind==="goal-continuation"&&(o.resumeRequested=r==="running"),["stopped","completed","failed"].includes(r)&&(o.stoppedAt=s,o.stopReason=Jt(i??r,"reason"));let u=r==="paused"?"loop.paused":r==="waiting"?"loop.waiting":r==="running"&&(c==="paused"||c==="waiting")?"loop.resumed":r==="completed"?"loop.completed":r==="failed"?"loop.failed":"loop.stopped";this.appendEvent(a,u,{loopId:t,goalId:o.goalId,data:{previous:c,status:r,...i?{reason:i}:{}}})},!1,r!=="running"&&r!=="waiting")}async acquireOwnership(e,t,n={}){return this.mutate(e,r=>{let i=this.now();if(r.owner&&!this.ownerExpired(r.owner,i)){if(r.owner.ownerId===t&&n.processId!==void 0&&r.owner.processId===n.processId&&(n.host===void 0||r.owner.host===n.host))return r.owner;throw new we("CONFLICT",`Session ${e} is owned by ${r.owner.ownerId}`,{owner:r.owner})}let o=r.owner&&this.ownerExpired(r.owner,i)?r.owner:void 0;if(o&&o.ownerId!==t)for(let c of r.handoffs.filter(l=>l.status==="claimed"&&l.claimedBy===o.ownerId))c.status="failed",c.failureReason=`Claimed owner ${o.ownerId} lost its execution lease before completing the handoff.`,c.failedAt=i,c.updatedAt=i,c.version+=1,this.appendEvent(r,"handoff.failed",{handoffId:c.id,goalId:c.goalId,loopId:c.loopId,data:{reason:c.failureReason,expiredLeaseId:o.leaseId}});let s=r.ownershipEpoch+1,a=this.newOwner(t,s,n,i);return r.owner=a,r.ownershipEpoch=s,this.appendEvent(r,"ownership.acquired",{ownerId:t,data:{epoch:s,leaseId:a.leaseId}}),a})}async renewOwnership(e,t,n,r=this.ownerLeaseMs){return this.mutate(e,i=>{let o=this.requireOwner(i,t,n);if(this.ownerExpired(o,this.now()))throw new we("LEASE_EXPIRED",`Ownership lease ${n} expired`);return o.heartbeatAt=this.now(),o.expiresAt=new Date(db(o.heartbeatAt)+r).toISOString(),this.appendEvent(i,"ownership.renewed",{ownerId:t,data:{epoch:o.epoch,leaseId:n}}),o})}async releaseOwnership(e,t,n){return this.mutate(e,r=>{let i=this.requireOwner(r,t,n);return r.owner=void 0,this.appendEvent(r,"ownership.released",{ownerId:t,data:{epoch:i.epoch}}),i},!0)}async createHandoff(e){return this.mutate(e.sessionId,t=>{let n=this.requireOwner(t,e.sourceOwnerId,e.sourceLeaseId);if(this.ownerExpired(n,this.now()))throw new we("LEASE_EXPIRED",`Ownership lease ${n.leaseId} expired`);let r=(e.operations??[]).filter(a=>a.status==="running"&&a.sideEffecting&&a.recovery==="retry");if(r.length>0)throw new we("UNSAFE_HANDOFF","Running side-effecting operations cannot be transferred with automatic retry",{operationIds:r.map(a=>a.operationId)});if(e.goalId&&this.requireGoal(t,e.goalId),e.loopId&&!t.loops.some(a=>a.id===e.loopId))throw new we("NOT_FOUND",`Loop ${e.loopId} was not found`);let i=t.handoffs.find(a=>["prepared","available","claimed"].includes(a.status));if(i)throw new we("CONFLICT",`Handoff ${i.id} is already active`);let o=this.now(),s={schemaVersion:1,id:this.idFactory("handoff"),version:1,sessionId:t.sessionId,...e.goalId?{goalId:e.goalId}:{},...e.loopId?{loopId:e.loopId}:{},status:"available",sourceOwnerId:n.ownerId,...e.targetOwnerId?{targetOwnerId:Jt(e.targetOwnerId,"targetOwnerId",512)}:{},sourceLeaseEpoch:n.epoch,...e.workspace?{workspace:Jt(e.workspace,"workspace",32768)}:{},...e.branch?{branch:Jt(e.branch,"branch",1024)}:{},...e.currentMilestoneId?{currentMilestoneId:e.currentMilestoneId}:{},...e.currentTaskId?{currentTaskId:e.currentTaskId}:{},agentIds:[...new Set(e.agentIds??[])],operations:ks(e.operations??[]),...e.contextDigest?{contextDigest:Jt(e.contextDigest,"contextDigest",512)}:{},createdAt:o,updatedAt:o};return t.handoffs.push(s),this.appendEvent(t,"handoff.created",{handoffId:s.id,goalId:s.goalId,loopId:s.loopId,ownerId:n.ownerId,data:{targetOwnerId:s.targetOwnerId}}),s})}async claimHandoff(e){let t;return{handoff:await this.mutate(e.sessionId,n=>{let r=n.handoffs.find(s=>s.id===e.handoffId);if(!r)throw new we("NOT_FOUND",`Handoff ${e.handoffId} was not found`);if(r.status!=="available")throw new we("CONFLICT",`Handoff ${r.id} is ${r.status}`,{claimedBy:r.claimedBy});if(r.targetOwnerId&&r.targetOwnerId!==e.targetOwnerId)throw new we("CONFLICT",`Handoff ${r.id} is reserved for ${r.targetOwnerId}`);let i=n.owner;if(!i||i.ownerId!==r.sourceOwnerId||i.epoch!==r.sourceLeaseEpoch)throw new we("CONFLICT",`Handoff ${r.id} no longer matches the source ownership epoch`);let o=this.now();return t=this.newOwner(e.targetOwnerId,i.epoch+1,{processId:e.processId,host:e.host},o),n.owner=t,n.ownershipEpoch=t.epoch,r.status="claimed",r.claimedBy=e.targetOwnerId,r.targetOwnerId=e.targetOwnerId,r.targetLeaseEpoch=t.epoch,r.claimedAt=o,r.updatedAt=o,r.version+=1,this.appendEvent(n,"handoff.claimed",{handoffId:r.id,goalId:r.goalId,loopId:r.loopId,ownerId:e.targetOwnerId,data:{sourceOwnerId:r.sourceOwnerId,epoch:t.epoch}}),r}),owner:ks(t)}}async completeHandoff(e,t,n,r){return this.mutate(e,i=>{this.requireOwner(i,n,r);let o=i.handoffs.find(s=>s.id===t);if(!o)throw new we("NOT_FOUND",`Handoff ${t} was not found`);if(o.status!=="claimed"||o.claimedBy!==n)throw new we("CONFLICT",`Handoff ${o.id} cannot be completed by ${n}`);return o.status="completed",o.completedAt=this.now(),o.updatedAt=o.completedAt,o.version+=1,this.appendEvent(i,"handoff.completed",{handoffId:t,goalId:o.goalId,loopId:o.loopId,ownerId:n,data:{epoch:i.owner?.epoch}}),o})}async failHandoff(e,t,n){return this.mutate(e,r=>{let i=r.handoffs.find(o=>o.id===t);if(!i)throw new we("NOT_FOUND",`Handoff ${t} was not found`);return["completed","cancelled","failed"].includes(i.status)||(i.status="failed",i.failureReason=Jt(n,"reason"),i.failedAt=this.now(),i.updatedAt=i.failedAt,i.version+=1,this.appendEvent(r,"handoff.failed",{handoffId:t,goalId:i.goalId,loopId:i.loopId,data:{reason:i.failureReason}})),i},!0)}async mutateGoal(e,t,n,r,i=!0){return this.mutate(e,o=>{let s=this.requireGoal(o,t);this.assertVersion(s.id,s.version,n);let a=this.now();return r(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,n,r,i=!0,o=!1){return this.mutate(e,s=>{let a=s.loops.find(l=>l.id===t);if(!a)throw new we("NOT_FOUND",`Loop ${t} was not found`);this.assertVersion(a.id,a.version,n);let c=this.now();return r(a,c,s),a.version+=1,a.updatedAt=c,i&&this.appendEvent(s,"loop.iteration",{loopId:t,goalId:a.goalId,data:{status:a.status,version:a.version}}),a},o)}assertGoalIterationAdmission(e,t,n){if(!t.goalId)return;let r=this.requireGoal(e,t.goalId);if(r.status!=="active")throw new we("CONFLICT",`Goal ${r.id} is ${r.status}; no iteration was admitted`);let i=mge(r.limits);if(i?.maxTokens!==void 0)throw new we("BUDGET_UNAVAILABLE","Goal token allowance is not bound to request-level admission; no iteration was admitted",{goalId:r.id,limit:"maxTokens"});if(i?.maxWallClockMs!==void 0){let o=Date.parse(r.createdAt),s=Date.parse(n);if(!Number.isFinite(o)||!Number.isFinite(s)||s<o)throw new we("BUDGET_UNAVAILABLE","Goal wall-clock allowance cannot be verified",{goalId:r.id,limit:"maxWallClockMs"});if(s-o>=i.maxWallClockMs)throw new we("BUDGET_EXCEEDED","Goal wall-clock limit reached; no iteration was admitted",{goalId:r.id,limit:"maxWallClockMs",maximum:i.maxWallClockMs})}if(i?.maxIterations!==void 0){let o=e.goalTurnAccounting!==void 0||e.schemaVersion===4?this.resolveGoalTurnAccounting(e,r):void 0;if(o?.coverage==="partial")throw new we("BUDGET_UNAVAILABLE","Legacy goal turn accounting is incomplete");let s=this.goalIterationCount(e,r)+(o?.baseIterations??0);if(!Number.isSafeInteger(s)||s<0)throw new we("BUDGET_UNAVAILABLE","Invalid goal iteration accounting");if(s>=i.maxIterations)throw new we("BUDGET_EXCEEDED","Goal iteration limit reached; no iteration was admitted",{goalId:r.id,limit:"maxIterations",admitted:s,maximum:i.maxIterations})}}isCliGoal(e){return"cli.accountedTurns"in e.metadata||"cli.createdByCliVersion"in e.metadata}goalIterationCount(e,t){let n=0;for(let r of e.loops.filter(i=>i.goalId===t.id)){if(!Array.isArray(r.iterations))throw new we("BUDGET_UNAVAILABLE","Goal iteration history is unavailable");let i=0;for(let o of r.iterations){if(!o||!Number.isSafeInteger(o.number)||o.number<=i)throw new we("BUDGET_UNAVAILABLE","Goal iteration history is invalid");i=o.number}if(n+=i,!Number.isSafeInteger(n))throw new we("BUDGET_UNAVAILABLE","Goal iteration count exceeds its supported range")}return n}resolveGoalTurnAccounting(e,t){let n=e.goalTurnAccounting;if(n!==void 0&&(!n||typeof n!="object"||Array.isArray(n)))throw new we("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");if(n&&Object.hasOwn(n,t.id)){let a=n[t.id];if(!a||a.schemaVersion!==1||!Number.isSafeInteger(a.baseIterations)||a.baseIterations<0||!["complete","partial"].includes(a.coverage))throw new we("BUDGET_UNAVAILABLE","Persisted goal turn accounting is invalid");return a}if(e.loops.some(a=>a.goalId===t.id&&a.iterations.some(c=>c.goalTurn||c.goalAccountingVersion)))throw new we("BUDGET_UNAVAILABLE","Recorded goal turns are missing their protected accounting");let r=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&&r>0);return{schemaVersion:1,baseIterations:o&&r===0?i:0,coverage:s?"partial":"complete"}}initializeGoalTurnAccounting(e,t){let n=this.resolveGoalTurnAccounting(e,t);if(n.coverage==="partial"&&t.limits?.maxIterations!==void 0)throw new we("BUDGET_UNAVAILABLE","Legacy goal turn accounting needs reconciliation before bounded execution");e.goalTurnAccounting??={},Object.defineProperty(e.goalTurnAccounting,t.id,{value:n,writable:!0,enumerable:!0,configurable:!0})}goalTurnHash(e){let t=Jt(e,"requestHash",64).toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new we("INVALID","Goal turn requestHash must be a SHA-256 digest");return t}goalTurnState(e,t,n,r){let i=this.resolveGoalTurnAccounting(e,t),o=this.goalIterationCount(e,t)+i.baseIterations;if(!Number.isSafeInteger(o))throw new we("BUDGET_UNAVAILABLE","Goal turn count exceeds its supported range");return ks({goal:t,admittedTurns:o,accountingCoverage:i.coverage,...n?{loopId:n.id,loopVersion:n.version,loopStatus:n.status,resumeRequested:n.resumeRequested===!0}:{},...r?{iterationNumber:r.number,iterationStatus:r.status,...r.goalTurn?{requestId:r.goalTurn.requestId,requestHash:r.goalTurn.requestHash}:{},canRecover:r.status==="running"&&this.goalTurnOwnerExited(r)}:{}})}goalTurnOwnerExited(e){let t=e.goalTurn?.executor;if(t?.kind!=="local-sdk"||t.host!==Hg.hostname()||!Number.isSafeInteger(t.processId)||t.processId<=0)return!1;try{return process.kill(t.processId,0),!1}catch(n){return n.code==="ESRCH"}}recalculateProgress(e,t){let n=e.tasks.filter(r=>r.status==="completed").length;e.progress.completedTaskCount=n,e.progress.totalTaskCount=e.tasks.length,e.progress.percent=e.tasks.length?Math.round(n/e.tasks.length*100):void 0,e.progress.outstanding=e.tasks.filter(r=>!["completed","cancelled"].includes(r.status)).map(r=>r.title),e.progress.updatedAt=t}requireGoal(e,t){let n=e.goals.find(r=>r.id===t);if(!n)throw new we("NOT_FOUND",`Goal ${t} was not found`);return n}requireOwner(e,t,n){let r=e.owner;if(!r||r.ownerId!==t||r.leaseId!==n)throw new we("NOT_OWNER",`${t} does not own session ${e.sessionId}`,{owner:r});return r}assertVersion(e,t,n){if(!Number.isInteger(n)||n<1||t!==n)throw new we("CONFLICT",`Expected ${e} version ${n}, found ${t}`,{expected:n,actual:t})}newOwner(e,t,n,r){let i=n.leaseMs??this.ownerLeaseMs;if(!Number.isSafeInteger(i)||i<1)throw new we("INVALID","leaseMs must be a positive safe integer");return{ownerId:Jt(e,"ownerId",512),leaseId:this.idFactory("owner"),epoch:t,acquiredAt:r,heartbeatAt:r,expiresAt:new Date(db(r)+i).toISOString(),...n.processId!==void 0?{processId:n.processId}:{},...n.host?{host:Jt(n.host,"host",512)}:{}}}ownerExpired(e,t){return db(e.expiresAt)<=db(t)?!0:e.processId!==void 0&&e.host===Hg.hostname()&&!A4(e.processId)}appendEvent(e,t,n){let r={schemaVersion:1,id:this.idFactory("event"),sequence:(e.events.at(-1)?.sequence??0)+1,type:t,sessionId:e.sessionId,...n.goalId?{goalId:n.goalId}:{},...n.loopId?{loopId:n.loopId}:{},...n.handoffId?{handoffId:n.handoffId}:{},...n.ownerId?{ownerId:n.ownerId}:{},timestamp:this.now(),data:ks(n.data)};e.events.push(r),e.events.length>this.maximumEventsPerSession&&e.events.splice(0,e.events.length-this.maximumEventsPerSession)}async mutate(e,t,n=!1,r=()=>!0){let i=Jt(e,"sessionId",1024);return this.withSessionLock(i,async()=>{let o=await this.readState(i);if(o.admissionFence&&!n)throw new we("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 r(a)&&(o.version+=1,o.updatedAt=this.now(),await this.writeState(o)),ks(a)})}statePath(e){return Rl.join(this.rootDirectory,"sessions",`${ySt(e)}.json`)}lockPath(e){return`${this.statePath(e)}.lock`}async readState(e){let t=this.statePath(e);try{let n=await Xn.readFile(t,"utf8"),r=JSON.parse(n);if(!fge.includes(r.schemaVersion)||r.sessionId!==e)throw new we("INVALID",`Coordination state at ${t} does not match session ${e}`);if(r.admissionFence!==void 0){let i=r.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 we("INVALID","Persisted lifecycle fence is corrupt; execution remains unavailable")}return(!Number.isSafeInteger(r.ownershipEpoch)||r.ownershipEpoch<0)&&(r.ownershipEpoch=Math.max(r.owner?.epoch??0,...r.handoffs.map(i=>i.targetLeaseEpoch??i.sourceLeaseEpoch??0))),r}catch(n){if(n.code!=="ENOENT")throw n;let r=this.now();return{schemaVersion:1,sessionId:e,version:0,ownershipEpoch:0,goals:[],loops:[],handoffs:[],events:[],createdAt:r,updatedAt:r}}}promoteGoalBudgetEnvelope(e){(e.goalTurnAccounting!==void 0||e.loops.some(t=>t.resumeRequested!==void 0||t.iterations.some(n=>n.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),n=Rl.dirname(t);await Xn.mkdir(n,{recursive:!0});let r=`${t}.${process.pid}.${gB()}.tmp`,i=await Xn.open(r,"wx");try{await i.writeFile(`${JSON.stringify(e,null,2)}
|
|
2708
2708
|
`,"utf8"),await i.sync()}finally{await i.close()}try{await this.renameReplacing(r,t);try{let o=await Xn.open(n,"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{await Xn.unlink(r).catch(()=>{})}}async renameReplacing(e,t){for(let n=0;;n+=1)try{await Xn.rename(e,t);return}catch(r){let i=r.code,o=pge[n];if(process.platform!=="win32"||!i||!AB.has(i)||o===void 0)throw r;await new Promise(s=>setTimeout(s,o))}}async withSessionLock(e,t){let n=this.lockPath(e),r=Rl.join(n,"owner.json"),i=gB(),o=`${n}.candidate.${i}`,s=Date.now();await Xn.mkdir(Rl.dirname(n),{recursive:!0});let a={schemaVersion:1,token:i,pid:process.pid,host:Hg.hostname(),acquiredAt:this.now()};await Xn.mkdir(o),await Xn.writeFile(Rl.join(o,"owner.json"),JSON.stringify(a),{encoding:"utf8",flag:"wx"});for(let c=0;;c+=1)try{await Xn.rename(o,n);break}catch(l){let u=l.code;if(!(u==="EEXIST"||process.platform==="win32"&&u&&AB.has(u)))throw await Xn.rm(o,{recursive:!0,force:!0}).catch(()=>{}),l;let d=await this.staleLockOwner(n,r);if(d){await this.quarantineLock(n,d.token,"stale");continue}if(Date.now()-s>=this.lockTimeoutMs)throw await Xn.rm(o,{recursive:!0,force:!0}).catch(()=>{}),new we("CONFLICT",`Timed out waiting for coordination lock for session ${e}`);await new Promise(p=>setTimeout(p,Math.min(100,5+c*5)+Math.floor(Math.random()*10)))}try{return await t()}finally{await this.quarantineLock(n,i,"released"),await Xn.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}async staleLockOwner(e,t){try{let[n,r]=await Promise.all([Xn.readFile(t,"utf8").catch(()=>""),Xn.stat(e)]),i=n?JSON.parse(n):void 0;return!i||i.host===Hg.hostname()&&A4(i.pid)?void 0:Date.now()-r.mtimeMs>this.lockStaleMs?i:void 0}catch{return}}async quarantineLock(e,t,n){let r=Rl.join(e,"owner.json"),i=`${e}.${n}.${t}.${gB()}`;for(let o=0;;o+=1){let s;try{s=JSON.parse(await Xn.readFile(r,"utf8"))}catch(a){if(a.code==="ENOENT")return;throw a}if(s.token!==t)return;try{await Xn.rename(e,i);break}catch(a){let c=a.code;if(c==="ENOENT"||c==="EEXIST")return;let l=pge[o];if(process.platform!=="win32"||!c||!AB.has(c)||l===void 0)throw a;await new Promise(u=>setTimeout(u,l))}}for(let o=0;;o+=1)try{await Xn.rm(i,{recursive:!0});return}catch(s){let a=s.code;if(a==="ENOENT")return;let c=hSt[o];if(process.platform!=="win32"||!a||!AB.has(a)||c===void 0)throw s;await new Promise(l=>setTimeout(l,c))}}};STe=class{sessionId;ownerId;store;processId;host;leaseMs;heartbeatMs;claimHandoffId;onOwnershipLost;timer;heartbeatInFlight=!1;owner;stopped=!1;lostError;preparedHandoffId;constructor(e){if(this.store=e.store??new HK,this.sessionId=e.sessionId,this.processId=e.processId??process.pid,this.host=e.host??vSt(),this.ownerId=e.ownerId??`runtime:${this.host}:${this.processId}:${bSt().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");this.claimHandoffId=e.claimHandoffId,this.onOwnershipLost=e.onOwnershipLost}get currentOwner(){return this.owner?structuredClone(this.owner):void 0}get active(){return!!this.owner&&!this.stopped&&this.lostError===void 0}async start(){if(this.owner)return structuredClone(this.owner);if(this.stopped)throw new Error("Execution lease session has already stopped");if(this.claimHandoffId){let e=await this.store.claimHandoff({sessionId:this.sessionId,handoffId:this.claimHandoffId,targetOwnerId:this.ownerId,processId:this.processId,host:this.host});this.owner=e.owner,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});return this.timer=setInterval(()=>{this.heartbeat()},this.heartbeatMs),this.timer.unref?.(),structuredClone(this.owner)}async assertOwned(){if(this.stopped)throw new Error("Execution surface is detached");if(this.lostError)throw this.lostError;if(this.preparedHandoffId)throw new Error(`Execution surface prepared handoff ${this.preparedHandoffId} and is detached from mutation`);if(!this.owner)throw new Error("Execution ownership was not started");return this.renewHeldLease()}async renewHeldLease(){if(!this.owner)throw new Error("Execution ownership was not started");try{return this.owner=await this.store.renewOwnership(this.sessionId,this.ownerId,this.owner.leaseId,this.leaseMs),structuredClone(this.owner)}catch(e){throw this.markLost(e),e}}async prepareHandoff(e={}){if(this.preparedHandoffId)throw new Error(`Handoff ${this.preparedHandoffId} is already prepared`);let t=await this.assertOwned(),n=await this.store.createHandoff({...e,sessionId:this.sessionId,sourceOwnerId:t.ownerId,sourceLeaseId:t.leaseId});return this.preparedHandoffId=n.id,n}async stop(e={}){if(this.stopped)return;this.stopped=!0,this.timer&&clearInterval(this.timer),this.timer=void 0;let t=this.owner;if(this.owner=void 0,!(e.release===!1||this.preparedHandoffId||!t||this.lostError))try{await this.store.releaseOwnership(this.sessionId,t.ownerId,t.leaseId)}catch{}}async heartbeat(){if(!(!this.active||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))}},CTe=1,xTe=1,RTe=1,TTe=1;av="xeno.hosted-execution-adapter-certification.v2",MN=2,WK=744*60*60*1e3;pv();GK=2,Yx=["Read","Write","Edit","Glob","Grep","WebFetch"],LSt=new Set(Yx);y2=1,b2=1;v2="xeno.oracle-report.v1",Wc=class extends Error{constructor(e){super(`XENO Oracle report is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoOracleValidationError"}issues;code="XENO_ORACLE_INVALID"},XTe=class{execute;adjudicate;now;idFactory;constructor(e){if(typeof e?.execute!="function"||typeof e?.adjudicate!="function")throw new TypeError("Oracle execution and adjudication functions are required");this.execute=e.execute,this.adjudicate=e.adjudicate,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(t=>`${t}_${Age()}`)}async run(e){let t=nPe(e.question,"question",128e3),n=e.runId??`oracle_run_${Age()}`;rPe(n,"runId");let r=[e.primary,...e.critics,e.adjudicator];KSt(r,e.primary,e.critics,e.adjudicator);let i=this.now(),o=await this.execute({runId:n,question:t,participant:structuredClone(e.primary)}),s=wge(o,e.primary,this.idFactory("opinion"),this.now()),a=await Promise.all(e.critics.map(async h=>{let g=await this.execute({runId:n,question:t,participant:structuredClone(h),primaryOpinion:structuredClone(s)});return wge(g,h,this.idFactory("opinion"),this.now())})),c=[s,...a],l=await this.adjudicate({runId:n,question:t,participant:structuredClone(e.adjudicator),opinions:structuredClone(c)}),u=YSt(l,e.adjudicator,this.now()),d=this.now(),p=new Set(r.map(LN)),f=new Set(c.flatMap(h=>h.citations.map(g=>g.citationId))),m={schemaVersion:v2,reportId:this.idFactory("oracle"),runId:n,question:t,questionHash:Io(t),startedAt:i,completedAt:d,opinions:c,adjudication:u,summary:{participantCount:r.length,distinctModelCount:p.size,totalInputTokens:c.reduce((h,g)=>h+g.usage.inputTokens,u.usage.inputTokens),totalOutputTokens:c.reduce((h,g)=>h+g.usage.outputTokens,u.usage.outputTokens),unresolvedDisagreements:u.disagreements.filter(h=>h.resolution==="unresolved").length,citationCount:f.size}};return Zx(m),m}};I2="xeno.source-research-report.v1",nA=class extends Error{constructor(e){super(`XENO source-research report is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoSourceResearchValidationError"}issues;code="XENO_SOURCE_RESEARCH_INVALID"};ZK="xeno.recipe.v1",ns=class extends Error{constructor(e){super(`XENO recipe is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoRecipeValidationError"}issues;code="XENO_RECIPE_INVALID"};Tx();YD();YD();_p();UN=[2,1],n9=["initialize","capabilities.get","thread.start","thread.get","thread.list","thread.resume","thread.archive","thread.delete","turn.start","turn.get","turn.steer","turn.interrupt","events.subscribe","events.unsubscribe","events.poll","events.replay","permission.respond","integrations.list"],Ut=class extends Error{constructor(e,t,n,r=!1,i="app_server",o){super(t),this.machineCode=e,this.rpcCode=n,this.retryable=r,this.category=i,this.details=o,this.name="AppServerProtocolError"}machineCode;rpcCode;retryable;category;details;toData(){return{code:this.machineCode,retryable:this.retryable,category:this.category,...this.details?{details:this.details}:{}}}};OCt=class{constructor(e,t){this.retention=t,Cge(e,{recursive:!0}),this.statePath=_ge(e,"state-v2.json"),this.lockPath=_ge(e,"state-v2.lock"),this.state=lz(),this.withLock(()=>{this.state=this.load(),this.commit(this.state)})}retention;statePath;lockPath;state;snapshot(){return this.state=this.load(),I4(this.state)}mutate(e,t=new Date){return this.withLock(()=>{this.state=this.load();let n=I4(this.state),r=e(n);return this.prune(n,t),this.commit(n),this.state=n,I4(r)})}reload(){return this.state=this.load(),this.snapshot()}load(){if(!TCt(this.statePath))return lz();try{return NCt(JSON.parse(_Ct(this.statePath,"utf8")))}catch{let e=`${this.statePath}.corrupt-${Date.now()}-${Ege().slice(0,8)}`;try{Rge(this.statePath,e)}catch{}throw new Ut("APP_SERVER_STATE_CORRUPT","The app-server state is malformed and was quarantined.",-32019,!1,"persistence",{quarantineFile:e.split(/[\\/]/).at(-1)})}}commit(e){Cge(BCt(this.statePath),{recursive:!0});let t=`${this.statePath}.${process.pid}.${Ege()}.tmp`,n=xge(t,"wx",384);try{Pge(n,`${JSON.stringify(e,null,2)}
|
|
2709
2709
|
`,"utf8"),PCt(n)}finally{Sge(n)}Rge(t,this.statePath)}prune(e,t){let n=t.getTime()-this.retention.maxAgeMs;for(let r of Object.values(e.streams)){let i=0;for(;i<r.events.length&&(r.events.length-i>this.retention.maxEvents||Date.parse(r.events[i].timestamp)<n);)i+=1;if(i>0){let o=r.events.splice(0,i);r.prunedThrough=Math.max(r.prunedThrough,o.at(-1)?.sequence??0)}}}withLock(e){let t=Date.now()+5e3,n;for(;n===void 0;)try{n=xge(this.lockPath,"wx",384),Pge(n,String(process.pid),"utf8")}catch(r){if(r.code!=="EEXIST")throw r;try{Date.now()-$Ct(this.lockPath).mtimeMs>3e4&&Tge(this.lockPath)}catch{}if(Date.now()>=t)throw new Ut("APP_SERVER_STATE_LOCKED","The app-server state is busy.",-32023,!0,"persistence");Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5)}try{return e()}finally{Sge(n);try{Tge(this.lockPath)}catch{}}}};is();DCt=new Set(n9),LCt=new Set(["thread.start","thread.resume","thread.archive","thread.delete","turn.start","turn.steer","turn.interrupt","permission.respond"]);Nge=class mPe{constructor(t={}){this.options=t,this.retention={maxEvents:Math.max(32,t.eventRetention?.maxEvents??2e3),maxAgeMs:Math.max(6e4,t.eventRetention?.maxAgeMs??1440*60*1e3)},this.maxSubscriptionQueue=Math.max(8,Math.min(4096,t.maxSubscriptionQueue??256)),this.now=t.now??(()=>new Date),this.idFactory=t.idFactory??CCt,this.defaultPrincipal=k4(t.defaultPrincipal??{id:"local-stdio",workspaceRoots:[process.cwd()],capabilities:["thread.delete.permanent","integrations.read"]});let n=t.stateDir??RCt(Ea(),"app-server-v2");this.store=new OCt(n,this.retention),this.turnRunner=t.turnRunner??(async({turn:r})=>({accepted:!0,turnId:r.turnId}))}options;static supports(t){return DCt.has(t)}retention;store;connections=new Map;subscriptions=new Map;activeTurns=new Map;permissionWaiters=new Map;maxSubscriptionQueue;now;idFactory;turnRunner;defaultPrincipal;stopping=!1;supports(t){return mPe.supports(t)}capabilities(){return{"protocol.v1":!0,"protocol.v2":!0,"threads.persistent":!0,"turns.steer":!0,"turns.interrupt":!0,"events.replay":!0,"events.atLeastOnce":!0,"permissions.respond":!0,"integrations.metadata":!0,"subscriptions.maxQueue":this.maxSubscriptionQueue,"events.maxRetained":this.retention.maxEvents}}async handle(t,n,r={transport:"test"}){if(!this.supports(t))return{handled:!1};let i=kge.now(),o="success",s;$n("xeno.app_server.method_calls",1,{component:"app_server_v2",method:t,transport:r.transport});try{let a=QCt(n);if(t==="initialize")return{handled:!0,result:this.initialize(a,r)};let c=this.requireConnection(r);if(t==="capabilities.get")return{handled:!0,result:{appProtocolVersion:c.protocolVersion,capabilities:this.capabilities()}};if(c.protocolVersion!==2)throw new Ut("APP_SERVER_VERSION_UNSUPPORTED","This method requires app protocol v2.",-32010);return{handled:!0,result:await this.handleV2Method(t,a,c)}}catch(a){throw o="error",s=a instanceof Ut?a.machineCode:a instanceof Error?a.name:"unknown_error",a}finally{$n("xeno.app_server.method_results",1,{component:"app_server_v2",method:t,transport:r.transport,outcome:o,...s?{error_code:s}:{}}),Di("xeno.app_server.method_duration_ms",kge.now()-i,{component:"app_server_v2",method:t,transport:r.transport,outcome:o})}}stop(){this.stopping=!0;for(let t of this.activeTurns.values())t.abort();this.activeTurns.clear();for(let t of this.permissionWaiters.values())clearTimeout(t.timer),t.resolve("deny");this.permissionWaiters.clear();for(let t of this.subscriptions.values())t.closed=!0}subscriptionSnapshots(){return[...this.subscriptions.values()].map(t=>({subscriptionId:t.subscriptionId,connectionId:t.connectionId,streamId:t.streamId,queuedEvents:t.queue.length,droppedEvents:t.droppedEvents,degraded:t.degraded,closed:t.closed}))}initialize(t,n){let r=t,i=Array.isArray(r.protocolVersions)?r.protocolVersions.filter(c=>Number.isInteger(c)):Number.isInteger(r.appProtocolVersion)?[r.appProtocolVersion]:[2],o=UN.find(c=>i.includes(c));if(!o)throw new Ut("APP_SERVER_VERSION_UNSUPPORTED","Client and server app protocol versions do not overlap.",-32010,!1,"protocol",{requested:i,supported:[...UN]});let s=k4(n.principal??this.defaultPrincipal);if(o===1){let c=`connection_${this.idFactory()}`;return this.connections.set(c,{connectionId:c,principal:s,protocolVersion:1,client:r.client,createdAt:this.now().toISOString()}),n.connectionId=c,{appProtocolVersion:1,connectionId:c,capabilities:{"protocol.v1":!0}}}let a=`connection_${this.idFactory()}`;return this.connections.set(a,{connectionId:a,principal:s,protocolVersion:2,client:r.client,createdAt:this.now().toISOString()}),n.connectionId=a,{appProtocolVersion:2,connectionId:a,principal:{id:s.id,...s.tenantId?{tenantId:s.tenantId}:{}},capabilities:this.capabilities(),eventRetention:this.retention}}requireConnection(t){let n=t.connectionId?.trim(),r=n?this.connections.get(n):void 0;if(!r)throw new Ut("APP_SERVER_INITIALIZATION_REQUIRED","Call initialize and provide its connection identity.",-32012,!1,"protocol");if(t.principal&&k4(t.principal).id!==r.principal.id)throw new Ut("APP_SERVER_UNAUTHORIZED","Connection principal mismatch.",-32011);return r}async handleV2Method(t,n,r){switch(t){case"thread.start":return this.startThread(n,r);case"thread.get":return this.getThread(n,r);case"thread.list":return this.listThreads(n,r);case"thread.resume":return this.mutateThreadStatus("resume",n,r);case"thread.archive":return this.mutateThreadStatus("archive",n,r);case"thread.delete":return this.deleteThread(n,r);case"turn.start":return this.startTurn(n,r);case"turn.get":return this.getTurn(n,r);case"turn.steer":return this.steerTurn(n,r);case"turn.interrupt":return this.interruptTurn(n,r);case"events.subscribe":return this.subscribe(n,r);case"events.unsubscribe":return this.unsubscribe(n,r);case"events.poll":return this.poll(n,r);case"events.replay":return this.replay(n,r);case"permission.respond":return this.respondPermission(n,r);case"integrations.list":return this.listIntegrations(r);default:throw new Ut("APP_SERVER_METHOD_UNKNOWN",`Unknown v2 method: ${t}`,-32601)}}startThread(t,n){let r=this.authorizeWorkspace(typeof t.workspaceRoot=="string"?t.workspaceRoot:n.principal.workspaceRoots[0],n.principal),i=this.now().toISOString(),o=this.idempotentMutation("thread.start",t,n,(s,a)=>{let c=`thread_${this.idFactory()}`,l={schemaVersion:2,threadId:c,streamId:`stream_${c}`,principalId:n.principal.id,...n.principal.tenantId?{tenantId:n.principal.tenantId}:{},workspaceRoot:r,...typeof t.title=="string"&&t.title.trim()?{title:t.title.trim().slice(0,200)}:{},status:"active",version:1,createdAt:i,updatedAt:i};return s.threads[c]=l,a.push(this.appendEvent(s,l,"thread.started",{version:l.version})),l});return this.publishMany(o.events),o.result}getThread(t,n){return this.requireThread(ya(t,"threadId"),n,{allowDeleted:t.includeDeleted===!0})}listThreads(t,n){let r=t.includeArchived===!0,i=t.includeDeleted===!0;return Object.values(this.store.snapshot().threads).filter(o=>this.ownsThread(o,n.principal)).filter(o=>r||o.status!=="archived").filter(o=>i||o.status!=="deleted").sort((o,s)=>s.updatedAt.localeCompare(o.updatedAt))}mutateThreadStatus(t,n,r){let i=ya(n,"threadId"),o=this.idempotentMutation(`thread.${t}`,n,r,(s,a)=>{let c=this.requireThreadFromState(s,i,r,{allowDeleted:!1});if(this.assertVersion(c.version,Du(n.threadVersion),"thread"),t==="archive"&&c.status==="archived"||t==="resume"&&c.status==="active")return c;let l=this.now().toISOString(),u={...c,status:t==="archive"?"archived":"active",version:c.version+1,updatedAt:l,...t==="archive"?{archivedAt:l}:{archivedAt:void 0}};return s.threads[i]=u,a.push(this.appendEvent(s,u,`thread.${t==="archive"?"archived":"resumed"}`,{version:u.version})),u});return this.publishMany(o.events),o.result}deleteThread(t,n){let r=ya(t,"threadId"),i=this.idempotentMutation("thread.delete",t,n,(o,s)=>{let a=this.requireThreadFromState(o,r,n,{allowDeleted:!0});if(this.assertVersion(a.version,Du(t.threadVersion),"thread"),t.permanent===!0){if(!n.principal.capabilities.includes("thread.delete.permanent"))throw new Ut("APP_SERVER_UNAUTHORIZED","Permanent thread deletion is not permitted.",-32011);if(a.legalHold)throw new Ut("APP_SERVER_LEGAL_HOLD","Thread is under legal hold.",-32016);delete o.threads[r];for(let u of Object.values(o.turns))u.threadId===r&&delete o.turns[u.turnId];for(let u of Object.values(o.permissions))u.threadId===r&&delete o.permissions[u.requestId];return delete o.streams[a.streamId],{threadId:r,permanentlyDeleted:!0}}if(a.status==="deleted")return a;let c=this.now().toISOString(),l={...a,status:"deleted",version:a.version+1,updatedAt:c,deletedAt:c};return o.threads[r]=l,s.push(this.appendEvent(o,l,"thread.deleted",{version:l.version})),l});return this.publishMany(i.events),i.result}startTurn(t,n){let r=ya(t,"threadId"),i=ya(t,"input"),o=!1,s=this.idempotentMutation("turn.start",t,n,(c,l)=>{let u=this.requireThreadFromState(c,r,n,{allowDeleted:!1});if(u.status!=="active")throw new Ut("THREAD_NOT_ACTIVE","Thread must be active to start a turn.",-32013);let d=Object.values(c.turns).find(h=>h.threadId===r&&["queued","running","needs_permission"].includes(h.status));if(d)throw new Ut("TURN_ALREADY_ACTIVE","A thread can have only one active turn.",-32015,!0,"concurrency",{turnId:d.turnId});this.assertVersion(u.version,Du(t.threadVersion),"thread");let p=this.now().toISOString(),f=`turn_${this.idFactory()}`,m={schemaVersion:2,turnId:f,threadId:r,principalId:n.principal.id,connectionId:n.connectionId,status:t.defer===!0?"queued":"running",version:1,input:i,steering:[],createdAt:p,updatedAt:p,...t.defer===!0?{}:{startedAt:p}};return c.turns[f]=m,c.threads[r]={...u,version:u.version+1,updatedAt:p},l.push(this.appendEvent(c,u,"turn.started",{status:m.status},f)),o=!0,m});this.publishMany(s.events);let a=s.result;return o&&a.status==="running"&&queueMicrotask(()=>{this.executeTurn(a.turnId)}),a}getTurn(t,n){let r=this.store.snapshot().turns[ya(t,"turnId")];if(!r)throw new Ut("TURN_NOT_FOUND","Turn not found.",-32014);return this.requireThread(r.threadId,n,{allowDeleted:!1}),r}steerTurn(t,n){let r=ya(t,"turnId"),i=ya(t,"input"),o=this.idempotentMutation("turn.steer",t,n,(s,a)=>{let c=this.requireTurnFromState(s,r,n);if(this.assertVersion(c.version,Du(t.turnVersion),"turn"),!["queued","running","needs_permission"].includes(c.status))throw new Ut("TURN_NOT_RUNNING","Only an active turn can be steered.",-32015);let l=this.now().toISOString(),u={...c,version:c.version+1,updatedAt:l,steering:[...c.steering,{id:`steer_${this.idFactory()}`,text:i,createdAt:l}]};s.turns[r]=u;let d=s.threads[c.threadId];return a.push(this.appendEvent(s,d,"turn.steering",{count:u.steering.length},r)),u});return this.publishMany(o.events),o.result}interruptTurn(t,n){let r=ya(t,"turnId"),i=this.idempotentMutation("turn.interrupt",t,n,(o,s)=>{let a=this.requireTurnFromState(o,r,n);if(this.assertVersion(a.version,Du(t.turnVersion),"turn"),["completed","failed","interrupted"].includes(a.status))return a;let c=this.now().toISOString(),l={...a,status:"interrupted",version:a.version+1,updatedAt:c,completedAt:c};o.turns[r]=l;let u=o.threads[a.threadId];return s.push(this.appendEvent(o,u,"turn.interrupted",{},r)),l});return this.activeTurns.get(r)?.abort(),this.publishMany(i.events),i.result}subscribe(t,n){let r=this.resolveAuthorizedStream(t,n),i=$ge(t.afterSequence,"afterSequence")??0,o=this.replayStream(r,i,Du(t.limit)??100,n),s=`subscription_${this.idFactory()}`,a=Math.max(8,Math.min(this.maxSubscriptionQueue,Du(t.maxQueue)??this.maxSubscriptionQueue));return this.subscriptions.set(s,{subscriptionId:s,connectionId:n.connectionId,principalId:n.principal.id,streamId:r,queue:[],maxQueue:a,droppedEvents:0,degraded:!1,closed:!1}),{subscriptionId:s,streamId:r,maxQueue:a,replay:o}}unsubscribe(t,n){let r=this.requireSubscription(ya(t,"subscriptionId"),n);return r.closed=!0,this.subscriptions.delete(r.subscriptionId),{unsubscribed:!0}}poll(t,n){let r=this.requireSubscription(ya(t,"subscriptionId"),n);if(this.threadForStream(r.streamId,n).status==="deleted")throw r.closed=!0,this.subscriptions.delete(r.subscriptionId),new Ut("APP_SERVER_UNAUTHORIZED","Event access has been revoked.",-32011);let i=Math.max(1,Math.min(256,Du(t.limit)??100)),o=r.queue.splice(0,i);return{subscriptionId:r.subscriptionId,events:o,degraded:r.degraded,droppedEvents:r.droppedEvents,closed:r.closed}}replay(t,n){let r=this.resolveAuthorizedStream(t,n);return this.replayStream(r,$ge(t.afterSequence,"afterSequence")??0,Du(t.limit)??100,n)}replayStream(t,n,r,i){if(this.threadForStream(t,i).status==="deleted")throw new Ut("APP_SERVER_UNAUTHORIZED","Event access has been revoked.",-32011);let o=this.store.snapshot().streams[t]??{nextSequence:1,prunedThrough:0,events:[]};if(n<o.prunedThrough)throw $n("xeno.app_server.cursor_expirations",1,{component:"app_server_v2",operation:"replay",reason:"cursor_expired"}),new Ut("EVENT_CURSOR_EXPIRED","The requested event cursor is older than retained history.",-32018,!1,"replay",{prunedThrough:o.prunedThrough});let s=Math.max(1,Math.min(256,r)),a=o.events.filter(l=>l.sequence>n).slice(0,s);Di("xeno.app_server.replay_events",a.length,{component:"app_server_v2",operation:"replay"});let c=new Set;for(let l of a){let u=`${l.streamId}:${l.sequence}`;if(c.has(u))throw new Ut("APP_SERVER_EVENT_DUPLICATE","Duplicate retained event detected.",-32019);c.add(u)}return{streamId:t,events:a,nextCursor:a.at(-1)?.sequence??n,hasMore:o.events.some(l=>l.sequence>(a.at(-1)?.sequence??n)),delivery:"at-least-once"}}respondPermission(t,n){let r=ya(t,"requestId"),i=ya(t,"response");if(!["allow","always","deny"].includes(i))throw new Ut("APP_SERVER_INVALID_PARAMS","Permission response is invalid.",-32602);let o=this.lookupIdempotentMutation("permission.respond",t,n);if(o.found)return o.result;let s=this.store.snapshot().permissions[r];if(!s||s.status!=="pending")throw new Ut("PERMISSION_RESPONSE_STALE","Permission request is not active.",-32017);if(s.principalId!==n.principal.id||s.connectionId!==n.connectionId)throw new Ut("APP_SERVER_UNAUTHORIZED","Permission request ownership mismatch.",-32011);if(Date.parse(s.expiresAt)<=this.now().getTime())throw this.store.mutate(l=>{let u=l.permissions[r];u?.status==="pending"&&(l.permissions[r]={...u,status:"expired"})},this.now()),new Ut("PERMISSION_RESPONSE_STALE","Permission request has expired.",-32017);let a=this.idempotentMutation("permission.respond",t,n,(l,u)=>{let d=l.permissions[r];if(!d)throw new Ut("PERMISSION_RESPONSE_STALE","Permission request is not active.",-32017);let p=this.now().toISOString(),f={...d,status:i==="deny"?"denied":"allowed",response:i,respondedAt:p};l.permissions[r]=f;let m=l.threads[d.threadId];return u.push(this.appendEvent(l,m,"permission.resolved",{requestId:r,response:i},d.turnId)),f}),c=this.permissionWaiters.get(r);return c&&(clearTimeout(c.timer),this.permissionWaiters.delete(r),c.resolve(i)),this.publishMany(a.events),a.result}async listIntegrations(t){return t.principal.capabilities.includes("integrations.read")?(await this.options.integrations?.()??[]).filter(n=>(n.requiredCapabilities??[]).every(r=>t.principal.capabilities.includes(r))).filter(n=>!n.workspaceRoot||t.principal.workspaceRoots.some(r=>E4(n.workspaceRoot,r))).map(n=>({id:n.id,kind:n.kind,name:n.name,...n.description?{description:n.description.slice(0,500)}:{},status:n.status,...n.workspaceRoot?{workspaceRoot:n.workspaceRoot}:{},requiredCapabilities:[...n.requiredCapabilities??[]],metadata:KC(n.metadata??{})})):[]}async executeTurn(t){let n=this.store.snapshot(),r=n.turns[t],i=r?n.threads[r.threadId]:void 0;if(!r||!i||r.status!=="running")return;let o=new AbortController;this.activeTurns.set(t,o);let s=new Set;try{let a=await this.turnRunner({thread:i,turn:r,signal:o.signal,emit:(l,u={})=>{if(this.stopping)return;let d=this.store.mutate(p=>{let f=p.threads[i.threadId];return f?this.appendEvent(p,f,l,KC(u),t):null},this.now());d&&this.publish(d)},takeSteering:()=>{let l=this.store.snapshot().turns[t];if(!l)return[];let u=l.steering.filter(d=>!s.has(d.id));return u.forEach(d=>s.add(d.id)),u},requestPermission:l=>this.createPermissionRequest(t,l)});if(this.stopping)return;let c=this.store.mutate(l=>{let u=l.turns[t];if(!u||u.status==="interrupted")return[];let d=this.now().toISOString();return l.turns[t]={...u,status:"completed",version:u.version+1,updatedAt:d,completedAt:d,result:KC(a)},[this.appendEvent(l,l.threads[u.threadId],"turn.completed",{},t)]},this.now());this.publishMany(c)}catch(a){if(this.stopping)return;let c=this.store.mutate(l=>{let u=l.turns[t];if(!u||u.status==="interrupted")return[];let d=this.now().toISOString(),p=FCt(a);return l.turns[t]={...u,status:"failed",version:u.version+1,updatedAt:d,completedAt:d,error:p},[this.appendEvent(l,l.threads[u.threadId],"turn.failed",{code:p.code},t)]},this.now());this.publishMany(c)}finally{this.activeTurns.delete(t)}}createPermissionRequest(t,n){let r=this.now(),i=Math.max(1e3,Math.min(10*6e4,n.expiresInMs??6e4)),o=this.store.mutate(s=>{let a=s.turns[t];if(!a)throw new Ut("TURN_NOT_FOUND","Turn not found.",-32014);let c=`permission_${this.idFactory()}`,l={schemaVersion:2,requestId:c,threadId:a.threadId,turnId:t,principalId:a.principalId,connectionId:a.connectionId,permission:n.permission.slice(0,200),...n.resource?{resource:n.resource.slice(0,500)}:{},status:"pending",createdAt:r.toISOString(),expiresAt:new Date(r.getTime()+i).toISOString()};s.permissions[c]=l,s.turns[t]={...a,status:"needs_permission",version:a.version+1,updatedAt:l.createdAt};let u=this.appendEvent(s,s.threads[a.threadId],"permission.requested",{requestId:c,permission:l.permission,...l.resource?{resource:l.resource}:{},expiresAt:l.expiresAt},t);return{permission:l,event:u}},r);return this.publish(o.event),new Promise(s=>{let a=setTimeout(()=>{if(this.stopping){s("deny");return}this.permissionWaiters.delete(o.permission.requestId);let c=this.store.mutate(l=>{let u=l.permissions[o.permission.requestId];if(!u||u.status!=="pending")return null;l.permissions[u.requestId]={...u,status:"expired"};let d=l.turns[u.turnId];return d?.status==="needs_permission"&&(l.turns[u.turnId]={...d,status:"running",version:d.version+1,updatedAt:this.now().toISOString()}),this.appendEvent(l,l.threads[u.threadId],"permission.expired",{requestId:u.requestId},u.turnId)},this.now());c&&this.publish(c),s("deny")},i);a.unref?.(),this.permissionWaiters.set(o.permission.requestId,{resolve:s,timer:a})})}idempotentMutation(t,n,r,i){if(!LCt.has(t))throw new Error(`Method ${t} is not registered as a mutation.`);let o=typeof n.idempotencyKey=="string"?n.idempotencyKey.trim():"",s={...n};delete s.idempotencyKey;let a=Mge(s),c=o?`${r.principal.id}:${t}:${o}`:"";return this.store.mutate(l=>{if(c){let p=l.idempotency[c];if(p){if(p.fingerprint!==a)throw new Ut("IDEMPOTENCY_KEY_REUSED","The idempotency key was already used with different parameters.",-32020);return{result:p.result,events:[]}}}let u=[],d=i(l,u);return c&&(l.idempotency[c]={fingerprint:a,result:d,createdAt:this.now().toISOString()}),{result:d,events:u}},this.now())}lookupIdempotentMutation(t,n,r){let i=typeof n.idempotencyKey=="string"?n.idempotencyKey.trim():"";if(!i)return{found:!1};let o={...n};delete o.idempotencyKey;let s=Mge(o),a=`${r.principal.id}:${t}:${i}`,c=this.store.snapshot().idempotency[a];if(!c)return{found:!1};if(c.fingerprint!==s)throw new Ut("IDEMPOTENCY_KEY_REUSED","The idempotency key was already used with different parameters.",-32020);return{found:!0,result:c.result}}appendEvent(t,n,r,i,o){let s=t.streams[n.streamId]??{nextSequence:1,prunedThrough:0,events:[]};t.streams[n.streamId]=s;let a={protocolVersion:2,schemaVersion:2,streamId:n.streamId,sequence:s.nextSequence,eventId:`event_${this.idFactory()}`,threadId:n.threadId,...o?{turnId:o}:{},type:r,timestamp:this.now().toISOString(),payload:i};return s.nextSequence+=1,s.events.push(a),a}publishMany(t){for(let n of t)this.publish(n)}publish(t){for(let n of this.subscriptions.values()){if(n.closed||n.streamId!==t.streamId)continue;if(n.queue.length<n.maxQueue){n.queue.push(t);continue}if(n.degraded=!0,$n("xeno.app_server.subscription_backpressure",1,{component:"app_server_v2",queue:"subscription",state:"degraded"}),qCt(t)){let i=-1;for(let o=n.queue.length-1;o>=0;o-=1){let s=n.queue[o];if(s.type===t.type&&s.turnId===t.turnId){i=o;break}}i>=0?n.queue[i]=t:(n.droppedEvents+=1,$n("xeno.app_server.subscription_dropped_events",1,{component:"app_server_v2",reason:"coalescing_unavailable"}));continue}let r=n.queue.findIndex(i=>!UCt(i));if(r>=0){n.queue.splice(r,1),n.queue.push(t),n.droppedEvents+=1,$n("xeno.app_server.subscription_dropped_events",1,{component:"app_server_v2",reason:"terminal_priority"});continue}n.closed=!0,n.queue=[],n.droppedEvents+=1,$n("xeno.app_server.subscription_closures",1,{component:"app_server_v2",reason:"irrecoverable_backpressure"})}}authorizeWorkspace(t,n){if(typeof t!="string"||!t.trim()||!xCt(t))throw new Ut("APP_SERVER_UNAUTHORIZED","A permitted workspace is required.",-32011);let r=t9(t);if(!n.workspaceRoots.some(i=>E4(r,i)))throw new Ut("APP_SERVER_UNAUTHORIZED","Workspace is outside the principal boundary.",-32011);return r}ownsThread(t,n){return t.principalId===n.id&&(t.tenantId??"")===(n.tenantId??"")&&n.workspaceRoots.some(r=>E4(t.workspaceRoot,r))}requireThread(t,n,r){return this.requireThreadFromState(this.store.snapshot(),t,n,r)}requireThreadFromState(t,n,r,i){let o=t.threads[n];if(!o||!this.ownsThread(o,r.principal)||!i.allowDeleted&&o.status==="deleted")throw new Ut("APP_SERVER_UNAUTHORIZED","Thread is not available to this principal.",-32011);return o}requireTurnFromState(t,n,r){let i=t.turns[n];if(!i)throw new Ut("TURN_NOT_FOUND","Turn not found.",-32014);return this.requireThreadFromState(t,i.threadId,r,{allowDeleted:!1}),i}assertVersion(t,n,r){if(n!==void 0&&n!==t)throw new Ut("APP_SERVER_VERSION_CONFLICT",`The ${r} version is stale.`,-32021,!0,"concurrency",{expected:n,actual:t})}resolveAuthorizedStream(t,n){if(typeof t.threadId=="string")return this.requireThread(t.threadId,n,{allowDeleted:!0}).streamId;let r=ya(t,"streamId");return this.threadForStream(r,n),r}threadForStream(t,n){let r=Object.values(this.store.snapshot().threads).find(i=>i.streamId===t);if(!r||!this.ownsThread(r,n.principal))throw new Ut("APP_SERVER_UNAUTHORIZED","Event stream is not available.",-32011);return r}requireSubscription(t,n){let r=this.subscriptions.get(t);if(!r||r.connectionId!==n.connectionId||r.principalId!==n.principal.id)throw new Ut("APP_SERVER_UNAUTHORIZED","Subscription is not available.",-32011);if(r.closed)throw new Ut("APP_SERVER_BACKPRESSURE","Subscription was closed because the client could not keep up.",-32022,!0,"backpressure");return r}},pA=class extends Error{constructor(e,t,n){super(e),this.rpcCode=t,this.data=n,this.name="AppServerRemoteError"}rpcCode;data},hPe=class{constructor(e){this.transport=e}transport;connectionId;async initialize(e={protocolVersions:[2]}){let t=await this.transport.request({method:"initialize",params:e});if(!t||typeof t!="object"||t.appProtocolVersion!==2)throw new pA("Server did not negotiate app protocol v2.",-32010,{code:"APP_SERVER_VERSION_UNSUPPORTED",retryable:!1,category:"protocol"});let n=t;return this.connectionId=n.connectionId,n}async call(e,t){if(!this.connectionId)throw new pA("Call initialize before stateful methods.",-32012,{code:"APP_SERVER_INITIALIZATION_REQUIRED",retryable:!1,category:"protocol"});return await this.transport.request({method:e,params:t,connectionId:this.connectionId})}getConnectionId(){return this.connectionId}};k2=class{constructor(e={}){this.options=e,this.execManager=e.execManager??Mp,this.ownerId=e.ownerId??`app-server-${ECt()}`;let t=e.defaultAgentOptions?.cwd??process.cwd();this.v2Options={...e.v2,defaultPrincipal:e.v2?.defaultPrincipal??{id:this.ownerId,workspaceRoots:[t],capabilities:["thread.delete.permanent","integrations.read"]},turnRunner:e.v2?.turnRunner??(async n=>FN({...this.options.defaultAgentOptions,prompt:n.turn.input,signal:n.signal,...this.options.defaultAgentOptions?.permissionEngine?{permissionEngine:this.options.defaultAgentOptions.permissionEngine.fork(async r=>n.requestPermission({permission:r.toolName,resource:r.filePath??r.directory??r.commandPrefix??r.detail}))}:{permissionPrompt:async r=>n.requestPermission({permission:r.toolName,resource:r.filePath??r.directory??r.commandPrefix??r.detail})},onPermissionRequest:async r=>{let i=await n.requestPermission({permission:r.toolName,resource:r.path||r.directory||r.reason});return{granted:i!=="deny",...i==="always"?{allowedDirectory:r.directory}:{}}},onRuntimeEvent:r=>n.emit("runtime.event",{eventType:r.type,timestamp:r.timestamp,sequence:r.sequence},{coalescible:/delta|progress/.test(r.type)})}))}}options;stopping=!1;execManager;ownerId;v2Runtime;v2Options;async start(e=process.stdin,t=process.stdout){let n=kCt({input:e,crlfDelay:1/0}),r={transport:"stdio",principal:this.options.v2?.defaultPrincipal??{id:this.ownerId,workspaceRoots:[this.options.defaultAgentOptions?.cwd??process.cwd()],capabilities:["thread.delete.permanent","integrations.read"]}};this.write(t,{jsonrpc:"2.0",method:"server.ready",params:{name:"xeno-app-server",protocolVersion:1,protocolVersions:[2,1],ownerId:this.ownerId,capabilities:{"exec.pty":this.execManager.getPtyCapability(),"exec.resize":!0}}});try{for await(let i of n){if(this.stopping)break;let o=i.trim();if(!o)continue;let s;try{s=JSON.parse(o)}catch(a){this.write(t,this.error(null,-32700,"Parse error",a));continue}await this.handleRequest(s,t,r)}}finally{this.stop()}}stop(){this.stopping||(this.stopping=!0,this.v2Runtime?.stop(),this.execManager.terminateOwner(this.ownerId,{force:!0}))}async handleJsonRpcRequest(e,t={transport:"test"}){let n=[],r={write(i){for(let o of i.split(/\r?\n/)){let s=o.trim();s&&n.push(JSON.parse(s))}return!0}};return await this.handleRequest(e,r,t),n}getSubscriptionSnapshots(){return this.v2Runtime?.subscriptionSnapshots()??[]}async handleRequest(e,t,n){try{if(Nge.supports(e.method)){let r=await this.appServerV2().handle(e.method,e.params,n);if(r.handled){this.write(t,this.success(e.id??null,r.result));return}}if(e.method==="health"){this.write(t,this.success(e.id??null,{ok:!0}));return}if(e.method==="exec.start"){let r=sm(e.params),i=typeof r.command=="string"?r.command:"";if(!i.trim()){this.write(t,this.error(e.id??null,-32602,"exec.start requires params.command"));return}this.write(t,this.success(e.id??null,this.execManager.start(i,{cwd:typeof r.cwd=="string"?r.cwd:void 0,timeoutMs:am(r.timeoutMs),maxOutputBytes:am(r.maxOutputBytes),env:jCt(r.env),tty:r.tty===!0,cols:am(r.cols),rows:am(r.rows),ownerSessionId:this.ownerId,origin:"app_server"})));return}if(e.method==="exec.write"){let r=sm(e.params),i=typeof r.processId=="string"?r.processId:"",o=typeof r.text=="string"?r.text:"";if(!this.isOwned(i)){this.write(t,this.error(e.id??null,-32004,"Process not found"));return}this.write(t,this.success(e.id??null,{ok:this.execManager.writeStdin(i,o,{source:"app_server"})}));return}if(e.method==="exec.output"){let r=sm(e.params),i=typeof r.processId=="string"?r.processId:"";if(!this.isOwned(i)){this.write(t,this.error(e.id??null,-32004,"Process not found"));return}this.write(t,this.success(e.id??null,this.execManager.readOutput(i)));return}if(e.method==="exec.output.delta"){let r=sm(e.params),i=typeof r.processId=="string"?r.processId:"";if(!this.isOwned(i)){this.write(t,this.error(e.id??null,-32004,"Process not found"));return}this.write(t,this.success(e.id??null,this.execManager.readOutputDelta(i,VCt(r.cursor)??0,{maxChunks:am(r.maxChunks),maxBytes:am(r.maxBytes)})));return}if(e.method==="exec.terminate"){let r=sm(e.params),i=typeof r.processId=="string"?r.processId:"";if(!this.isOwned(i)){this.write(t,this.error(e.id??null,-32004,"Process not found"));return}this.write(t,this.success(e.id??null,{ok:this.execManager.terminate(i)}));return}if(e.method==="exec.resize"){let r=sm(e.params),i=typeof r.processId=="string"?r.processId:"";if(!this.isOwned(i)){this.write(t,this.error(e.id??null,-32004,"Process not found"));return}let o=am(r.cols),s=am(r.rows);if(!o||!s){this.write(t,this.error(e.id??null,-32602,"INVALID_SIZE: exec.resize requires positive cols and rows"));return}let a=this.execManager.get(i);if(a.status!=="running"){this.write(t,this.error(e.id??null,-32005,`TASK_NOT_RUNNING: ${a.status}`));return}if(!a.interactive){this.write(t,this.error(e.id??null,-32006,"TASK_NOT_INTERACTIVE: process is pipe-backed"));return}if(!this.execManager.resize(i,o,s)){this.write(t,this.error(e.id??null,-32602,"INVALID_SIZE: terminal dimensions are outside supported bounds"));return}this.write(t,this.success(e.id??null,{ok:!0}));return}if(e.method==="exec.list"){this.write(t,this.success(e.id??null,this.execManager.list({ownerSessionId:this.ownerId})));return}if(e.method==="thread.run"){let r=sm(e.params),i=typeof r.prompt=="string"?r.prompt:"";if(!i.trim()){this.write(t,this.error(e.id??null,-32602,"thread.run requires params.prompt"));return}let o=sm(r.options),s=await FN({...this.options.defaultAgentOptions,...o,prompt:i,onRuntimeEvent:a=>{this.write(t,{jsonrpc:"2.0",method:"runtime.event",params:a})}});this.write(t,this.success(e.id??null,s));return}if(e.method==="server.stop"){this.write(t,this.success(e.id??null,{ok:!0})),this.stop();return}this.write(t,this.error(e.id??null,-32601,`Unknown method: ${e.method}`))}catch(r){if(r instanceof Ut){this.write(t,this.error(e.id??null,r.rpcCode,r.message,r.toData()));return}let i=r instanceof Error?r.message:String(r);this.write(t,this.error(e.id??null,-32e3,i))}}success(e,t){return{jsonrpc:"2.0",id:e,result:t}}appServerV2(){return this.v2Runtime??=new Nge(this.v2Options),this.v2Runtime}isOwned(e){return this.execManager.get(e)?.ownerSessionId===this.ownerId}error(e,t,n,r){return{jsonrpc:"2.0",id:e,error:{code:t,message:n,...r?{data:HCt(r)}:{}}}}write(e,t){e.write(`${JSON.stringify(t)}
|
|
2710
|
-
`)}};SO();LO();cx();ka();rs();os();px();WCt=1e4,GCt=6e4,JCt="session.lock",XCt="lock.json",xb=new Map;$v(zCt);qN=class APe{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(t){this.sessionDir=t,this.lockPath=$m.join(t,JCt),this.legacyLockPath=$m.join(t,XCt),this.sessionId=$m.basename(t)}async acquire(){let t=new Date().toISOString(),n={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:dz.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:Tp,acquiredAt:t,updatedAt:t,heartbeat:t},r=$m.dirname(this.lockPath);await Sm.promises.mkdir(r,{recursive:!0});let i=await this.findExistingLockPath();if(i){if(!await this.isStalePath(i)){let o=await this.readLockAt(i);throw new Error(`Session ${this.sessionId} is already locked by PID ${o?.pid} on ${o?.hostname}`)}await yb(i)}try{await Sm.promises.writeFile(this.lockPath,JSON.stringify(n,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=n,xb.set(this.lockPath,n)}catch(o){if(o.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let s=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${s?.pid} on ${s?.hostname}`)}await yb(this.lockPath);try{await Sm.promises.writeFile(this.lockPath,JSON.stringify(n,null,2),{flag:"wx",encoding:"utf-8"})}catch(s){throw s.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):s}this.acquiredOwner=n,xb.set(this.lockPath,n)}else throw o}}async release(){this.stopHeartbeat();let t=this.acquiredOwner;if(this.acquiredOwner=void 0,!t)return;xb.delete(this.lockPath);let n=await this.readLockAt(this.lockPath);pz(n,t)&&await yb(this.lockPath)}async isLocked(){let t=await this.findExistingLockPath();return t?!await this.isStalePath(t):!1}async isStale(){let t=await this.findExistingLockPath();return t?this.isStalePath(t):!1}async isStalePath(t){let n=await this.readLockAt(t);if(!n)return!1;if(n.hostname===dz.hostname())try{process.kill(n.pid,0)}catch(i){if(i.code!=="EPERM")return!0}let r=new Date(n.heartbeat).getTime();return Date.now()-r>GCt}startHeartbeat(t=WCt){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(n){let r=n instanceof Error?n.message:String(n);if(n?.code==="ENOENT"){_n("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}_n(`SessionLock: Failed to update heartbeat: ${r}`)}},t),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let t=await this.readLockAt(this.lockPath),n=this.acquiredOwner;if(!(!t||!n)){if(!pz(t,n)){this.acquiredOwner=void 0,xb.delete(this.lockPath),this.stopHeartbeat();return}t.heartbeat=new Date().toISOString(),t.updatedAt=t.heartbeat,await Li(this.lockPath,JSON.stringify(t,null,2))}}async readLock(){let t=await this.findExistingLockPath();return t?this.readLockAt(t):null}async readLockAt(t){let n=await fi(t);return n?Er(n,null):null}async findExistingLockPath(){return await fi(this.lockPath)?this.lockPath:await fi(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(t){let n=await QAe(t),r=[];for(let i of n){let o=new APe(i);if(await o.isStale()){let s=await o.findExistingLockPath();s&&await yb(s),r.push($m.basename(i))}}return r}};$8();ka();rs();LO();cx();$8();SO();pv();DO();os();cx();LO();Bye();Yv=class fz{sessionDir;_meta;_transcript;_checkpoints;_lock;_recovery;_detachedForHandoff=!1;constructor(t,n,r,i,o,s){this.sessionDir=t,this._meta=n,this._transcript=r,this._checkpoints=i,this._lock=o,this._recovery=s}static async create(t){NC(t.executionMode);let n=t.role??"default",r=rx(n),i=qe.getSessionDir(r),o=null,s=null;try{await IA(i);let a={id:r,role:n,status:"creating",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),lastActivity:new Date().toISOString(),workingDirectory:t.workingDirectory,model:t.model,...t.executionMode!==void 0?{executionMode:t.executionMode}:{},parentSession:t.parentSession,...t.hostBinding?{hostBinding:structuredClone(t.hostBinding)}:{},checkpoints:[],messageCount:0,tokenUsage:{input:0,output:0,total:0},formatVersion:1},c=dM.join(i,"meta.json");await Li(c,JSON.stringify(a,null,2)),s=new Ri(i);let l=new Jc(i);o=new qN(i),await o.acquire(),o.startHeartbeat(),await s.append({type:"session_start",data:{sessionId:r,role:n,workingDirectory:t.workingDirectory,model:t.model,formatVersion:1}});let u=new fz(i,a,s,l,o,{messages:[],transcriptMessages:[],source:"empty",issues:[],repairMessages:[],transcriptEventCount:1});return await u.updateMeta({status:"active"}),u}catch(a){if(o)try{o.stopHeartbeat(),await o.release()}catch(c){_n("Error releasing lock during cleanup",c)}throw a}}static async resume(t){let n=qe.getSessionDir(t.sessionId),r=null,i=null;try{let o=dM.join(n,"meta.json"),s=await fi(o);if(!s)throw new Error(`SessionManager: Session not found: ${t.sessionId}`);let a=Er(s,null);if(!a)throw new Error(`SessionManager: Invalid session metadata: ${t.sessionId}`);NC(a.executionMode),a.formatVersion=r9(a),i=new Ri(n),await i.initialize();let c=new Jc(n);r=new qN(n),await r.acquire(),r.startHeartbeat();let l;if(t.fromCheckpoint){let{info:d,messages:p}=await c.restore(t.fromCheckpoint);a.messageCount=d.messageCount,await i.append({type:"checkpoint",data:{id:t.fromCheckpoint,trigger:"manual",messageCount:d.messageCount}}),l={messages:p,transcriptMessages:p,source:"checkpoint",sourceId:t.fromCheckpoint,issues:[],repairMessages:[],transcriptEventCount:i.getSequence()}}else l=await zv(n,{metadataMessageCount:a.messageCount}),a.messageCount=l.messages.length;let u=new fz(n,a,i,c,r,l);return await u.updateMeta({status:"active",lastActivity:new Date().toISOString()}),u}catch(o){if(r)try{r.stopHeartbeat(),await r.release()}catch(s){_n("Error releasing lock during cleanup",s)}throw o}}get meta(){return{...this._meta}}get transcript(){return this._transcript}get checkpoints(){return this._checkpoints}get recovery(){return{...this._recovery,messages:[...this._recovery.messages],transcriptMessages:[...this._recovery.transcriptMessages],repairMessages:[...this._recovery.repairMessages],issues:[...this._recovery.issues]}}async detachForHandoff(){this._detachedForHandoff||(await this._transcript.flush(),this._lock.stopHeartbeat(),await this._lock.release(),this._detachedForHandoff=!0)}get detachedForHandoff(){return this._detachedForHandoff}async updateMeta(t){if(NC(t.executionMode),this._detachedForHandoff)throw new Error(`Session ${this._meta.id} is detached after execution handoff`);this._meta={...this._meta,...t,updatedAt:new Date().toISOString()};let n=dM.join(this.sessionDir,"meta.json"),r=3,i=null;for(let o=0;o<r;o++)try{await Li(n,JSON.stringify(this._meta,null,2));return}catch(s){i=s instanceof Error?s:new Error(String(s)),mi(`Failed to write session metadata (attempt ${o+1}/${r}): ${i.message}`),o<r-1&&await new Promise(a=>setTimeout(a,Math.pow(2,o)*100))}_n(`Failed to write session metadata after ${r} attempts. Session will continue but metadata may be stale.`)}async end(t="completed"){await this._transcript.append({type:"session_end",data:{reason:t==="completed"?"completed":"user_exit",messageCount:this._meta.messageCount,totalTokens:this._meta.tokenUsage.total}}),await this._transcript.flush(),await this.updateMeta({status:t}),this._lock.stopHeartbeat(),await this._lock.release()}async recordUserMessage(t){await this._transcript.append({type:"user_message",data:{role:"user",content:t}}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()})}async recordDirectShellResult(t){let n=Dm(t);return await this._transcript.append({type:"user_message",data:n}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()}),n}async recordAssistantMessage(t,n){await this._transcript.append({type:"assistant_message",data:{role:"assistant",content:t},tokenCount:n}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()})}async recordTokenUsage(t,n){let r={input:this._meta.tokenUsage.input+t,output:this._meta.tokenUsage.output+n,total:this._meta.tokenUsage.total+t+n};await this.updateMeta({tokenUsage:r})}async recordDelegationSummary(t){await this._transcript.append({type:"delegation_summary",data:t}),await this.updateMeta({lastActivity:new Date().toISOString()})}async updateMessageCount(t){t!==this._meta.messageCount&&await this.updateMeta({messageCount:t,lastActivity:new Date().toISOString()})}};DO();Qye();ic();Fi();C4=2,Qge=400,x4=80,mz=12,Fge=3e4,R4=64*1024*1024;Wm=class{constructor(e,t){this.sessionDir=e,this.workspaceDir=t,this.restoreRoot=lr.join(e,"turn-restores")}sessionDir;workspaceDir;restoreRoot;operationQueue=Promise.resolve();async create(e){let t={id:e.id??jN(),createdAt:new Date().toISOString(),restoreMessageCount:e.restoreMessageCount,userPrompt:e.userPrompt,mutations:[],unsupportedTools:[]};return this.enqueue(async()=>{let n=this.getRestoreDir(t.id);return await RC(lr.join(n,"backups"),{recursive:!0}),await this.savePoint(t),t})}async recordToolExecution(e,t,n){t=Gt(t);let r=s0t(t),i=r?await this.ensureGitCheckpoint(e):null;if(t==="Write"||t==="Edit"||t==="NotebookEdit"){let o=typeof n.file_path=="string"?n.file_path:typeof n.notebook_path=="string"?n.notebook_path:"";if(!o)return;await this.captureFileMutation(e,o);return}(t==="Bash"||r)&&(!i||a0t(t,n))&&await this.markUnsupportedTool(e,t)}async restoreAtOrAfter(e){return this.enqueue(async()=>{let t=await this.inspectAtOrAfterInternal(e);if(!t.hadRestorePoints)return{...t,restoredFiles:0,removedFiles:0};let n=t.points.find(s=>s.gitCheckpoint)?.gitCheckpoint;n&&await this.restoreGitCheckpoint(n);let r=new Map;for(let s of t.points)for(let a of s.mutations){if(!a.existedBefore||!a.backupFile)continue;let c=this.getBackupPath(s.id,a.backupFile);r.set(c,await iC(c,"utf8"))}let i=0,o=0;for(let s of[...t.points].reverse())for(let a of[...s.mutations].reverse()){let c=lr.join(this.workspaceDir,a.relativePath);if(a.existedBefore&&a.backupFile){let l=this.getBackupPath(s.id,a.backupFile);await RC(lr.dirname(c),{recursive:!0}),await S4(c,r.get(l)??"","utf8"),i+=1;continue}await IB(c,{recursive:!0,force:!0}),await this.pruneEmptyParentDirs(lr.dirname(c)),o+=1}for(let s of t.points)await this.deleteGitCheckpointRef(s.gitCheckpoint),await IB(this.getRestoreDir(s.id),{recursive:!0,force:!0});return{...t,restoredFiles:i,removedFiles:o}})}async deleteAtOrAfter(e){await this.enqueue(async()=>{let t=await this.listPointsAtOrAfter(e);for(let n of t)await this.deleteGitCheckpointRef(n.gitCheckpoint),await IB(this.getRestoreDir(n.id),{recursive:!0,force:!0})})}async inspectAtOrAfter(e){return this.enqueue(async()=>this.inspectAtOrAfterInternal(e))}async findByRestoreMessageCount(e){return(await this.inspectAtOrAfter(e)).points.filter(t=>t.restoreMessageCount===e).at(-1)??null}async captureFileMutation(e,t){await this.enqueue(async()=>{let n=await this.loadPoint(e),r;try{r=zt(this.workspaceDir,t)}catch{return}let i=lr.relative(this.workspaceDir,r);if(!i||n.mutations.some(c=>c.relativePath===i))return;try{if(!(await n0t(r)).isFile()){n.mutations.push({relativePath:i,existedBefore:!1}),await this.savePoint(n);return}}catch(c){if(c.code==="ENOENT"){n.mutations.push({relativePath:i,existedBefore:!1}),await this.savePoint(n);return}throw c}let o=`${n.mutations.length+1}.txt`,s=this.getBackupPath(e,o),a=await iC(r,"utf8");await RC(lr.dirname(s),{recursive:!0}),await S4(s,a,"utf8"),n.mutations.push({relativePath:i,existedBefore:!0,backupFile:o}),await this.savePoint(n)})}async markUnsupportedTool(e,t){await this.enqueue(async()=>{let n=await this.loadPoint(e);n.unsupportedTools.includes(t)||(n.unsupportedTools.push(t),await this.savePoint(n))})}async ensureGitCheckpoint(e){return this.enqueue(async()=>{let t=await this.loadPoint(e);if(t.gitCheckpoint)return t.gitCheckpoint;let n=await c0t(this.workspaceDir,this.getRestoreDir(e),t.id).catch(()=>null);return n?(t.gitCheckpoint=n,await this.savePoint(t),n):null})}async restoreGitCheckpoint(e){let t=await i9(e.repositoryRoot,this.workspaceDir,lr.join(this.restoreRoot,`.restore-index-${jN()}`)),n=await tR(e.repositoryRoot,["diff","--binary","--full-index","--no-ext-diff",t,e.commit,"--",e.workspacePathspec]);n.length!==0&&(await Gge(e.repositoryRoot,n,!0),await Gge(e.repositoryRoot,n,!1))}async deleteGitCheckpointRef(e){e&&await Gu(e.repositoryRoot,["update-ref","-d",e.ref,e.commit]).catch(()=>{})}async inspectAtOrAfterInternal(e){let t=await this.listPointsAtOrAfter(e),n=Array.from(new Set(t.flatMap(c=>c.unsupportedTools))),r=t.find(c=>c.gitCheckpoint)?.gitCheckpoint,i=r?await u0t(r,this.workspaceDir).catch(()=>({changedPaths:[],previews:[]})):{changedPaths:[],previews:[]},o=await this.buildFilePreviews(t),s=new Set(o.map(c=>c.relativePath.replace(/\\/g,"/"))),a=i.previews.filter(c=>!s.has(c.relativePath.replace(/\\/g,"/")));return{points:t,hadRestorePoints:t.length>0,exactWorkspaceRestore:t.length>0&&n.length===0,unsupportedTools:n,filePreviews:[...o,...a].slice(0,mz),gitChangedPaths:i.changedPaths,gitCheckpointCount:t.filter(c=>c.gitCheckpoint).length}}async buildFilePreviews(e){let t=new Map;for(let r of e)for(let i of r.mutations)t.has(i.relativePath)||(i.existedBefore&&i.backupFile?t.set(i.relativePath,{action:"revert",pointId:r.id,backupFile:i.backupFile}):t.set(i.relativePath,{action:"remove"}));let n=[];for(let[r,i]of t){if(n.length>=mz)break;let o=lr.join(this.workspaceDir,r),s="",a=!1;try{s=await iC(o,"utf8")}catch(u){if(u.code==="ENOENT")a=!0;else{n.push({relativePath:r,action:i.action,lines:[`(current file unavailable: ${u.message})`],truncated:!1});continue}}if(i.action==="remove"){let u=a?{lines:[`--- current/${r}`,"+++ /dev/null","(already missing)"],truncated:!1}:hz(r,s,"",`current/${r}`,"/dev/null");n.push({relativePath:r,action:"remove",lines:u.lines,truncated:u.truncated});continue}let c=await iC(this.getBackupPath(i.pointId,i.backupFile),"utf8"),l=hz(r,s,c,a?`missing/${r}`:`current/${r}`,`restore/${r}`);n.push({relativePath:r,action:"revert",lines:l.lines,truncated:l.truncated})}return n}async listPointsAtOrAfter(e){try{let t=await Dge(this.restoreRoot,{withFileTypes:!0}),n=[];for(let r of t)if(r.isDirectory())try{let i=await this.loadPoint(r.name);i.restoreMessageCount>=e&&n.push(i)}catch{continue}return n.sort((r,i)=>r.createdAt.localeCompare(i.createdAt)),n}catch{return[]}}async loadPoint(e){let t=lr.join(this.getRestoreDir(e),"meta.json"),n=await iC(t,"utf8"),r=JSON.parse(n);if(!r||typeof r.id!="string"||typeof r.restoreMessageCount!="number")throw new Error(`Invalid restore point metadata: ${e}`);return r}async savePoint(e){let t=this.getRestoreDir(e.id);await RC(t,{recursive:!0}),await S4(lr.join(t,"meta.json"),JSON.stringify(e,null,2),"utf8")}async pruneEmptyParentDirs(e){let t=lr.resolve(this.workspaceDir),n=lr.resolve(e);for(;n.startsWith(`${t}${lr.sep}`)&&n!==t;){let r;try{r=await Dge(n)}catch(i){if(i.code==="ENOENT"){n=lr.dirname(n);continue}throw i}if(r.length>0)break;await IB(n,{recursive:!1,force:!0}),n=lr.dirname(n)}}getRestoreDir(e){return lr.join(this.restoreRoot,e)}getBackupPath(e,t){return lr.join(this.getRestoreDir(e),"backups",t)}enqueue(e){let t=this.operationQueue.then(e,e);return this.operationQueue=t.then(()=>{},()=>{}),t}};f0t={pixel:"XENO Pixel (Image Editor)",motion:"XENO Motion (Video Editor)",sound:"XENO Sound (Audio Editor / DAW)"},E2=class{provider;setProvider(e){this.provider=e}getContext(){return this.provider?this.provider():{app:"pixel"}}formatForPrompt(){if(!this.provider)return"";let e=this.provider(),t=[];if(t.push("[Current Context]"),t.push(`App: ${f0t[e.app]??e.app}`),e.document){let n=e.document.modified?" (unsaved changes)":"";t.push(`Document: ${e.document.name}${n}`),e.document.path&&t.push(`Path: ${e.document.path}`)}return e.app==="pixel"&&(e.activeLayer&&t.push(`Active Layer: "${e.activeLayer.name}" (${e.activeLayer.type}, id: ${e.activeLayer.id})`),e.selectedTool&&t.push(`Selected Tool: ${e.selectedTool}`),e.canvasSize&&t.push(`Canvas: ${e.canvasSize.width} x ${e.canvasSize.height}px`)),e.app==="motion"&&(e.currentFrame!==void 0&&t.push(`Playhead: frame ${e.currentFrame}`),e.selectedClip&&t.push(`Selected Clip: "${e.selectedClip.name}" (${e.selectedClip.type}, id: ${e.selectedClip.id})`),e.timelineLength!==void 0&&t.push(`Timeline Length: ${e.timelineLength} frames`)),e.app==="sound"&&(e.bpm!==void 0&&t.push(`BPM: ${e.bpm}`),e.currentPosition!==void 0&&t.push(`Position: ${e.currentPosition.toFixed(2)}s`),e.selectedTrack&&t.push(`Selected Track: "${e.selectedTrack.name}" (id: ${e.selectedTrack.id})`),e.isRecording&&t.push("Status: RECORDING")),t.join(`
|
|
2710
|
+
`)}};SO();LO();cx();ka();rs();os();px();WCt=1e4,GCt=6e4,JCt="session.lock",XCt="lock.json",xb=new Map;$v(zCt);qN=class APe{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(t){this.sessionDir=t,this.lockPath=$m.join(t,JCt),this.legacyLockPath=$m.join(t,XCt),this.sessionId=$m.basename(t)}async acquire(){let t=new Date().toISOString(),n={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:dz.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:Tp,acquiredAt:t,updatedAt:t,heartbeat:t},r=$m.dirname(this.lockPath);await Sm.promises.mkdir(r,{recursive:!0});let i=await this.findExistingLockPath();if(i){if(!await this.isStalePath(i)){let o=await this.readLockAt(i);throw new Error(`Session ${this.sessionId} is already locked by PID ${o?.pid} on ${o?.hostname}`)}await yb(i)}try{await Sm.promises.writeFile(this.lockPath,JSON.stringify(n,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=n,xb.set(this.lockPath,n)}catch(o){if(o.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let s=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${s?.pid} on ${s?.hostname}`)}await yb(this.lockPath);try{await Sm.promises.writeFile(this.lockPath,JSON.stringify(n,null,2),{flag:"wx",encoding:"utf-8"})}catch(s){throw s.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):s}this.acquiredOwner=n,xb.set(this.lockPath,n)}else throw o}}async release(){this.stopHeartbeat();let t=this.acquiredOwner;if(this.acquiredOwner=void 0,!t)return;xb.delete(this.lockPath);let n=await this.readLockAt(this.lockPath);pz(n,t)&&await yb(this.lockPath)}async isLocked(){let t=await this.findExistingLockPath();return t?!await this.isStalePath(t):!1}async isStale(){let t=await this.findExistingLockPath();return t?this.isStalePath(t):!1}async isStalePath(t){let n=await this.readLockAt(t);if(!n)return!1;if(n.hostname===dz.hostname())try{return process.kill(n.pid,0),!1}catch(i){return i.code!=="EPERM"}let r=new Date(n.heartbeat).getTime();return Date.now()-r>GCt}startHeartbeat(t=WCt){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(n){let r=n instanceof Error?n.message:String(n);if(n?.code==="ENOENT"){_n("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}_n(`SessionLock: Failed to update heartbeat: ${r}`)}},t),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let t=await this.readLockAt(this.lockPath),n=this.acquiredOwner;if(!(!t||!n)){if(!pz(t,n)){this.acquiredOwner=void 0,xb.delete(this.lockPath),this.stopHeartbeat();return}t.heartbeat=new Date().toISOString(),t.updatedAt=t.heartbeat,await Li(this.lockPath,JSON.stringify(t,null,2))}}async readLock(){let t=await this.findExistingLockPath();return t?this.readLockAt(t):null}async readLockAt(t){let n=await fi(t);return n?Er(n,null):null}async findExistingLockPath(){return await fi(this.lockPath)?this.lockPath:await fi(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(t){let n=await QAe(t),r=[];for(let i of n){let o=new APe(i);if(await o.isStale()){let s=await o.findExistingLockPath();s&&await yb(s),r.push($m.basename(i))}}return r}};$8();ka();rs();LO();cx();$8();SO();pv();DO();os();cx();LO();Bye();Yv=class fz{sessionDir;_meta;_transcript;_checkpoints;_lock;_recovery;_detachedForHandoff=!1;constructor(t,n,r,i,o,s){this.sessionDir=t,this._meta=n,this._transcript=r,this._checkpoints=i,this._lock=o,this._recovery=s}static async create(t){NC(t.executionMode);let n=t.role??"default",r=rx(n),i=qe.getSessionDir(r),o=null,s=null;try{await IA(i);let a={id:r,role:n,status:"creating",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),lastActivity:new Date().toISOString(),workingDirectory:t.workingDirectory,model:t.model,...t.executionMode!==void 0?{executionMode:t.executionMode}:{},parentSession:t.parentSession,...t.hostBinding?{hostBinding:structuredClone(t.hostBinding)}:{},checkpoints:[],messageCount:0,tokenUsage:{input:0,output:0,total:0},formatVersion:1},c=dM.join(i,"meta.json");await Li(c,JSON.stringify(a,null,2)),s=new Ri(i);let l=new Jc(i);o=new qN(i),await o.acquire(),o.startHeartbeat(),await s.append({type:"session_start",data:{sessionId:r,role:n,workingDirectory:t.workingDirectory,model:t.model,formatVersion:1}});let u=new fz(i,a,s,l,o,{messages:[],transcriptMessages:[],source:"empty",issues:[],repairMessages:[],transcriptEventCount:1});return await u.updateMeta({status:"active"}),u}catch(a){if(o)try{o.stopHeartbeat(),await o.release()}catch(c){_n("Error releasing lock during cleanup",c)}throw a}}static async resume(t){let n=qe.getSessionDir(t.sessionId),r=null,i=null;try{let o=dM.join(n,"meta.json"),s=await fi(o);if(!s)throw new Error(`SessionManager: Session not found: ${t.sessionId}`);let a=Er(s,null);if(!a)throw new Error(`SessionManager: Invalid session metadata: ${t.sessionId}`);NC(a.executionMode),a.formatVersion=r9(a),i=new Ri(n),await i.initialize();let c=new Jc(n);r=new qN(n),await r.acquire(),r.startHeartbeat();let l;if(t.fromCheckpoint){let{info:d,messages:p}=await c.restore(t.fromCheckpoint);a.messageCount=d.messageCount,await i.append({type:"checkpoint",data:{id:t.fromCheckpoint,trigger:"manual",messageCount:d.messageCount}}),l={messages:p,transcriptMessages:p,source:"checkpoint",sourceId:t.fromCheckpoint,issues:[],repairMessages:[],transcriptEventCount:i.getSequence()}}else l=await zv(n,{metadataMessageCount:a.messageCount}),a.messageCount=l.messages.length;let u=new fz(n,a,i,c,r,l);return await u.updateMeta({status:"active",lastActivity:new Date().toISOString()}),u}catch(o){if(r)try{r.stopHeartbeat(),await r.release()}catch(s){_n("Error releasing lock during cleanup",s)}throw o}}get meta(){return{...this._meta}}get transcript(){return this._transcript}get checkpoints(){return this._checkpoints}get recovery(){return{...this._recovery,messages:[...this._recovery.messages],transcriptMessages:[...this._recovery.transcriptMessages],repairMessages:[...this._recovery.repairMessages],issues:[...this._recovery.issues]}}async detachForHandoff(){this._detachedForHandoff||(await this._transcript.flush(),this._lock.stopHeartbeat(),await this._lock.release(),this._detachedForHandoff=!0)}get detachedForHandoff(){return this._detachedForHandoff}async updateMeta(t){if(NC(t.executionMode),this._detachedForHandoff)throw new Error(`Session ${this._meta.id} is detached after execution handoff`);this._meta={...this._meta,...t,updatedAt:new Date().toISOString()};let n=dM.join(this.sessionDir,"meta.json"),r=3,i=null;for(let o=0;o<r;o++)try{await Li(n,JSON.stringify(this._meta,null,2));return}catch(s){i=s instanceof Error?s:new Error(String(s)),mi(`Failed to write session metadata (attempt ${o+1}/${r}): ${i.message}`),o<r-1&&await new Promise(a=>setTimeout(a,Math.pow(2,o)*100))}_n(`Failed to write session metadata after ${r} attempts. Session will continue but metadata may be stale.`)}async end(t="completed"){await this._transcript.append({type:"session_end",data:{reason:t==="completed"?"completed":"user_exit",messageCount:this._meta.messageCount,totalTokens:this._meta.tokenUsage.total}}),await this._transcript.flush(),await this.updateMeta({status:t}),this._lock.stopHeartbeat(),await this._lock.release()}async recordUserMessage(t){await this._transcript.append({type:"user_message",data:{role:"user",content:t}}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()})}async recordDirectShellResult(t){let n=Dm(t);return await this._transcript.append({type:"user_message",data:n}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()}),n}async recordAssistantMessage(t,n){await this._transcript.append({type:"assistant_message",data:{role:"assistant",content:t},tokenCount:n}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()})}async recordTokenUsage(t,n){let r={input:this._meta.tokenUsage.input+t,output:this._meta.tokenUsage.output+n,total:this._meta.tokenUsage.total+t+n};await this.updateMeta({tokenUsage:r})}async recordDelegationSummary(t){await this._transcript.append({type:"delegation_summary",data:t}),await this.updateMeta({lastActivity:new Date().toISOString()})}async updateMessageCount(t){t!==this._meta.messageCount&&await this.updateMeta({messageCount:t,lastActivity:new Date().toISOString()})}};DO();Qye();ic();Fi();C4=2,Qge=400,x4=80,mz=12,Fge=3e4,R4=64*1024*1024;Wm=class{constructor(e,t){this.sessionDir=e,this.workspaceDir=t,this.restoreRoot=lr.join(e,"turn-restores")}sessionDir;workspaceDir;restoreRoot;operationQueue=Promise.resolve();async create(e){let t={id:e.id??jN(),createdAt:new Date().toISOString(),restoreMessageCount:e.restoreMessageCount,userPrompt:e.userPrompt,mutations:[],unsupportedTools:[]};return this.enqueue(async()=>{let n=this.getRestoreDir(t.id);return await RC(lr.join(n,"backups"),{recursive:!0}),await this.savePoint(t),t})}async recordToolExecution(e,t,n){t=Gt(t);let r=s0t(t),i=r?await this.ensureGitCheckpoint(e):null;if(t==="Write"||t==="Edit"||t==="NotebookEdit"){let o=typeof n.file_path=="string"?n.file_path:typeof n.notebook_path=="string"?n.notebook_path:"";if(!o)return;await this.captureFileMutation(e,o);return}(t==="Bash"||r)&&(!i||a0t(t,n))&&await this.markUnsupportedTool(e,t)}async restoreAtOrAfter(e){return this.enqueue(async()=>{let t=await this.inspectAtOrAfterInternal(e);if(!t.hadRestorePoints)return{...t,restoredFiles:0,removedFiles:0};let n=t.points.find(s=>s.gitCheckpoint)?.gitCheckpoint;n&&await this.restoreGitCheckpoint(n);let r=new Map;for(let s of t.points)for(let a of s.mutations){if(!a.existedBefore||!a.backupFile)continue;let c=this.getBackupPath(s.id,a.backupFile);r.set(c,await iC(c,"utf8"))}let i=0,o=0;for(let s of[...t.points].reverse())for(let a of[...s.mutations].reverse()){let c=lr.join(this.workspaceDir,a.relativePath);if(a.existedBefore&&a.backupFile){let l=this.getBackupPath(s.id,a.backupFile);await RC(lr.dirname(c),{recursive:!0}),await S4(c,r.get(l)??"","utf8"),i+=1;continue}await IB(c,{recursive:!0,force:!0}),await this.pruneEmptyParentDirs(lr.dirname(c)),o+=1}for(let s of t.points)await this.deleteGitCheckpointRef(s.gitCheckpoint),await IB(this.getRestoreDir(s.id),{recursive:!0,force:!0});return{...t,restoredFiles:i,removedFiles:o}})}async deleteAtOrAfter(e){await this.enqueue(async()=>{let t=await this.listPointsAtOrAfter(e);for(let n of t)await this.deleteGitCheckpointRef(n.gitCheckpoint),await IB(this.getRestoreDir(n.id),{recursive:!0,force:!0})})}async inspectAtOrAfter(e){return this.enqueue(async()=>this.inspectAtOrAfterInternal(e))}async findByRestoreMessageCount(e){return(await this.inspectAtOrAfter(e)).points.filter(t=>t.restoreMessageCount===e).at(-1)??null}async captureFileMutation(e,t){await this.enqueue(async()=>{let n=await this.loadPoint(e),r;try{r=zt(this.workspaceDir,t)}catch{return}let i=lr.relative(this.workspaceDir,r);if(!i||n.mutations.some(c=>c.relativePath===i))return;try{if(!(await n0t(r)).isFile()){n.mutations.push({relativePath:i,existedBefore:!1}),await this.savePoint(n);return}}catch(c){if(c.code==="ENOENT"){n.mutations.push({relativePath:i,existedBefore:!1}),await this.savePoint(n);return}throw c}let o=`${n.mutations.length+1}.txt`,s=this.getBackupPath(e,o),a=await iC(r,"utf8");await RC(lr.dirname(s),{recursive:!0}),await S4(s,a,"utf8"),n.mutations.push({relativePath:i,existedBefore:!0,backupFile:o}),await this.savePoint(n)})}async markUnsupportedTool(e,t){await this.enqueue(async()=>{let n=await this.loadPoint(e);n.unsupportedTools.includes(t)||(n.unsupportedTools.push(t),await this.savePoint(n))})}async ensureGitCheckpoint(e){return this.enqueue(async()=>{let t=await this.loadPoint(e);if(t.gitCheckpoint)return t.gitCheckpoint;let n=await c0t(this.workspaceDir,this.getRestoreDir(e),t.id).catch(()=>null);return n?(t.gitCheckpoint=n,await this.savePoint(t),n):null})}async restoreGitCheckpoint(e){let t=await i9(e.repositoryRoot,this.workspaceDir,lr.join(this.restoreRoot,`.restore-index-${jN()}`)),n=await tR(e.repositoryRoot,["diff","--binary","--full-index","--no-ext-diff",t,e.commit,"--",e.workspacePathspec]);n.length!==0&&(await Gge(e.repositoryRoot,n,!0),await Gge(e.repositoryRoot,n,!1))}async deleteGitCheckpointRef(e){e&&await Gu(e.repositoryRoot,["update-ref","-d",e.ref,e.commit]).catch(()=>{})}async inspectAtOrAfterInternal(e){let t=await this.listPointsAtOrAfter(e),n=Array.from(new Set(t.flatMap(c=>c.unsupportedTools))),r=t.find(c=>c.gitCheckpoint)?.gitCheckpoint,i=r?await u0t(r,this.workspaceDir).catch(()=>({changedPaths:[],previews:[]})):{changedPaths:[],previews:[]},o=await this.buildFilePreviews(t),s=new Set(o.map(c=>c.relativePath.replace(/\\/g,"/"))),a=i.previews.filter(c=>!s.has(c.relativePath.replace(/\\/g,"/")));return{points:t,hadRestorePoints:t.length>0,exactWorkspaceRestore:t.length>0&&n.length===0,unsupportedTools:n,filePreviews:[...o,...a].slice(0,mz),gitChangedPaths:i.changedPaths,gitCheckpointCount:t.filter(c=>c.gitCheckpoint).length}}async buildFilePreviews(e){let t=new Map;for(let r of e)for(let i of r.mutations)t.has(i.relativePath)||(i.existedBefore&&i.backupFile?t.set(i.relativePath,{action:"revert",pointId:r.id,backupFile:i.backupFile}):t.set(i.relativePath,{action:"remove"}));let n=[];for(let[r,i]of t){if(n.length>=mz)break;let o=lr.join(this.workspaceDir,r),s="",a=!1;try{s=await iC(o,"utf8")}catch(u){if(u.code==="ENOENT")a=!0;else{n.push({relativePath:r,action:i.action,lines:[`(current file unavailable: ${u.message})`],truncated:!1});continue}}if(i.action==="remove"){let u=a?{lines:[`--- current/${r}`,"+++ /dev/null","(already missing)"],truncated:!1}:hz(r,s,"",`current/${r}`,"/dev/null");n.push({relativePath:r,action:"remove",lines:u.lines,truncated:u.truncated});continue}let c=await iC(this.getBackupPath(i.pointId,i.backupFile),"utf8"),l=hz(r,s,c,a?`missing/${r}`:`current/${r}`,`restore/${r}`);n.push({relativePath:r,action:"revert",lines:l.lines,truncated:l.truncated})}return n}async listPointsAtOrAfter(e){try{let t=await Dge(this.restoreRoot,{withFileTypes:!0}),n=[];for(let r of t)if(r.isDirectory())try{let i=await this.loadPoint(r.name);i.restoreMessageCount>=e&&n.push(i)}catch{continue}return n.sort((r,i)=>r.createdAt.localeCompare(i.createdAt)),n}catch{return[]}}async loadPoint(e){let t=lr.join(this.getRestoreDir(e),"meta.json"),n=await iC(t,"utf8"),r=JSON.parse(n);if(!r||typeof r.id!="string"||typeof r.restoreMessageCount!="number")throw new Error(`Invalid restore point metadata: ${e}`);return r}async savePoint(e){let t=this.getRestoreDir(e.id);await RC(t,{recursive:!0}),await S4(lr.join(t,"meta.json"),JSON.stringify(e,null,2),"utf8")}async pruneEmptyParentDirs(e){let t=lr.resolve(this.workspaceDir),n=lr.resolve(e);for(;n.startsWith(`${t}${lr.sep}`)&&n!==t;){let r;try{r=await Dge(n)}catch(i){if(i.code==="ENOENT"){n=lr.dirname(n);continue}throw i}if(r.length>0)break;await IB(n,{recursive:!1,force:!0}),n=lr.dirname(n)}}getRestoreDir(e){return lr.join(this.restoreRoot,e)}getBackupPath(e,t){return lr.join(this.getRestoreDir(e),"backups",t)}enqueue(e){let t=this.operationQueue.then(e,e);return this.operationQueue=t.then(()=>{},()=>{}),t}};f0t={pixel:"XENO Pixel (Image Editor)",motion:"XENO Motion (Video Editor)",sound:"XENO Sound (Audio Editor / DAW)"},E2=class{provider;setProvider(e){this.provider=e}getContext(){return this.provider?this.provider():{app:"pixel"}}formatForPrompt(){if(!this.provider)return"";let e=this.provider(),t=[];if(t.push("[Current Context]"),t.push(`App: ${f0t[e.app]??e.app}`),e.document){let n=e.document.modified?" (unsaved changes)":"";t.push(`Document: ${e.document.name}${n}`),e.document.path&&t.push(`Path: ${e.document.path}`)}return e.app==="pixel"&&(e.activeLayer&&t.push(`Active Layer: "${e.activeLayer.name}" (${e.activeLayer.type}, id: ${e.activeLayer.id})`),e.selectedTool&&t.push(`Selected Tool: ${e.selectedTool}`),e.canvasSize&&t.push(`Canvas: ${e.canvasSize.width} x ${e.canvasSize.height}px`)),e.app==="motion"&&(e.currentFrame!==void 0&&t.push(`Playhead: frame ${e.currentFrame}`),e.selectedClip&&t.push(`Selected Clip: "${e.selectedClip.name}" (${e.selectedClip.type}, id: ${e.selectedClip.id})`),e.timelineLength!==void 0&&t.push(`Timeline Length: ${e.timelineLength} frames`)),e.app==="sound"&&(e.bpm!==void 0&&t.push(`BPM: ${e.bpm}`),e.currentPosition!==void 0&&t.push(`Position: ${e.currentPosition.toFixed(2)}s`),e.selectedTrack&&t.push(`Selected Track: "${e.selectedTrack.name}" (id: ${e.selectedTrack.id})`),e.isRecording&&t.push("Status: RECORDING")),t.join(`
|
|
2711
2711
|
`)}},vPe=class{config;desktopCapturer;constructor(e){this.config={maxWidth:e?.maxWidth??1024,quality:e?.quality??.7,format:e?.format??"jpeg"},this.desktopCapturer=e?.desktopCapturer}async captureWindow(){let e=this.getDesktopCapturer();if(!e)throw new Error("Screen capture requires an injected desktopCapturer host adapter.");let t=await e.getSources({types:["window"],thumbnailSize:{width:this.config.maxWidth,height:Math.round(this.config.maxWidth*.75)}});if(t.length===0)throw new Error("No capturable windows found.");let n=t[0];return this.encodeThumbnail(n.thumbnail)}async captureElement(e){return this.isCanvasElement(e)?this.canvasToBase64(e):this.captureWindow()}formatForLLM(e,t){return{type:"image",source:{type:"base64",media_type:t,data:e}}}getMimeType(){return this.config.format==="png"?"image/png":"image/jpeg"}getDesktopCapturer(){return this.desktopCapturer}encodeThumbnail(e){let t=e.getSize(),n=e;if(t.width>this.config.maxWidth){let r=this.config.maxWidth/t.width;n=e.resize({width:this.config.maxWidth,height:Math.round(t.height*r)})}return(this.config.format==="png"?n.toPNG():n.toJPEG(Math.round(this.config.quality*100))).toString("base64")}isCanvasElement(e){return!e||typeof e!="object"?!1:typeof e.toDataURL=="function"}canvasToBase64(e){let t=this.getMimeType(),n=e.toDataURL(t,this.config.quality),r=n.indexOf(",");return r>=0?n.slice(r+1):n}};os();w0t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".nuxt","__pycache__",".pytest_cache","target",".gradle",".idea",".vscode",".vs","coverage",".nyc_output","vendor",".cargo","bin","obj"]),y0t={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".rs":"rust",".go":"go",".java":"java",".kt":"kotlin",".scala":"scala",".swift":"swift",".c":"c",".cpp":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".sh":"bash",".bash":"bash",".zsh":"bash",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".xml":"xml",".html":"html",".css":"css",".scss":"scss",".less":"css",".sql":"sql",".md":"markdown",".txt":"text"},b0t={react:{deps:["react","react-dom"],files:[]},nextjs:{deps:["next"],files:["next.config.js","next.config.mjs","next.config.ts"]},express:{deps:["express"],files:[]},fastify:{deps:["fastify"],files:[]},electron:{deps:["electron"],files:[]},vue:{deps:["vue"],files:[]},angular:{deps:["@angular/core"],files:["angular.json"]},svelte:{deps:["svelte"],files:["svelte.config.js"]},django:{deps:["django"],files:["manage.py"]},flask:{deps:["flask"],files:[]},fastapi:{deps:["fastapi"],files:[]}},kPe=class{cwd;files=[];dependencies=[];projectInfo=null;scanned=!1;constructor(e){this.cwd=e}async scan(e){let t=e?.maxFiles??1e4,n=e?.maxDepth??15,r=new Set(e?.excludePatterns??[]),i=new Set([...w0t,...r]);this.files=[],this.dependencies=[],this.walkDirectory(this.cwd,"",n,t,i),this.projectInfo=this.detectProjectInfo(),e?.buildDependencyGraph&&this.buildDependencyGraph(),this.scanned=!0}getProjectInfo(){return this.projectInfo}getFiles(){return[...this.files]}getFilesByLanguage(e){return this.files.filter(t=>t.language===e)}getFilesByExtension(e){return this.files.filter(t=>t.extension===e)}getDependencies(){return[...this.dependencies]}getLanguageDistribution(){let e={};for(let t of this.files)t.language!=="unknown"&&(e[t.language]=(e[t.language]??0)+1);return e}getSummary(){if(!this.projectInfo)return"Workspace not scanned";let e=this.projectInfo,t=[];t.push(`Project: ${e.name}`),t.push(`Language: ${e.language}`),e.framework&&t.push(`Framework: ${e.framework}`),e.packageManager&&t.push(`Package Manager: ${e.packageManager}`),e.projectType&&t.push(`Type: ${e.projectType}`),t.push(`Files: ${e.fileCount}`);let n=this.getLanguageDistribution(),r=Object.entries(n).sort((o,s)=>s[1]-o[1]);if(r.length>0){t.push("Language Distribution:");for(let[o,s]of r.slice(0,8))t.push(` ${o}: ${s} files`)}let i=Object.keys(e.dependencies).length;return i>0&&t.push(`Dependencies: ${i}`),e.workspaces&&e.workspaces.length>0&&t.push(`Workspaces: ${e.workspaces.join(", ")}`),t.join(`
|
|
2712
2712
|
`)}get isScanned(){return this.scanned}walkDirectory(e,t,n,r,i){if(n<=0||this.files.length>=r)return;let o;try{o=m0t(e)}catch{return}for(let s of o){if(this.files.length>=r)break;if(i.has(s)||s.startsWith(".")&&s!==".env.example")continue;let a=ba(e,s),c=t?`${t}/${s}`:s,l;try{l=h0t(a)}catch{continue}if(l.isDirectory())this.walkDirectory(a,c,n-1,r,i);else if(l.isFile()){let u=g0t(s).toLowerCase(),d=y0t[u]??"unknown";this.files.push({path:c,extension:u,size:l.size,language:d,modifiedAt:l.mtimeMs})}}}detectProjectInfo(){let e={name:A0t(this.cwd),language:"unknown",fileCount:this.files.length,dependencies:{}},t=ba(this.cwd,"package.json");if(qc(t))try{let o=JSON.parse(kB(t,"utf-8"));e.name=o.name??e.name,e.dependencies=o.dependencies??{},e.devDependencies=o.devDependencies??{},e.scripts=o.scripts??{},e.packageManager="npm",o.workspaces&&(e.workspaces=Array.isArray(o.workspaces)?o.workspaces:o.workspaces.packages,e.projectType="monorepo")}catch{}let n=ba(this.cwd,"Cargo.toml");if(qc(n)&&(e.language="rust",e.packageManager="cargo"),qc(ba(this.cwd,"go.mod"))&&(e.language="go",e.packageManager="go"),(qc(ba(this.cwd,"requirements.txt"))||qc(ba(this.cwd,"pyproject.toml")))&&(e.language="python",e.packageManager="pip"),e.language==="unknown"){let o=this.getLanguageDistribution(),s=Object.entries(o).filter(([a])=>!["json","markdown","text","yaml","xml"].includes(a)).sort((a,c)=>c[1]-a[1]);s.length>0&&(e.language=s[0][0])}let r={...e.dependencies,...e.devDependencies};for(let[o,s]of Object.entries(b0t)){let a=s.deps.some(l=>l in r),c=s.files.some(l=>qc(ba(this.cwd,l)));if(a||c){e.framework=o;break}}e.projectType||(r.electron?e.projectType="application":e.scripts?.start&&(r.express||r.fastify)?e.projectType="api":e.scripts?.bin||qc(ba(this.cwd,"bin"))?e.projectType="cli":r.react||r.vue||r.svelte?e.projectType="application":e.projectType="library"),qc(ba(this.cwd,"yarn.lock"))?e.packageManager="yarn":qc(ba(this.cwd,"pnpm-lock.yaml"))?e.packageManager="pnpm":qc(ba(this.cwd,"bun.lockb"))&&(e.packageManager="bun");let i=ba(this.cwd,".git","HEAD");if(qc(i))try{let o=kB(i,"utf-8").trim().match(/ref: refs\/heads\/(.+)/);e.git={branch:o?o[1]:"detached"};let s=ba(this.cwd,".git","config");if(qc(s)){let a=kB(s,"utf-8").match(/url\s*=\s*(.+)/);a&&(e.git.remoteUrl=a[1].trim())}}catch{}return e}buildDependencyGraph(){let e=this.files.filter(t=>["typescript","javascript"].includes(t.language));for(let t of e){let n=ba(this.cwd,t.path);try{let r=kB(n,"utf-8"),i=/(?:import|from)\s+['"]([^'"]+)['"]/g,o;for(;(o=i.exec(r))!==null;){let a=o[1];a.startsWith(".")&&this.dependencies.push({from:t.path,to:this.resolveRelativeImport(t.path,a),type:"import"})}let s=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(o=s.exec(r))!==null;){let a=o[1];a.startsWith(".")&&this.dependencies.push({from:t.path,to:this.resolveRelativeImport(t.path,a),type:"require"})}}catch{_n(`Failed to read file for dependency graph: ${t.path}`)}}}resolveRelativeImport(e,t){let n=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",r=t.split("/"),i=n?n.split("/"):[];for(let o of r)o!=="."&&(o===".."?i.pop():i.push(o));return i.join("/")}};iY();BA();gL();c9=`You are an AI assistant embedded in XENO Pixel, a professional image editor.
|
|
2713
2713
|
|
|
@@ -2878,7 +2878,7 @@ ${Re}${X.compose(nQ(),X.bold)("\u2717")} ${bR(e)}
|
|
|
2878
2878
|
`)}function oI(){return`
|
|
2879
2879
|
${Re}${ke("Goodbye.")}
|
|
2880
2880
|
`}var _Tt,u1e,nQ,en,ke,IR,bR,$Tt,kR,BTt,NTt,OTt,U,Re,g1e,aZ,S,dZ,m1e,vR,as=Ie(()=>{"use strict";ha();Ca();i1e();eQ();_Tt=new id(process.stdout),u1e=new id(process.stderr),nQ=()=>Sr(),en=e=>nQ()(e),ke=X.dim,IR=X.bold,bR=e=>nQ()(e),$Tt="\u25A0",kR="\u2514",BTt={open:"\x1B[4m",close:"\x1B[24m"};NTt={Read:e=>Kc()(e),ReadImage:e=>Kc()(e),Glob:e=>Kc()(e),Grep:e=>Kc()(e),ElfAnalyze:e=>Kc()(e),MemoryRead:e=>Kc()(e),Write:e=>yR()(e),Edit:e=>yR()(e),MemoryWrite:e=>yR()(e),Bash:e=>nZ()(e),GitStatus:e=>Kc()(e),GitDiff:e=>Kc()(e),GitLog:e=>Kc()(e),GitBranch:e=>Kc()(e),GitCommit:e=>nZ()(e),WebSearch:e=>X.cyan(e),WebFetch:e=>X.cyan(e),TaskOutput:e=>Kc()(e),TaskInput:e=>X.cyan(e),TaskStop:e=>HA()(e)};OTt={Edit:"Update",Glob:"Search",Grep:"Search",WebSearch:"Web Search",WebFetch:"Web Fetch"};U={accent:en,purple:bR,cyan:bR,dim:ke,bold:IR,red:bR,green:bR},Re=" ",g1e=1e3,aZ=3;S={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"};dZ=class{atLineStart=!0;writeFn;constructor(t){this.writeFn=t??(n=>{_Tt.writeOrdered(n,"stream")})}write(t){let n="";for(let r of t)this.atLineStart&&(n+=Re,this.atLineStart=!1),n+=r,r===`
|
|
2881
|
-
`&&(this.atLineStart=!0);this.writeFn(n)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},m1e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],vR=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,n){this.writeFn=t??(r=>{u1e.writeFrame(r,"spinner")}),this.clearFn=n??(()=>{u1e.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let n=m1e[this.frameIndex%m1e.length],r=`${en(n)} ${ke(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${r}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});var he,gi=Ie(()=>{"use strict";he="0.5.48"});import{readFileSync as l_t}from"node:fs";import{WebContextClient as u_t}from"@xenosystem/web-context-client";function p_t(e=process.env){let t=e.XENO_WEB_CONTEXT_TOKEN?.trim();if(t)return t;let n=e.XENO_WEB_CONTEXT_TOKEN_FILE?.trim();if(n){let r=l_t(n,"utf8").trim();if(r)return r}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 _Z(e=process.env){return new u_t({baseUrl:e.XENO_WEB_CONTEXT_URL?.trim()||d_t,token:p_t(e)})}function X1e(e=process.env){return{client:new PZ(e),createRequest:nD({actor:{id:"xeno-agent-cli",kind:"agent"},scope:{kind:"local-profile",profileId:"pending-token-scope"},classification:"public",purposePrefix:"xeno-agent-cli:chat",budget:{durationMs:12e4,maxAttempts:3,maxConcurrency:4,maxBytes:1e7,maxPages:100,maxRedirects:8,maxProviderCostUsd:0}})}}var d_t,PZ,$Z=Ie(()=>{"use strict";at();d_t="http://127.0.0.1:8080";PZ=class{constructor(t){this.env=t}env;client;tenantId;async search(t){return this.getClient().search(await this.bindTenant(t))}async scrapeAndWait(t,n){return this.getClient().scrapeAndWait(await this.bindTenant(t),n)}getClient(){return this.client??=_Z(this.env),this.client}async bindTenant(t){this.tenantId??=this.getClient().account().then(r=>r.tenantId);let n=await this.tenantId;return{...t,scope:{kind:"tenant",tenantId:n}}}}});var z1e=Ie(()=>{"use strict"});function Y1e(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 n=t.snapshot,r=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,i=(o,s,a,c=!1)=>Array.isArray(o)&&o.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&typeof l[s]=="string"&&r(l[a])&&(!c||l.cost===null));return n.source==="local-runtime-journal"&&n.billingStatus==="unavailable"&&n.totalCost===null&&typeof n.observedAt=="string"&&Number.isFinite(Date.parse(n.observedAt))&&r(n.totalTokens)&&r(n.totalRequests)&&r(n.unmeasuredRequests)&&n.unmeasuredRequests<=n.totalRequests&&i(n.dailyUsage,"label","value")&&i(n.weeklyUsage,"label","value")&&i(n.monthlyUsage,"label","value")&&i(n.costByModel,"model","tokens",!0)&&i(n.topAgents,"name","tokens",!0)}var K1e=Ie(()=>{"use strict"});var Z1e=Ie(()=>{"use strict"});function e$e(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(n=>n&&typeof n=="object"&&["id","timestamp","action","actor","target","details"].every(r=>typeof n[r]=="string")&&Number.isFinite(Date.parse(n.timestamp)))}var t$e=Ie(()=>{"use strict"});function r$e(e){return!BZ(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&&!n$e(e.loadedModel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length>1e3||!e.models.every(t=>BZ(t)&&n$e(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&&(!BZ(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 BZ,n$e,i$e=Ie(()=>{"use strict";BZ=e=>!!e&&typeof e=="object"&&!Array.isArray(e),n$e=e=>typeof e=="string"&&e.length>0&&e.length<=512&&!/[\x00-\x1f\x7f]/.test(e)});var jMn,o$e=Ie(()=>{"use strict";jMn=new TextEncoder});var s$e=Ie(()=>{"use strict"});var a$e=Ie(()=>{"use strict"});var c$e=Ie(()=>{"use strict"});var l$e=Ie(()=>{"use strict"});var u$e=Ie(()=>{"use strict"});var d$e=Ie(()=>{"use strict";u$e()});var p$e=Ie(()=>{"use strict"});var f$e=Ie(()=>{"use strict"});var m$e=Ie(()=>{"use strict"});var f_t,h$e=Ie(()=>{"use strict";mI();f_t=1024*1024});import{WEB_JOB_PROGRESS_OPERATIONS as KMn,WEB_JOB_PROGRESS_SCHEMA as ZMn,WEB_JOB_PROGRESS_SCHEMA_VERSION as eNn,WEB_JOB_PROGRESS_STATES as tNn,TERMINAL_WEB_JOB_STATES as nNn,isTerminalWebJobState as rNn,isWebJobProgress as iNn,parseWebJobProgress as oNn}from"@xenosystem/web-context-client/progress";function w_t(e){return typeof e=="string"&&m_t.includes(e)}function g$e(e){return so(e)?Bn(e.clientId)&&Bn(e.clientVersion)&&Bn(e.instanceId)&&w_t(e.surface):!1}function w$e(e){return!so(e)||!so(e.protocol)||!so(e.host)||!so(e.storage)?!1:Number.isInteger(e.protocol.current)&&E_t(e.protocol.supported)&&Bn(e.host.instanceId)&&Bn(e.host.version)&&(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)&&g$e(e.surface)}function MZ(e){return!so(e)||!Bn(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(I_t)}function y_t(e){return!so(e)||!so(e.event)?!1:Bn(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&Bn(e.timestamp)&&Bn(e.conversationId)&&Bn(e.requestId)&&Bn(e.type)&&Bn(e.source)}function y$e(e){return!so(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(y_t)}function b$e(e){return!so(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&Bn(e.conversationId)&&Bn(e.requestId)&&Bn(e.adapterId)&&so(e.selection)&&Bn(e.selection.providerId)&&Bn(e.selection.catalogRevision):Bn(e.code)&&Bn(e.safeError)}function v$e(e){return!so(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&Bn(e.conversationId)&&Bn(e.requestId):Bn(e.code)&&Bn(e.safeError)}function I$e(e){return so(e)&&Bn(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&b_t(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e}function b_t(e){return typeof e=="string"&&A_t.includes(e)}function k$e(e,t,n){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new qi("surface_mismatch",`Agent host acknowledged ${e.surface.surface}/${e.surface.instanceId} instead of ${t.surface}/${t.instanceId}.`);if(e.protocol.current<n.min||e.protocol.current>n.max||n.max<e.protocol.supported.min||n.min>e.protocol.supported.max)throw new qi("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${n.min}-${n.max}.`)}function v_t(e){return!(!so(e)||e.chatExecution!==void 0&&!NR(e.chatExecution)||e.durableResume!==void 0&&!NR(e.durableResume)||e.nativeTuiAttach!==void 0&&!NR(e.nativeTuiAttach)||e.reconciliation!==void 0&&!NR(e.reconciliation)||e.modelSwitchInPlace!==void 0&&!NR(e.modelSwitchInPlace)||e.resumeCompatibilityKey!==void 0&&typeof e.resumeCompatibilityKey!="string")}function NR(e){return so(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 I_t(e){return so(e)?Bn(e.id)&&typeof e.kind=="string"&&h_t.includes(e.kind)&&Bn(e.displayName)&&E$e(e.availability)&&so(e.capabilities)&&(e.providerSession===void 0||v_t(e.providerSession))&&Array.isArray(e.models)&&e.models.every(k_t)&&Bn(e.catalogRevision):!1}function k_t(e){return so(e)&&Bn(e.id)&&Bn(e.displayName)&&E$e(e.availability)&&(e.reasoningOptions===void 0||Array.isArray(e.reasoningOptions)&&e.reasoningOptions.every(t=>so(t)&&Bn(t.id)&&Bn(t.label)&&(t.runtimeModelId===void 0||Bn(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 E$e(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function E_t(e){return so(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 Bn(e){return typeof e=="string"&&e.trim().length>0}function so(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function S$e(e){for(let t of C_t)for(let n of S_t)if(e===`${t}tool.${n}`)return n;return null}function KA(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n:void 0}function C$e(e){let t=e.event;return KA(t,"toolName")||KA(t,"tool")||KA(t,"name")||KA(t,"title")||KA(t,"kind")}function x$e(e){let t=e.event;return KA(t,"toolCallId")||KA(t,"tool_call_id")}function R$e(e){let t=e.event;for(let n of["rawInput","input","arguments","parameters","args"]){let r=t?.[n];if(r&&typeof r=="object"&&!Array.isArray(r))return r}}function T$e(e){let t=e.event;for(let n of["rawOutput","output","result","content"]){let r=t?.[n];if(typeof r=="string")return r.length>0?r:void 0;if(r!=null)try{let i=JSON.stringify(r);if(i&&i!=="{}"&&i!=="[]")return i}catch{}}}function P$e(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var hI,A$e,m_t,h_t,g_t,sNn,A_t,qi,S_t,C_t,mI=Ie(()=>{"use strict";z1e();K1e();Z1e();t$e();i$e();o$e();s$e();a$e();c$e();l$e();d$e();p$e();f$e();m$e();h$e();hI=1,A$e=1,m_t=["standalone-desktop","hub-embed","shell-embed","embed-preview","panel-embed","headless-client"],h_t=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"],g_t=["workspace.usage","workspace.audit","inference.request","workspace.schedule","workspace.backup","workspace.environment","account.request","workforce.request","workspace.notifications","workspace.rules","workspace.browser","workspace.browser.session","host.handshake","providers.list","providers.refresh","runtime.events.list","workspace.lifecycle.apply","state.workspaces.load","state.workspaces.save","state.conversations.load","state.conversations.save","state.conversations.delete","workspace.access.grant","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.resume","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"],sNn=new Set(g_t),A_t=["host.ready","provider.catalog.changed","state.workspaces.changed","runtime.event.appended","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"],qi=class extends Error{code;constructor(t,n){super(n),this.name="AgentHostProtocolError",this.code=t}};S_t=["started","updated","completed","failed","cancelled"],C_t=["","acp."]});import{createHash as x_t}from"node:crypto";import{setTimeout as R_t}from"node:timers/promises";function __t(e,t){return`subrun-${x_t("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}async function $_t(e,t,n){return((await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}))?.events??[]).map(i=>{let o=String(i.type??"").toLowerCase();if(!o.includes("text")&&!o.includes("message")&&!o.includes("delta"))return"";let s=i.event??{};return typeof s.text=="string"?s.text:typeof s.delta=="string"?s.delta:""}).join("")}function B_t(e,t,n,r){let i=new Set,o=typeof r.onToolStart=="function"||typeof r.onToolEnd=="function",s=a=>{try{a()}catch{}};return async function(){if(!o)return;let c=await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}).catch(()=>null);for(let l of c?.events??[]){let u=S$e(String(l.type??""));if(!u)continue;let d=`${x$e(l)??l.id}:${u}`;if(i.has(d))continue;i.add(d);let p=C$e(l)??"unknown";if(u==="started"&&r.onToolStart){let m=r.onToolStart;s(()=>m(p,R$e(l)??{}))}let f=P$e(u);if(f!==null&&r.onToolEnd){let m=r.onToolEnd;s(()=>m(p,{success:f,output:T$e(l)??""}))}}}}function _$e(e){let t=e.pollIntervalMs??250;return async n=>{let r=n.task,i=__t(e.rootTraceId,r.id),o={lastTraceId:null,tokenUsage:{input:0,output:0,total:0},async run(s){let a=Math.max(1e3,e.deadline-Date.now()),c={parentConversationId:e.parentConversationId,...e.parentRequestId===void 0?{}:{parentRequestId:e.parentRequestId},parentAgentId:e.parentAgentId,childConversationId:i,childAgentId:r.role?`delegated-${r.role}`:"delegated-branch",workspaceId:e.workspaceId,teamId:e.teamId,objective:s,...r.role===void 0?{}:{role:r.role},policy:{maxRuntimeMs:a}},l=await e.client.createSubagentRun(c);if(!l?.success||!l.run)throw new Error(l?.safeError??"The Agent host refused to create a subagent run for this delegated branch.");let u=l.run.id;o.lastTraceId=u;let d=B_t(e.client,i,u,{onToolStart:n.onToolStart,onToolEnd:n.onToolEnd});for(;;){if(e.signal?.aborted){await e.client.cancelSubagentRun({runId:u}).catch(()=>{});let h=new Error("Delegated branch was cancelled.");throw h.name="AgentInterruptedError",h}let f=((await e.client.listSubagentRuns({parentConversationId:e.parentConversationId}))?.runs??[]).find(h=>h.id===u),m=String(f?.status??"");if(T_t.has(m)){if(P_t.has(m))throw new Error(f?.error??`The delegated branch ended as '${m}' without reporting a reason.`);await d();let h=await $_t(e.client,i,u);if(h.length===0)throw new Error(`The delegated branch reported '${m}' but produced no readable output. Its runtime events carry no text for this run id.`);return h}if(Date.now()>=e.deadline)throw await e.client.cancelSubagentRun({runId:u}).catch(()=>{}),new Error("The delegated branch exceeded the time this run was given to wait.");await d(),await R_t(t,void 0,{signal:e.signal})}}};return o}}var T_t,P_t,$$e=Ie(()=>{"use strict";mI();T_t=new Set(["completed","succeeded","failed","cancelled","error"]),P_t=new Set(["failed","cancelled","error"])});import{execFile as B$e,execFileSync as NZ}from"node:child_process";import{promisify as M$e}from"node:util";import{createHash as M_t}from"node:crypto";import{existsSync as N_t,readFileSync as OZ,readlinkSync as O_t}from"node:fs";import{hostname as ZA}from"node:os";function wQ(e){return Number.isInteger(e)&&e>0}function L_t(e){return M_t("sha256").update(e).digest("hex")}function DR(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${L_t(t)}`:void 0}function AQ(){if(process.platform==="linux")try{return OZ("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function Fp(e){if(typeof e!="number"||!wQ(e))return"dead";try{return process.kill(e,0),"live"}catch(t){return t.code==="ESRCH"?"dead":"unknown"}}function DZ(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function N$e(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 { '' }; [pscustomobject]@{ pid = [int]$_.Id; startedAt = $_.StartTime.ToUniversalTime().ToString('o'); executable = $path } })","$out | ConvertTo-Json -Compress"].join("; ")]}function O$e(e){let t=new Map;try{if(!e)return t;let n=JSON.parse(e);for(let r of Array.isArray(n)?n:[n]){let i=Number(r.pid),o=DZ(String(r.startedAt??""));!wQ(i)||!o||t.set(i,{pid:i,processStartedAt:o,hostname:ZA(),...DR(r.executable)?{executableFingerprint:DR(r.executable)}:{},confidence:"observed"})}}catch{return t}return t}function Q_t(e){if(!e.length)return new Map;try{return O$e(NZ("powershell.exe",N$e(e),{encoding:"utf8",windowsHide:!0,timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim())}catch{return new Map}}function F_t(){if(OR)return OR;try{let e=Number.parseInt(NZ("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);OR=Number.isFinite(e)&&e>0?e:100}catch{OR=100}return OR}function U_t(){try{let e=/^btime\s+(\d+)$/m.exec(OZ("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function q_t(e){try{let t=OZ(`/proc/${e}/stat`,"utf8"),n=t.lastIndexOf(")");if(n<0)return null;let r=t.slice(n+2).trim().split(/\s+/),i=Number(r[19]),o=U_t();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/F_t())*1e3).toISOString(),a;try{a=O_t(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:ZA(),...AQ()?{bootId:AQ()}:{},...DR(a)?{executableFingerprint:DR(a)}:{},confidence:"observed"}}catch{return null}}function D$e(e){let t=new Map;if(process.platform==="linux"){for(let n of e){let r=q_t(n);r&&t.set(n,r)}return t}for(let n of e)try{let r=NZ("ps",["-p",String(n),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=DZ(r);if(!i)continue;t.set(n,{pid:n,processStartedAt:i,hostname:ZA(),confidence:"observed"})}catch{continue}return t}function LR(e){let t=[...new Set(e.filter(wQ))],n=t.includes(process.pid),r=n?t.filter(o=>o!==process.pid):t,i=process.platform==="win32"?Q_t(r):D$e(r);return n&&i.set(process.pid,zm()),i}function L$e(e){return LR([e]).get(e)??null}async function Q$e(e,t){t?.throwIfAborted();let n=[...new Set(e.filter(wQ))],r=n.filter(o=>o!==process.pid),i=new Map;if(process.platform==="win32"&&r.length)try{let o=await M$e(B$e)("powershell.exe",N$e(r),{encoding:"utf8",windowsHide:!0,timeout:1e4,maxBuffer:1048576,signal:t});i=O$e(o.stdout.trim())}catch{t?.throwIfAborted()}else if(process.platform==="linux")i=D$e(r);else if(process.platform!=="win32")for(let o of r){t?.throwIfAborted();try{let{stdout:s}=await M$e(B$e)("ps",["-p",String(o),"-o","lstart="],{encoding:"utf8",timeout:2e3,signal:t,env:{...process.env,LC_ALL:"C"},maxBuffer:4096}),a=DZ(s.trim());a&&i.set(o,{pid:o,processStartedAt:a,hostname:ZA(),confidence:"observed"})}catch{t?.throwIfAborted()}}return t?.throwIfAborted(),n.includes(process.pid)&&i.set(process.pid,zm()),i}function yQ(e,t=new Date,n=!1){return(n?L$e(e):null)??{pid:e,processStartedAt:t.toISOString(),hostname:ZA(),confidence:"degraded"}}function zm(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:ZA(),...AQ()?{bootId:AQ()}:{},...N_t(process.execPath)?{executableFingerprint:DR(process.execPath)}:{},confidence:"self"}}function Lo(e,t=L$e){if(e.hostname!==ZA())return{status:"remote",expected:e,reason:"Process belongs to another host."};if(Fp(e.pid)==="dead")return{status:"dead",expected:e,reason:"Process ID is not live."};let n=t(e.pid);if(!n)return{status:"degraded",expected:e,reason:"Creation time could not be observed."};let r=Date.parse(e.processStartedAt),i=Date.parse(n.processStartedAt);return!Number.isFinite(r)||!Number.isFinite(i)||Math.abs(r-i)>D_t?{status:"mismatch",expected:e,observed:n,reason:"Process creation time does not match."}:e.bootId&&n.bootId&&e.bootId!==n.bootId?{status:"mismatch",expected:e,observed:n,reason:"Host boot identity does not match."}:e.executableFingerprint&&n.executableFingerprint&&e.executableFingerprint!==n.executableFingerprint?{status:"mismatch",expected:e,observed:n,reason:"Executable identity does not match."}:{status:"live",expected:e,observed:n}}var D_t,OR,sd=Ie(()=>{"use strict";D_t=3e3});import{createHash as j_t,randomBytes as V_t}from"node:crypto";import{chmodSync as H_t,existsSync as W_t,mkdirSync as U$e,readFileSync as G_t,renameSync as J_t,unlinkSync as q$e,writeFileSync as X_t}from"node:fs";import{dirname as z_t,join as QR}from"node:path";function j$e(){return Qc()}function Y_t(e){return j_t("sha256").update(e).digest("hex").slice(0,16)}function Mn(){return QR(j$e(),"daemon")}function LZ(){return QR(Mn(),"daemon.json")}function V$e(){return QR(Mn(),"daemon.lock")}function gI(){return QR(Mn(),"daemon.log")}function QZ(){let e=Y_t(j$e());return process.platform==="win32"?{transport:"named-pipe",endpoint:`\\\\.\\pipe\\xeno-agent-daemon-${e}`}:{transport:"unix-socket",endpoint:QR(Mn(),"daemon.sock")}}function bQ(){U$e(Mn(),{recursive:!0})}function H$e(){return V_t(32).toString("base64url")}function F$e(e){if(process.platform!=="win32")try{H_t(e,384)}catch{}}function FZ(){try{let e=LZ(),t=G_t(e,"utf8"),n=JSON.parse(t);if(!n||n.schemaVersion!==1||n.protocolVersion!==1||n.transport!=="named-pipe"&&n.transport!=="unix-socket"||typeof n.endpoint!="string"||typeof n.authToken!="string"||!Number.isSafeInteger(n.pid)||typeof n.startedAt!="string"||typeof n.cliVersion!="string"||typeof n.logPath!="string")throw new Error("daemon state schema is invalid");return n}catch(e){if(e.code==="ENOENT")return null;throw new Error(`Daemon state is corrupt or unreadable: ${e instanceof Error?e.message:String(e)}`)}}function W$e(e){let t=LZ();U$e(z_t(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;X_t(n,JSON.stringify(e,null,2)+`
|
|
2881
|
+
`&&(this.atLineStart=!0);this.writeFn(n)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},m1e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],vR=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,n){this.writeFn=t??(r=>{u1e.writeFrame(r,"spinner")}),this.clearFn=n??(()=>{u1e.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let n=m1e[this.frameIndex%m1e.length],r=`${en(n)} ${ke(t)}`;this.writeFn(`\r${" ".repeat(this.lastLength)}\r${r}`),this.lastLength=t.length+4,this.frameIndex++},80)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,this.clearFn(),this.lastLength=0)}}});var he,gi=Ie(()=>{"use strict";he="0.5.49"});import{readFileSync as l_t}from"node:fs";import{WebContextClient as u_t}from"@xenosystem/web-context-client";function p_t(e=process.env){let t=e.XENO_WEB_CONTEXT_TOKEN?.trim();if(t)return t;let n=e.XENO_WEB_CONTEXT_TOKEN_FILE?.trim();if(n){let r=l_t(n,"utf8").trim();if(r)return r}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 _Z(e=process.env){return new u_t({baseUrl:e.XENO_WEB_CONTEXT_URL?.trim()||d_t,token:p_t(e)})}function X1e(e=process.env){return{client:new PZ(e),createRequest:nD({actor:{id:"xeno-agent-cli",kind:"agent"},scope:{kind:"local-profile",profileId:"pending-token-scope"},classification:"public",purposePrefix:"xeno-agent-cli:chat",budget:{durationMs:12e4,maxAttempts:3,maxConcurrency:4,maxBytes:1e7,maxPages:100,maxRedirects:8,maxProviderCostUsd:0}})}}var d_t,PZ,$Z=Ie(()=>{"use strict";at();d_t="http://127.0.0.1:8080";PZ=class{constructor(t){this.env=t}env;client;tenantId;async search(t){return this.getClient().search(await this.bindTenant(t))}async scrapeAndWait(t,n){return this.getClient().scrapeAndWait(await this.bindTenant(t),n)}getClient(){return this.client??=_Z(this.env),this.client}async bindTenant(t){this.tenantId??=this.getClient().account().then(r=>r.tenantId);let n=await this.tenantId;return{...t,scope:{kind:"tenant",tenantId:n}}}}});var z1e=Ie(()=>{"use strict"});function Y1e(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 n=t.snapshot,r=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,i=(o,s,a,c=!1)=>Array.isArray(o)&&o.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&typeof l[s]=="string"&&r(l[a])&&(!c||l.cost===null));return n.source==="local-runtime-journal"&&n.billingStatus==="unavailable"&&n.totalCost===null&&typeof n.observedAt=="string"&&Number.isFinite(Date.parse(n.observedAt))&&r(n.totalTokens)&&r(n.totalRequests)&&r(n.unmeasuredRequests)&&n.unmeasuredRequests<=n.totalRequests&&i(n.dailyUsage,"label","value")&&i(n.weeklyUsage,"label","value")&&i(n.monthlyUsage,"label","value")&&i(n.costByModel,"model","tokens",!0)&&i(n.topAgents,"name","tokens",!0)}var K1e=Ie(()=>{"use strict"});var Z1e=Ie(()=>{"use strict"});function e$e(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(n=>n&&typeof n=="object"&&["id","timestamp","action","actor","target","details"].every(r=>typeof n[r]=="string")&&Number.isFinite(Date.parse(n.timestamp)))}var t$e=Ie(()=>{"use strict"});function r$e(e){return!BZ(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&&!n$e(e.loadedModel)||e.models!==void 0&&(!Array.isArray(e.models)||e.models.length>1e3||!e.models.every(t=>BZ(t)&&n$e(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&&(!BZ(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 BZ,n$e,i$e=Ie(()=>{"use strict";BZ=e=>!!e&&typeof e=="object"&&!Array.isArray(e),n$e=e=>typeof e=="string"&&e.length>0&&e.length<=512&&!/[\x00-\x1f\x7f]/.test(e)});var jMn,o$e=Ie(()=>{"use strict";jMn=new TextEncoder});var s$e=Ie(()=>{"use strict"});var a$e=Ie(()=>{"use strict"});var c$e=Ie(()=>{"use strict"});var l$e=Ie(()=>{"use strict"});var u$e=Ie(()=>{"use strict"});var d$e=Ie(()=>{"use strict";u$e()});var p$e=Ie(()=>{"use strict"});var f$e=Ie(()=>{"use strict"});var m$e=Ie(()=>{"use strict"});var f_t,h$e=Ie(()=>{"use strict";mI();f_t=1024*1024});import{WEB_JOB_PROGRESS_OPERATIONS as KMn,WEB_JOB_PROGRESS_SCHEMA as ZMn,WEB_JOB_PROGRESS_SCHEMA_VERSION as eNn,WEB_JOB_PROGRESS_STATES as tNn,TERMINAL_WEB_JOB_STATES as nNn,isTerminalWebJobState as rNn,isWebJobProgress as iNn,parseWebJobProgress as oNn}from"@xenosystem/web-context-client/progress";function w_t(e){return typeof e=="string"&&m_t.includes(e)}function g$e(e){return so(e)?Bn(e.clientId)&&Bn(e.clientVersion)&&Bn(e.instanceId)&&w_t(e.surface):!1}function w$e(e){return!so(e)||!so(e.protocol)||!so(e.host)||!so(e.storage)?!1:Number.isInteger(e.protocol.current)&&E_t(e.protocol.supported)&&Bn(e.host.instanceId)&&Bn(e.host.version)&&(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)&&g$e(e.surface)}function MZ(e){return!so(e)||!Bn(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(I_t)}function y_t(e){return!so(e)||!so(e.event)?!1:Bn(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&Bn(e.timestamp)&&Bn(e.conversationId)&&Bn(e.requestId)&&Bn(e.type)&&Bn(e.source)}function y$e(e){return!so(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(y_t)}function b$e(e){return!so(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&Bn(e.conversationId)&&Bn(e.requestId)&&Bn(e.adapterId)&&so(e.selection)&&Bn(e.selection.providerId)&&Bn(e.selection.catalogRevision):Bn(e.code)&&Bn(e.safeError)}function v$e(e){return!so(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&Bn(e.conversationId)&&Bn(e.requestId):Bn(e.code)&&Bn(e.safeError)}function I$e(e){return so(e)&&Bn(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&b_t(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e}function b_t(e){return typeof e=="string"&&A_t.includes(e)}function k$e(e,t,n){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new qi("surface_mismatch",`Agent host acknowledged ${e.surface.surface}/${e.surface.instanceId} instead of ${t.surface}/${t.instanceId}.`);if(e.protocol.current<n.min||e.protocol.current>n.max||n.max<e.protocol.supported.min||n.min>e.protocol.supported.max)throw new qi("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${n.min}-${n.max}.`)}function v_t(e){return!(!so(e)||e.chatExecution!==void 0&&!NR(e.chatExecution)||e.durableResume!==void 0&&!NR(e.durableResume)||e.nativeTuiAttach!==void 0&&!NR(e.nativeTuiAttach)||e.reconciliation!==void 0&&!NR(e.reconciliation)||e.modelSwitchInPlace!==void 0&&!NR(e.modelSwitchInPlace)||e.resumeCompatibilityKey!==void 0&&typeof e.resumeCompatibilityKey!="string")}function NR(e){return so(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 I_t(e){return so(e)?Bn(e.id)&&typeof e.kind=="string"&&h_t.includes(e.kind)&&Bn(e.displayName)&&E$e(e.availability)&&so(e.capabilities)&&(e.providerSession===void 0||v_t(e.providerSession))&&Array.isArray(e.models)&&e.models.every(k_t)&&Bn(e.catalogRevision):!1}function k_t(e){return so(e)&&Bn(e.id)&&Bn(e.displayName)&&E$e(e.availability)&&(e.reasoningOptions===void 0||Array.isArray(e.reasoningOptions)&&e.reasoningOptions.every(t=>so(t)&&Bn(t.id)&&Bn(t.label)&&(t.runtimeModelId===void 0||Bn(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 E$e(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function E_t(e){return so(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 Bn(e){return typeof e=="string"&&e.trim().length>0}function so(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function S$e(e){for(let t of C_t)for(let n of S_t)if(e===`${t}tool.${n}`)return n;return null}function KA(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n:void 0}function C$e(e){let t=e.event;return KA(t,"toolName")||KA(t,"tool")||KA(t,"name")||KA(t,"title")||KA(t,"kind")}function x$e(e){let t=e.event;return KA(t,"toolCallId")||KA(t,"tool_call_id")}function R$e(e){let t=e.event;for(let n of["rawInput","input","arguments","parameters","args"]){let r=t?.[n];if(r&&typeof r=="object"&&!Array.isArray(r))return r}}function T$e(e){let t=e.event;for(let n of["rawOutput","output","result","content"]){let r=t?.[n];if(typeof r=="string")return r.length>0?r:void 0;if(r!=null)try{let i=JSON.stringify(r);if(i&&i!=="{}"&&i!=="[]")return i}catch{}}}function P$e(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var hI,A$e,m_t,h_t,g_t,sNn,A_t,qi,S_t,C_t,mI=Ie(()=>{"use strict";z1e();K1e();Z1e();t$e();i$e();o$e();s$e();a$e();c$e();l$e();d$e();p$e();f$e();m$e();h$e();hI=1,A$e=1,m_t=["standalone-desktop","hub-embed","shell-embed","embed-preview","panel-embed","headless-client"],h_t=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"],g_t=["workspace.usage","workspace.audit","inference.request","workspace.schedule","workspace.backup","workspace.environment","account.request","workforce.request","workspace.notifications","workspace.rules","workspace.browser","workspace.browser.session","host.handshake","providers.list","providers.refresh","runtime.events.list","workspace.lifecycle.apply","state.workspaces.load","state.workspaces.save","state.conversations.load","state.conversations.save","state.conversations.delete","workspace.access.grant","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.resume","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"],sNn=new Set(g_t),A_t=["host.ready","provider.catalog.changed","state.workspaces.changed","runtime.event.appended","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"],qi=class extends Error{code;constructor(t,n){super(n),this.name="AgentHostProtocolError",this.code=t}};S_t=["started","updated","completed","failed","cancelled"],C_t=["","acp."]});import{createHash as x_t}from"node:crypto";import{setTimeout as R_t}from"node:timers/promises";function __t(e,t){return`subrun-${x_t("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}async function $_t(e,t,n){return((await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}))?.events??[]).map(i=>{let o=String(i.type??"").toLowerCase();if(!o.includes("text")&&!o.includes("message")&&!o.includes("delta"))return"";let s=i.event??{};return typeof s.text=="string"?s.text:typeof s.delta=="string"?s.delta:""}).join("")}function B_t(e,t,n,r){let i=new Set,o=typeof r.onToolStart=="function"||typeof r.onToolEnd=="function",s=a=>{try{a()}catch{}};return async function(){if(!o)return;let c=await e.listRuntimeEvents({conversationId:t,subagentRunId:n,limit:500}).catch(()=>null);for(let l of c?.events??[]){let u=S$e(String(l.type??""));if(!u)continue;let d=`${x$e(l)??l.id}:${u}`;if(i.has(d))continue;i.add(d);let p=C$e(l)??"unknown";if(u==="started"&&r.onToolStart){let m=r.onToolStart;s(()=>m(p,R$e(l)??{}))}let f=P$e(u);if(f!==null&&r.onToolEnd){let m=r.onToolEnd;s(()=>m(p,{success:f,output:T$e(l)??""}))}}}}function _$e(e){let t=e.pollIntervalMs??250;return async n=>{let r=n.task,i=__t(e.rootTraceId,r.id),o={lastTraceId:null,tokenUsage:{input:0,output:0,total:0},async run(s){let a=Math.max(1e3,e.deadline-Date.now()),c={parentConversationId:e.parentConversationId,...e.parentRequestId===void 0?{}:{parentRequestId:e.parentRequestId},parentAgentId:e.parentAgentId,childConversationId:i,childAgentId:r.role?`delegated-${r.role}`:"delegated-branch",workspaceId:e.workspaceId,teamId:e.teamId,objective:s,...r.role===void 0?{}:{role:r.role},policy:{maxRuntimeMs:a}},l=await e.client.createSubagentRun(c);if(!l?.success||!l.run)throw new Error(l?.safeError??"The Agent host refused to create a subagent run for this delegated branch.");let u=l.run.id;o.lastTraceId=u;let d=B_t(e.client,i,u,{onToolStart:n.onToolStart,onToolEnd:n.onToolEnd});for(;;){if(e.signal?.aborted){await e.client.cancelSubagentRun({runId:u}).catch(()=>{});let h=new Error("Delegated branch was cancelled.");throw h.name="AgentInterruptedError",h}let f=((await e.client.listSubagentRuns({parentConversationId:e.parentConversationId}))?.runs??[]).find(h=>h.id===u),m=String(f?.status??"");if(T_t.has(m)){if(P_t.has(m))throw new Error(f?.error??`The delegated branch ended as '${m}' without reporting a reason.`);await d();let h=await $_t(e.client,i,u);if(h.length===0)throw new Error(`The delegated branch reported '${m}' but produced no readable output. Its runtime events carry no text for this run id.`);return h}if(Date.now()>=e.deadline)throw await e.client.cancelSubagentRun({runId:u}).catch(()=>{}),new Error("The delegated branch exceeded the time this run was given to wait.");await d(),await R_t(t,void 0,{signal:e.signal})}}};return o}}var T_t,P_t,$$e=Ie(()=>{"use strict";mI();T_t=new Set(["completed","succeeded","failed","cancelled","error"]),P_t=new Set(["failed","cancelled","error"])});import{execFile as B$e,execFileSync as NZ}from"node:child_process";import{promisify as M$e}from"node:util";import{createHash as M_t}from"node:crypto";import{existsSync as N_t,readFileSync as OZ,readlinkSync as O_t}from"node:fs";import{hostname as ZA}from"node:os";function wQ(e){return Number.isInteger(e)&&e>0}function L_t(e){return M_t("sha256").update(e).digest("hex")}function DR(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${L_t(t)}`:void 0}function AQ(){if(process.platform==="linux")try{return OZ("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function Fp(e){if(typeof e!="number"||!wQ(e))return"dead";try{return process.kill(e,0),"live"}catch(t){return t.code==="ESRCH"?"dead":"unknown"}}function DZ(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function N$e(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 { '' }; [pscustomobject]@{ pid = [int]$_.Id; startedAt = $_.StartTime.ToUniversalTime().ToString('o'); executable = $path } })","$out | ConvertTo-Json -Compress"].join("; ")]}function O$e(e){let t=new Map;try{if(!e)return t;let n=JSON.parse(e);for(let r of Array.isArray(n)?n:[n]){let i=Number(r.pid),o=DZ(String(r.startedAt??""));!wQ(i)||!o||t.set(i,{pid:i,processStartedAt:o,hostname:ZA(),...DR(r.executable)?{executableFingerprint:DR(r.executable)}:{},confidence:"observed"})}}catch{return t}return t}function Q_t(e){if(!e.length)return new Map;try{return O$e(NZ("powershell.exe",N$e(e),{encoding:"utf8",windowsHide:!0,timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim())}catch{return new Map}}function F_t(){if(OR)return OR;try{let e=Number.parseInt(NZ("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);OR=Number.isFinite(e)&&e>0?e:100}catch{OR=100}return OR}function U_t(){try{let e=/^btime\s+(\d+)$/m.exec(OZ("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function q_t(e){try{let t=OZ(`/proc/${e}/stat`,"utf8"),n=t.lastIndexOf(")");if(n<0)return null;let r=t.slice(n+2).trim().split(/\s+/),i=Number(r[19]),o=U_t();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/F_t())*1e3).toISOString(),a;try{a=O_t(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:ZA(),...AQ()?{bootId:AQ()}:{},...DR(a)?{executableFingerprint:DR(a)}:{},confidence:"observed"}}catch{return null}}function D$e(e){let t=new Map;if(process.platform==="linux"){for(let n of e){let r=q_t(n);r&&t.set(n,r)}return t}for(let n of e)try{let r=NZ("ps",["-p",String(n),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=DZ(r);if(!i)continue;t.set(n,{pid:n,processStartedAt:i,hostname:ZA(),confidence:"observed"})}catch{continue}return t}function LR(e){let t=[...new Set(e.filter(wQ))],n=t.includes(process.pid),r=n?t.filter(o=>o!==process.pid):t,i=process.platform==="win32"?Q_t(r):D$e(r);return n&&i.set(process.pid,zm()),i}function L$e(e){return LR([e]).get(e)??null}async function Q$e(e,t){t?.throwIfAborted();let n=[...new Set(e.filter(wQ))],r=n.filter(o=>o!==process.pid),i=new Map;if(process.platform==="win32"&&r.length)try{let o=await M$e(B$e)("powershell.exe",N$e(r),{encoding:"utf8",windowsHide:!0,timeout:1e4,maxBuffer:1048576,signal:t});i=O$e(o.stdout.trim())}catch{t?.throwIfAborted()}else if(process.platform==="linux")i=D$e(r);else if(process.platform!=="win32")for(let o of r){t?.throwIfAborted();try{let{stdout:s}=await M$e(B$e)("ps",["-p",String(o),"-o","lstart="],{encoding:"utf8",timeout:2e3,signal:t,env:{...process.env,LC_ALL:"C"},maxBuffer:4096}),a=DZ(s.trim());a&&i.set(o,{pid:o,processStartedAt:a,hostname:ZA(),confidence:"observed"})}catch{t?.throwIfAborted()}}return t?.throwIfAborted(),n.includes(process.pid)&&i.set(process.pid,zm()),i}function yQ(e,t=new Date,n=!1){return(n?L$e(e):null)??{pid:e,processStartedAt:t.toISOString(),hostname:ZA(),confidence:"degraded"}}function zm(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:ZA(),...AQ()?{bootId:AQ()}:{},...N_t(process.execPath)?{executableFingerprint:DR(process.execPath)}:{},confidence:"self"}}function Lo(e,t=L$e){if(e.hostname!==ZA())return{status:"remote",expected:e,reason:"Process belongs to another host."};if(Fp(e.pid)==="dead")return{status:"dead",expected:e,reason:"Process ID is not live."};let n=t(e.pid);if(!n)return{status:"degraded",expected:e,reason:"Creation time could not be observed."};let r=Date.parse(e.processStartedAt),i=Date.parse(n.processStartedAt);return!Number.isFinite(r)||!Number.isFinite(i)||Math.abs(r-i)>D_t?{status:"mismatch",expected:e,observed:n,reason:"Process creation time does not match."}:e.bootId&&n.bootId&&e.bootId!==n.bootId?{status:"mismatch",expected:e,observed:n,reason:"Host boot identity does not match."}:e.executableFingerprint&&n.executableFingerprint&&e.executableFingerprint!==n.executableFingerprint?{status:"mismatch",expected:e,observed:n,reason:"Executable identity does not match."}:{status:"live",expected:e,observed:n}}var D_t,OR,sd=Ie(()=>{"use strict";D_t=3e3});import{createHash as j_t,randomBytes as V_t}from"node:crypto";import{chmodSync as H_t,existsSync as W_t,mkdirSync as U$e,readFileSync as G_t,renameSync as J_t,unlinkSync as q$e,writeFileSync as X_t}from"node:fs";import{dirname as z_t,join as QR}from"node:path";function j$e(){return Qc()}function Y_t(e){return j_t("sha256").update(e).digest("hex").slice(0,16)}function Mn(){return QR(j$e(),"daemon")}function LZ(){return QR(Mn(),"daemon.json")}function V$e(){return QR(Mn(),"daemon.lock")}function gI(){return QR(Mn(),"daemon.log")}function QZ(){let e=Y_t(j$e());return process.platform==="win32"?{transport:"named-pipe",endpoint:`\\\\.\\pipe\\xeno-agent-daemon-${e}`}:{transport:"unix-socket",endpoint:QR(Mn(),"daemon.sock")}}function bQ(){U$e(Mn(),{recursive:!0})}function H$e(){return V_t(32).toString("base64url")}function F$e(e){if(process.platform!=="win32")try{H_t(e,384)}catch{}}function FZ(){try{let e=LZ(),t=G_t(e,"utf8"),n=JSON.parse(t);if(!n||n.schemaVersion!==1||n.protocolVersion!==1||n.transport!=="named-pipe"&&n.transport!=="unix-socket"||typeof n.endpoint!="string"||typeof n.authToken!="string"||!Number.isSafeInteger(n.pid)||typeof n.startedAt!="string"||typeof n.cliVersion!="string"||typeof n.logPath!="string")throw new Error("daemon state schema is invalid");return n}catch(e){if(e.code==="ENOENT")return null;throw new Error(`Daemon state is corrupt or unreadable: ${e instanceof Error?e.message:String(e)}`)}}function W$e(e){let t=LZ();U$e(z_t(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;X_t(n,JSON.stringify(e,null,2)+`
|
|
2882
2882
|
`,{encoding:"utf8",mode:384}),F$e(n),J_t(n,t),F$e(t)}function vQ(){try{q$e(LZ())}catch{}}function G$e(){if(process.platform==="win32")return;let{endpoint:e}=QZ();if(W_t(e))try{q$e(e)}catch{}}function Xs(e){return Fp(e)!=="dead"}var ko=Ie(()=>{"use strict";Rg();sd()});import{existsSync as K_t,linkSync as Z_t,mkdirSync as e1t,readFileSync as t1t,rmSync as qZ,statSync as n1t,writeFileSync as r1t}from"node:fs";import{hostname as J$e}from"node:os";import{dirname as i1t}from"node:path";import{randomUUID as o1t}from"node:crypto";function s1t(){return new Date().toISOString()}function UZ(e){try{return JSON.parse(t1t(e,"utf8"))}catch{return null}}function a1t(e){if(e.hostname!==J$e())return!0;let t=Date.parse(e.acquiredAt);if(Number.isFinite(t)&&Date.now()-t<3e4)return!0;if(!Xs(e.pid))return!1;if(e.processIdentity){let n=Lo(e.processIdentity);return n.status==="live"||n.status==="degraded"||n.status==="remote"}return!0}function X$e(e,t){e1t(i1t(e),{recursive:!0});let n=`${e}.${process.pid}.${o1t()}.tmp`;r1t(n,JSON.stringify(t,null,2)+`
|
|
2883
2883
|
`,{encoding:"utf8",flag:"wx"});try{Z_t(n,e)}finally{qZ(n,{force:!0})}}function c1t(e){try{return Date.now()-n1t(e).mtimeMs<3e4}catch{return!1}}function l1t(e,t){return e?.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}function FR(e,t){return Object.assign(new Error(`${e} is already locked ${t}.`),{code:"CONTROL_PLANE_LOCK_BUSY"})}function Up(e){return e instanceof Error&&"code"in e&&e.code==="CONTROL_PLANE_LOCK_BUSY"}function u1t(e,t,n){try{X$e(e,t)}catch(r){throw r.code==="EEXIST"?FR(n,"by another contender"):r}}function d1t(e,t){let n=UZ(e);n?.pid!==t.pid||n.hostname!==t.hostname||n.processStartedAt!==t.processStartedAt||qZ(e,{force:!0})}function Eo(e,t,n){let r=s1t(),i=zm(),o={schemaVersion:1,name:t,pid:process.pid,hostname:J$e(),processStartedAt:i.processStartedAt,processIdentity:i,version:n,acquiredAt:r,updatedAt:r};try{X$e(e,o)}catch(s){if(s.code!=="EEXIST")throw s;let c=UZ(e);if(c&&a1t(c))throw FR(t,`by PID ${c.pid} on ${c.hostname}`);if(c){if(!l1t(UZ(e),c))throw FR(t,"while ownership was changing")}else{if(!K_t(e))throw FR(t,"while ownership was changing");if(c1t(e))throw FR(t,"by an owner whose record is still being published")}qZ(e,{force:!0}),u1t(e,o,t)}return{record:o,release:()=>{d1t(e,o)}}}var qp=Ie(()=>{"use strict";ko();sd()});import{createHash as eBe,randomBytes as p1t,randomUUID as tBe}from"node:crypto";import{closeSync as nBe,existsSync as HZ,fstatSync as f1t,fsyncSync as m1t,mkdirSync as WZ,openSync as rBe,readFileSync as VZ,readSync as h1t,renameSync as g1t,writeFileSync as iBe}from"node:fs";import{cpus as A1t}from"node:os";import{dirname as oBe,isAbsolute as w1t,join as yI,resolve as y1t}from"node:path";function qR(e,t,n=1,r=Number.MAX_SAFE_INTEGER){let i=typeof e=="number"?e:Number.parseInt(String(e??""),10);return Number.isFinite(i)?Math.min(r,Math.max(n,Math.trunc(i))):t}function I1t(e,t,n=0,r=Number.MAX_SAFE_INTEGER){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.min(r,Math.max(n,i)):t}function AI(e,t){return t===void 0?e:Math.min(e,t)}function UR(e,t){return{maxConcurrency:AI(e.maxConcurrency,t?.maxConcurrency),maxCredentialConcurrency:AI(e.maxCredentialConcurrency,t?.maxCredentialConcurrency),maxRequestsPerWindow:AI(e.maxRequestsPerWindow,t?.maxRequestsPerWindow),maxTokensPerWindow:AI(e.maxTokensPerWindow,t?.maxTokensPerWindow),windowMs:t?.windowMs===void 0?e.windowMs:Math.max(1e3,t.windowMs)}}function k1t(e={}){let t=e.env??process.env,n=Math.max(1,e.cpuCount??A1t().length),r=Math.min(Math.max(1,n-2),b1t),i=qR(t.XENO_WORKFLOW_GLOBAL_CONCURRENCY,r,1,jZ),s=t.XENO_WORKFLOW_TRUSTED_CONCURRENCY_OVERRIDE==="1"?i:Math.min(r,i);s=AI(s,e.user?.globalConcurrency),s=AI(s,e.managed?.globalConcurrency),s=qR(s,r,1,jZ);let a={maxConcurrency:Math.min(s,8),maxCredentialConcurrency:Math.min(s,4),maxRequestsPerWindow:120,maxTokensPerWindow:2e6,windowMs:6e4},c=UR(a,e.user?.providerDefault),l=UR(c,e.managed?.providerDefault),u=new Set([...Object.keys(e.user?.providers??{}),...Object.keys(e.managed?.providers??{})]),d=Object.fromEntries([...u].map(f=>[f,UR(UR(l,e.user?.providers?.[f]),e.managed?.providers?.[f])])),p=(f,m,h=1,g=Number.MAX_SAFE_INTEGER)=>{let A=m,y=e.user?.[f],w=e.managed?.[f];return typeof y=="number"&&(A=Math.min(A,y)),typeof w=="number"&&(A=Math.min(A,w)),qR(A,m,h,g)};return{schemaVersion:1,productHardConcurrency:jZ,globalConcurrency:s,perRunConcurrency:p("perRunConcurrency",s,1,s),perParentConcurrency:p("perParentConcurrency",s,1,s),reservedPrioritySlots:Math.min(2,Math.max(0,s-1)),maxQueueLength:p("maxQueueLength",4096,1,65536),maxQueueWaitMs:p("maxQueueWaitMs",5*6e4,1e3,1440*6e4),maxAttemptsPerLogicalChild:p("maxAttemptsPerLogicalChild",3,1,100),maxAttemptsPerRun:p("maxAttemptsPerRun",1e3,1,1e4),maxReservedTokens:p("maxReservedTokens",4e6,1,Number.MAX_SAFE_INTEGER),maxReservedCostUsd:I1t(Math.min(e.user?.maxReservedCostUsd??500,e.managed?.maxReservedCostUsd??500),500,.01,1e6),leaseTtlMs:p("leaseTtlMs",4e3,2e3,5*6e4),heartbeatIntervalMs:p("heartbeatIntervalMs",1e3,250,6e4),maxStarvationMs:p("maxStarvationMs",3e4,1e3,60*6e4),providerDefault:l,providers:d}}function Y$e(e,t){if(!HZ(e)){if(t)throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy file not found: ${e}`);return}try{let n=JSON.parse(VZ(e,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("policy root must be an object");return n}catch(n){throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy is invalid: ${e}: ${n instanceof Error?n.message:String(n)}`)}}function E1t(e=process.env){let t=oBe(Mn()),n=e.XENO_WORKFLOW_RESOURCE_POLICY?.trim(),r=e.XENO_MANAGED_WORKFLOW_RESOURCE_POLICY?.trim(),i=a=>w1t(a)?a:y1t(a),o=Y$e(n?i(n):yI(t,"resource-policy.json"),!!n),s=r?Y$e(i(r),!0):void 0;return k1t({env:e,user:o,managed:s})}function So(e){return new Date(e).toISOString()}function S1t(e){return{schemaVersion:1,revision:0,nextFencingToken:1,updatedAt:So(e),permits:[],queue:[],attempts:[],usage:[],providerRates:[],effects:[]}}function C1t(e){let t=e,n=p=>!!(p&&typeof p=="object"&&!Array.isArray(p)),r=p=>typeof p=="string"&&p.length>0&&p.length<=512,i=p=>typeof p=="string"&&Number.isFinite(Date.parse(p)),o=p=>n(p)&&Number.isInteger(p.pid)&&Number(p.pid)>0&&r(p.hostname)&&i(p.processStartedAt),s=p=>n(p)&&r(p.permitId)&&r(p.requestId)&&r(p.operationId)&&r(p.runId)&&r(p.providerId)&&r(p.logicalChildId)&&r(p.attemptId)&&r(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,a=p=>n(p)&&r(p.requestId)&&r(p.operationId)&&r(p.runId)&&r(p.providerId)&&r(p.logicalChildId)&&r(p.attemptId)&&r(p.idempotencyKey)&&o(p.owner)&&i(p.enqueuedAt)&&i(p.updatedAt),c=p=>n(p)&&r(p.runId)&&r(p.logicalChildId)&&r(p.attemptId)&&r(p.idempotencyKey)&&r(p.state)&&i(p.startedAt),l=p=>n(p)&&r(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),u=p=>n(p)&&r(p.providerId)&&i(p.timestamp)&&Number.isFinite(p.tokens)&&Number(p.tokens)>=0,d=p=>n(p)&&r(p.effectKey)&&r(p.idempotencyKey)&&r(p.permitId)&&Number.isInteger(p.fencingToken)&&Number(p.fencingToken)>0&&r(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(c)&&Array.isArray(t.usage)&&t.usage.every(l)&&Array.isArray(t.providerRates)&&t.providerRates.every(u)&&Array.isArray(t.effects)&&t.effects.every(d))}function x1t(e,t){WZ(oBe(e),{recursive:!0});let n=`${e}.${process.pid}.${tBe()}.tmp`,r=rBe(n,"wx",384);try{iBe(r,JSON.stringify(t,null,2)+`
|
|
2884
2884
|
`,"utf8"),m1t(r)}finally{nBe(r)}g1t(n,e)}function R1t(e,t,n){let r=Date.parse(e.requestedAt??""),i=Number.isFinite(r)?r:t,o=Date.parse(e.queueDeadlineAt??"");return{requestedAt:So(i),deadlineAt:So(Number.isFinite(o)?Math.min(o,i+n):i+n)}}function sBe(e,t){return UR(e.providerDefault,e.providers[t])}function K$e(e,t,n){let r=Math.max(0,t-Date.parse(e.enqueuedAt));return v1t[e.priorityClass]+Math.floor(r/n.maxStarvationMs)*1001}function T1t(e,t,n){return[...e].sort((r,i)=>K$e(i,t,n)-K$e(r,t,n)||Date.parse(r.enqueuedAt)-Date.parse(i.enqueuedAt)||r.requestId.localeCompare(i.requestId))}function P1t(e,t){return e.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt}function wI(e){return Number.isFinite(e)?Math.max(0,Number(e)):0}function Z$e(e,t,n,r){let i=e.permits;if(i.length>=n.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,n.globalConcurrency-n.reservedPrioritySlots))return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"reserved_priority_capacity"};let s=Math.min(n.perRunConcurrency,qR(t.runConcurrencyLimit,n.perRunConcurrency,1,n.globalConcurrency));if(i.filter(b=>b.runId===t.runId).length>=s)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"run_concurrency"};if(t.parentId&&i.filter(b=>b.parentId===t.parentId).length>=n.perParentConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"parent_concurrency"};let a=sBe(n,t.providerId);if(i.filter(b=>b.providerId===t.providerId).length>=a.maxConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"provider_concurrency"};if(t.credentialFingerprint&&i.filter(b=>b.providerId===t.providerId&&b.credentialFingerprint===t.credentialFingerprint).length>=a.maxCredentialConcurrency)return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"credential_concurrency"};if(i.some(b=>b.logicalChildId===t.logicalChildId))return{code:"WORKFLOW_CONCURRENCY_LIMIT",reason:"logical_child_active"};let c=new Set(e.attempts.filter(b=>b.logicalChildId===t.logicalChildId).map(b=>b.attemptId));if(!c.has(t.attemptId)&&c.size>=n.maxAttemptsPerLogicalChild)return{code:"WORKFLOW_ATTEMPT_LIMIT",reason:"logical_child_attempt_limit"};let l=new Set(e.attempts.filter(b=>b.runId===t.runId).map(b=>b.attemptId)),u=Math.min(n.maxAttemptsPerRun,qR(t.runAttemptLimit,n.maxAttemptsPerRun,1,n.maxAttemptsPerRun));if(!l.has(t.attemptId)&&l.size>=u)return{code:"WORKFLOW_ATTEMPT_LIMIT",reason:"run_attempt_limit"};let d=wI(t.reservedTokens);if(i.reduce((b,I)=>b+I.reservedTokens,0)+d>n.maxReservedTokens)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"global_token_reservation"};let f=wI(t.reservedCostUsd);if(i.reduce((b,I)=>b+I.reservedCostUsd,0)+f>n.maxReservedCostUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"global_cost_reservation"};let h=e.usage.find(b=>b.runId===t.runId),g=i.filter(b=>b.runId===t.runId).reduce((b,I)=>b+I.reservedTokens,0);if(t.runTokenLimit!==void 0&&(h?.tokens??0)+g+d>t.runTokenLimit)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"run_token_limit"};let A=i.filter(b=>b.runId===t.runId).reduce((b,I)=>b+I.reservedCostUsd,0);if(t.runCostLimitUsd!==void 0&&(h?.costUsd??0)+A+f>t.runCostLimitUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"run_cost_limit"};let y=r-a.windowMs,w=e.providerRates.filter(b=>b.providerId===t.providerId&&Date.parse(b.timestamp)>=y&&(!t.credentialFingerprint||b.credentialFingerprint===t.credentialFingerprint));return w.length>=a.maxRequestsPerWindow?{reason:"provider_request_rate"}:w.reduce((b,I)=>b+I.tokens,0)+d>a.maxTokensPerWindow?{reason:"provider_token_rate"}:{}}function _1t(e){for(let[t,n]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 n!="string"||!n.trim()||n.length>512)throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE",`Invalid resource request field: ${t}.`);if(e.credentialFingerprint&&!/^(?:cred_)?sha256_[a-f0-9]{32,64}$/i.test(e.credentialFingerprint))throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE","credentialFingerprint must be a scoped SHA-256 fingerprint.")}function Ym(e,t){let n=String(e??"default").trim().toLowerCase().split(/[/:]/,1)[0]||"default",r=t?.trim()?eBe("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16):"default";return`${n}@${r}`}function GZ(e){let t=eBe("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 JZ(e=yI(Mn(),"governor")){let t=yI(e,"credential-salt.bin");if(WZ(e,{recursive:!0}),HZ(t))return VZ(t);let n=p1t(32);try{return iBe(t,n,{flag:"wx",mode:384}),n}catch{return VZ(t)}}function bI(e,t=process.env,n){let r=e.split("@",1)[0]?.toLowerCase(),o=(r==="anthropic"||r==="claude"?["ANTHROPIC_API_KEY","XENO_API_KEY"]:r==="openai"||r==="gpt"?["OPENAI_API_KEY","XENO_API_KEY"]:r==="google"||r==="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(s=>t[s]?.trim()).find(Boolean);return o?GZ({providerId:e,endpoint:n,credential:o,salt:JZ()}):void 0}function IQ(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 XZ(e=process.env){let t=e.XENO_RESOURCE_PERMIT_ID?.trim(),n=Number.parseInt(e.XENO_RESOURCE_FENCING_TOKEN??"",10);return t&&Number.isInteger(n)&&n>0?{permitId:t,fencingToken:n}:null}function Km(e,t,n=process.env){if(n.XENO_RESOURCE_OPERATION_ID?.trim()!==e)return;let r=XZ(n);if(!t||!r||t.permitId!==r.permitId||t.fencingToken!==r.fencingToken)throw new cs("WORKER_LEASE_EXPIRED","Worker state write rejected because its fencing token is stale.");new Zr().assertFence(r.permitId,r.fencingToken)}var jZ,b1t,z$e,cs,v1t,Zr,jp=Ie(()=>{"use strict";gi();nI();ko();qp();sd();jZ=64,b1t=16,z$e=16*1024*1024,cs=class extends Error{constructor(n,r){super(r);this.code=n;this.name="WorkflowResourceError"}code},v1t={control:1e3,foreground:900,reconciliation:850,terminal:800,"app-server":700,workflow:500,background:400,scheduled:300};Zr=class{policy;rootDir;ledgerPath;lockPath;now;owner;fault;constructor(t={}){this.rootDir=t.rootDir??yI(Mn(),"governor"),this.ledgerPath=yI(this.rootDir,"resource-ledger.json"),this.lockPath=yI(this.rootDir,"resource-ledger.lock"),this.policy=t.policy??E1t(),this.now=t.now??Date.now,this.owner=t.owner??zm,this.fault=t.fault,WZ(this.rootDir,{recursive:!0})}acquire(t){_1t(t);let n=0,r=this.withLedger((a,c)=>{this.cleanupExpired(a,c);let l=a.permits.find(I=>I.requestId===t.requestId||I.attemptId===t.attemptId);if(l)return n=a.permits.length,{value:{status:"active",permit:l,reason:"attempt_already_active"},changed:!0};let u=R1t(t,c,this.policy.maxQueueWaitMs);if(c>Date.parse(u.deadlineAt))return{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!1};let d=a.queue.find(I=>I.requestId===t.requestId);if(d&&c>Date.parse(d.queueDeadlineAt??u.deadlineAt))return a.queue=a.queue.filter(I=>I.requestId!==t.requestId),{value:{status:"rejected",code:"WORKFLOW_QUEUE_EXPIRED",reason:"Queued work exceeded its deadline."},changed:!0};if(!d&&a.queue.length>=this.policy.maxQueueLength)return{value:{status:"rejected",code:"WORKFLOW_QUEUE_FULL",reason:"The host workflow queue is full."},changed:!1};let p=t.owner??this.owner(),f=d?{...d,...t,owner:d.owner,updatedAt:So(c)}:{...t,owner:p,requestedAt:u.requestedAt,queueDeadlineAt:u.deadlineAt,enqueuedAt:So(c),updatedAt:So(c)};d?a.queue=a.queue.map(I=>I.requestId===f.requestId?f:I):a.queue.push(f);let m=T1t(a.queue,c,this.policy),h,g={};for(let I of m){let v=Z$e(a,I,this.policy,c);if(I.requestId===f.requestId&&(g=v),!v.reason){h=I;break}}if(g.code==="WORKFLOW_ATTEMPT_LIMIT"||g.code==="WORKFLOW_TOKEN_LIMIT"||g.code==="WORKFLOW_COST_LIMIT")return a.queue=a.queue.filter(I=>I.requestId!==f.requestId),{value:{status:"rejected",code:g.code,reason:g.reason??"resource_limit"},changed:!0};if(!h||h.requestId!==f.requestId){let I=a.permits.map(x=>Date.parse(x.expiresAt)).filter(Number.isFinite).sort((x,C)=>x-C)[0],v=sBe(this.policy,f.providerId),k=a.providerRates.filter(x=>x.providerId===f.providerId&&(!f.credentialFingerprint||x.credentialFingerprint===f.credentialFingerprint)).map(x=>Date.parse(x.timestamp)+v.windowMs).filter(x=>Number.isFinite(x)&&x>c).sort((x,C)=>x-C)[0],R=[I,k].filter(x=>typeof x=="number").sort((x,C)=>x-C)[0];return{value:{status:"queued",request:f,reason:g.reason??"waiting_for_fair_turn",...R?{estimatedEligibleAt:So(R)}:{}},changed:!0}}let A=Z$e(a,f,this.policy,c);if(A.reason)return A.code==="WORKFLOW_ATTEMPT_LIMIT"||A.code==="WORKFLOW_TOKEN_LIMIT"||A.code==="WORKFLOW_COST_LIMIT"?(a.queue=a.queue.filter(I=>I.requestId!==f.requestId),{value:{status:"rejected",code:A.code,reason:A.reason},changed:!0}):{value:{status:"queued",request:f,reason:A.reason},changed:!0};let y=So(c),w={permitId:`permit_${tBe()}`,requestId:f.requestId,operationId:f.operationId,surface:f.surface,priorityClass:f.priorityClass,runId:f.runId,...f.parentId?{parentId:f.parentId}:{},providerId:f.providerId,...f.credentialFingerprint?{credentialFingerprint:f.credentialFingerprint}:{},logicalChildId:f.logicalChildId,attemptId:f.attemptId,idempotencyKey:f.idempotencyKey,fencingToken:a.nextFencingToken++,owner:f.owner,acquiredAt:y,heartbeatAt:y,expiresAt:So(c+this.policy.leaseTtlMs),reservedTokens:wI(f.reservedTokens),reservedCostUsd:wI(f.reservedCostUsd),lastDurableSequence:0};a.queue=a.queue.filter(I=>I.requestId!==f.requestId),a.permits.push(w),n=a.permits.length;let b=a.attempts.find(I=>I.attemptId===f.attemptId);return b?Object.assign(b,{state:"active",permitId:w.permitId,endedAt:void 0,outcome:void 0}):a.attempts.push({runId:f.runId,logicalChildId:f.logicalChildId,attemptId:f.attemptId,idempotencyKey:f.idempotencyKey,state:"active",permitId:w.permitId,startedAt:y}),a.providerRates.push({providerId:f.providerId,...f.credentialFingerprint?{credentialFingerprint:f.credentialFingerprint}:{},timestamp:y,tokens:w.reservedTokens}),this.fault?.("acquire.before_commit"),{value:{status:"acquired",permit:w},changed:!0,afterCommit:()=>this.fault?.("acquire.after_commit")}}),i=r.status==="rejected"?r.code:r.status==="acquired"?"admitted":r.reason;Mr("xeno.workflow.admission_results",1,{component:"resource_governor",provider:t.providerId,state:r.status,reason:i,...r.status==="rejected"?{error_code:r.code}:{}}),(i==="provider_request_rate"||i==="provider_token_rate"||i==="provider_concurrency"||i==="credential_concurrency")&&Mr("xeno.workflow.provider_throttles",1,{component:"resource_governor",provider:t.providerId,reason:i});let o=Date.parse((r.status==="queued"?r.request.requestedAt:t.requestedAt)??""),s=r.status==="acquired"||r.status==="active"?Date.parse(r.permit.acquiredAt):this.now();return Number.isFinite(o)&&Number.isFinite(s)&&ss("xeno.workflow.queue_wait_ms",Math.max(0,s-o),{component:"resource_governor",provider:t.providerId,state:r.status}),n>0&&ss("xeno.workflow.active_concurrency",n,{component:"resource_governor",provider:t.providerId}),r}heartbeat(t){return this.withLedger((n,r)=>{let i=this.currentPermit(n,t.permitId,t.fencingToken,r),o=t.owner??this.owner();if(!P1t(i.owner,o))throw new cs("WORKER_IDENTITY_MISMATCH","Permit heartbeat came from a different worker identity.");return i.heartbeatAt=So(r),i.expiresAt=So(r+this.policy.leaseTtlMs),i.lastDurableSequence=Math.max(i.lastDurableSequence,Math.max(0,t.lastDurableSequence??0)),{value:{...i},changed:!0}})}assertFence(t,n){return this.withLedger((r,i)=>({value:{...this.currentPermit(r,t,n,i)},changed:!1}))}transfer(t,n,r){return this.withLedger((i,o)=>{let s=this.currentPermit(i,t,n,o);return s.owner=r,s.heartbeatAt=So(o),s.expiresAt=So(o+this.policy.leaseTtlMs),{value:{...s},changed:!0}})}settle(t){return this.withLedger((n,r)=>{let i=n.permits.find(c=>c.permitId===t.permitId);if(!i)return{value:!1,changed:!1};if(i.fencingToken!==t.fencingToken||Date.parse(i.expiresAt)<=r)throw new cs("WORKER_LEASE_EXPIRED","The worker fencing token is stale.");n.permits=n.permits.filter(c=>c.permitId!==i.permitId);let o=n.attempts.find(c=>c.attemptId===i.attemptId);o&&Object.assign(o,{state:"settled",endedAt:So(r),outcome:t.outcome});let s=n.usage.find(c=>c.runId===i.runId),a={runId:i.runId,tokens:(s?.tokens??0)+wI(t.actualTokens),costUsd:(s?.costUsd??0)+wI(t.actualCostUsd),attempts:(s?.attempts??0)+1,updatedAt:So(r)};return n.usage=[...n.usage.filter(c=>c.runId!==i.runId),a],{value:!0,changed:!0}})}settleOperation(t,n,r=0,i=0){let o=this.snapshot().permits.find(s=>s.operationId===t);return o?this.settle({permitId:o.permitId,fencingToken:o.fencingToken,outcome:n,actualTokens:r,actualCostUsd:i}):!1}cancelQueued(t){return this.withLedger(n=>{let r=n.queue.some(i=>i.requestId===t);return n.queue=n.queue.filter(i=>i.requestId!==t),{value:r,changed:r}})}claimEffect(t){return this.withLedger((n,r)=>{let i=this.currentPermit(n,t.permitId,t.fencingToken,r),o=n.effects.find(s=>s.effectKey===t.effectKey||s.idempotencyKey===i.idempotencyKey);return o?{value:o.permitId===i.permitId&&o.fencingToken===i.fencingToken&&o.state==="claimed",changed:!1}:(n.effects.push({effectKey:t.effectKey,idempotencyKey:i.idempotencyKey,permitId:i.permitId,fencingToken:i.fencingToken,state:"claimed",claimedAt:So(r)}),{value:!0,changed:!0})})}commitEffect(t){return this.withLedger((n,r)=>{this.currentPermit(n,t.permitId,t.fencingToken,r);let i=n.effects.find(o=>o.effectKey===t.effectKey);return!i||i.permitId!==t.permitId||i.fencingToken!==t.fencingToken?{value:!1,changed:!1}:i.state==="committed"?{value:!0,changed:!1}:(i.state="committed",i.committedAt=So(r),{value:!0,changed:!0})})}reconcile(t){let n=this.withLedger((r,i)=>{let o=[...r.permits],s=[...r.queue],a=t??LR(o.map(h=>h.owner.pid)),c=new Set,l=new Set;for(let h of o){let g=Lo(h.owner,A=>a.get(A)??null);g.status==="mismatch"&&c.add(h.permitId),(g.status==="degraded"||g.status==="remote")&&l.add(h.permitId)}this.cleanupExpired(r,i,c);let u=new Set(r.permits.map(h=>h.permitId)),d=o.filter(h=>!u.has(h.permitId)&&!c.has(h.permitId)),p=o.filter(h=>c.has(h.permitId)),f=new Set(r.queue.map(h=>h.requestId)),m=s.filter(h=>!f.has(h.requestId));return{value:{expiredPermits:d,identityMismatches:p,expiredQueue:m,livePermits:r.permits.length,degradedPermits:r.permits.filter(h=>l.has(h.permitId)).length},changed:d.length>0||p.length>0||m.length>0}});return ss("xeno.worker.live_leases",n.livePermits,{component:"resource_governor",operation:"reconcile"}),ss("xeno.worker.degraded_leases",n.degradedPermits,{component:"resource_governor",operation:"reconcile"}),n.expiredPermits.length>0&&Mr("xeno.worker.lease_expirations",n.expiredPermits.length,{component:"resource_governor",operation:"reconcile"}),n.identityMismatches.length>0&&Mr("xeno.worker.identity_mismatches",n.identityMismatches.length,{component:"resource_governor",operation:"reconcile"}),n}snapshot(){return this.withLedger(t=>({value:structuredClone(t),changed:!1}))}cleanupExpired(t,n,r=new Set){let i=new Set(t.permits.filter(s=>Date.parse(s.expiresAt)<=n||r.has(s.permitId)).map(s=>s.permitId));if(i.size>0){t.permits=t.permits.filter(s=>!i.has(s.permitId));for(let s of t.attempts)s.permitId&&i.has(s.permitId)&&s.state==="active"&&(s.state="expired",s.endedAt=So(n),s.outcome=r.has(s.permitId)?"WORKER_IDENTITY_MISMATCH":"WORKER_LEASE_EXPIRED")}t.queue=t.queue.filter(s=>Date.parse(s.queueDeadlineAt??s.updatedAt)>n);let o=Math.max(this.policy.providerDefault.windowMs,...Object.values(this.policy.providers).map(s=>s.windowMs??0));if(t.providerRates=t.providerRates.filter(s=>Date.parse(s.timestamp)>n-o),t.attempts.length>2e4){let s=t.attempts.filter(c=>c.state==="active"),a=t.attempts.filter(c=>c.state!=="active").slice(-Math.max(0,2e4-s.length));t.attempts=[...a,...s]}t.effects.length>2e4&&(t.effects=t.effects.slice(-2e4)),t.usage.length>1e4&&(t.usage=t.usage.slice(-1e4))}currentPermit(t,n,r,i){let o=t.permits.find(s=>s.permitId===n);if(!o||Date.parse(o.expiresAt)<=i||o.fencingToken!==r)throw new cs("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out.");return o}readLedger(t){if(!HZ(this.ledgerPath))return S1t(t);let n;try{n=rBe(this.ledgerPath,"r");let r=f1t(n).size;if(!Number.isSafeInteger(r)||r>z$e)throw new Error(`ledger exceeds the ${z$e} byte limit`);let i=Buffer.alloc(r),o=0;for(;o<r;){let c=h1t(n,i,o,r-o,o);if(c===0)throw new Error("Resource ledger changed during read");o+=c}let s=i.toString("utf8"),a=JSON.parse(s);if(!C1t(a))throw new Error("Unsupported resource ledger schema.");return a}catch(r){throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource ledger is unreadable and was not overwritten: ${r instanceof Error?r.message:String(r)}`)}finally{n!==void 0&&nBe(n)}}withLedger(t){let n=Date.now()+5e3,r=new Int32Array(new SharedArrayBuffer(4)),i,o;for(;!i&&Date.now()<=n;)try{i=Eo(this.lockPath,"workflow-resource-governor",he)}catch(s){if(o=s,!(s instanceof Error)||!s.message.includes("is already locked"))break;Atomics.wait(r,0,0,10)}if(!i)throw new cs("WORKFLOW_GOVERNOR_UNAVAILABLE",o instanceof Error?o.message:String(o??"Resource governor lock unavailable."));try{let s=this.now(),a=this.readLedger(s),c=t(a,s);return c.changed&&(a.revision+=1,a.updatedAt=So(s),x1t(this.ledgerPath,a)),c.afterCommit?.(),c.value}finally{i.release()}}}});import{createHash as $1t,randomUUID as B1t}from"node:crypto";import{setTimeout as M1t}from"node:timers/promises";function N1t(){return`delegation-${Date.now().toString(36)}-${B1t().slice(0,8)}`}function O1t(e){return async t=>(await ql({cwd:e.cwd,apiKey:e.apiKey,baseURL:e.baseURL,model:e.model,...e.fallbackModels?{fallbackModels:e.fallbackModels}:{},...e.effort?{effort:e.effort}:{},maxTokens:t.task.maxTokens,maxIterations:t.task.maxIterations,parentSystemPrompt:e.parentSystemPrompt,parentExecutionMode:e.parentExecutionMode,subagentRole:t.task.role,permissionEngine:e.permissionEngine,toolRegistry:e.createToolRegistry?.(),...e.auditLogger?{session:{auditLogger:e.auditLogger}}:{},onIteration:t.onIteration,onToolStart:t.onToolStart,onToolWillExecute:t.onToolWillExecute,onToolEnd:t.onToolEnd})).agent}async function D1t(e){for(;;){if(e.signal?.aborted){e.governor.cancelQueued(e.request.requestId);let n=new Error("Delegated branch admission was cancelled.");throw n.name="AgentInterruptedError",n}let t=e.governor.acquire(e.request);if(t.status==="acquired")return t.permit;if(t.status==="active")throw new cs("WORKFLOW_CONCURRENCY_LIMIT","Delegated branch attempt is already active.");if(t.status==="rejected")throw new cs(t.code,t.reason);if(Date.now()>=e.deadline)throw e.governor.cancelQueued(e.request.requestId),new cs("WORKFLOW_QUEUE_EXPIRED","Delegated branch exceeded its admission deadline.");await M1t(50,void 0,{signal:e.signal})}}function L1t(e,t,n){let r=e.run.bind(e),i=!1,o=a=>{i||(i=!0,t.settle({permitId:n.permitId,fencingToken:n.fencingToken,outcome:a,actualTokens:e.tokenUsage.total}))};e.run=async a=>{try{let c=await r(a);return o("completed"),c}catch(c){throw o(c instanceof Error&&c.name==="AgentInterruptedError"?"cancelled":"failed"),c}};let s=e;if(s.cancelCurrentTurn){let a=s.cancelCurrentTurn.bind(s);s.cancelCurrentTurn=()=>(o("cancelled"),a())}else if(s.cancel){let a=s.cancel.bind(s);s.cancel=()=>(o("cancelled"),a())}return e}async function jR(e){let t=new Zr,n=e.rootTraceId??N1t(),r=Ym(e.model,e.baseURL),i=e.apiKey?GZ({providerId:r,endpoint:e.baseURL,credential:e.apiKey,salt:JZ()}):bI(r,process.env,e.baseURL),o=e.createBranchAgent??O1t(e),s=Date.now()+e.timeoutMs,a=async c=>{let l=c.task,u=`${n}:${l.id}`,d=`${u}:attempt-1`,p=$1t("sha256").update(`${n}\0${l.id}\0${l.prompt}`).digest("hex"),f=await D1t({governor:t,request:{requestId:`admit:${u}:attempt-1`,operationId:u,surface:"delegated-branch",priorityClass:"foreground",runId:n,parentId:n,providerId:r,...i?{credentialFingerprint:i}:{},logicalChildId:u,attemptId:d,idempotencyKey:p,reservedTokens:l.maxTokens,runConcurrencyLimit:e.branchPolicy?.maxConcurrentBranches,runAttemptLimit:e.branchPolicy?.roles?.length,runTokenLimit:e.maxTotalTokens,queueDeadlineAt:new Date(s).toISOString()},deadline:s,signal:l.signal??e.signal});if(!t.claimEffect({permitId:f.permitId,fencingToken:f.fencingToken,effectKey:`delegated:${f.operationId}`}))throw t.settle({permitId:f.permitId,fencingToken:f.fencingToken,outcome:"duplicate_branch_suppressed"}),new cs("WORKFLOW_CONCURRENCY_LIMIT","Duplicate delegated branch execution was suppressed.");try{let m=await o(c);return t.commitEffect({permitId:f.permitId,fencingToken:f.fencingToken,effectKey:`delegated:${f.operationId}`}),L1t(m,t,f)}catch(m){throw t.settle({permitId:f.permitId,fencingToken:f.fencingToken,outcome:"branch_creation_failed"}),m}};if(e.hostDelegation){if(e.createBranchAgent)throw new Error("Host-routed delegation and a local createBranchAgent are mutually exclusive: the branch either executes on the Agent host or in this process. Pass one.");if(typeof e.onToolWillExecute=="function")throw new Error("Host-routed delegation cannot honour onToolWillExecute: it delays tool execution until it resolves, and a branch running on the Agent host does not wait for this process. A hook that cannot delay is not the hook you asked for, so it is refused rather than silently downgraded. Remove it to delegate on the host, or run without host delegation.");if(typeof e.onIteration=="function")throw new Error("Host-routed delegation cannot report onIteration: the host mints no iteration-bearing runtime event, so there is nothing to read \u2014 unlike onToolStart/onToolEnd, which now fire. Remove onIteration to delegate on the host, or run without host delegation.");return R2({...e,rootTraceId:n,createBranchAgent:_$e({...e.hostDelegation,rootTraceId:n,deadline:s,...e.signal===void 0?{}:{signal:e.signal}})})}return R2({...e,rootTraceId:n,createBranchAgent:a})}var aBe=Ie(()=>{"use strict";at();$$e();jp();at()});import{renameSync as Q1t}from"node:fs";function ew(e,t){for(let n=0;;n++)try{Q1t(e,t);return}catch(r){if(n>=10||!["EPERM","EACCES","EBUSY"].includes(r.code??""))throw r;Atomics.wait(F1t,0,0,Math.min(25,(n+1)*5))}}var F1t,kQ=Ie(()=>{"use strict";F1t=new Int32Array(new SharedArrayBuffer(4))});import{closeSync as U1t,fstatSync as q1t,openSync as j1t,readSync as V1t}from"node:fs";function vI(e){let t;try{t=j1t(e,"r")}catch(n){if(n.code==="ENOENT")return{text:"",startOffset:0,endOffset:0,totalBytes:0};throw n}try{let n=q1t(t);if(!n.isFile()||!Number.isSafeInteger(n.size))throw new Error("Output preview requires a regular file of supported size.");let r=n.size,i=Math.max(0,r-H1t),o=Buffer.allocUnsafe(r-i),s=0;for(;s<o.length;){let u=V1t(t,o,s,o.length-s,i+s);if(u===0)throw new Error("Output changed during preview; retry.");s+=u}let a=0;if(i>0)for(;a<Math.min(3,o.length)&&(o[a]&192)===128;)a++;let c=i+a,l;try{l=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:l,startOffset:c,endOffset:c+Buffer.byteLength(l,"utf8"),totalBytes:r}}finally{U1t(t)}}var H1t,EQ=Ie(()=>{"use strict";H1t=64*1024});import*as oc from"node:fs/promises";import*as Zm from"node:path";import{homedir as Z1t,platform as e$t,release as t$t}from"node:os";import{spawnSync as o$t}from"node:child_process";async function W1t(e){await oc.mkdir(e,{recursive:!0})}async function ei(e,t){let n=Zm.dirname(e);await W1t(n);let r=Math.random().toString(36).substring(2,15),i=`${e}.tmp.${process.pid}.${r}`;try{await oc.writeFile(i,t),await X1t(i,e)}finally{try{await oc.unlink(i)}catch{}}}async function X1t(e,t){for(let n=0;;n+=1)try{await oc.rename(e,t);return}catch(r){let i=r.code,o=J1t[n];if(process.platform!=="win32"||!i||!G1t.has(i)||o===void 0)throw r;await new Promise(s=>setTimeout(s,o))}}function lBe(e,t){try{return JSON.parse(e)}catch{return t}}function zZ(e){let t=z1t(e);return{frontmatter:t.frontmatter,content:t.content.trim()}}function z1t(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return{frontmatter:{},content:e};let n=t.search(/\r?\n/);if(n<0||t.slice(0,n).trim()!=="---")return{frontmatter:{},content:e};let r=t.slice(n+(t[n]==="\r"?2:1)),i=r.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!i||i.index===void 0)throw new Error("YAML frontmatter is not closed.");let o=r.slice(0,i.index),s=i[0],a=i.index+s.length;return{frontmatter:uBe(o),content:r.slice(a)}}function uBe(e){let t={},n=e.split(/\r?\n/);for(let r=0;r<n.length;r+=1){let i=n[r];if(!i.trim()||i.trimStart().startsWith("#"))continue;if(/^\s/.test(i))throw new Error(`Unexpected indentation at line ${r+1}.`);let o=K1t(i,r+1);if(o.key==="<<")throw new Error("YAML merge keys are not supported.");if(o.value!==""){t[o.key]=dBe(o.value,r+1);continue}let s=Y1t(n,r+1);t[o.key]=s.value,r=s.nextIndex-1}return t}function Y1t(e,t){let n=[],r=t;for(;r<e.length;r+=1){let o=e[r];if(!o.trim()){n.push(o);continue}if(!/^\s/.test(o))break;n.push(o.replace(/^ {2}/,""))}let i=n.filter(o=>o.trim()&&!o.trimStart().startsWith("#"));return i.length===0?{value:{},nextIndex:r}:i.every(o=>o.trimStart().startsWith("- "))?{value:i.map((o,s)=>dBe(o.trimStart().slice(2),t+s+1)),nextIndex:r}:{value:uBe(n.join(`
|
|
@@ -2946,7 +2946,7 @@ foreach ($id in $ids) {
|
|
|
2946
2946
|
`),a=s.length===0?[]:s.split(`
|
|
2947
2947
|
`);if(a.length>o)throw new Ta(`Unified diff exceeds ${o} lines`);let c=[],l,u=0,d=(m,h)=>{if(l&&nOe(l,c),c.length>=r)throw new Ta(`Unified diff exceeds ${r} files`);return l={oldPath:m,newPath:h,status:"modified",binary:!1,headerLines:[],hunks:[]},l};for(let m=0;m<a.length;m+=1){let h=a[m];if(h.startsWith("diff --git ")){let[g,A]=kLt(h.slice(11),m+1);d(g,A).headerLines.push(h);continue}if(h.startsWith("--- ")){(!l||l.hunks.length>0)&&(l=d()),l.oldPath=rOe(h.slice(4)),l.headerLines.push(h);continue}if(h.startsWith("+++ ")){l||(l=d()),l.newPath=rOe(h.slice(4)),l.headerLines.push(h);continue}if(h.startsWith("@@ ")){if(!l)throw new Ta("Hunk appears before a file header",m+1);if(u>=i)throw new Ta(`Unified diff exceeds ${i} hunks`,m+1);let g=ILt.exec(h);if(!g)throw new Ta("Malformed unified diff hunk header",m+1);let A=Number(g[1]),y=g[2]===void 0?1:Number(g[2]),w=Number(g[3]),b=g[4]===void 0?1:Number(g[4]),I=[],v=A,k=w,R=0,x=0,C=m+1;for(;C<a.length;C+=1){let D=a[C],V=v-A===y,B=k-w===b;if(V&&B&&D.length===0||D.startsWith("diff --git ")||D.startsWith("@@ ")||D.startsWith("--- ")&&a[C+1]?.startsWith("+++ "))break;if(D.startsWith("+"))I.push({kind:"addition",text:D.slice(1),newLine:k}),k+=1,R+=1;else if(D.startsWith("-"))I.push({kind:"deletion",text:D.slice(1),oldLine:v}),v+=1,x+=1;else if(D.startsWith(" "))I.push({kind:"context",text:D.slice(1),oldLine:v,newLine:k}),v+=1,k+=1;else if(D==="\")I.push({kind:"no-newline",text:D});else{if(D.length===0&&C===a.length-1)break;throw new Ta("Unexpected line inside unified diff hunk",C+1)}}let P=I.filter(D=>D.kind==="context"||D.kind==="deletion").length,N=I.filter(D=>D.kind==="context"||D.kind==="addition").length;if(P!==y||N!==b)throw new Ta(`Hunk line counts do not match header (expected -${y}/+${b}, observed -${P}/+${N})`,m+1);let $=h,_=Lr(JSON.stringify({oldPath:l.oldPath??null,newPath:l.newPath??null,header:$,lines:I})).value.slice(0,32);l.hunks.push({hunkId:_,header:$,...g[5]?{section:g[5]}:{},oldStart:A,oldLines:y,newStart:w,newLines:b,additions:R,deletions:x,lines:I}),u+=1,m=C-1;continue}if(!l){if(h.trim().length===0)continue;throw new Ta("Content appears before the first diff file header",m+1)}l.headerLines.push(h),h.startsWith("new file mode ")?l.status="added":h.startsWith("deleted file mode ")?l.status="deleted":h.startsWith("rename from ")?(l.status="renamed",l.oldPath=Aw(h.slice(12))):h.startsWith("rename to ")?(l.status="renamed",l.newPath=Aw(h.slice(10))):h.startsWith("copy from ")?(l.status="copied",l.oldPath=Aw(h.slice(10))):h.startsWith("copy to ")?(l.status="copied",l.newPath=Aw(h.slice(8))):(h.startsWith("Binary files ")||h==="GIT binary patch")&&(l.binary=!0,l.status="binary")}l&&nOe(l,c);let p=c.reduce((m,h)=>m+h.additions,0),f=c.reduce((m,h)=>m+h.deletions,0);return{schemaVersion:1,mode:t.mode??"working-tree",...t.repositoryId?{repositoryId:t.repositoryId}:{},...t.baseRef?{baseRef:t.baseRef}:{},...t.headRef?{headRef:t.headRef}:{},files:c,additions:p,deletions:f,rawDiff:s}}function OF(e,t){let n=xOe(e,{mode:t.mode,repositoryId:t.repositoryId,baseRef:t.baseRef,headRef:t.headRef}),r=n,i=pc(r),o=[t.identity?.runId,t.identity?.turnId,t.identity?.taskId,t.repositoryId,t.mode].filter(Boolean).join(":"),s=t.kind??"diff",a=t.artifactId??`${s}_${Lr(`${o}:${n.rawDiff}`).value.slice(0,24)}`,c=t.revision??1,l={schemaVersion:1,artifactId:a,revision:c,kind:s,title:t.title??`${CLt(n.mode)} diff (${n.files.length} files)`,...t.description?{description:t.description}:{},state:"pending_review",createdAt:t.createdAt??new Date().toISOString(),mediaType:`application/vnd.xeno.${s}+json`,sensitivity:t.sensitivity??"internal",...t.identity?{identity:structuredClone(t.identity)}:{},content:{hash:Iw(r),sizeBytes:COe.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i},redactedPreview:`${n.files.length} files, +${n.additions}/-${n.deletions}`},provenance:{producer:{...t.producer}},anchors:n.files.flatMap(u=>[{kind:"file",path:u.displayPath,...t.repositoryId?{repositoryId:t.repositoryId}:{}},...u.hunks.map(d=>({kind:"diff-hunk",path:u.displayPath,hunkId:d.hunkId,artifactId:a,revision:c}))]),...c>1?{predecessorRevision:t.predecessorRevision??c-1}:{},...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.diff.mode":n.mode,"xeno.diff.files":n.files.length,"xeno.diff.additions":n.additions,"xeno.diff.deletions":n.deletions}};return mh(l),l}function hh(e){if(mh(e),e.kind!=="diff"&&e.kind!=="patch")throw new TypeError("Artifact is not a diff or patch");if(e.content.storage.type!=="inline"||typeof e.content.storage.text!="string")throw new TypeError("Diff artifact content is not available inline");let t;try{t=JSON.parse(e.content.storage.text)}catch(r){throw new Ta(`Diff artifact JSON is malformed: ${xLt(r).message}`)}if(!SLt(t))throw new Ta("Diff artifact document is invalid");let n=xOe(t.rawDiff,{mode:t.mode,repositoryId:t.repositoryId,baseRef:t.baseRef,headRef:t.headRef});if(pc(n)!==pc(t))throw new Ta("Diff artifact document does not match its raw diff");return n}function nOe(e,t){if(!e.oldPath&&!e.newPath)throw new Ta("Diff file has no path");e.oldPath||(e.status="added"),e.newPath||(e.status="deleted"),e.binary&&(e.status="binary");let n=e.hunks.reduce((i,o)=>i+o.additions,0),r=e.hunks.reduce((i,o)=>i+o.deletions,0);t.push({...e.oldPath?{oldPath:e.oldPath}:{},...e.newPath?{newPath:e.newPath}:{},displayPath:e.newPath??e.oldPath,status:e.status,additions:n,deletions:r,binary:e.binary,headerLines:[...e.headerLines],hunks:structuredClone(e.hunks)})}function kLt(e,t){let n=ELt(e);if(n.length!==2)throw new Ta("Malformed diff --git path pair",t);return[Aw(n[0]),Aw(n[1])]}function ELt(e){let t=[],n=0;for(;n<e.length;){for(;e[n]===" ";)n+=1;if(n>=e.length)break;if(e[n]==='"'){let r='"';n+=1;let i=!1;for(;n<e.length;){let o=e[n];if(r+=o,n+=1,!i&&o==='"')break;i=!i&&o==="\\",o!=="\\"&&(i=!1)}t.push(ROe(r))}else{let r=e.indexOf(" ",n);if(r===-1){t.push(e.slice(n));break}t.push(e.slice(n,r)),n=r+1}}return t}function ROe(e){return!e.startsWith('"')||!e.endsWith('"')?e:e.slice(1,-1).replace(/\\([\\"tnr]|[0-7]{1,3})/g,(t,n)=>n==="t"?" ":n==="n"?`
|
|
2948
2948
|
`:n==="r"?"\r":n==="\\"?"\\":n==='"'?'"':String.fromCharCode(Number.parseInt(n,8)))}function rOe(e){let t=e.split(" ",1)[0].trim();if(t!=="/dev/null")return Aw(ROe(t))}function Aw(e){let t=e.replace(/\\/g,"/");return t.startsWith("a/")||t.startsWith("b/")?t.slice(2):t}function SLt(e){return!iOe(e)||e.schemaVersion!==1||!["working-tree","staged","turn","commit","preview"].includes(String(e.mode))||!Array.isArray(e.files)||!Number.isSafeInteger(e.additions)||!Number.isSafeInteger(e.deletions)||typeof e.rawDiff!="string"?!1:e.files.every(t=>iOe(t)&&typeof t.displayPath=="string"&&Array.isArray(t.headerLines)&&Array.isArray(t.hunks))}function iOe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function RF(e,t,n,r,i){if(e===void 0)return t;if(!Number.isInteger(e)||e<n||e>r)throw new TypeError(`${i} must be an integer between ${n} and ${r}`);return e}function CLt(e){return e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" ")}function xLt(e){return e instanceof Error?e:new Error(String(e))}function oOe(e,t){if((t.line!==void 0||t.hunkId!==void 0)&&!t.file)throw ef("Line and hunk anchors require a file");if(t.line!==void 0&&t.hunkId!==void 0)throw ef("Line and hunk anchors cannot be combined");if(!t.file)return;let n=TLt(t.file);if(t.line!==void 0&&(!Number.isInteger(t.line)||t.line<1))throw ef("Review line must be a positive integer");if(e.artifact.kind==="diff"||e.artifact.kind==="patch"){let r=hh(e.artifact).files.find(i=>i.displayPath===n);if(!r)throw ef(`File ${n} is not present in this artifact`);if(t.hunkId&&!r.hunks.some(i=>i.hunkId===t.hunkId))throw ef(`Hunk ${t.hunkId} is not present in ${n}`)}return t.hunkId?{kind:"diff-hunk",path:n,hunkId:_F(t.hunkId,"Hunk ID"),artifactId:e.artifact.artifactId,revision:e.artifact.revision}:t.line!==void 0?{kind:"source-line",path:n,startLine:t.line}:{kind:"file",path:n}}function TLt(e){let t=DF(e,"Artifact review file",4096).replace(/\\/g,"/").replace(/^\.\//,"");if(t.startsWith("../")||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").some(n=>n===".."||n.length===0))throw ef("Artifact review file anchors must be repository-relative paths");return t}function DF(e,t,n){let r=typeof e=="string"?e.trim():"";if(!r)throw ef(`${t} cannot be empty`);if(r.length>n)throw ef(`${t} exceeds ${n} characters`);return r}function sOe(e,t,n){if(e!==void 0)return DF(e,t,n)}function _F(e,t){let n=DF(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(n))throw ef(`${t} contains unsupported characters`);return n}function PLt(e,t){return e===void 0?void 0:_F(e,t)}function ef(e){return new St("ARTIFACT_REVIEW_INVALID",e)}function ww(e){let t=MLt(e,"specId");return{plan:`spec_${t}_plan`,requirements:`spec_${t}_requirements`,design:`spec_${t}_design`,taskGraph:`spec_${t}_task_graph`}}function $Lt(e){let t=[];e?.schemaVersion!==yw&&t.push(`schemaVersion must be ${yw}`),JT(e?.specId,"specId",t),(!Number.isInteger(e?.revision)||e.revision<1)&&t.push("revision must be a positive integer"),Jl(e?.title,"title",t),Jl(e?.problem,"problem",t),BF(e?.createdAt,"createdAt",t),BF(e?.updatedAt,"updatedAt",t),e?.predecessorRevision!==void 0&&(!Number.isInteger(e.predecessorRevision)||e.predecessorRevision!==e.revision-1)&&t.push("predecessorRevision must be the immediately preceding revision");let n=TF(e?.requirements,"requirement",t),r=TF(e?.tasks,"task",t),i=new Set,o=[...Array.isArray(e?.acceptanceCriteria)?e.acceptanceCriteria:[],...Array.isArray(e?.requirements)?e.requirements.flatMap(c=>Array.isArray(c.acceptanceCriteria)?c.acceptanceCriteria:[]):[]];for(let c of o){JT(c?.id,"acceptance criterion id",t),Jl(c?.text,`acceptance criterion ${c?.id??"?"}`,t),i.has(c?.id)&&t.push(`Duplicate acceptance criterion: ${c?.id}`),i.add(c?.id);for(let l of c?.requiredEvidenceKinds??[])JT(l,"required evidence kind",t)}for(let c of e?.requirements??[])Jl(c?.text,`requirement ${c?.id??"?"}`,t),["must","should","could"].includes(c?.priority)||t.push(`Requirement ${c?.id??"?"} has invalid priority`),(!Array.isArray(c?.acceptanceCriteria)||c.acceptanceCriteria.length===0)&&t.push(`Requirement ${c?.id??"?"} needs at least one acceptance criterion`);Jl(e?.design?.summary,"design summary",t);let s=TF(e?.design?.decisions,"design decision",t),a=TF(e?.design?.risks,"risk",t);for(let c of e?.design?.decisions??[]){Jl(c?.decision,`design decision ${c?.id??"?"}`,t),Jl(c?.rationale,`design rationale ${c?.id??"?"}`,t);for(let l of c?.requirementIds??[])n.has(l)||t.push(`Design decision ${c.id} references unknown requirement ${l}`)}for(let c of e?.design?.risks??[])Jl(c?.description,`risk ${c?.id??"?"}`,t),Jl(c?.mitigation,`risk mitigation ${c?.id??"?"}`,t),["low","medium","high","critical"].includes(c?.impact)||t.push(`Risk ${c?.id??"?"} has invalid impact`);for(let c of e?.tasks??[]){Jl(c?.title,`task title ${c?.id??"?"}`,t),Jl(c?.description,`task description ${c?.id??"?"}`,t);for(let l of c?.dependsOn??[])r.has(l)||t.push(`Task ${c.id} depends on unknown task ${l}`),l===c.id&&t.push(`Task ${c.id} cannot depend on itself`);for(let l of c?.requirementIds??[])n.has(l)||t.push(`Task ${c.id} references unknown requirement ${l}`);for(let l of c?.acceptanceCriterionIds??[])i.has(l)||t.push(`Task ${c.id} references unknown acceptance criterion ${l}`);for(let l of c?.expectedPaths??[])$Oe(l)||t.push(`Task ${c.id} has unsafe expected path ${l}`)}return NLt(e?.tasks??[])&&t.push("Task dependency graph contains a cycle"),[...new Set(t)]}function $ee(e){let t=$Lt(e);if(t.length>0)throw new Ys(t)}function aOe(e,t){$ee(e);let n=ww(e.specId),r=e.revision,i={...t,createdAt:e.updatedAt,state:"draft"},o=HT({artifactId:n.requirements,revision:r,predecessorRevision:e.predecessorRevision,kind:"requirements",title:`${e.title} - requirements`,value:{schemaVersion:yw,specId:e.specId,revision:r,problem:e.problem,requirements:e.requirements,acceptanceCriteria:e.acceptanceCriteria},context:i}),s=HT({artifactId:n.design,revision:r,predecessorRevision:e.predecessorRevision,kind:"design",title:`${e.title} - design`,value:{schemaVersion:yw,specId:e.specId,revision:r,design:e.design,...e.sourceBaseline?{sourceBaseline:e.sourceBaseline}:{}},context:i}),a=HT({artifactId:n.taskGraph,revision:r,predecessorRevision:e.predecessorRevision,kind:"task-graph",title:`${e.title} - task graph`,value:{schemaVersion:yw,specId:e.specId,revision:r,tasks:e.tasks},context:i}),c=[o,s,a].map(u=>({relation:"decomposes",target:{type:"artifact",id:u.artifactId,revision:u.revision}})),l=HT({artifactId:n.plan,revision:r,predecessorRevision:e.predecessorRevision,kind:"plan",title:e.title,description:e.problem,value:e,context:{...t,createdAt:e.updatedAt,state:"pending_review"},relationships:c,extensions:{"xeno.spec.id":e.specId,"xeno.spec.revision":e.revision,"xeno.spec.requirements_hash":o.content.hash.value,"xeno.spec.design_hash":s.content.hash.value,"xeno.spec.task_graph_hash":a.content.hash.value}});return{document:structuredClone(e),plan:l,requirements:o,design:s,taskGraph:a}}function bw(e){if(e.kind!=="plan"||e.mediaType!=="application/vnd.xeno.spec+json")throw new Ys([`Artifact ${e.artifactId} is not a XENO spec plan`]);let t=_Oe(e);if($ee(t),t.revision!==e.revision)throw new Ys(["Spec and artifact revisions differ"]);if(!XT(Iw(t),e.content.hash))throw new Ys(["Spec artifact content hash is invalid"]);return structuredClone(t)}function cOe(e,t,n=1,r){let i=structuredClone(e);return HT({artifactId:e.executionId,revision:n,predecessorRevision:r,kind:"custom:xeno.spec-execution",title:`Execution of ${e.specId} revision ${e.specRevision}`,description:`Execution state: ${e.state}`,value:i,context:{...t,createdAt:e.updatedAt,state:e.state==="completed"?"pending_review":"draft"},relationships:[{relation:"implements",target:{type:"artifact",id:e.planArtifactId,revision:e.specRevision}}],extensions:{"xeno.spec.execution_state":e.state,"xeno.spec.plan_hash":e.planHash.value}})}function YT(e){if(e.kind!=="custom:xeno.spec-execution")throw new Ys([`Artifact ${e.artifactId} is not a spec execution`]);let t=_Oe(e);if(t.schemaVersion!==$F||t.executionId!==e.artifactId)throw new Ys(["Spec execution identity or schema is invalid"]);if(!XT(Iw(t),e.content.hash))throw new Ys(["Spec execution content hash is invalid"]);return structuredClone(t)}function TOe(e,t){let n=[];e.schemaVersion!==$F&&n.push("Execution schema is invalid"),(e.specId!==t.specId||e.specRevision!==t.revision)&&n.push("Execution is bound to the wrong spec revision");let r=new Map(t.tasks.map(o=>[o.id,o])),i=new Set;for(let o of e.tasks){i.has(o.taskId)&&n.push(`Duplicate execution task ${o.taskId}`),i.add(o.taskId);let s=r.get(o.taskId);if(!s){n.push(`Unknown execution task ${o.taskId}`);continue}for(let a of s.acceptanceCriterionIds)Array.isArray(o.acceptanceEvidence?.[a])||n.push(`Task ${o.taskId} is missing acceptance evidence slot ${a}`)}for(let o of r.keys())i.has(o)||n.push(`Execution is missing task ${o}`);for(let o of e.observedPaths)OLt(o)||n.push(`Unsafe observed path ${o}`);if(BF(e.createdAt,"execution createdAt",n),BF(e.updatedAt,"execution updatedAt",n),n.length>0)throw new Ys([...new Set(n)])}function POe(e,t,n,r,i=new Date().toISOString()){$ee(e),TOe(n,e);let o=[];(!XT(t,r)||!XT(n.planHash,r))&&o.push({code:"PLAN_HASH_MISMATCH",severity:"error",message:"Execution is not bound to the approved plan content hash"});let s=new Map(e.tasks.map(l=>[l.id,l])),a=new Map(n.tasks.map(l=>[l.taskId,l]));for(let l of n.tasks){let u=s.get(l.taskId);if(!u){o.push({code:"UNKNOWN_TASK",severity:"error",taskId:l.taskId,message:`Unknown task ${l.taskId}`});continue}if(l.status==="completed"){l.evidence.length===0&&o.push({code:"MISSING_TASK_EVIDENCE",severity:"error",taskId:u.id,message:`Completed task ${u.id} has no evidence`});for(let d of u.dependsOn??[])a.get(d)?.status!=="completed"&&o.push({code:"DEPENDENCY_INCOMPLETE",severity:"error",taskId:u.id,message:`Task ${u.id} completed before dependency ${d}`});for(let d of u.acceptanceCriterionIds)(l.acceptanceEvidence[d]??[]).length===0&&o.push({code:"MISSING_ACCEPTANCE_EVIDENCE",severity:"error",taskId:u.id,criterionId:d,message:`Completed task ${u.id} has no evidence for ${d}`})}}let c=e.tasks.flatMap(l=>l.expectedPaths??[]);for(let l of n.observedPaths)c.some(u=>DLt(l,u))||o.push({code:"UNKNOWN_PATH",severity:"warning",path:l,message:`Observed path ${l} is outside the approved task plan`});return{schemaVersion:"xeno.spec-drift.v1",specId:e.specId,specRevision:e.revision,executionId:n.executionId,checkedAt:i,drifted:o.length>0,findings:o}}function HT(e){let t=e.value,n=pc(t);return{schemaVersion:1,artifactId:e.artifactId,revision:e.revision,kind:e.kind,title:e.title,...e.description?{description:e.description}:{},state:e.context.state,createdAt:e.context.createdAt??new Date().toISOString(),mediaType:BLt(e.kind),sensitivity:e.context.sensitivity??"internal",...e.context.identity?{identity:structuredClone(e.context.identity)}:{},content:{hash:Iw(t),sizeBytes:Buffer.byteLength(n,"utf8"),encoding:"utf8",storage:{type:"inline",text:n},redactedPreview:e.title},provenance:{producer:structuredClone(e.context.producer)},...e.relationships?.length?{relationships:structuredClone(e.relationships)}:{},...e.predecessorRevision!==void 0?{predecessorRevision:e.predecessorRevision}:{},...e.context.accessPolicyId?{accessPolicyId:e.context.accessPolicyId}:{},...e.extensions?{extensions:structuredClone(e.extensions)}:{}}}function BLt(e){return e==="plan"?"application/vnd.xeno.spec+json":e==="custom:xeno.spec-execution"?"application/vnd.xeno.spec-execution+json":`application/vnd.xeno.spec-${e}+json`}function _Oe(e){let t=e.content.storage;if(t.type!=="inline"||typeof t.text!="string")throw new Ys(["Spec artifacts require inline JSON content"]);try{return JSON.parse(t.text)}catch(n){throw new Ys([`Spec artifact JSON is invalid: ${n instanceof Error?n.message:String(n)}`])}}function TF(e,t,n){let r=new Set;(!Array.isArray(e)||e.length===0)&&n.push(`${t} list cannot be empty`);for(let i of e??[])JT(i?.id,`${t} id`,n),r.has(i?.id??"")&&n.push(`Duplicate ${t}: ${i?.id}`),i?.id&&r.add(i.id);return r}function JT(e,t,n){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(e))&&n.push(`${t} must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}`)}function Jl(e,t,n){(typeof e!="string"||e.trim().length===0||e.length>64*1024)&&n.push(`${t} must be non-empty and no longer than 65536 characters`)}function BF(e,t,n){(typeof e!="string"||!e.includes("T")||!Number.isFinite(Date.parse(e)))&&n.push(`${t} must be an ISO 8601 timestamp`)}function MLt(e,t){let n=[];if(JT(e,t,n),n.length>0)throw new Ys(n);return e}function NLt(e){let t=new Map(e.map(o=>[o.id,o])),n=new Set,r=new Set,i=o=>{if(n.has(o))return!0;if(r.has(o))return!1;n.add(o);for(let s of t.get(o)?.dependsOn??[])if(i(s))return!0;return n.delete(o),r.add(o),!1};return e.some(o=>i(o.id))}function $Oe(e){let t=e.replace(/\\/gu,"/");return t.length>0&&t.length<=4096&&!t.startsWith("/")&&!/^[A-Za-z]:/u.test(t)&&!t.split("/").includes("..")}function OLt(e){return $Oe(e)&&!e.includes("*")}function DLt(e,t){let n=e.replace(/\\/gu,"/"),r=t.replace(/\\/gu,"/");if(r.endsWith("/**")){let i=r.slice(0,-3).replace(/\/$/u,"");return n===i||n.startsWith(`${i}/`)}if(r.endsWith("/*")){let i=r.slice(0,-2).replace(/\/$/u,""),o=n.startsWith(`${i}/`)?n.slice(i.length+1):"";return o.length>0&&!o.includes("/")}return n===r}function XT(e,t){return e.algorithm===t.algorithm&&e.value===t.value}function NOe(e="xeno-production-review"){return{schemaVersion:"xeno.review-pack.v1",packId:e,version:"1.0.0",dimensions:["correctness","security","performance","api","tests","documentation"],verifierCount:1,minimumVerifierReproductions:1,allowIndependentEvidenceVerification:!1,minimumIndependentEvidenceProducers:2,maxFindings:256}}function OOe(e){let t=[];e?.schemaVersion!=="xeno.review-pack.v1"&&t.push("Review pack schemaVersion must be xeno.review-pack.v1"),Xl(e?.packId,"packId",t),(typeof e?.version!="string"||!/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/u.test(e.version))&&t.push("Review pack version must be semantic version text"),(!Array.isArray(e?.dimensions)||e.dimensions.length===0)&&t.push("Review pack needs at least one dimension"),new Set(e?.dimensions??[]).size!==(e?.dimensions??[]).length&&t.push("Review pack dimensions must be unique");for(let n of e?.dimensions??[])WOe(n)||t.push(`Invalid review dimension ${n}`);if((!Number.isInteger(e?.verifierCount)||e.verifierCount<0||e.verifierCount>8)&&t.push("verifierCount must be 0 through 8"),(!Number.isInteger(e?.minimumVerifierReproductions)||e.minimumVerifierReproductions<1||e.minimumVerifierReproductions>Math.max(1,e.verifierCount))&&t.push("minimumVerifierReproductions must be positive and no greater than verifierCount"),(!Number.isInteger(e?.minimumIndependentEvidenceProducers)||e.minimumIndependentEvidenceProducers<2)&&t.push("minimumIndependentEvidenceProducers must be at least 2"),(!Number.isInteger(e?.maxFindings)||e.maxFindings<1||e.maxFindings>2048)&&t.push("maxFindings must be 1 through 2048"),t.length>0)throw new zl(t)}function DOe(e){let t=[];if(Xl(e?.artifactId,"target artifactId",t),(!Number.isInteger(e?.revision)||e.revision<1)&&t.push("Target revision must be positive"),vw(e?.title,"target title",t),(e?.contentHash?.algorithm!=="sha256"||!/^[a-f0-9]{64}$/u.test(e?.contentHash?.value??""))&&t.push("Target contentHash must be lowercase sha256"),t.length>0)throw new zl(t)}function LOe(e){let t=[];e?.schemaVersion!==BOe&&t.push("Review report schemaVersion is invalid"),Xl(e?.reportId,"reportId",t),Xl(e?.runId,"runId",t),NF(e?.startedAt,"startedAt",t),NF(e?.completedAt,"completedAt",t),Date.parse(e?.completedAt)<Date.parse(e?.startedAt)&&t.push("completedAt cannot precede startedAt");try{OOe(e.pack)}catch(o){t.push(o instanceof Error?o.message:String(o))}try{DOe(e.target)}catch(o){t.push(o instanceof Error?o.message:String(o))}let n=new Set,r=new Set;for(let o of e?.findings??[])Xl(o?.findingId,"findingId",t),n.has(o.findingId)&&t.push(`Duplicate findingId ${o.findingId}`),n.add(o.findingId),/^[a-f0-9]{64}$/u.test(o?.fingerprint??"")||t.push(`Finding ${o.findingId} has invalid fingerprint`),r.has(o.fingerprint)&&t.push(`Duplicate finding fingerprint ${o.fingerprint}`),r.add(o.fingerprint),vw(o?.title,`finding ${o.findingId} title`,t),vw(o?.summary,`finding ${o.findingId} summary`,t),HOe(o?.severity)||t.push(`Finding ${o.findingId} has invalid severity`),(!Number.isFinite(o?.confidence)||o.confidence<0||o.confidence>1)&&t.push(`Finding ${o.findingId} has invalid confidence`),o?.state==="verified"&&o.verificationBasis==="none"&&t.push(`Finding ${o.findingId} cannot be verified without a basis`),o?.state!=="verified"&&o.verificationBasis==="independent-evidence"&&t.push(`Finding ${o.findingId} has inconsistent evidence verification`);let i=VOe(e?.findings??[]);if((i.total!==e?.summary?.total||i.verified!==e?.summary?.verified||i.unverified!==e?.summary?.unverified||i.rejected!==e?.summary?.rejected||Object.keys(i.bySeverity).some(o=>i.bySeverity[o]!==e?.summary?.bySeverity?.[o]))&&t.push("Review report summary is inconsistent"),t.length>0)throw new zl([...new Set(t)])}function QOe(e,t){LOe(e);let n=e,r=pc(n),i=t.artifactId??`review_${Lr(`${e.runId}:${e.target.artifactId}:${e.target.contentHash.value}`).value.slice(0,24)}`,o={schemaVersion:1,artifactId:i,revision:1,kind:"review-report",title:`Review of ${e.target.title}`,description:`${e.summary.verified} verified, ${e.summary.unverified} unverified, ${e.summary.rejected} rejected findings`,state:"pending_review",createdAt:t.createdAt??e.completedAt,mediaType:"application/vnd.xeno.review-report+json",sensitivity:t.sensitivity??"internal",...t.identity?{identity:structuredClone(t.identity)}:{},content:{hash:Iw(n),sizeBytes:Buffer.byteLength(r,"utf8"),encoding:"utf8",storage:{type:"inline",text:r},redactedPreview:`${e.summary.total} findings; ${e.summary.verified} verified`},provenance:{producer:structuredClone(t.producer),sourceArtifactIds:[e.target.artifactId],attributes:{reviewPackId:e.pack.packId,reviewPackVersion:e.pack.version}},relationships:[{relation:"reviews",target:{type:"artifact",id:e.target.artifactId,revision:e.target.revision}}],anchors:qOe(e.findings.flatMap(s=>s.anchors)),...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.review.pack":e.pack.packId,"xeno.review.verified":e.summary.verified,"xeno.review.unverified":e.summary.unverified,"xeno.review.rejected":e.summary.rejected}};return mh(o),o}function ULt(e,t){let n=new Map;for(let r of e){FOe(r.finding),MF(r.reviewerAgentId,"reviewerAgentId");let i=qLt(r.finding),o=n.get(i)??[];o.push(structuredClone(r)),n.set(i,o)}return[...n.entries()].map(([r,i])=>{let o=[...i].sort((a,c)=>HI(c.finding.severity)-HI(a.finding.severity))[0],s=UOe(i.flatMap(a=>a.finding.evidence));return{findingId:MF(t("finding"),"findingId"),fingerprint:r,ruleIds:[...new Set(i.flatMap(a=>a.finding.ruleId?[a.finding.ruleId]:[]))].sort(),dimensions:[...new Set(i.map(a=>a.finding.dimension))].sort(),reviewerAgentIds:[...new Set(i.map(a=>a.reviewerAgentId))].sort(),title:o.finding.title,summary:o.finding.summary,severity:i.reduce((a,c)=>HI(c.finding.severity)>HI(a)?c.finding.severity:a,o.finding.severity),confidence:GOe(Math.max(...i.map(a=>a.finding.confidence))),state:"unverified",verificationBasis:"none",anchors:qOe(i.flatMap(a=>a.finding.anchors)),evidence:s,verifications:[],...o.finding.remediation?{remediation:o.finding.remediation}:{},duplicateProposalCount:i.length}})}function qLt(e){let t=e.anchors.map(jOe).sort();return Iw({ruleId:e.ruleId??"",title:GLt(e.title),anchors:t}).value}function jLt(e,t,n){let r=[];Xl(e?.reviewerAgentId,"reviewerAgentId",r),e?.dimension!==t&&r.push(`Reviewer returned dimension ${e?.dimension} for requested ${t}`),NF(e?.completedAt,"reviewer completedAt",r),(!Array.isArray(e?.findings)||e.findings.length>n)&&r.push("Reviewer finding list is invalid or exceeds maxFindings");for(let i of e?.findings??[]){try{FOe(i)}catch(o){r.push(o instanceof Error?o.message:String(o))}i.dimension!==t&&r.push(`Finding dimension ${i.dimension} differs from reviewer dimension ${t}`)}if(r.length>0)throw new zl([...new Set(r)])}function FOe(e){let t=[];WOe(e?.dimension)||t.push(`Invalid finding dimension ${e?.dimension}`),vw(e?.title,"finding title",t),vw(e?.summary,"finding summary",t),HOe(e?.severity)||t.push(`Invalid finding severity ${e?.severity}`),(!Number.isFinite(e?.confidence)||e.confidence<0||e.confidence>1)&&t.push("Finding confidence must be 0 through 1"),(!Array.isArray(e?.anchors)||e.anchors.length===0)&&t.push("Finding needs at least one source or artifact anchor"),Array.isArray(e?.evidence)||t.push("Finding evidence must be an array");for(let n of e?.evidence??[])Bee(n,t);if(e?.ruleId!==void 0&&Xl(e.ruleId,"ruleId",t),t.length>0)throw new zl([...new Set(t)])}function VLt(e){let t=[];Xl(e?.verifierAgentId,"verifierAgentId",t),["reproduced","rejected","inconclusive"].includes(e?.outcome)||t.push("Verifier outcome is invalid"),vw(e?.rationale,"verifier rationale",t),NF(e?.completedAt,"verifier completedAt",t),Array.isArray(e?.evidence)||t.push("Verifier evidence must be an array");for(let n of e?.evidence??[])Bee(n,t);if(e?.outcome==="reproduced"&&(e?.evidence?.length??0)===0&&t.push("A reproduced finding requires verifier evidence"),e?.confidence!==void 0&&(!Number.isFinite(e.confidence)||e.confidence<0||e.confidence>1)&&t.push("Verifier confidence must be 0 through 1"),t.length>0)throw new zl([...new Set(t)])}function Bee(e,t){Xl(e?.evidenceId,"evidenceId",t),Xl(e?.producerId,"evidence producerId",t),vw(e?.summary,"evidence summary",t),(typeof e?.kind!="string"||!(FLt.includes(e.kind)||Pee(e.kind)))&&t.push(`Invalid evidence kind ${e?.kind}`)}function UOe(e){let t=new Map;for(let n of e){let r=[];if(Bee(n,r),r.length>0)throw new zl(r);let i=t.get(n.evidenceId);if(i&&pc(i)!==pc(n))throw new zl([`Conflicting evidence ID ${n.evidenceId}`]);t.set(n.evidenceId,structuredClone(n))}return[...t.values()].sort((n,r)=>n.evidenceId.localeCompare(r.evidenceId))}function HLt(e){let t=new Map;for(let n of e){if(t.has(n.verifierAgentId))throw new zl([`Verifier ${n.verifierAgentId} returned more than one result for a finding`]);t.set(n.verifierAgentId,structuredClone(n))}return[...t.values()].sort((n,r)=>n.verifierAgentId.localeCompare(r.verifierAgentId))}function qOe(e){let t=new Map;for(let n of e)t.set(jOe(n),structuredClone(n));return[...t.entries()].sort(([n],[r])=>n.localeCompare(r)).map(([,n])=>n)}function jOe(e){return pc(e)}function VOe(e){let t={info:0,low:0,medium:0,high:0,critical:0};for(let n of e)t[n.severity]+=1;return{total:e.length,verified:e.filter(n=>n.state==="verified").length,unverified:e.filter(n=>n.state==="unverified").length,rejected:e.filter(n=>n.state==="rejected").length,bySeverity:t}}function WLt(e,t){return HI(t.severity)-HI(e.severity)||+(t.state==="verified")-+(e.state==="verified")||e.fingerprint.localeCompare(t.fingerprint)}function HI(e){return{info:0,low:1,medium:2,high:3,critical:4}[e]}function HOe(e){return typeof e=="string"&&["info","low","medium","high","critical"].includes(e)}function WOe(e){return typeof e=="string"&&(QLt.includes(e)||Pee(e))}function GLt(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function GOe(e){return Math.max(0,Math.min(1,Number(e.toFixed(6))))}function Xl(e,t,n){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u.test(e))&&n.push(`${t} has an invalid identifier`)}function MF(e,t){let n=[];if(Xl(e,t,n),n.length>0)throw new zl(n);return e}function vw(e,t,n){(typeof e!="string"||e.trim().length===0||e.length>64*1024)&&n.push(`${t} must be non-empty and no longer than 65536 characters`)}function NF(e,t,n){(typeof e!="string"||!e.includes("T")||!Number.isFinite(Date.parse(e)))&&n.push(`${t} must be an ISO 8601 timestamp`)}function JOe(e,t){let n=XLt(e),r=e.files.map(s=>s.patch).filter(s=>!!s);if(e.files.length>0&&r.length===e.files.length&&r.every(s=>s.startsWith("diff --git ")))try{let s=OF(r.join(`
|
|
2949
|
-
`),{artifactId:t.artifactId??`turn_diff_${e.turnId}`,revision:t.revision??1,createdAt:t.createdAt??e.completedAt,title:`Turn ${e.turnId} changes`,producer:t.producer,identity:{...t.identity?structuredClone(t.identity):{},turnId:t.identity?.turnId??e.turnId},sensitivity:t.sensitivity??"internal",...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},mode:"turn"}),a={...s,state:t.state??s.state,extensions:{...s.extensions??{},"xeno.legacy.turnDiffSummary":n}};return mh(a),a}catch{}let i=pc(n),o={schemaVersion:1,artifactId:t.artifactId??`turn_diff_${e.turnId}`,revision:t.revision??1,kind:"diff",title:`Turn ${e.turnId} changes`,state:t.state??"pending_review",createdAt:t.createdAt??e.completedAt,mediaType:"application/vnd.xeno.turn-diff+json",sensitivity:t.sensitivity??"internal",identity:{...t.identity?structuredClone(t.identity):{},turnId:t.identity?.turnId??e.turnId},content:{hash:Iw(n),sizeBytes:JLt.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i}},provenance:{producer:{...t.producer}},anchors:e.files.map(s=>({kind:"custom:source-file",data:{path:s.path}})),...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.legacy.turnDiffSummary":n}};return mh(o),o}function XLt(e){return JSON.parse(JSON.stringify(e))}var lOe,kDt,EDt,SDt,CDt,uOe,dOe,RDt,TDt,_ee,PDt,_Dt,$Dt,BDt,pOe,MDt,NDt,ODt,DDt,LDt,QDt,FDt,EQn,SQn,St,gOe,cLt,kOe,lLt,uLt,dLt,pLt,EOe,wLt,yLt,bLt,vLt,ILt,Ta,WI,yw,$F,Ys,zT,BOe,QLt,FLt,zl,MOe,gh=Ie(()=>{"use strict";lOe=1,kDt=["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"],EDt=["draft","pending_review","approved","rejected","superseded","archived"],SDt=["public","internal","confidential","restricted"],CDt=["agent","tool","user","system","integration"],uOe=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],dOe=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];RDt=/^[a-z0-9][a-z0-9._/-]{0,127}$/,TDt="custom:";_ee=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(n=>({...n}))}},PDt=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"},_Dt={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},$Dt="[\\u0000-\\u001f\\u007f]",BDt=new RegExp($Dt),pOe=/^[a-f0-9]{64}$/,MDt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,NDt=new Set(EDt),ODt=new Set(SDt),DDt=new Set(CDt),LDt=new Set(kDt),QDt=new Set(uOe),FDt=new Set(dOe);EQn=new Set(uOe),SQn=new Set(dOe),St=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoArtifactRepositoryError"}code;detail},gOe=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(zNe).map(t=>({artifact:GT(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(mh(e),this.assertInitialState(e),e.revision!==1)throw new St("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 St("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=GT(e),n=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),r={artifact:t,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,r]])),this.currentRevisions.set(t.artifactId,t.revision),hw(r)}async createRevision(e,t={}){mh(e),this.assertInitialState(e);let n=this.getMutable(e.artifactId);this.assertVersion(n,t.expectedRecordVersion);let r=n.artifact.revision+1;if(e.revision!==r||e.predecessorRevision!==n.artifact.revision)throw new St("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:e.artifactId,currentRevision:n.artifact.revision,requestedRevision:e.revision});if(VDt(e,n.artifact))throw new St("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(n.artifact.state==="archived")throw new St("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){xee(n.artifact.state,"superseded");let a=this.now(),c=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});n.artifact.state="superseded",n.artifact.updatedAt=a,n.lifecycleEvents.push(c),n.recordVersion+=1}let i=GT(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-${n.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),hw(s)}async get(e,t){let n=this.records.get(e);if(!n)return;let r=t??this.currentRevisions.get(e);if(r===void 0)return;let i=n.get(r);return i?hw(i):void 0}async require(e,t){let n=await this.get(e,t);if(!n)throw new St("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return n}async list(e={}){let t=[];for(let[n,r]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(n)))if(e.includeSuperseded)t.push(...r.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let o=r.get(i);o&&t.push(o)}}return t.filter(n=>HDt(n.artifact,e)).sort(zNe).map(hw)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((n,r)=>n.artifact.revision-r.artifact.revision).map(hw):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),xee(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=hOe(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new St("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 St("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let n=this.now(),r=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:r,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:n});return t.artifact.state=e.toState,t.artifact.updatedAt=n,t.lifecycleEvents.push(i),t.recordVersion+=1,hw(t)}async appendReviewEvent(e){let t=e.event,n=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(n,e.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new St("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(n,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new St("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let r={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=mOe(r,n.artifact);if(i.length>0)throw new _ee("XENO artifact review event validation failed",i);return n.reviewEvents.push(r),n.recordVersion+=1,hw(n)}getMutable(e,t){let n=this.records.get(e),r=t??this.currentRevisions.get(e),i=r===void 0?void 0:n?.get(r);if(!i)throw new St("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 St("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 St("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(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.parentCommentId))throw new St("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(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let n=WDt(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&n.resolved)throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!n.resolved)throw new St("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 St("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 St("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((n,r)=>n.artifact.artifactId.localeCompare(r.artifact.artifactId)||n.artifact.revision-r.artifact.revision);for(let n of t){let r=jDt(n,this.eventIds),i=this.records.get(r.artifact.artifactId);if(i||(i=new Map,this.records.set(r.artifact.artifactId,i)),i.has(r.artifact.revision))throw new St("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${r.artifact.artifactId}:${r.artifact.revision}`);i.set(r.artifact.revision,r),this.currentRevisions.set(r.artifact.artifactId,r.artifact.revision)}for(let[n,r]of this.records){let i=[...r.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 St("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new St("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new St("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new St("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${a} must be superseded`)}}}};cLt="0.9.31",kOe=1,lLt="repository.v1.json",uLt=5e3,dLt=20,pLt=64*1024*1024,EOe=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??lLt;if(KNe(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=YDt(e.directory),this.snapshotPath=zDt(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=kee(e.lockTimeoutMs,uLt,100,6e4,"lockTimeoutMs"),this.lockRetryMs=kee(e.lockRetryMs,dLt,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=kee(e.maxSnapshotBytes,pLt,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(n=>n.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 n=await this.load(),r=await e(n.repository);return await this.persist(n),r}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 aLt(this.lockPath,`artifact-repository:${KNe(this.snapshotPath)}`,cLt)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;t=n,await ALt(this.lockRetryMs)}throw new St("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,n=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=PF(i)}if(!t&&(e||await gLt(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,n=!0)}catch(i){throw e?new St("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,PF(i)])}):i}if(!t&&e)throw e;let r=t?.state??{schemaVersion:1,records:[]};return{repository:new gOe({now:this.now,idFactory:i=>`${i}_${AOe()}`,initialState:r}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:n,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),n={schemaVersion:kOe,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},r=mLt(n),i=`${JSON.stringify(r,null,2)}
|
|
2949
|
+
`),{artifactId:t.artifactId??`turn_diff_${e.turnId}`,revision:t.revision??1,createdAt:t.createdAt??e.completedAt,title:`Turn ${e.turnId} changes`,producer:t.producer,identity:{...t.identity?structuredClone(t.identity):{},turnId:t.identity?.turnId??e.turnId},sensitivity:t.sensitivity??"internal",...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},mode:"turn"}),a={...s,state:t.state??s.state,extensions:{...s.extensions??{},"xeno.legacy.turnDiffSummary":n}};return mh(a),a}catch{}let i=pc(n),o={schemaVersion:1,artifactId:t.artifactId??`turn_diff_${e.turnId}`,revision:t.revision??1,kind:"diff",title:`Turn ${e.turnId} changes`,state:t.state??"pending_review",createdAt:t.createdAt??e.completedAt,mediaType:"application/vnd.xeno.turn-diff+json",sensitivity:t.sensitivity??"internal",identity:{...t.identity?structuredClone(t.identity):{},turnId:t.identity?.turnId??e.turnId},content:{hash:Iw(n),sizeBytes:JLt.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i}},provenance:{producer:{...t.producer}},anchors:e.files.map(s=>({kind:"custom:source-file",data:{path:s.path}})),...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.legacy.turnDiffSummary":n}};return mh(o),o}function XLt(e){return JSON.parse(JSON.stringify(e))}var lOe,kDt,EDt,SDt,CDt,uOe,dOe,RDt,TDt,_ee,PDt,_Dt,$Dt,BDt,pOe,MDt,NDt,ODt,DDt,LDt,QDt,FDt,EQn,SQn,St,gOe,cLt,kOe,lLt,uLt,dLt,pLt,EOe,wLt,yLt,bLt,vLt,ILt,Ta,WI,yw,$F,Ys,zT,BOe,QLt,FLt,zl,MOe,gh=Ie(()=>{"use strict";lOe=1,kDt=["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"],EDt=["draft","pending_review","approved","rejected","superseded","archived"],SDt=["public","internal","confidential","restricted"],CDt=["agent","tool","user","system","integration"],uOe=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],dOe=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];RDt=/^[a-z0-9][a-z0-9._/-]{0,127}$/,TDt="custom:";_ee=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,t){super(e),this.name="XenoArtifactValidationError",this.issues=t.map(n=>({...n}))}},PDt=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"},_Dt={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},$Dt="[\\u0000-\\u001f\\u007f]",BDt=new RegExp($Dt),pOe=/^[a-f0-9]{64}$/,MDt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,NDt=new Set(EDt),ODt=new Set(SDt),DDt=new Set(CDt),LDt=new Set(kDt),QDt=new Set(uOe),FDt=new Set(dOe);EQn=new Set(uOe),SQn=new Set(dOe),St=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.detail=n,this.name="XenoArtifactRepositoryError"}code;detail},gOe=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(zNe).map(t=>({artifact:GT(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}))}}async create(e){if(mh(e),this.assertInitialState(e),e.revision!==1)throw new St("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 St("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let t=GT(e),n=this.createLifecycleEvent({artifact:t,sequence:1,actor:t.provenance.producer,fromState:null,toState:t.state,reason:"artifact-created"}),r={artifact:t,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(t.artifactId,new Map([[t.revision,r]])),this.currentRevisions.set(t.artifactId,t.revision),hw(r)}async createRevision(e,t={}){mh(e),this.assertInitialState(e);let n=this.getMutable(e.artifactId);this.assertVersion(n,t.expectedRecordVersion);let r=n.artifact.revision+1;if(e.revision!==r||e.predecessorRevision!==n.artifact.revision)throw new St("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:e.artifactId,currentRevision:n.artifact.revision,requestedRevision:e.revision});if(VDt(e,n.artifact))throw new St("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(n.artifact.state==="archived")throw new St("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){xee(n.artifact.state,"superseded");let a=this.now(),c=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor??e.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:t.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});n.artifact.state="superseded",n.artifact.updatedAt=a,n.lifecycleEvents.push(c),n.recordVersion+=1}let i=GT(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-${n.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),hw(s)}async get(e,t){let n=this.records.get(e);if(!n)return;let r=t??this.currentRevisions.get(e);if(r===void 0)return;let i=n.get(r);return i?hw(i):void 0}async require(e,t){let n=await this.get(e,t);if(!n)throw new St("ARTIFACT_NOT_FOUND",`Artifact ${e}${t===void 0?"":` revision ${t}`} was not found`,{artifactId:e,...t===void 0?{}:{revision:t}});return n}async list(e={}){let t=[];for(let[n,r]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(n)))if(e.includeSuperseded)t.push(...r.values());else{let i=this.currentRevisions.get(n);if(i!==void 0){let o=r.get(i);o&&t.push(o)}}return t.filter(n=>HDt(n.artifact,e)).sort(zNe).map(hw)}async listRevisions(e){let t=this.records.get(e);return t?[...t.values()].sort((n,r)=>n.artifact.revision-r.artifact.revision).map(hw):[]}async transition(e){let t=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(t,e.expectedRecordVersion),xee(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=hOe(t.reviewEvents);if(!o||o.decision!==e.toState||s.latestDecisionEventId!==o.eventId)throw new St("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 St("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${s.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:t.artifact.revision,unresolvedComments:s.unresolvedComments})}let n=this.now(),r=t.artifact.state,i=this.createLifecycleEvent({artifact:t.artifact,sequence:t.lifecycleEvents.length+1,actor:e.actor,fromState:r,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:n});return t.artifact.state=e.toState,t.artifact.updatedAt=n,t.lifecycleEvents.push(i),t.recordVersion+=1,hw(t)}async appendReviewEvent(e){let t=e.event,n=this.getMutable(t.artifactId,t.artifactRevision);if(this.assertVersion(n,e.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new St("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:t.artifactId,revision:t.artifactRevision});if(this.assertReviewCommentState(n,t),(t.type==="review-requested"||t.type==="review-withdrawn"||t.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new St("ARTIFACT_REVIEW_INVALID",`${t.type} requires an artifact in pending_review state`,{artifactId:t.artifactId,revision:t.artifactRevision});let r={...structuredClone(t),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},i=mOe(r,n.artifact);if(i.length>0)throw new _ee("XENO artifact review event validation failed",i);return n.reviewEvents.push(r),n.recordVersion+=1,hw(n)}getMutable(e,t){let n=this.records.get(e),r=t??this.currentRevisions.get(e),i=r===void 0?void 0:n?.get(r);if(!i)throw new St("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 St("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 St("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(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} already exists`);if(t.parentCommentId&&!e.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===t.parentCommentId))throw new St("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(r=>r.type==="comment-added"&&r.commentId===t.commentId))throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} does not exist`);let n=WDt(e.reviewEvents,t.commentId);if(t.type==="comment-resolved"&&n.resolved)throw new St("ARTIFACT_REVIEW_INVALID",`Comment ${t.commentId} is already resolved`);if(t.type==="comment-reopened"&&!n.resolved)throw new St("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 St("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 St("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let t=[...e.records].sort((n,r)=>n.artifact.artifactId.localeCompare(r.artifact.artifactId)||n.artifact.revision-r.artifact.revision);for(let n of t){let r=jDt(n,this.eventIds),i=this.records.get(r.artifact.artifactId);if(i||(i=new Map,this.records.set(r.artifact.artifactId,i)),i.has(r.artifact.revision))throw new St("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${r.artifact.artifactId}:${r.artifact.revision}`);i.set(r.artifact.revision,r),this.currentRevisions.set(r.artifact.artifactId,r.artifact.revision)}for(let[n,r]of this.records){let i=[...r.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 St("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${a}`);if(o===0&&s.artifact.predecessorRevision!==void 0)throw new St("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(o>0&&s.artifact.predecessorRevision!==a-1)throw new St("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${a} has an invalid predecessor`);if(o<i.length-1&&s.artifact.state!=="superseded")throw new St("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${a} must be superseded`)}}}};cLt="0.9.32",kOe=1,lLt="repository.v1.json",uLt=5e3,dLt=20,pLt=64*1024*1024,EOe=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??lLt;if(KNe(t)!==t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=YDt(e.directory),this.snapshotPath=zDt(this.directory,t),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=kee(e.lockTimeoutMs,uLt,100,6e4,"lockTimeoutMs"),this.lockRetryMs=kee(e.lockRetryMs,dLt,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=kee(e.maxSnapshotBytes,pLt,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(n=>n.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 n=await this.load(),r=await e(n.repository);return await this.persist(n),r}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 aLt(this.lockPath,`artifact-repository:${KNe(this.snapshotPath)}`,cLt)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;t=n,await ALt(this.lockRetryMs)}throw new St("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:t})}async load(){let e,t,n=!1;try{t=await this.readSnapshot(this.snapshotPath,!1)}catch(i){e=PF(i)}if(!t&&(e||await gLt(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,n=!0)}catch(i){throw e?new St("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,PF(i)])}):i}if(!t&&e)throw e;let r=t?.state??{schemaVersion:1,records:[]};return{repository:new gOe({now:this.now,idFactory:i=>`${i}_${AOe()}`,initialState:r}),generation:t?.generation??0,createdAt:t?.createdAt??this.now(),hasSnapshot:t!==void 0,recoveredFromBackup:n,...t?{sourceSnapshot:t}:{}}}async persist(e){let t=this.now(),n={schemaVersion:kOe,generation:e.generation,createdAt:e.createdAt,updatedAt:t,state:e.repository.exportState(),generation:e.generation+1},r=mLt(n),i=`${JSON.stringify(r,null,2)}
|
|
2950
2950
|
`;if(Buffer.byteLength(i,"utf8")>this.maxSnapshotBytes)throw new St("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await wOe(this.directory,{recursive:!0,mode:448}),e.hasSnapshot&&!e.recoveredFromBackup&&e.sourceSnapshot&&await tOe(this.backupPath,`${JSON.stringify(e.sourceSnapshot,null,2)}
|
|
2951
2951
|
`),await tOe(this.snapshotPath,i)}async readSnapshot(e,t){let n;try{n=await yOe(e)}catch(r){if(!t&&Ree(r,"ENOENT")||t&&Ree(r,"ENOENT"))return;throw Tee("Unable to inspect artifact repository snapshot",e,r)}if(!n.isFile()||n.size>this.maxSnapshotBytes)throw new St("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:e,sizeBytes:n.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let r=await GDt(e);if(r.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return fLt(JSON.parse(r.toString("utf8")),e)}catch(r){throw r instanceof St?r:Tee("Unable to parse artifact repository snapshot",e,r,!0)}}};wLt=16*1024*1024,yLt=5e3,bLt=1e5,vLt=1e6,ILt=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,Ta=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"};WI=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_${RLt()}`)}async addComment(e){let t=DF(e.body,"Review comment body",65536),n=await this.repository.require(e.artifactId,e.revision),r=oOe(n,e),i=_F(this.idFactory(),"Comment ID"),o=PLt(e.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:"comment-added",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,commentId:i,body:t,...r?{anchor:r}:{},...o?{parentCommentId:o}:{}}})}async setCommentResolution(e){let t=_F(e.commentId,"Review comment ID"),n=sOe(e.reason,"Resolution reason",16*1024),r=await this.repository.require(e.artifactId,e.revision);return this.repository.appendReviewEvent({expectedRecordVersion:r.recordVersion,event:{type:e.resolved?"comment-resolved":"comment-reopened",artifactId:r.artifact.artifactId,artifactRevision:r.artifact.revision,artifactHash:r.artifact.content.hash,actor:this.actor,commentId:t,...n?{reason:n}:{}}})}async decide(e){let t=await this.repository.require(e.artifactId,e.revision);if(t.artifact.state!=="pending_review")throw new St("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${t.artifact.state}`);let n=oOe(t,e),r=sOe(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,...r?{rationale:r}:{},...n?{scope:n}:{}}});if(n||e.decision==="changes_requested")return i;let o=i.reviewEvents.at(-1);if(!o||o.type!=="decision-recorded")throw new St("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,...r?{reason:r}:{}})}};yw="xeno.spec.v1",$F="xeno.spec-execution.v1",Ys=class extends Error{constructor(e){super(`XENO spec is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},zT=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??(()=>_Lt())}async create(e,t){if(e.revision!==1||e.predecessorRevision!==void 0)throw new Ys(["A new spec must begin at revision 1 without a predecessor"]);let n=aOe(e,t);return await this.repository.create(n.requirements),await this.repository.create(n.design),await this.repository.create(n.taskGraph),await this.repository.create(n.plan),n}async revise(e,t){let n=ww(e.specId),r=await this.repository.require(n.plan);if(e.revision!==r.artifact.revision+1||e.predecessorRevision!==r.artifact.revision)throw new Ys([`Revision ${e.revision} must follow approved or reviewed revision ${r.artifact.revision}`]);let i=aOe(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,n){return new WI({repository:this.repository,actor:t}).decide({artifactId:ww(e).plan,decision:"approved",...n?{rationale:n}:{}})}async reject(e,t,n){return new WI({repository:this.repository,actor:t}).decide({artifactId:ww(e).plan,decision:"rejected",rationale:n})}async startExecution(e,t){let n=await this.repository.require(ww(e).plan);if(n.artifact.state!=="approved")throw new Ys([`Spec ${e} must be approved before execution`]);let r=bw(n.artifact),i=this.now(),o={schemaVersion:$F,executionId:`spec_execution_${this.idFactory()}`,specId:r.specId,specRevision:r.revision,planArtifactId:n.artifact.artifactId,planHash:{...n.artifact.content.hash},state:"ready",createdAt:i,updatedAt:i,observedPaths:[],tasks:r.tasks.map(s=>({taskId:s.id,status:"pending",evidence:[],acceptanceEvidence:Object.fromEntries(s.acceptanceCriterionIds.map(a=>[a,[]]))}))};return this.repository.create(cOe(o,{producer:t,identity:n.artifact.identity,sensitivity:n.artifact.sensitivity,accessPolicyId:n.artifact.accessPolicyId}))}async updateExecution(e,t,n){let r=await this.repository.require(e),i=YT(r.artifact),o=await this.repository.require(i.planArtifactId,i.specRevision);if(o.artifact.state!=="approved"||!XT(o.artifact.content.hash,i.planHash))throw new Ys(["Execution is no longer bound to the approved plan revision"]);let s=t(structuredClone(i));s.schemaVersion=$F,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(),TOe(s,bw(o.artifact));let a=cOe(s,{producer:n,identity:r.artifact.identity,sensitivity:r.artifact.sensitivity,accessPolicyId:r.artifact.accessPolicyId},r.artifact.revision+1,r.artifact.revision);return this.repository.createRevision(a,{actor:n,reason:"spec-execution-updated"})}};BOe="xeno.review-report.v1",QLt=["correctness","security","performance","api","tests","documentation"],FLt=["source","test","trace","artifact","reproduction","benchmark"],zl=class extends Error{constructor(e){super(`XENO review is invalid: ${e.join("; ")}`),this.issues=e,this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},MOe=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}_${LLt()}`)}async run(e){OOe(e.pack),DOe(e.target),MF(e.runId,"runId");let t=this.now(),n=await Promise.all(e.pack.dimensions.map(async(a,c)=>{let l=await this.reviewer({...e,dimension:a,reviewerSlot:c});return jLt(l,a,e.pack.maxFindings),structuredClone(l)})),r=n.flatMap(a=>a.findings.map(c=>({finding:c,reviewerAgentId:a.reviewerAgentId})));if(r.length>e.pack.maxFindings)throw new zl([`Reviewers returned ${r.length} findings, exceeding maxFindings ${e.pack.maxFindings}`]);let i=ULt(r,this.idFactory);for(let a of i){let c=this.verifier?await Promise.all(Array.from({length:e.pack.verifierCount},async(f,m)=>{let h=await this.verifier({...e,finding:structuredClone(a),verifierSlot:m});return VLt(h),structuredClone(h)})):[];a.verifications=HLt(c),a.evidence=UOe([...a.evidence,...a.verifications.flatMap(f=>f.evidence)]);let l=new Set(a.verifications.filter(f=>f.outcome==="reproduced").map(f=>f.verifierAgentId)).size,u=a.verifications.length>0&&a.verifications.every(f=>f.outcome==="rejected"),d=new Set(a.evidence.map(f=>f.producerId)).size;l>=e.pack.minimumVerifierReproductions?(a.state="verified",a.verificationBasis="verifier"):e.pack.allowIndependentEvidenceVerification&&d>=e.pack.minimumIndependentEvidenceProducers?(a.state="verified",a.verificationBasis="independent-evidence"):u?(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=GOe(Math.min(a.confidence,...p)))}i.sort(WLt);let o=this.now(),s={schemaVersion:BOe,reportId:MF(this.idFactory("report"),"reportId"),runId:e.runId,pack:structuredClone(e.pack),target:structuredClone(e.target),startedAt:t,completedAt:o,reviewers:n.map(a=>({agentId:a.reviewerAgentId,dimension:a.dimension,findingCount:a.findings.length})),findings:i,summary:VOe(i)};return LOe(s),s}}});import{existsSync as WF,mkdirSync as y2t,readFileSync as b2t,readdirSync as v2t,writeFileSync as I2t}from"node:fs";import{basename as k2t,dirname as E2t,join as ZI,parse as S2t,resolve as C2t}from"node:path";import{homedir as hDe,platform as _2t,release as $2t}from"node:os";import{resolve as pDe}from"node:path";import{createHash as Y2t}from"node:crypto";function x2t(e){let t=R2t(e);return{frontmatter:t.frontmatter,content:t.content.trim()}}function R2t(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return{frontmatter:{},content:e};let n=t.search(/\r?\n/);if(n<0||t.slice(0,n).trim()!=="---")return{frontmatter:{},content:e};let r=t.slice(n+(t[n]==="\r"?2:1)),i=r.match(/(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/);if(!i||i.index===void 0)throw new Error("YAML frontmatter is not closed.");let o=r.slice(0,i.index),s=i[0],a=i.index+s.length;return{frontmatter:fDe(o),content:r.slice(a)}}function fDe(e){let t={},n=e.split(/\r?\n/);for(let r=0;r<n.length;r+=1){let i=n[r];if(!i.trim()||i.trimStart().startsWith("#"))continue;if(/^\s/.test(i))throw new Error(`Unexpected indentation at line ${r+1}.`);let o=P2t(i,r+1);if(o.key==="<<")throw new Error("YAML merge keys are not supported.");if(o.value!==""){t[o.key]=mDe(o.value,r+1);continue}let s=T2t(n,r+1);t[o.key]=s.value,r=s.nextIndex-1}return t}function T2t(e,t){let n=[],r=t;for(;r<e.length;r+=1){let o=e[r];if(!o.trim()){n.push(o);continue}if(!/^\s/.test(o))break;n.push(o.replace(/^ {2}/,""))}let i=n.filter(o=>o.trim()&&!o.trimStart().startsWith("#"));return i.length===0?{value:{},nextIndex:r}:i.every(o=>o.trimStart().startsWith("- "))?{value:i.map((o,s)=>mDe(o.trimStart().slice(2),t+s+1)),nextIndex:r}:{value:fDe(n.join(`
|
|
2952
2952
|
`)),nextIndex:r}}function P2t(e,t){let n=e.indexOf(":");if(n<=0)throw new Error(`Invalid YAML line ${t}.`);let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!r)throw new Error(`Invalid YAML key at line ${t}.`);return{key:r,value:i}}function mDe(e,t){if(e==="")return"";if(e==="[]")return[];if(e==="{}")return{};if(e==="true")return!0;if(e==="false")return!1;if(e==="null"||e==="~")return null;if(/^-?\d+(?:\.\d+)?$/.test(e))return Number(e);if(e.startsWith('"'))return dDe(e,t);if(e.startsWith("'")){if(!e.endsWith("'"))throw new Error(`Unclosed quoted scalar at line ${t}.`);return e.slice(1,-1).replace(/''/g,"'")}if(e.startsWith("[")||e.startsWith("{"))return dDe(e,t);if(e.includes("[")||e.includes("]")||e.includes("{")||e.includes("}"))throw new Error(`Unsupported YAML scalar at line ${t}.`);return e}function dDe(e,t){try{return JSON.parse(e)}catch{throw new Error(`Invalid YAML scalar at line ${t}.`)}}function B2t(){let e=process.env.XENO_AGENT_HOME?.trim();return e?pDe(e):pDe(hDe(),".xeno-agent")}function N2t(){return B2t()}function Vee(e=N2t()){return ZI(e,"agents")}function gDe(e){return C2t(e)}function O2t(e){let t=E2t(e);return t===e?e:t}function ADe(e=process.cwd()){let t=gDe(e),n=[],r=t;for(;;){let o=ZI(r,".claude","agents"),s=ZI(r,".xeno","agents");n.push({...WF(o)?{claude:o}:{},...WF(s)?{xeno:s}:{}});let a=O2t(r);if(a===r)break;r=a}n.reverse();let i=[];for(let o of n)o.claude&&i.push(o.claude),o.xeno&&i.push(o.xeno);return i}function wDe(e=process.cwd()){return ZI(gDe(e),".xeno","agents")}function D2t(e){return WF(e)?v2t(e,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.toLowerCase().endsWith(".md")).map(t=>ZI(e,t.name)).sort((t,n)=>t.localeCompare(n)):[]}function YI(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function KI(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean):typeof e=="string"?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function L2t(e){if(typeof e=="boolean")return e;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(["1","true","yes","on"].includes(t))return!0;if(["0","false","no","off"].includes(t))return!1}function Q2t(e){return S2t(k2t(e)).name.toLowerCase()}function Hee(e){return M2t.test(e)}function F2t(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function U2t(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t==="inherit")return"inherit";if(t==="none"||t==="off"||t==="disabled")return"none";if(t==="read"||t==="readonly"||t==="read-only")return"readOnly";if(t==="default"||t==="standard")return"default";if(t==="full"||t==="fullaccess"||t==="full-access")return"fullAccess"}function q2t(e){if(e===void 0)return;if(typeof e=="string"||Array.isArray(e)){let o=KI(e);return o.length>0?{allow:o}:void 0}if(!F2t(e))return;let t=KI(e.allow),n=KI(e.deny),r=U2t(e.mode),i={};return r&&(i.mode=r),t.length>0&&(i.allow=t),n.length>0&&(i.deny=n),Object.keys(i).length>0?i:void 0}function j2t(e){let t=L2t(e.worktree??e.defaultWorktreeIsolation);if(t===!0)return"worktree";if(t===!1)return"none";let n=YI(e.isolation)?.toLowerCase();if(n==="worktree")return"worktree";if(n==="none"||n==="off"||n==="disabled")return"none"}function yDe(e){let t=[];return Hee(e.name)||t.push(`Invalid agent name "${e.name}". Use 1-64 lowercase letters, digits, hyphens, or underscores, starting with a letter.`),e.prompt.trim().length===0&&t.push("Agent definition body is empty."),t}function V2t(e,t,n){let r=b2t(e,"utf8"),i=x2t(r),o=i.frontmatter,s=Q2t(e),a=YI(o.name)?.toLowerCase()??s,c=i.content.trim(),l=yDe({name:a,prompt:c});if(l.length>0)throw new Error(l.join(" "));let u=YI(o.description),d=YI(o.model),p=YI(o.color),f=YI(o.memory??o.memoryScope),m=j2t(o),h=q2t(o.tools);return{name:a,scope:t,path:e,...u?{description:u}:{},...d?{model:d}:{},...p?{color:p}:{},...f?{memory:f}:{},...m?{isolation:m}:{},tags:KI(o.tags),skills:KI(o.skills),hooks:KI(o.hooks),prompt:c,active:!0,priority:n,...h?{toolPolicy:h}:{}}}function qF(e,t,n,r,i){for(let o of D2t(e))try{r.push(V2t(o,t,n))}catch(s){i.push({path:o,scope:t,message:s instanceof Error?s.message:String(s)})}}function H2t(e){let t=new Map;for(let n of e){let r=t.get(n.name);(!r||n.priority>r.priority)&&t.set(n.name,n)}return t}function W2t(e,t){let n=t.get(e.name),r=n?.path===e.path;return{name:e.name,scope:e.scope,path:e.path,...e.description?{description:e.description}:{},...e.model?{model:e.model}:{},...e.color?{color:e.color}:{},...e.memory?{memory:e.memory}:{},...e.isolation?{isolation:e.isolation}:{},tags:e.tags,skills:e.skills,hooks:e.hooks,prompt:e.prompt,active:r,...e.toolPolicy?{toolPolicy:e.toolPolicy}:{},...!r&&n?{shadowedBy:{name:n.name,scope:n.scope,path:n.path}}:{}}}function hd(e=process.cwd(),t={}){let n=t.cwd??e,r=t.userDir??Vee(t.agentHome),i=t.projectDirs??ADe(n),o=t.pluginDirs??[],s=t.builtInDirs??[],a=[],c=[];t.includeUser!==!1&&qF(r,"user",0,a,c),t.includeProject!==!1&&i.forEach((d,p)=>qF(d,"project",100+p,a,c)),t.includePlugins&&o.forEach((d,p)=>qF(d,"plugin",1e3+p,a,c)),t.includeBuiltIns&&s.forEach((d,p)=>qF(d,"built-in",2e3+p,a,c));let l=H2t(a),u=a.map(d=>W2t(d,l));return u.sort((d,p)=>{if(d.active!==p.active)return d.active?-1:1;let f=d.name.localeCompare(p.name);return f!==0?f:d.path.localeCompare(p.path)}),{definitions:u,issues:c,searchPaths:{...t.includeUser!==!1?{user:r}:{},project:t.includeProject===!1?[]:i,plugin:t.includePlugins?o:[],builtIn:t.includeBuiltIns?s:[]}}}function ek(e,t=process.cwd(),n={}){let r=e.trim().toLowerCase(),i=hd(t,n);return{definition:i.definitions.find(o=>o.active&&o.name===r)??null,scan:i}}function jF(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(n=>n.trim()).filter(Boolean)));return t.length>0?t:void 0}function J2t(e,t){if(!e&&!t)return;if(!e)return jF(t);if(!t)return jF(e);let n=new Set(t);return jF(e.filter(r=>n.has(r)))}function X2t(e,t){let n={none:0,readOnly:1,default:2,fullAccess:3,inherit:4},r=t??"inherit",i=e??"inherit";return n[r]<=n[i]?r:i}function qee(e,t={}){let n=e.toolPolicy??{},r={mode:X2t(n.mode,t.mode)},i=J2t(t.allow,n.allow),o=jF([...t.deny??[],...n.deny??[]]);return i&&(r.allow=i),o&&(r.deny=o),r}function z2t(e){return{name:`custom-agent:${e.name}`,order:20,provide(){let t=["","","# Custom Agent",`Active agent: ${e.name}`,`Definition scope: ${e.scope}`,`Definition path: ${e.path}`];return e.description&&t.push(`Description: ${e.description}`),t.push("",e.prompt),t.join(`
|
|
@@ -4194,7 +4194,7 @@ ${r}`}}import{execFileSync as tQe}from"node:child_process";function Wqt(){let e=
|
|
|
4194
4194
|
`),i.model||i.baseURL||i.apiKey||i.maxTokens||i.permissionMode||i.plugins&&i.plugins.length>0||i.mcpServers&&i.mcpServers.length>0||n.onOutput(` (no settings configured)
|
|
4195
4195
|
`),n.onOutput(`
|
|
4196
4196
|
`),{handled:!0}}function Th(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/1e3),r=Math.floor(n/3600),i=Math.floor(n%3600/60),o=n%60;return r>0?`${r}h ${i}m ${o}s`:i>0?`${i}m ${o}s`:`${o}s`}function pQe(e){let t=["Last Session Summary",`- model: ${e.model}`,`- mode: ${e.mode??"unknown"}`,`- status: ${e.status??"unknown"}`,`- started: ${e.startedAt}`,`- ended: ${e.endedAt}`,`- duration: ${Th(e.durationMs)}`,`- tokens: ${e.tokenUsage.input.toLocaleString()} in / ${e.tokenUsage.output.toLocaleString()} out / ${e.tokenUsage.total.toLocaleString()} total`,`- estimated cost: ${nw(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(`
|
|
4197
|
-
`)}function kjt(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function jU(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${kjt(e.targetPrompt)}"`,n=await e.checkpointManager.create({trigger:"manual",messages:e.messages,description:t});if(e.sessionManager){let r=[n.id,...e.sessionManager.meta.checkpoints.filter(i=>i!==n.id)];await e.sessionManager.updateMeta({checkpoints:r}),await e.sessionManager.transcript.append({type:"checkpoint",data:{id:n.id,action:"create",name:t,trigger:"manual",messageCount:e.messages.length}})}return n.id}Br();gi();var Ejt={"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 Zte(e=he){return Ejt[e]??[]}function Sjt(e=he){let t=ht().lastReleaseNotesSeen;return Zte(e).length>0&&t!==e}function yk(e=he){hi({lastReleaseNotesSeen:e})}function VU(e){let t=e??he,n=Zte(t);return n.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...n.map(r=>`- ${r}`)].join(`
|
|
4197
|
+
`)}function kjt(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function jU(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${kjt(e.targetPrompt)}"`,n=await e.checkpointManager.create({trigger:"manual",messages:e.messages,description:t});if(e.sessionManager){let r=[n.id,...e.sessionManager.meta.checkpoints.filter(i=>i!==n.id)];await e.sessionManager.updateMeta({checkpoints:r}),await e.sessionManager.transcript.append({type:"checkpoint",data:{id:n.id,action:"create",name:t,trigger:"manual",messageCount:e.messages.length}})}return n.id}Br();gi();var Ejt={"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 Zte(e=he){return Ejt[e]??[]}function Sjt(e=he){let t=ht().lastReleaseNotesSeen;return Zte(e).length>0&&t!==e}function yk(e=he){hi({lastReleaseNotesSeen:e})}function VU(e){let t=e??he,n=Zte(t);return n.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...n.map(r=>`- ${r}`)].join(`
|
|
4198
4198
|
`)}function fQe(e=he){if(Sjt(e))return[`What's new in XENO AGENT v${e}`,...Zte(e).map(t=>`- ${t}`),"Run `xeno release-notes` to view this again."].join(`
|
|
4199
4199
|
`)}Rt();ac();ao();dT();import{spawn as Cjt}from"node:child_process";import{setTimeout as tne}from"node:timers/promises";iw();import{resolve as HU}from"node:path";var mQe="cancel",Pa={name:"WorkflowCancel",command:`workflows ${mQe}`,nativeVerb:mQe,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 bk(e,t){let n=e.run?.workflowName??t;return e.accepted?e.cancelled?`Cancelled ${n}`:`Cancellation pending for ${n}; inspect operation ${e.operationId}`:`Workflow run not found: ${t}`}function hQe(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 gQe=()=>[Pa.description,`Mode: ${Pa.mode}; requiresDisplay: ${Pa.requiresDisplay}; reversibility: ${Pa.reversibility}. Read back with ${Pa.readingTools.join(" or ")}.`,"Returns JSON: "+Object.entries(Pa.replyFields).map(([e,t])=>`${e}: ${t}`).join(" "),"Cancellation progress: "+Object.entries(Pa.cancellationFields).map(([e,t])=>`${e}: ${t}`).join(" ")].join(" ");function Ks(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
4200
4200
|
`)}function xjt(e,t){if(t){Ks(e);return}if(e.ok&&e.definition){process.stdout.write(`Workflow valid: ${e.definition.name}
|