@xenosystem/agent-cli 0.5.27 → 0.5.28
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 +3 -3
- package/dist/metafile-esm.json +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -2688,7 +2688,7 @@ ${be}${H.compose(nD(),H.bold)("\u2717")} ${ZC(e)}
|
|
|
2688
2688
|
`)}function vb(){return`
|
|
2689
2689
|
${be}${Ae("Goodbye.")}
|
|
2690
2690
|
`}var Jwt,GSe,nD,Gt,Ae,t0,ZC,zwt,n0,Xwt,Kwt,Zwt,q,be,ZSe,k3,S,x3,YSe,e0,Lo=Me(()=>{"use strict";Zs();la();USe();eD();Jwt=new hu(process.stdout),GSe=new hu(process.stderr),nD=()=>or(),Gt=e=>nD()(e),Ae=H.dim,t0=H.bold,ZC=e=>nD()(e),zwt="\u25A0",n0="\u2514",Xwt={open:"\x1B[4m",close:"\x1B[24m"};Kwt={Read:e=>Cc()(e),ReadImage:e=>Cc()(e),Glob:e=>Cc()(e),Grep:e=>Cc()(e),ElfAnalyze:e=>Cc()(e),MemoryRead:e=>Cc()(e),Write:e=>KC()(e),Edit:e=>KC()(e),MemoryWrite:e=>KC()(e),Bash:e=>y3()(e),GitStatus:e=>Cc()(e),GitDiff:e=>Cc()(e),GitLog:e=>Cc()(e),GitBranch:e=>Cc()(e),GitCommit:e=>y3()(e),WebSearch:e=>H.cyan(e),WebFetch:e=>H.cyan(e),TaskOutput:e=>Cc()(e),TaskInput:e=>H.cyan(e),TaskStop:e=>xg()(e)};Zwt={Edit:"Update",Glob:"Search",Grep:"Search",WebSearch:"Web Search",WebFetch:"Web Fetch"};q={accent:Gt,purple:ZC,cyan:ZC,dim:Ae,bold:t0,red:ZC,green:ZC},be=" ",ZSe=1e3,k3=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"};x3=class{atLineStart=!0;writeFn;constructor(t){this.writeFn=t??(n=>{Jwt.writeOrdered(n,"stream")})}write(t){let n="";for(let r of t)this.atLineStart&&(n+=be,this.atLineStart=!1),n+=r,r===`
|
|
2691
|
-
`&&(this.atLineStart=!0);this.writeFn(n)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},YSe=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],e0=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,n){this.writeFn=t??(r=>{GSe.writeFrame(r,"spinner")}),this.clearFn=n??(()=>{GSe.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let n=YSe[this.frameIndex%YSe.length],r=`${Gt(n)} ${Ae(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 ve,Ci=Me(()=>{"use strict";ve="0.5.27"});var CCe=Me(()=>{"use strict"});var xCe=Me(()=>{"use strict"});var RCe=Me(()=>{"use strict"});function dvt(e){return typeof e=="string"&&avt.includes(e)}function pvt(e){return Qo(e)?Mn(e.clientId)&&Mn(e.clientVersion)&&Mn(e.instanceId)&&dvt(e.surface):!1}function PCe(e){return!Qo(e)||!Qo(e.protocol)||!Qo(e.host)||!Qo(e.storage)?!1:Number.isInteger(e.protocol.current)&&Avt(e.protocol.supported)&&Mn(e.host.instanceId)&&Mn(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)&&pvt(e.surface)}function q3(e){return!Qo(e)||!Mn(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(hvt)}function mvt(e){return!Qo(e)||!Qo(e.event)?!1:Mn(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&Mn(e.timestamp)&&Mn(e.conversationId)&&Mn(e.requestId)&&Mn(e.type)&&Mn(e.source)}function _Ce(e){return!Qo(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(mvt)}function BCe(e){return!Qo(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&Mn(e.conversationId)&&Mn(e.requestId)&&Mn(e.adapterId)&&Qo(e.selection)&&Mn(e.selection.providerId)&&Mn(e.selection.catalogRevision):Mn(e.code)&&Mn(e.safeError)}function $Ce(e){return!Qo(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&Mn(e.conversationId)&&Mn(e.requestId):Mn(e.code)&&Mn(e.safeError)}function MCe(e){return Qo(e)&&Mn(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&fvt(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e}function fvt(e){return typeof e=="string"&&uvt.includes(e)}function NCe(e,t,n){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new ui("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 ui("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${n.min}-${n.max}.`)}function hvt(e){return Qo(e)?Mn(e.id)&&typeof e.kind=="string"&&cvt.includes(e.kind)&&Mn(e.displayName)&&OCe(e.availability)&&Qo(e.capabilities)&&Array.isArray(e.models)&&e.models.every(gvt)&&Mn(e.catalogRevision):!1}function gvt(e){return Qo(e)&&Mn(e.id)&&Mn(e.displayName)&&OCe(e.availability)}function OCe(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function Avt(e){return Qo(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 Mn(e){return typeof e=="string"&&e.trim().length>0}function Qo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DCe(e){for(let t of wvt)for(let n of yvt)if(e===`${t}tool.${n}`)return n;return null}function Bg(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n:void 0}function LCe(e){let t=e.event;return Bg(t,"toolName")||Bg(t,"tool")||Bg(t,"name")||Bg(t,"title")||Bg(t,"kind")}function QCe(e){let t=e.event;return Bg(t,"toolCallId")||Bg(t,"tool_call_id")}function FCe(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 UCe(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 jCe(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var Tb,TCe,avt,cvt,lvt,LIn,uvt,ui,yvt,wvt,f0=Me(()=>{"use strict";CCe();xCe();RCe();Tb=1,TCe=1,avt=["standalone-desktop","hub-embed","shell-embed","embed-preview","headless-client"],cvt=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"],lvt=["host.handshake","providers.list","providers.refresh","runtime.events.list","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","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","turn.start","turn.cancel","turn.steer","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","session.list","session.attach","session.detach","session.snapshot","session.input","session.takeover","session.release","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"],LIn=new Set(lvt),uvt=["host.ready","provider.catalog.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"],ui=class extends Error{code;constructor(t,n){super(n),this.name="AgentHostProtocolError",this.code=t}};yvt=["started","updated","completed","failed","cancelled"],wvt=["","acp."]});import{createHash as bvt}from"node:crypto";import{setTimeout as vvt}from"node:timers/promises";function Evt(e,t){return`subrun-${bvt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}async function Svt(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 Cvt(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=DCe(String(l.type??""));if(!u)continue;let d=`${QCe(l)??l.id}:${u}`;if(i.has(d))continue;i.add(d);let p=LCe(l)??"unknown";if(u==="started"&&r.onToolStart){let f=r.onToolStart;s(()=>f(p,FCe(l)??{}))}let m=jCe(u);if(m!==null&&r.onToolEnd){let f=r.onToolEnd;s(()=>f(p,{success:m,output:UCe(l)??""}))}}}}function qCe(e){let t=e.pollIntervalMs??250;return async n=>{let r=n.task,i=Evt(e.rootTraceId,r.id),o={lastTraceId:null,tokenUsage:{input:0,output:0,total:0},async run(s){let a=await e.client.createSubagentRun({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}});if(!a?.success||!a.run)throw new Error(a?.safeError??"The Agent host refused to create a subagent run for this delegated branch.");let c=a.run.id;o.lastTraceId=c;let l=Cvt(e.client,i,c,{onToolStart:n.onToolStart,onToolEnd:n.onToolEnd});for(;;){if(e.signal?.aborted){await e.client.cancelSubagentRun({runId:c}).catch(()=>{});let m=new Error("Delegated branch was cancelled.");throw m.name="AgentInterruptedError",m}let d=((await e.client.listSubagentRuns({parentConversationId:e.parentConversationId}))?.runs??[]).find(m=>m.id===c),p=String(d?.status??"");if(Ivt.has(p)){if(kvt.has(p))throw new Error(d?.error??`The delegated branch ended as '${p}' without reporting a reason.`);await l();let m=await Svt(e.client,i,c);if(m.length===0)throw new Error(`The delegated branch reported '${p}' but produced no readable output. Its runtime events carry no text for this run id.`);return m}if(Date.now()>=e.deadline)throw await e.client.cancelSubagentRun({runId:c}).catch(()=>{}),new Error("The delegated branch exceeded the time this run was given to wait.");await l(),await vvt(t,void 0,{signal:e.signal})}}};return o}}var Ivt,kvt,VCe=Me(()=>{"use strict";f0();Ivt=new Set(["completed","succeeded","failed","cancelled","error"]),kvt=new Set(["failed","cancelled","error"])});import{createHash as xvt,randomBytes as Rvt}from"node:crypto";import{chmodSync as Tvt,existsSync as Pvt,mkdirSync as WCe,readFileSync as _vt,renameSync as Bvt,unlinkSync as GCe,writeFileSync as $vt}from"node:fs";import{dirname as Mvt,join as h0}from"node:path";function JCe(){return hc()}function Nvt(e){return xvt("sha256").update(e).digest("hex").slice(0,16)}function Rn(){return h0(JCe(),"daemon")}function V3(){return h0(Rn(),"daemon.json")}function zCe(){return h0(Rn(),"daemon.lock")}function Pb(){return h0(Rn(),"daemon.log")}function H3(){let e=Nvt(JCe());return process.platform==="win32"?{transport:"named-pipe",endpoint:`\\\\.\\pipe\\xeno-agent-daemon-${e}`}:{transport:"unix-socket",endpoint:h0(Rn(),"daemon.sock")}}function mD(){WCe(Rn(),{recursive:!0})}function XCe(){return Rvt(32).toString("base64url")}function HCe(e){if(process.platform!=="win32")try{Tvt(e,384)}catch{}}function W3(){try{return JSON.parse(_vt(V3(),"utf8"))}catch{return null}}function YCe(e){let t=V3();WCe(Mvt(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;$vt(n,JSON.stringify(e,null,2)+`
|
|
2691
|
+
`&&(this.atLineStart=!0);this.writeFn(n)}reset(){this.atLineStart=!0}markLineStarted(){this.atLineStart=!1}},YSe=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],e0=class{interval=null;frameIndex=0;lastLength=0;writeFn;clearFn;constructor(t,n){this.writeFn=t??(r=>{GSe.writeFrame(r,"spinner")}),this.clearFn=n??(()=>{GSe.writeFrame(`\r${" ".repeat(this.lastLength)}\r`,"spinner")})}start(t){this.stop(),this.frameIndex=0,this.interval=setInterval(()=>{let n=YSe[this.frameIndex%YSe.length],r=`${Gt(n)} ${Ae(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 ve,Ci=Me(()=>{"use strict";ve="0.5.28"});var CCe=Me(()=>{"use strict"});var xCe=Me(()=>{"use strict"});var RCe=Me(()=>{"use strict"});function dvt(e){return typeof e=="string"&&avt.includes(e)}function pvt(e){return Qo(e)?Mn(e.clientId)&&Mn(e.clientVersion)&&Mn(e.instanceId)&&dvt(e.surface):!1}function PCe(e){return!Qo(e)||!Qo(e.protocol)||!Qo(e.host)||!Qo(e.storage)?!1:Number.isInteger(e.protocol.current)&&Avt(e.protocol.supported)&&Mn(e.host.instanceId)&&Mn(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)&&pvt(e.surface)}function q3(e){return!Qo(e)||!Mn(e.revision)||!Array.isArray(e.providers)?!1:e.providers.every(hvt)}function mvt(e){return!Qo(e)||!Qo(e.event)?!1:Mn(e.id)&&Number.isInteger(e.sequence)&&typeof e.sequence=="number"&&e.sequence>=0&&Mn(e.timestamp)&&Mn(e.conversationId)&&Mn(e.requestId)&&Mn(e.type)&&Mn(e.source)}function _Ce(e){return!Qo(e)||!Array.isArray(e.events)?!1:(e.nextSequence===null||typeof e.nextSequence=="number"&&Number.isInteger(e.nextSequence)&&e.nextSequence>=0)&&e.events.every(mvt)}function BCe(e){return!Qo(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="accepted"||e.status==="replayed")&&Mn(e.conversationId)&&Mn(e.requestId)&&Mn(e.adapterId)&&Qo(e.selection)&&Mn(e.selection.providerId)&&Mn(e.selection.catalogRevision):Mn(e.code)&&Mn(e.safeError)}function $Ce(e){return!Qo(e)||typeof e.success!="boolean"?!1:e.success?(e.status==="cancel_requested"||e.status==="replayed")&&Mn(e.conversationId)&&Mn(e.requestId):Mn(e.code)&&Mn(e.safeError)}function MCe(e){return Qo(e)&&Mn(e.id)&&typeof e.sequence=="number"&&Number.isInteger(e.sequence)&&e.sequence>0&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&fvt(e.type)&&e.source==="host"&&e.schemaVersion===1&&e.redactionState==="safe"&&"payload"in e}function fvt(e){return typeof e=="string"&&uvt.includes(e)}function NCe(e,t,n){if(e.surface.surface!==t.surface||e.surface.instanceId!==t.instanceId)throw new ui("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 ui("protocol_mismatch",`Agent host protocol ${e.protocol.current} is incompatible with client range ${n.min}-${n.max}.`)}function hvt(e){return Qo(e)?Mn(e.id)&&typeof e.kind=="string"&&cvt.includes(e.kind)&&Mn(e.displayName)&&OCe(e.availability)&&Qo(e.capabilities)&&Array.isArray(e.models)&&e.models.every(gvt)&&Mn(e.catalogRevision):!1}function gvt(e){return Qo(e)&&Mn(e.id)&&Mn(e.displayName)&&OCe(e.availability)}function OCe(e){return e==="available"||e==="degraded"||e==="blocked"||e==="unavailable"}function Avt(e){return Qo(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 Mn(e){return typeof e=="string"&&e.trim().length>0}function Qo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DCe(e){for(let t of wvt)for(let n of yvt)if(e===`${t}tool.${n}`)return n;return null}function Bg(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n:void 0}function LCe(e){let t=e.event;return Bg(t,"toolName")||Bg(t,"tool")||Bg(t,"name")||Bg(t,"title")||Bg(t,"kind")}function QCe(e){let t=e.event;return Bg(t,"toolCallId")||Bg(t,"tool_call_id")}function FCe(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 UCe(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 jCe(e){return e==="completed"?!0:e==="failed"||e==="cancelled"?!1:null}var Tb,TCe,avt,cvt,lvt,LIn,uvt,ui,yvt,wvt,f0=Me(()=>{"use strict";CCe();xCe();RCe();Tb=1,TCe=1,avt=["standalone-desktop","hub-embed","shell-embed","embed-preview","headless-client"],cvt=["sdk-native","xeno-cloud","cli-app-server","cli-remote","acp"],lvt=["host.handshake","providers.list","providers.refresh","runtime.events.list","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","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","turn.start","turn.cancel","turn.steer","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","session.list","session.attach","session.detach","session.snapshot","session.input","session.takeover","session.release","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"],LIn=new Set(lvt),uvt=["host.ready","provider.catalog.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"],ui=class extends Error{code;constructor(t,n){super(n),this.name="AgentHostProtocolError",this.code=t}};yvt=["started","updated","completed","failed","cancelled"],wvt=["","acp."]});import{createHash as bvt}from"node:crypto";import{setTimeout as vvt}from"node:timers/promises";function Evt(e,t){return`subrun-${bvt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32)}`}async function Svt(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 Cvt(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=DCe(String(l.type??""));if(!u)continue;let d=`${QCe(l)??l.id}:${u}`;if(i.has(d))continue;i.add(d);let p=LCe(l)??"unknown";if(u==="started"&&r.onToolStart){let f=r.onToolStart;s(()=>f(p,FCe(l)??{}))}let m=jCe(u);if(m!==null&&r.onToolEnd){let f=r.onToolEnd;s(()=>f(p,{success:m,output:UCe(l)??""}))}}}}function qCe(e){let t=e.pollIntervalMs??250;return async n=>{let r=n.task,i=Evt(e.rootTraceId,r.id),o={lastTraceId:null,tokenUsage:{input:0,output:0,total:0},async run(s){let a=await e.client.createSubagentRun({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}});if(!a?.success||!a.run)throw new Error(a?.safeError??"The Agent host refused to create a subagent run for this delegated branch.");let c=a.run.id;o.lastTraceId=c;let l=Cvt(e.client,i,c,{onToolStart:n.onToolStart,onToolEnd:n.onToolEnd});for(;;){if(e.signal?.aborted){await e.client.cancelSubagentRun({runId:c}).catch(()=>{});let m=new Error("Delegated branch was cancelled.");throw m.name="AgentInterruptedError",m}let d=((await e.client.listSubagentRuns({parentConversationId:e.parentConversationId}))?.runs??[]).find(m=>m.id===c),p=String(d?.status??"");if(Ivt.has(p)){if(kvt.has(p))throw new Error(d?.error??`The delegated branch ended as '${p}' without reporting a reason.`);await l();let m=await Svt(e.client,i,c);if(m.length===0)throw new Error(`The delegated branch reported '${p}' but produced no readable output. Its runtime events carry no text for this run id.`);return m}if(Date.now()>=e.deadline)throw await e.client.cancelSubagentRun({runId:c}).catch(()=>{}),new Error("The delegated branch exceeded the time this run was given to wait.");await l(),await vvt(t,void 0,{signal:e.signal})}}};return o}}var Ivt,kvt,VCe=Me(()=>{"use strict";f0();Ivt=new Set(["completed","succeeded","failed","cancelled","error"]),kvt=new Set(["failed","cancelled","error"])});import{createHash as xvt,randomBytes as Rvt}from"node:crypto";import{chmodSync as Tvt,existsSync as Pvt,mkdirSync as WCe,readFileSync as _vt,renameSync as Bvt,unlinkSync as GCe,writeFileSync as $vt}from"node:fs";import{dirname as Mvt,join as h0}from"node:path";function JCe(){return hc()}function Nvt(e){return xvt("sha256").update(e).digest("hex").slice(0,16)}function Rn(){return h0(JCe(),"daemon")}function V3(){return h0(Rn(),"daemon.json")}function zCe(){return h0(Rn(),"daemon.lock")}function Pb(){return h0(Rn(),"daemon.log")}function H3(){let e=Nvt(JCe());return process.platform==="win32"?{transport:"named-pipe",endpoint:`\\\\.\\pipe\\xeno-agent-daemon-${e}`}:{transport:"unix-socket",endpoint:h0(Rn(),"daemon.sock")}}function mD(){WCe(Rn(),{recursive:!0})}function XCe(){return Rvt(32).toString("base64url")}function HCe(e){if(process.platform!=="win32")try{Tvt(e,384)}catch{}}function W3(){try{return JSON.parse(_vt(V3(),"utf8"))}catch{return null}}function YCe(e){let t=V3();WCe(Mvt(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;$vt(n,JSON.stringify(e,null,2)+`
|
|
2692
2692
|
`,{encoding:"utf8",mode:384}),HCe(n),Bvt(n,t),HCe(t)}function fD(){try{GCe(V3())}catch{}}function KCe(){if(process.platform==="win32")return;let{endpoint:e}=H3();if(Pvt(e))try{GCe(e)}catch{}}function Au(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}var Fo=Me(()=>{"use strict";gh()});import{execFileSync as G3}from"node:child_process";import{createHash as Ovt}from"node:crypto";import{existsSync as Dvt,readFileSync as J3,readlinkSync as Lvt}from"node:fs";import{hostname as _b}from"node:os";function z3(e){return Number.isInteger(e)&&e>0}function Fvt(e){return Ovt("sha256").update(e).digest("hex")}function A0(e){let t=e?.trim().replaceAll("\\","/").toLowerCase();return t?`sha256:${Fvt(t)}`:void 0}function hD(){if(process.platform==="linux")try{return J3("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function Uvt(e){if(!z3(e))return!1;try{return process.kill(e,0),!0}catch{return!1}}function ZCe(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function jvt(e){let t=new Map;if(e.length===0)return t;let r=["$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("; ");try{let i=G3("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",r],{encoding:"utf8",windowsHide:!0,timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();if(!i)return t;let o=JSON.parse(i);for(let s of Array.isArray(o)?o:[o]){let a=Number(s.pid),c=ZCe(String(s.startedAt??""));!z3(a)||!c||t.set(a,{pid:a,processStartedAt:c,hostname:_b(),...A0(s.executable)?{executableFingerprint:A0(s.executable)}:{},confidence:"observed"})}}catch{return t}return t}function qvt(){if(g0)return g0;try{let e=Number.parseInt(G3("getconf",["CLK_TCK"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),10);g0=Number.isFinite(e)&&e>0?e:100}catch{g0=100}return g0}function Vvt(){try{let e=/^btime\s+(\d+)$/m.exec(J3("/proc/stat","utf8"));return e?Number.parseInt(e[1]??"",10):null}catch{return null}}function Hvt(e){try{let t=J3(`/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=Vvt();if(!Number.isFinite(i)||o===null)return null;let s=new Date((o+i/qvt())*1e3).toISOString(),a;try{a=Lvt(`/proc/${e}/exe`)}catch{a=void 0}return{pid:e,processStartedAt:s,hostname:_b(),...hD()?{bootId:hD()}:{},...A0(a)?{executableFingerprint:A0(a)}:{},confidence:"observed"}}catch{return null}}function Wvt(e){let t=new Map;if(process.platform==="linux"){for(let n of e){let r=Hvt(n);r&&t.set(n,r)}return t}for(let n of e)try{let r=G3("ps",["-p",String(n),"-o","lstart="],{encoding:"utf8",timeout:2e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim(),i=ZCe(r);if(!i)continue;t.set(n,{pid:n,processStartedAt:i,hostname:_b(),confidence:"observed"})}catch{continue}return t}function y0(e){let t=[...new Set(e.filter(z3))],n=t.includes(process.pid),r=n?t.filter(o=>o!==process.pid):t,i=process.platform==="win32"?jvt(r):Wvt(r);return n&&i.set(process.pid,$g()),i}function e0e(e){return y0([e]).get(e)??null}function gD(e,t=new Date,n=!1){return(n?e0e(e):null)??{pid:e,processStartedAt:t.toISOString(),hostname:_b(),confidence:"degraded"}}function $g(){let e=new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString();return{pid:process.pid,processStartedAt:e,hostname:_b(),...hD()?{bootId:hD()}:{},...Dvt(process.execPath)?{executableFingerprint:A0(process.execPath)}:{},confidence:"self"}}function yu(e,t=e0e){if(e.hostname!==_b())return{status:"remote",expected:e,reason:"Process belongs to another host."};if(!Uvt(e.pid))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)>Qvt?{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 Qvt,g0,Mg=Me(()=>{"use strict";Qvt=3e3});import{existsSync as Gvt,linkSync as Jvt,mkdirSync as zvt,readFileSync as Xvt,rmSync as Y3,statSync as Yvt,writeFileSync as Kvt}from"node:fs";import{hostname as t0e}from"node:os";import{dirname as Zvt}from"node:path";import{randomUUID as eIt}from"node:crypto";function tIt(){return new Date().toISOString()}function X3(e){try{return JSON.parse(Xvt(e,"utf8"))}catch{return null}}function nIt(e){if(e.hostname!==t0e())return!0;let t=Date.parse(e.acquiredAt);if(Number.isFinite(t)&&Date.now()-t<3e4)return!0;if(!Au(e.pid))return!1;if(e.processIdentity){let n=yu(e.processIdentity);return n.status==="live"||n.status==="degraded"||n.status==="remote"}return!0}function n0e(e,t){zvt(Zvt(e),{recursive:!0});let n=`${e}.${process.pid}.${eIt()}.tmp`;Kvt(n,JSON.stringify(t,null,2)+`
|
|
2693
2693
|
`,{encoding:"utf8",flag:"wx"});try{Jvt(n,e)}finally{Y3(n,{force:!0})}}function rIt(e){try{return Date.now()-Yvt(e).mtimeMs<3e4}catch{return!1}}function iIt(e,t){return e?.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}function w0(e,t){return new Error(`${e} is already locked ${t}.`)}function oIt(e,t,n){try{n0e(e,t)}catch(r){throw r.code==="EEXIST"?w0(n,"by another contender"):r}}function sIt(e,t){let n=X3(e);n?.pid!==t.pid||n.hostname!==t.hostname||n.processStartedAt!==t.processStartedAt||Y3(e,{force:!0})}function _s(e,t,n){let r=tIt(),i=$g(),o={schemaVersion:1,name:t,pid:process.pid,hostname:t0e(),processStartedAt:i.processStartedAt,processIdentity:i,version:n,acquiredAt:r,updatedAt:r};try{n0e(e,o)}catch(s){if(s.code!=="EEXIST")throw s;let c=X3(e);if(c&&nIt(c))throw w0(t,`by PID ${c.pid} on ${c.hostname}`);if(c){if(!iIt(X3(e),c))throw w0(t,"while ownership was changing")}else{if(!Gvt(e))throw w0(t,"while ownership was changing");if(rIt(e))throw w0(t,"by an owner whose record is still being published")}Y3(e,{force:!0}),oIt(e,o,t)}return{record:o,release:()=>{sIt(e,o)}}}var Ng=Me(()=>{"use strict";Fo();Mg()});import{createHash as s0e,randomBytes as aIt,randomUUID as a0e}from"node:crypto";import{closeSync as cIt,existsSync as Z3,fsyncSync as lIt,mkdirSync as e6,openSync as uIt,readFileSync as AD,renameSync as dIt,writeFileSync as c0e}from"node:fs";import{cpus as pIt}from"node:os";import{dirname as l0e,isAbsolute as mIt,join as Mb,resolve as fIt}from"node:path";function v0(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 AIt(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 Bb(e,t){return t===void 0?e:Math.min(e,t)}function b0(e,t){return{maxConcurrency:Bb(e.maxConcurrency,t?.maxConcurrency),maxCredentialConcurrency:Bb(e.maxCredentialConcurrency,t?.maxCredentialConcurrency),maxRequestsPerWindow:Bb(e.maxRequestsPerWindow,t?.maxRequestsPerWindow),maxTokensPerWindow:Bb(e.maxTokensPerWindow,t?.maxTokensPerWindow),windowMs:t?.windowMs===void 0?e.windowMs:Math.max(1e3,t.windowMs)}}function yIt(e={}){let t=e.env??process.env,n=Math.max(1,e.cpuCount??pIt().length),r=Math.min(Math.max(1,n-2),hIt),i=v0(t.XENO_WORKFLOW_GLOBAL_CONCURRENCY,r,1,K3),s=t.XENO_WORKFLOW_TRUSTED_CONCURRENCY_OVERRIDE==="1"?i:Math.min(r,i);s=Bb(s,e.user?.globalConcurrency),s=Bb(s,e.managed?.globalConcurrency),s=v0(s,r,1,K3);let a={maxConcurrency:Math.min(s,8),maxCredentialConcurrency:Math.min(s,4),maxRequestsPerWindow:120,maxTokensPerWindow:2e6,windowMs:6e4},c=b0(a,e.user?.providerDefault),l=b0(c,e.managed?.providerDefault),u=new Set([...Object.keys(e.user?.providers??{}),...Object.keys(e.managed?.providers??{})]),d=Object.fromEntries([...u].map(m=>[m,b0(b0(l,e.user?.providers?.[m]),e.managed?.providers?.[m])])),p=(m,f,h=1,g=Number.MAX_SAFE_INTEGER)=>{let A=f,w=e.user?.[m],y=e.managed?.[m];return typeof w=="number"&&(A=Math.min(A,w)),typeof y=="number"&&(A=Math.min(A,y)),v0(A,f,h,g)};return{schemaVersion:1,productHardConcurrency:K3,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:AIt(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 r0e(e,t){if(!Z3(e)){if(t)throw new Uo("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy file not found: ${e}`);return}try{let n=JSON.parse(AD(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 Uo("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource policy is invalid: ${e}: ${n instanceof Error?n.message:String(n)}`)}}function wIt(e=process.env){let t=l0e(Rn()),n=e.XENO_WORKFLOW_RESOURCE_POLICY?.trim(),r=e.XENO_MANAGED_WORKFLOW_RESOURCE_POLICY?.trim(),i=a=>mIt(a)?a:fIt(a),o=r0e(n?i(n):Mb(t,"resource-policy.json"),!!n),s=r?r0e(i(r),!0):void 0;return yIt({env:e,user:o,managed:s})}function Yi(e){return new Date(e).toISOString()}function bIt(e){return{schemaVersion:1,revision:0,nextFencingToken:1,updatedAt:Yi(e),permits:[],queue:[],attempts:[],usage:[],providerRates:[],effects:[]}}function vIt(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 IIt(e,t){e6(l0e(e),{recursive:!0});let n=`${e}.${process.pid}.${a0e()}.tmp`,r=uIt(n,"wx",384);try{c0e(r,JSON.stringify(t,null,2)+`
|
|
2694
2694
|
`,"utf8"),lIt(r)}finally{cIt(r)}dIt(n,e)}function kIt(e,t,n){let r=Date.parse(e.requestedAt??""),i=Number.isFinite(r)?r:t,o=Date.parse(e.queueDeadlineAt??"");return{requestedAt:Yi(i),deadlineAt:Yi(Number.isFinite(o)?Math.min(o,i+n):i+n)}}function u0e(e,t){return b0(e.providerDefault,e.providers[t])}function i0e(e,t,n){let r=Math.max(0,t-Date.parse(e.enqueuedAt));return gIt[e.priorityClass]+Math.floor(r/n.maxStarvationMs)*1001}function EIt(e,t,n){return[...e].sort((r,i)=>i0e(i,t,n)-i0e(r,t,n)||Date.parse(r.enqueuedAt)-Date.parse(i.enqueuedAt)||r.requestId.localeCompare(i.requestId))}function SIt(e,t){return e.pid===t.pid&&e.hostname===t.hostname&&e.processStartedAt===t.processStartedAt}function $b(e){return Number.isFinite(e)?Math.max(0,Number(e)):0}function o0e(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,v0(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=u0e(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,v0(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=$b(t.reservedTokens);if(i.reduce((b,v)=>b+v.reservedTokens,0)+d>n.maxReservedTokens)return{code:"WORKFLOW_TOKEN_LIMIT",reason:"global_token_reservation"};let m=$b(t.reservedCostUsd);if(i.reduce((b,v)=>b+v.reservedCostUsd,0)+m>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,v)=>b+v.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,v)=>b+v.reservedCostUsd,0);if(t.runCostLimitUsd!==void 0&&(h?.costUsd??0)+A+m>t.runCostLimitUsd)return{code:"WORKFLOW_COST_LIMIT",reason:"run_cost_limit"};let w=r-a.windowMs,y=e.providerRates.filter(b=>b.providerId===t.providerId&&Date.parse(b.timestamp)>=w&&(!t.credentialFingerprint||b.credentialFingerprint===t.credentialFingerprint));return y.length>=a.maxRequestsPerWindow?{reason:"provider_request_rate"}:y.reduce((b,v)=>b+v.tokens,0)+d>a.maxTokensPerWindow?{reason:"provider_token_rate"}:{}}function CIt(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 Uo("WORKFLOW_GOVERNOR_UNAVAILABLE",`Invalid resource request field: ${t}.`);if(e.credentialFingerprint&&!/^(?:cred_)?sha256_[a-f0-9]{32,64}$/i.test(e.credentialFingerprint))throw new Uo("WORKFLOW_GOVERNOR_UNAVAILABLE","credentialFingerprint must be a scoped SHA-256 fingerprint.")}function qm(e,t){let n=String(e??"default").trim().toLowerCase().split(/[/:]/,1)[0]||"default",r=t?.trim()?s0e("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16):"default";return`${n}@${r}`}function t6(e){let t=s0e("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 n6(e=Mb(Rn(),"governor")){let t=Mb(e,"credential-salt.bin");if(e6(e,{recursive:!0}),Z3(t))return AD(t);let n=aIt(32);try{return c0e(t,n,{flag:"wx",mode:384}),n}catch{return AD(t)}}function Nb(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?t6({providerId:e,endpoint:n,credential:o,salt:n6()}):void 0}function yD(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 r6(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 Og(e,t,n=process.env){if(n.XENO_RESOURCE_OPERATION_ID?.trim()!==e)return;let r=r6(n);if(!t||!r||t.permitId!==r.permitId||t.fencingToken!==r.fencingToken)throw new Uo("WORKER_LEASE_EXPIRED","Worker state write rejected because its fencing token is stale.");new Br().assertFence(r.permitId,r.fencingToken)}var K3,hIt,Uo,gIt,Br,zd=Me(()=>{"use strict";Ci();yb();Fo();Ng();Mg();K3=64,hIt=16,Uo=class extends Error{constructor(n,r){super(r);this.code=n;this.name="WorkflowResourceError"}code},gIt={control:1e3,foreground:900,reconciliation:850,terminal:800,"app-server":700,workflow:500,background:400,scheduled:300};Br=class{policy;rootDir;ledgerPath;lockPath;now;owner;fault;constructor(t={}){this.rootDir=t.rootDir??Mb(Rn(),"governor"),this.ledgerPath=Mb(this.rootDir,"resource-ledger.json"),this.lockPath=Mb(this.rootDir,"resource-ledger.lock"),this.policy=t.policy??wIt(),this.now=t.now??Date.now,this.owner=t.owner??$g,this.fault=t.fault,e6(this.rootDir,{recursive:!0})}acquire(t){CIt(t);let n=0,r=this.withLedger((a,c)=>{this.cleanupExpired(a,c);let l=a.permits.find(v=>v.requestId===t.requestId||v.attemptId===t.attemptId);if(l)return n=a.permits.length,{value:{status:"active",permit:l,reason:"attempt_already_active"},changed:!0};let u=kIt(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(v=>v.requestId===t.requestId);if(d&&c>Date.parse(d.queueDeadlineAt??u.deadlineAt))return a.queue=a.queue.filter(v=>v.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(),m=d?{...d,...t,owner:d.owner,updatedAt:Yi(c)}:{...t,owner:p,requestedAt:u.requestedAt,queueDeadlineAt:u.deadlineAt,enqueuedAt:Yi(c),updatedAt:Yi(c)};d?a.queue=a.queue.map(v=>v.requestId===m.requestId?m:v):a.queue.push(m);let f=EIt(a.queue,c,this.policy),h,g={};for(let v of f){let I=o0e(a,v,this.policy,c);if(v.requestId===m.requestId&&(g=I),!I.reason){h=v;break}}if(g.code==="WORKFLOW_ATTEMPT_LIMIT"||g.code==="WORKFLOW_TOKEN_LIMIT"||g.code==="WORKFLOW_COST_LIMIT")return a.queue=a.queue.filter(v=>v.requestId!==m.requestId),{value:{status:"rejected",code:g.code,reason:g.reason??"resource_limit"},changed:!0};if(!h||h.requestId!==m.requestId){let v=a.permits.map(R=>Date.parse(R.expiresAt)).filter(Number.isFinite).sort((R,C)=>R-C)[0],I=u0e(this.policy,m.providerId),k=a.providerRates.filter(R=>R.providerId===m.providerId&&(!m.credentialFingerprint||R.credentialFingerprint===m.credentialFingerprint)).map(R=>Date.parse(R.timestamp)+I.windowMs).filter(R=>Number.isFinite(R)&&R>c).sort((R,C)=>R-C)[0],x=[v,k].filter(R=>typeof R=="number").sort((R,C)=>R-C)[0];return{value:{status:"queued",request:m,reason:g.reason??"waiting_for_fair_turn",...x?{estimatedEligibleAt:Yi(x)}:{}},changed:!0}}let A=o0e(a,m,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(v=>v.requestId!==m.requestId),{value:{status:"rejected",code:A.code,reason:A.reason},changed:!0}):{value:{status:"queued",request:m,reason:A.reason},changed:!0};let w=Yi(c),y={permitId:`permit_${a0e()}`,requestId:m.requestId,operationId:m.operationId,surface:m.surface,priorityClass:m.priorityClass,runId:m.runId,...m.parentId?{parentId:m.parentId}:{},providerId:m.providerId,...m.credentialFingerprint?{credentialFingerprint:m.credentialFingerprint}:{},logicalChildId:m.logicalChildId,attemptId:m.attemptId,idempotencyKey:m.idempotencyKey,fencingToken:a.nextFencingToken++,owner:m.owner,acquiredAt:w,heartbeatAt:w,expiresAt:Yi(c+this.policy.leaseTtlMs),reservedTokens:$b(m.reservedTokens),reservedCostUsd:$b(m.reservedCostUsd),lastDurableSequence:0};a.queue=a.queue.filter(v=>v.requestId!==m.requestId),a.permits.push(y),n=a.permits.length;let b=a.attempts.find(v=>v.attemptId===m.attemptId);return b?Object.assign(b,{state:"active",permitId:y.permitId,endedAt:void 0,outcome:void 0}):a.attempts.push({runId:m.runId,logicalChildId:m.logicalChildId,attemptId:m.attemptId,idempotencyKey:m.idempotencyKey,state:"active",permitId:y.permitId,startedAt:w}),a.providerRates.push({providerId:m.providerId,...m.credentialFingerprint?{credentialFingerprint:m.credentialFingerprint}:{},timestamp:w,tokens:y.reservedTokens}),this.fault?.("acquire.before_commit"),{value:{status:"acquired",permit:y},changed:!0,afterCommit:()=>this.fault?.("acquire.after_commit")}}),i=r.status==="rejected"?r.code:r.status==="acquired"?"admitted":r.reason;wr("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")&&wr("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)&&Do("xeno.workflow.queue_wait_ms",Math.max(0,s-o),{component:"resource_governor",provider:t.providerId,state:r.status}),n>0&&Do("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(!SIt(i.owner,o))throw new Uo("WORKER_IDENTITY_MISMATCH","Permit heartbeat came from a different worker identity.");return i.heartbeatAt=Yi(r),i.expiresAt=Yi(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=Yi(o),s.expiresAt=Yi(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 Uo("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:Yi(r),outcome:t.outcome});let s=n.usage.find(c=>c.runId===i.runId),a={runId:i.runId,tokens:(s?.tokens??0)+$b(t.actualTokens),costUsd:(s?.costUsd??0)+$b(t.actualCostUsd),attempts:(s?.attempts??0)+1,updatedAt:Yi(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:Yi(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=Yi(r),{value:!0,changed:!0})})}reconcile(t){let n=this.withLedger((r,i)=>{let o=[...r.permits],s=[...r.queue],a=t??y0(o.map(h=>h.owner.pid)),c=new Set,l=new Set;for(let h of o){let g=yu(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)),m=new Set(r.queue.map(h=>h.requestId)),f=s.filter(h=>!m.has(h.requestId));return{value:{expiredPermits:d,identityMismatches:p,expiredQueue:f,livePermits:r.permits.length,degradedPermits:r.permits.filter(h=>l.has(h.permitId)).length},changed:d.length>0||p.length>0||f.length>0}});return Do("xeno.worker.live_leases",n.livePermits,{component:"resource_governor",operation:"reconcile"}),Do("xeno.worker.degraded_leases",n.degradedPermits,{component:"resource_governor",operation:"reconcile"}),n.expiredPermits.length>0&&wr("xeno.worker.lease_expirations",n.expiredPermits.length,{component:"resource_governor",operation:"reconcile"}),n.identityMismatches.length>0&&wr("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=Yi(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 Uo("WORKER_LEASE_EXPIRED","The worker lease is missing, expired, or fenced out.");return o}readLedger(t){if(!Z3(this.ledgerPath))return bIt(t);try{let n=JSON.parse(AD(this.ledgerPath,"utf8"));if(!vIt(n))throw new Error("Unsupported resource ledger schema.");return n}catch(n){throw new Uo("WORKFLOW_GOVERNOR_UNAVAILABLE",`Resource ledger is unreadable and was not overwritten: ${n instanceof Error?n.message:String(n)}`)}}withLedger(t){let n=Date.now()+5e3,r=new Int32Array(new SharedArrayBuffer(4)),i,o;for(;!i&&Date.now()<=n;)try{i=_s(this.lockPath,"workflow-resource-governor",ve)}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 Uo("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=Yi(s),IIt(this.ledgerPath,a)),c.afterCommit?.(),c.value}finally{i.release()}}}});import{createHash as xIt,randomUUID as RIt}from"node:crypto";import{setTimeout as TIt}from"node:timers/promises";function PIt(){return`delegation-${Date.now().toString(36)}-${RIt().slice(0,8)}`}function _It(e){return async t=>(await pl({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 BIt(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 Uo("WORKFLOW_CONCURRENCY_LIMIT","Delegated branch attempt is already active.");if(t.status==="rejected")throw new Uo(t.code,t.reason);if(Date.now()>=e.deadline)throw e.governor.cancelQueued(e.request.requestId),new Uo("WORKFLOW_QUEUE_EXPIRED","Delegated branch exceeded its admission deadline.");await TIt(50,void 0,{signal:e.signal})}}function $It(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 I0(e){let t=new Br,n=e.rootTraceId??PIt(),r=qm(e.model,e.baseURL),i=e.apiKey?t6({providerId:r,endpoint:e.baseURL,credential:e.apiKey,salt:n6()}):Nb(r,process.env,e.baseURL),o=e.createBranchAgent??_It(e),s=Date.now()+e.timeoutMs,a=async c=>{let l=c.task,u=`${n}:${l.id}`,d=`${u}:attempt-1`,p=xIt("sha256").update(`${n}\0${l.id}\0${l.prompt}`).digest("hex"),m=await BIt({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:m.permitId,fencingToken:m.fencingToken,effectKey:`delegated:${m.operationId}`}))throw t.settle({permitId:m.permitId,fencingToken:m.fencingToken,outcome:"duplicate_branch_suppressed"}),new Uo("WORKFLOW_CONCURRENCY_LIMIT","Duplicate delegated branch execution was suppressed.");try{let f=await o(c);return t.commitEffect({permitId:m.permitId,fencingToken:m.fencingToken,effectKey:`delegated:${m.operationId}`}),$It(f,t,m)}catch(f){throw t.settle({permitId:m.permitId,fencingToken:m.fencingToken,outcome:"branch_creation_failed"}),f}};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 vO({...e,rootTraceId:n,createBranchAgent:qCe({...e.hostDelegation,rootTraceId:n,deadline:s,...e.signal===void 0?{}:{signal:e.signal}})})}return vO({...e,rootTraceId:n,createBranchAgent:a})}var d0e=Me(()=>{"use strict";Et();VCe();zd();Et()});function xc(e=ve){return{createdByCliVersion:e,createdBySdkVersion:Qd}}var Dg=Me(()=>{"use strict";Fn();Ci()});var A0e={};fc(A0e,{AgentRunStore:()=>Fe,createAgentRunId:()=>g0e,getAgentRunDir:()=>HIt,getAgentRunStoreDir:()=>l6,projectRecordStatus:()=>a6});import{randomUUID as MIt}from"node:crypto";import{appendFileSync as NIt,existsSync as wD,mkdirSync as C0,readFileSync as f0e,readdirSync as k0,renameSync as OIt,rmSync as E0,writeFileSync as vD}from"node:fs";import{basename as i6,dirname as h0e,join as is,resolve as DIt}from"node:path";function di(){return new Date().toISOString()}function FIt(e=new Date){return e.toISOString().replace(/[^0-9]/g,"").slice(0,14)}function ID(e){return e.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)}function c6(e){return DIt(e)}function kD(e){return c6(e).toLowerCase()}function m0e(e,t){let n=kD(e),r=kD(t);return n===r||n.startsWith(`${r}\\`)||n.startsWith(`${r}/`)}function s6(e,t){return!!(kD(e.cwd)===kD(t)||e.git?.root&&m0e(t,e.git.root)||e.git?.worktree&&m0e(t,e.git.worktree))}function UIt(e){return ID(Buffer.from(c6(e)).toString("base64url"))}function jIt(){return{input:0,output:0,total:0}}function Xd(e){try{return JSON.parse(f0e(e,"utf8"))}catch{return null}}function qIt(e){return e instanceof Error&&/\balready locked by PID\b/.test(e.message)}function S0(e,t){C0(h0e(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;vD(n,JSON.stringify(t,null,2)+`
|
|
@@ -3966,7 +3966,7 @@ ${r}`}}import{execFileSync as I1e}from"node:child_process";function t1t(){let e=
|
|
|
3966
3966
|
`),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)
|
|
3967
3967
|
`),n.onOutput(`
|
|
3968
3968
|
`),{handled:!0}}function hf(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 $1e(e){let t=["Last Session Summary",`- model: ${e.model}`,`- mode: ${e.mode??"unknown"}`,`- status: ${e.status??"unknown"}`,`- started: ${e.startedAt}`,`- ended: ${e.endedAt}`,`- duration: ${hf(e.durationMs)}`,`- tokens: ${e.tokenUsage.input.toLocaleString()} in / ${e.tokenUsage.output.toLocaleString()} out / ${e.tokenUsage.total.toLocaleString()} total`,`- estimated cost: ${Iu(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(`
|
|
3969
|
-
`)}function B1t(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function y2(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${B1t(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}yr();Ci();var $1t={"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.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 _K(e=ve){return $1t[e]??[]}function M1t(e=ve){let t=dt().lastReleaseNotesSeen;return _K(e).length>0&&t!==e}function kv(e=ve){Wr({lastReleaseNotesSeen:e})}function w2(e){let t=e??ve,n=_K(t);return n.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...n.map(r=>`- ${r}`)].join(`
|
|
3969
|
+
`)}function B1t(e){let t=e.replace(/\s+/g," ").trim();return t.length>72?`${t.slice(0,69)}...`:t}async function y2(e){if(!e.checkpointManager||e.messages.length===0)return null;let t=`Branch before rewind to "${B1t(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}yr();Ci();var $1t={"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.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 _K(e=ve){return $1t[e]??[]}function M1t(e=ve){let t=dt().lastReleaseNotesSeen;return _K(e).length>0&&t!==e}function kv(e=ve){Wr({lastReleaseNotesSeen:e})}function w2(e){let t=e??ve,n=_K(t);return n.length===0?`No release notes available for version ${t}.`:[`Release notes for version ${t}`,"",...n.map(r=>`- ${r}`)].join(`
|
|
3970
3970
|
`)}function M1e(e=ve){if(M1t(e))return[`What's new in XENO AGENT v${e}`,..._K(e).map(t=>`- ${t}`),"Run `xeno release-notes` to view this again."].join(`
|
|
3971
3971
|
`)}Rt();Fa();Ki();F0();import{spawn as N1t}from"node:child_process";import{setTimeout as $K}from"node:timers/promises";function $s(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
3972
3972
|
`)}function O1t(e,t){if(t){$s(e);return}if(e.ok&&e.definition){process.stdout.write(`Workflow valid: ${e.definition.name}
|
|
@@ -7312,7 +7312,7 @@ compdef _xeno xeno
|
|
|
7312
7312
|
`)}
|
|
7313
7313
|
`}async function gmn(e={}){let t=await Xa({validate:e.validate!==!1}),n=["Xeno auth doctor",""];return n.push(up(t).trimEnd()),n.push(""),n.push(`Auth base URL: ${e.authBaseURL??t.authBaseURL??Ti}`),n.push(`Model API base URL: ${e.apiBaseURL??t.apiBaseURL??Ar}`),t.expired?n.push("Action: session is expired; run `xeno login` again."):t.signedIn?t.hasApiKey?t.valid===!1?n.push("Action: model API credential validation failed; run `xeno login --api-key <key>`."):n.push("Action: auth state looks usable."):n.push("Action: no model credential is configured; run `xeno login` or `xeno login --api-key <key>`."):n.push("Action: run `xeno login`."),`${n.join(`
|
|
7314
7314
|
`)}
|
|
7315
|
-
`}function Amn(e,t){let n=Math.max(0,Math.floor((t-Pe(e))/2));return" ".repeat(n)+e}function doe(e){let t=Math.max(48,process.stdout.columns??80),n=Math.max(18,process.stdout.rows??24),r=or(),i=e.email?`Signed in to Xeno as ${e.email}`:"Signed in to Xeno",o=e.credentialsPath?`Credentials: ${e.credentialsPath}`:"Credentials stored locally",s=(l,u)=>S.moveTo(l,1)+S.eraseLine()+Amn(u,t),a=Math.max(6,Math.floor(n/2)),c=S.clearScreen();return c+=S.hideCursor(),c+=s(3,i),c+=s(a-1,r("XENO")),c+=s(a+1,"AI-native command-line agent"),c+=s(Math.max(1,n-4),o),c+=s(Math.max(1,n-2),"Run `xeno` to start. Use `xeno --tui` to test fullscreen mode."),c+=S.moveTo(n,1)+S.showCursor(),c}fe.name("xeno").description("XENO AGENT - AI-powered terminal agent by Xeno Corporation").version(ve).option("--safe-mode","Disable user/project customizations for troubleshooting").addHelpText("after",["","Default chat/background options:"," --bg [prompt] Start an interactive background agent session and print its session ID"," --exec <command> With --bg, start a background shell session for this command",""].join(`
|
|
7315
|
+
`}function Amn(e,t){let n=Math.max(0,Math.floor((t-Pe(e))/2));return" ".repeat(n)+e}function doe(e){let t=Math.max(48,process.stdout.columns??80),n=Math.max(18,process.stdout.rows??24),r=or(),i=e.email?`Signed in to Xeno as ${e.email}`:"Signed in to Xeno",o=e.credentialsPath?`Credentials: ${e.credentialsPath}`:"Credentials stored locally",s=(l,u)=>S.moveTo(l,1)+S.eraseLine()+Amn(u,t),a=Math.max(6,Math.floor(n/2)),c=S.clearScreen();return c+=S.hideCursor(),c+=s(3,i),c+=s(a-1,r("XENO")),c+=s(a+1,"AI-native command-line agent"),c+=s(Math.max(1,n-4),o),c+=s(Math.max(1,n-2),"Run `xeno` to start. Use `xeno --tui` to test fullscreen mode."),c+=S.moveTo(n,1)+S.showCursor(),c}fe.name("xeno").description("XENO AGENT - AI-powered terminal agent by Xeno Corporation").version(ve).option("--safe-mode","Disable user/project customizations for troubleshooting").addHelpText("after",["","Default chat/background options:"," --resume [id] Resume the latest session or an exact session ID"," --interface Open XENO Agent Interface and resume this workspace's session"," --bg [prompt] Start an interactive background agent session and print its session ID"," --exec <command> With --bg, start a background shell session for this command",""].join(`
|
|
7316
7316
|
`));fe.command("login").description("Sign in to Xeno or store a model API key for the CLI").option("--email <email>","Xeno account email").option("--password <password>","Xeno account password (prefer --stdin-password for automation)").option("--stdin-password","Read the account password from stdin").option("--api-key <key>","Store a Xeno model API key directly").option("--token <token>","Store an existing Xeno account token directly").option("--auth-base-url <url>","Authentication API base URL",Ti).option("--api-base-url <url>","Model API base URL").option("--status","Show current auth status instead of signing in").option("--no-provision-api-key","Do not try to create/reuse a model API key after account login").option("--no-validate","Skip live validation after storing credentials").option("--json","Emit machine-readable JSON output").action(async e=>{let t=Tk(e.authBaseUrl)??Ti,n=Tk(e.apiBaseUrl);if(e.status){let m=await Xa({validate:e.validate!==!1});process.stdout.write(e.json?JSON.stringify(m,null,2)+`
|
|
7317
7317
|
`:up(m));return}let r=!(typeof e.email=="string"&&e.email.trim().length>0),i=!e.stdinPassword&&!(typeof e.password=="string"&&e.password.length>0),o=!(typeof e.apiKey=="string"&&e.apiKey.trim().length>0),s=!(typeof e.token=="string"&&e.token.trim().length>0);if(r&&i&&o&&s){let{runWelcomeAuthFlow:m}=await Promise.resolve().then(()=>(RR(),mQ)),f=await m({apiBaseURL:n??Ar,authBaseURL:t});if(f.kind==="exit"){e.json&&process.stdout.write(JSON.stringify({ok:!1,cancelled:!0},null,2)+`
|
|
7318
7318
|
`);return}if(f.kind==="error"){e.json?process.stdout.write(JSON.stringify({ok:!1,error:f.message},null,2)+`
|