@xenosystem/agent-sdk 0.9.31 → 0.9.32

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 CHANGED
@@ -2448,7 +2448,7 @@ try {
2448
2448
 
2449
2449
  ---
2450
2450
 
2451
- `));let h=t.systemPrompt??S2({cwd:e,model:n,date:t.date??new Date().toISOString().split("T")[0],identity:u,memory:f||void 0,sessionId:t.sessionId,executionMode:r}),y=t.dispatchAgent??(async v=>{let{createDelegatedXenoAgent:S}=await Promise.resolve().then(()=>(fg(),r$)),{agent:x}=await S({cwd:e,apiKey:o,baseURL:i,model:n,...t.fallbackModels?{fallbackModels:t.fallbackModels}:{},...t.effort?{effort:t.effort}:{},maxTokens:Math.max(512,Math.min(t.maxTokens??o$,4096)),maxIterations:Math.max(3,Math.min(t.maxIterations??i$,12)),parentSystemPrompt:h,parentExecutionMode:r,subagentRole:"explorer",permissionEngine:d,...t.sandbox?{sandbox:t.sandbox}:{},...t.onPermissionRequest?{onPermissionRequest:t.onPermissionRequest}:{}}),E=()=>{x.cancelCurrentTurn()};if(v.signal?.aborted)throw E(),new Error("dispatch_agent was aborted before the helper started");v.signal?.addEventListener("abort",E,{once:!0});try{return{output:await x.run(v.prompt)}}finally{v.signal?.removeEventListener("abort",E)}});if(t.validateToolInputs===!1)throw new Error("Agent tool input validation cannot be disabled.");let b=t.toolRegistry??zt({cwd:e,askUser:t.askUser,dispatchAgent:y,...t.webSearchApiKey?{webSearchApiKey:t.webSearchApiKey}:{},...t.permissionConfig?.profile?{permissionProfile:t.permissionConfig.profile}:{},...t.ownerSessionId?{ownerSessionId:t.ownerSessionId}:{},...t.getOwnerSessionId?{getOwnerSessionId:t.getOwnerSessionId}:{},...t.sandbox?{sandbox:t.sandbox}:{},...g?{memoryManager:g}:{},validateInputs:!0});return t.toolRegistry&&t.validateToolInputs===!0&&b.setValidateInputs(!0),{agent:new oi({apiKey:o,baseURL:i,ollamaBaseURL:s,localRuntimeProtocol:t.localRuntimeProtocol,localTransportLimits:t.localTransportLimits,...(t.apiRequestTimeoutMs??l)!==void 0?{apiRequestTimeoutMs:t.apiRequestTimeoutMs??l}:{},model:n,...t.fallbackModels?{fallbackModels:t.fallbackModels}:{},...t.effort?{effort:t.effort}:{},maxTokens:t.maxTokens??o$,maxIterations:t.maxIterations??i$,maxContextTokens:t.maxContextTokens,maxContextMessages:t.maxContextMessages,compressionKeepRecentMessages:t.compressionKeepRecentMessages,contextCompressionLlm:t.contextCompressionLlm,tokenEstimator:t.tokenEstimator,tokenAccountingAdapter:t.tokenAccountingAdapter,queryIdleTimeoutMs:t.queryIdleTimeoutMs,queryLeaseTimeoutMs:t.queryLeaseTimeoutMs,queryHardTimeoutMs:t.queryHardTimeoutMs,...t.reserveFinalSynthesisTurn!==void 0?{reserveFinalSynthesisTurn:t.reserveFinalSynthesisTurn}:{},systemPrompt:h,requesterLabel:t.requesterLabel,ownerSessionId:t.ownerSessionId,getOwnerSessionId:t.getOwnerSessionId,executionMode:r,permissionEngine:d,toolRegistry:b,sandbox:t.sandbox,onPermissionRequest:t.onPermissionRequest,onText:t.onText,onToolStart:t.onToolStart,onToolWillExecute:t.onToolWillExecute,onToolEnd:t.onToolEnd,onIteration:t.onIteration,onError:t.onError,onTranscriptError:t.onTranscriptError,onRuntimeEvent:t.onRuntimeEvent,runtimeEventBus:t.runtimeEventBus,turnDiffTracker:t.turnDiffTracker,onTurnDiff:t.onTurnDiff,onModeSwitchRequest:t.onModeSwitchRequest,onExecutionModeChanged:t.onExecutionModeChanged,completionGuard:t.completionGuard,maxCompletionGuardReminders:t.maxCompletionGuardReminders,progressGuardEveryIterations:t.progressGuardEveryIterations,...t.toolMiddleware?{toolMiddleware:t.toolMiddleware}:{},...t.promptSections?{promptSections:t.promptSections}:{},...t.promptSectionsTokenBudget!==void 0?{promptSectionsTokenBudget:t.promptSectionsTokenBudget}:{},...t.completionGuards?{completionGuards:t.completionGuards}:{},...t.provider?{provider:t.provider}:{},...t.session}),systemPrompt:h,permissionEngine:d,toolRegistry:b,...u?{identity:u}:{},...p?{memory:{resolved:p,...m?{projectSessionContext:m}:{},prompt:f}}:{}}}var o$,i$,zs=T(()=>{"use strict";Lr();er();Zm();pS();of();ic();wf();to();o$=8192,i$=50});vo();var qn="0.9.31";bt();Ze();import{randomUUID as C5}from"node:crypto";var ca=class{filePath;sessionId;labels;sequence=0;writeQueue=Promise.resolve();constructor(e){this.filePath=e.filePath,this.sessionId=e.sessionId,this.labels={run_id:e.runId,agent_id:e.agentId,parent_agent_id:e.parentAgentId,workspace:e.workspace,model:e.model,provider:e.provider}}get path(){return this.filePath}async append(e){let n=C5(),r={id:n,sequence:this.sequence++,timestamp:new Date().toISOString(),session_id:e.session_id??this.sessionId,...this.labels,...e};return this.writeQueue=this.writeQueue.then(async()=>{await Ti(this.filePath,JSON.stringify(r))}),await this.writeQueue,n}async read(e){let n=await pe(this.filePath);if(!n)return[];let r=So(n);return e?.eventType&&(r=r.filter(o=>o.event_type===e.eventType)),e?.traceId&&(r=r.filter(o=>o.trace_id===e.traceId)),e?.limit!==void 0&&(r=r.slice(-Math.max(0,e.limit))),r}async tail(e=20){let n=Math.max(1,Math.min(e,500));return this.read({limit:n})}async exportJson(e){let n=await this.read();return await he(e,JSON.stringify(n,null,2)),n.length}async flush(){await this.writeQueue}};function _5(t,e){return e.endedAt.localeCompare(t.endedAt)}function qg(t,e){t.set(e,(t.get(e)??0)+1)}function Gg(t,e){let n=Date.parse(t),r=Date.parse(e);return!Number.isFinite(n)||!Number.isFinite(r)?0:Math.max(0,r-n)}function FI(t){return t.filter(e=>e.tool_name||e.event_type.startsWith("tool_")).length}function jI(t){return t.filter(e=>e.event_type==="permission_decision").length}function HI(t){return t.filter(e=>e.status==="error"||e.event_type.endsWith("_failed")).length}function Vg(t){return t.split(/[_\s-]+/).filter(e=>e.length>0).map(e=>e[0].toUpperCase()+e.slice(1)).join(" ")}function zg(t){if(!t)return;let e=Object.entries(t).filter(([,n])=>typeof n=="string"||typeof n=="number"||typeof n=="boolean").slice(0,3).map(([n,r])=>`${n}=${String(r)}`);return e.length>0?e.join(" | "):void 0}function M5(t){let e=[];for(let n=1;n<t.length;n+=1){let r=t[n-1],o=t[n],i=Date.parse(r.timestamp),s=Date.parse(o.timestamp),a=Number.isFinite(i)&&Number.isFinite(s)?Math.max(0,s-i):0;e.push({fromSequence:r.sequence,toSequence:o.sequence,fromEventType:r.event_type,toEventType:o.event_type,gapMs:a})}return e.sort((n,r)=>r.gapMs-n.gapMs).slice(0,5)}function O5(t){let e=Vg(t.event_type),n=t.reason;if(t.event_type==="permission_decision")e=`${t.decision==="deny"?"Denied":"Approved"} ${t.tool_name??"tool"} permission`,n=t.reason;else if(t.tool_name&&t.event_type.startsWith("tool_"))e=`${Vg(t.event_type)}: ${t.tool_name}`;else if(t.event_type==="delegation_completed"){let r=typeof t.metadata?.selected_from=="object"&&t.metadata?.selected_from?String(t.metadata.selected_from.role??"unknown"):void 0;e=r?`Delegation completed via ${r}`:"Delegation completed",n=zg(t.metadata)}else t.event_type==="delegation_started"?(e="Delegation started",n=zg(t.metadata)):t.tool_name?e=`${Vg(t.event_type)}: ${t.tool_name}`:n||(n=zg(t.metadata));return{sequence:t.sequence,timestamp:t.timestamp,title:e,...n?{detail:n}:{},actor:t.actor,riskLevel:t.risk_level,...t.status?{status:t.status}:{}}}function Wg(t){let e=new Map;for(let r of t){let o=r.trace_id?.trim();if(!o)continue;let i=e.get(o);i?i.push(r):e.set(o,[r])}let n=[];for(let[r,o]of e.entries()){let i=[...o].sort((c,l)=>c.sequence-l.sequence),s=i[0]?.timestamp??"",a=i[i.length-1]?.timestamp??s;n.push({traceId:r,eventCount:i.length,startedAt:s,endedAt:a,durationMs:Gg(s,a),toolEvents:FI(i),permissionEvents:jI(i),errorEvents:HI(i),lastEventType:i[i.length-1]?.event_type??"unknown"})}return n.sort(_5)}function N5(t,e){let n=Wg(t),r=e??n[0]?.traceId;if(!r)return null;let o=t.filter(u=>u.trace_id===r).sort((u,p)=>u.sequence-p.sequence);if(o.length===0)return null;let i=new Map,s=new Map,a=new Map,c=new Map;for(let u of o){if(qg(i,u.event_type),qg(a,u.actor),qg(c,u.risk_level),!u.tool_name)continue;let p=s.get(u.tool_name)??{toolName:u.tool_name,count:0,ok:0,error:0,denied:0};p.count+=1,u.status==="error"?p.error+=1:p.ok+=1,u.decision==="deny"&&(p.denied+=1),s.set(u.tool_name,p)}let l=o[0]?.timestamp??"",d=o[o.length-1]?.timestamp??l;return{traceId:r,eventCount:o.length,startedAt:l,endedAt:d,durationMs:Gg(l,d),toolEvents:FI(o),permissionEvents:jI(o),deniedPermissions:o.filter(u=>u.event_type==="permission_decision"&&u.decision==="deny").length,errorEvents:HI(o),eventTypes:Object.fromEntries([...i.entries()].sort((u,p)=>u[0].localeCompare(p[0]))),actorSummary:Object.fromEntries([...a.entries()].sort((u,p)=>u[0].localeCompare(p[0]))),riskSummary:Object.fromEntries([...c.entries()].sort((u,p)=>u[0].localeCompare(p[0]))),toolSummary:[...s.values()].sort((u,p)=>u.toolName.localeCompare(p.toolName)),topLatencyGaps:M5(o),timeline:o.map(u=>({sequence:u.sequence,timestamp:u.timestamp,eventType:u.event_type,actor:u.actor,riskLevel:u.risk_level,...u.tool_name?{toolName:u.tool_name}:{},...u.decision?{decision:u.decision}:{},...u.status?{status:u.status}:{},...u.reason?{reason:u.reason}:{}}))}}function D5(t,e){let n=Wg(t),r=e??n[0]?.traceId;if(!r)return null;let o=t.filter(a=>a.trace_id===r).sort((a,c)=>a.sequence-c.sequence);if(o.length===0)return null;let i=o[0]?.timestamp??"",s=o[o.length-1]?.timestamp??i;return{traceId:r,startedAt:i,endedAt:s,durationMs:Gg(i,s),steps:o.map(O5)}}function L5(t){if(t.length===0)return"No audit traces recorded.";let e=["Audit traces",""];for(let n of t)e.push(`${n.traceId} | ${n.eventCount} events | ${n.toolEvents} tool | ${n.permissionEvents} perms | ${n.errorEvents} errors | ${Math.round(n.durationMs/1e3)}s`);return e.join(`
2451
+ `));let h=t.systemPrompt??S2({cwd:e,model:n,date:t.date??new Date().toISOString().split("T")[0],identity:u,memory:f||void 0,sessionId:t.sessionId,executionMode:r}),y=t.dispatchAgent??(async v=>{let{createDelegatedXenoAgent:S}=await Promise.resolve().then(()=>(fg(),r$)),{agent:x}=await S({cwd:e,apiKey:o,baseURL:i,model:n,...t.fallbackModels?{fallbackModels:t.fallbackModels}:{},...t.effort?{effort:t.effort}:{},maxTokens:Math.max(512,Math.min(t.maxTokens??o$,4096)),maxIterations:Math.max(3,Math.min(t.maxIterations??i$,12)),parentSystemPrompt:h,parentExecutionMode:r,subagentRole:"explorer",permissionEngine:d,...t.sandbox?{sandbox:t.sandbox}:{},...t.onPermissionRequest?{onPermissionRequest:t.onPermissionRequest}:{}}),E=()=>{x.cancelCurrentTurn()};if(v.signal?.aborted)throw E(),new Error("dispatch_agent was aborted before the helper started");v.signal?.addEventListener("abort",E,{once:!0});try{return{output:await x.run(v.prompt)}}finally{v.signal?.removeEventListener("abort",E)}});if(t.validateToolInputs===!1)throw new Error("Agent tool input validation cannot be disabled.");let b=t.toolRegistry??zt({cwd:e,askUser:t.askUser,dispatchAgent:y,...t.webSearchApiKey?{webSearchApiKey:t.webSearchApiKey}:{},...t.permissionConfig?.profile?{permissionProfile:t.permissionConfig.profile}:{},...t.ownerSessionId?{ownerSessionId:t.ownerSessionId}:{},...t.getOwnerSessionId?{getOwnerSessionId:t.getOwnerSessionId}:{},...t.sandbox?{sandbox:t.sandbox}:{},...g?{memoryManager:g}:{},validateInputs:!0});return t.toolRegistry&&t.validateToolInputs===!0&&b.setValidateInputs(!0),{agent:new oi({apiKey:o,baseURL:i,ollamaBaseURL:s,localRuntimeProtocol:t.localRuntimeProtocol,localTransportLimits:t.localTransportLimits,...(t.apiRequestTimeoutMs??l)!==void 0?{apiRequestTimeoutMs:t.apiRequestTimeoutMs??l}:{},model:n,...t.fallbackModels?{fallbackModels:t.fallbackModels}:{},...t.effort?{effort:t.effort}:{},maxTokens:t.maxTokens??o$,maxIterations:t.maxIterations??i$,maxContextTokens:t.maxContextTokens,maxContextMessages:t.maxContextMessages,compressionKeepRecentMessages:t.compressionKeepRecentMessages,contextCompressionLlm:t.contextCompressionLlm,tokenEstimator:t.tokenEstimator,tokenAccountingAdapter:t.tokenAccountingAdapter,queryIdleTimeoutMs:t.queryIdleTimeoutMs,queryLeaseTimeoutMs:t.queryLeaseTimeoutMs,queryHardTimeoutMs:t.queryHardTimeoutMs,...t.reserveFinalSynthesisTurn!==void 0?{reserveFinalSynthesisTurn:t.reserveFinalSynthesisTurn}:{},systemPrompt:h,requesterLabel:t.requesterLabel,ownerSessionId:t.ownerSessionId,getOwnerSessionId:t.getOwnerSessionId,executionMode:r,permissionEngine:d,toolRegistry:b,sandbox:t.sandbox,onPermissionRequest:t.onPermissionRequest,onText:t.onText,onToolStart:t.onToolStart,onToolWillExecute:t.onToolWillExecute,onToolEnd:t.onToolEnd,onIteration:t.onIteration,onError:t.onError,onTranscriptError:t.onTranscriptError,onRuntimeEvent:t.onRuntimeEvent,runtimeEventBus:t.runtimeEventBus,turnDiffTracker:t.turnDiffTracker,onTurnDiff:t.onTurnDiff,onModeSwitchRequest:t.onModeSwitchRequest,onExecutionModeChanged:t.onExecutionModeChanged,completionGuard:t.completionGuard,maxCompletionGuardReminders:t.maxCompletionGuardReminders,progressGuardEveryIterations:t.progressGuardEveryIterations,...t.toolMiddleware?{toolMiddleware:t.toolMiddleware}:{},...t.promptSections?{promptSections:t.promptSections}:{},...t.promptSectionsTokenBudget!==void 0?{promptSectionsTokenBudget:t.promptSectionsTokenBudget}:{},...t.completionGuards?{completionGuards:t.completionGuards}:{},...t.provider?{provider:t.provider}:{},...t.session}),systemPrompt:h,permissionEngine:d,toolRegistry:b,...u?{identity:u}:{},...p?{memory:{resolved:p,...m?{projectSessionContext:m}:{},prompt:f}}:{}}}var o$,i$,zs=T(()=>{"use strict";Lr();er();Zm();pS();of();ic();wf();to();o$=8192,i$=50});vo();var qn="0.9.32";bt();Ze();import{randomUUID as C5}from"node:crypto";var ca=class{filePath;sessionId;labels;sequence=0;writeQueue=Promise.resolve();constructor(e){this.filePath=e.filePath,this.sessionId=e.sessionId,this.labels={run_id:e.runId,agent_id:e.agentId,parent_agent_id:e.parentAgentId,workspace:e.workspace,model:e.model,provider:e.provider}}get path(){return this.filePath}async append(e){let n=C5(),r={id:n,sequence:this.sequence++,timestamp:new Date().toISOString(),session_id:e.session_id??this.sessionId,...this.labels,...e};return this.writeQueue=this.writeQueue.then(async()=>{await Ti(this.filePath,JSON.stringify(r))}),await this.writeQueue,n}async read(e){let n=await pe(this.filePath);if(!n)return[];let r=So(n);return e?.eventType&&(r=r.filter(o=>o.event_type===e.eventType)),e?.traceId&&(r=r.filter(o=>o.trace_id===e.traceId)),e?.limit!==void 0&&(r=r.slice(-Math.max(0,e.limit))),r}async tail(e=20){let n=Math.max(1,Math.min(e,500));return this.read({limit:n})}async exportJson(e){let n=await this.read();return await he(e,JSON.stringify(n,null,2)),n.length}async flush(){await this.writeQueue}};function _5(t,e){return e.endedAt.localeCompare(t.endedAt)}function qg(t,e){t.set(e,(t.get(e)??0)+1)}function Gg(t,e){let n=Date.parse(t),r=Date.parse(e);return!Number.isFinite(n)||!Number.isFinite(r)?0:Math.max(0,r-n)}function FI(t){return t.filter(e=>e.tool_name||e.event_type.startsWith("tool_")).length}function jI(t){return t.filter(e=>e.event_type==="permission_decision").length}function HI(t){return t.filter(e=>e.status==="error"||e.event_type.endsWith("_failed")).length}function Vg(t){return t.split(/[_\s-]+/).filter(e=>e.length>0).map(e=>e[0].toUpperCase()+e.slice(1)).join(" ")}function zg(t){if(!t)return;let e=Object.entries(t).filter(([,n])=>typeof n=="string"||typeof n=="number"||typeof n=="boolean").slice(0,3).map(([n,r])=>`${n}=${String(r)}`);return e.length>0?e.join(" | "):void 0}function M5(t){let e=[];for(let n=1;n<t.length;n+=1){let r=t[n-1],o=t[n],i=Date.parse(r.timestamp),s=Date.parse(o.timestamp),a=Number.isFinite(i)&&Number.isFinite(s)?Math.max(0,s-i):0;e.push({fromSequence:r.sequence,toSequence:o.sequence,fromEventType:r.event_type,toEventType:o.event_type,gapMs:a})}return e.sort((n,r)=>r.gapMs-n.gapMs).slice(0,5)}function O5(t){let e=Vg(t.event_type),n=t.reason;if(t.event_type==="permission_decision")e=`${t.decision==="deny"?"Denied":"Approved"} ${t.tool_name??"tool"} permission`,n=t.reason;else if(t.tool_name&&t.event_type.startsWith("tool_"))e=`${Vg(t.event_type)}: ${t.tool_name}`;else if(t.event_type==="delegation_completed"){let r=typeof t.metadata?.selected_from=="object"&&t.metadata?.selected_from?String(t.metadata.selected_from.role??"unknown"):void 0;e=r?`Delegation completed via ${r}`:"Delegation completed",n=zg(t.metadata)}else t.event_type==="delegation_started"?(e="Delegation started",n=zg(t.metadata)):t.tool_name?e=`${Vg(t.event_type)}: ${t.tool_name}`:n||(n=zg(t.metadata));return{sequence:t.sequence,timestamp:t.timestamp,title:e,...n?{detail:n}:{},actor:t.actor,riskLevel:t.risk_level,...t.status?{status:t.status}:{}}}function Wg(t){let e=new Map;for(let r of t){let o=r.trace_id?.trim();if(!o)continue;let i=e.get(o);i?i.push(r):e.set(o,[r])}let n=[];for(let[r,o]of e.entries()){let i=[...o].sort((c,l)=>c.sequence-l.sequence),s=i[0]?.timestamp??"",a=i[i.length-1]?.timestamp??s;n.push({traceId:r,eventCount:i.length,startedAt:s,endedAt:a,durationMs:Gg(s,a),toolEvents:FI(i),permissionEvents:jI(i),errorEvents:HI(i),lastEventType:i[i.length-1]?.event_type??"unknown"})}return n.sort(_5)}function N5(t,e){let n=Wg(t),r=e??n[0]?.traceId;if(!r)return null;let o=t.filter(u=>u.trace_id===r).sort((u,p)=>u.sequence-p.sequence);if(o.length===0)return null;let i=new Map,s=new Map,a=new Map,c=new Map;for(let u of o){if(qg(i,u.event_type),qg(a,u.actor),qg(c,u.risk_level),!u.tool_name)continue;let p=s.get(u.tool_name)??{toolName:u.tool_name,count:0,ok:0,error:0,denied:0};p.count+=1,u.status==="error"?p.error+=1:p.ok+=1,u.decision==="deny"&&(p.denied+=1),s.set(u.tool_name,p)}let l=o[0]?.timestamp??"",d=o[o.length-1]?.timestamp??l;return{traceId:r,eventCount:o.length,startedAt:l,endedAt:d,durationMs:Gg(l,d),toolEvents:FI(o),permissionEvents:jI(o),deniedPermissions:o.filter(u=>u.event_type==="permission_decision"&&u.decision==="deny").length,errorEvents:HI(o),eventTypes:Object.fromEntries([...i.entries()].sort((u,p)=>u[0].localeCompare(p[0]))),actorSummary:Object.fromEntries([...a.entries()].sort((u,p)=>u[0].localeCompare(p[0]))),riskSummary:Object.fromEntries([...c.entries()].sort((u,p)=>u[0].localeCompare(p[0]))),toolSummary:[...s.values()].sort((u,p)=>u.toolName.localeCompare(p.toolName)),topLatencyGaps:M5(o),timeline:o.map(u=>({sequence:u.sequence,timestamp:u.timestamp,eventType:u.event_type,actor:u.actor,riskLevel:u.risk_level,...u.tool_name?{toolName:u.tool_name}:{},...u.decision?{decision:u.decision}:{},...u.status?{status:u.status}:{},...u.reason?{reason:u.reason}:{}}))}}function D5(t,e){let n=Wg(t),r=e??n[0]?.traceId;if(!r)return null;let o=t.filter(a=>a.trace_id===r).sort((a,c)=>a.sequence-c.sequence);if(o.length===0)return null;let i=o[0]?.timestamp??"",s=o[o.length-1]?.timestamp??i;return{traceId:r,startedAt:i,endedAt:s,durationMs:Gg(i,s),steps:o.map(O5)}}function L5(t){if(t.length===0)return"No audit traces recorded.";let e=["Audit traces",""];for(let n of t)e.push(`${n.traceId} | ${n.eventCount} events | ${n.toolEvents} tool | ${n.permissionEvents} perms | ${n.errorEvents} errors | ${Math.round(n.durationMs/1e3)}s`);return e.join(`
2452
2452
  `)}function $5(t){let e=[`Audit trace ${t.traceId}`,`Started: ${t.startedAt}`,`Ended: ${t.endedAt}`,`Duration: ${t.durationMs} ms`,`Events: ${t.eventCount}`,`Tool events: ${t.toolEvents}`,`Permission events: ${t.permissionEvents}`,`Denied permissions: ${t.deniedPermissions}`,`Errors: ${t.errorEvents}`,"","Event types"];for(let[n,r]of Object.entries(t.eventTypes))e.push(` ${n}: ${r}`);e.push(""),e.push("Actors");for(let[n,r]of Object.entries(t.actorSummary))e.push(` ${n}: ${r}`);e.push(""),e.push("Risk levels");for(let[n,r]of Object.entries(t.riskSummary))e.push(` ${n}: ${r}`);if(e.push(""),e.push("Tools"),t.toolSummary.length===0)e.push(" (no tool activity)");else for(let n of t.toolSummary)e.push(` ${n.toolName}: ${n.count} total | ${n.ok} ok | ${n.error} error | ${n.denied} denied`);if(e.push(""),e.push("Largest gaps"),t.topLatencyGaps.length===0)e.push(" (no gaps)");else for(let n of t.topLatencyGaps)e.push(` #${n.fromSequence}->#${n.toSequence}: ${n.gapMs} ms | ${n.fromEventType} -> ${n.toEventType}`);e.push(""),e.push("Timeline");for(let n of t.timeline){let r=[n.eventType,n.toolName,n.decision,n.status,n.reason].filter(o=>typeof o=="string"&&o.length>0);e.push(` #${n.sequence} ${n.timestamp} | ${r.join(" | ")||n.eventType}`)}return e.join(`
2453
2453
  `)}function X5(t){return[`## Audit Trace ${t.traceId}`,"",`- Started: \`${t.startedAt}\``,`- Ended: \`${t.endedAt}\``,`- Duration: \`${t.durationMs}\` ms`,`- Events: \`${t.eventCount}\``,`- Tool events: \`${t.toolEvents}\``,`- Permission events: \`${t.permissionEvents}\``,`- Denied permissions: \`${t.deniedPermissions}\``,`- Errors: \`${t.errorEvents}\``,"","### Tool Summary","","| Tool | Total | OK | Error | Denied |","| --- | ---: | ---: | ---: | ---: |",...t.toolSummary.length>0?t.toolSummary.map(n=>`| ${n.toolName} | ${n.count} | ${n.ok} | ${n.error} | ${n.denied} |`):["| (none) | 0 | 0 | 0 | 0 |"],"","### Largest Gaps","","| From | To | Gap ms | Events |","| ---: | ---: | ---: | --- |",...t.topLatencyGaps.length>0?t.topLatencyGaps.map(n=>`| ${n.fromSequence} | ${n.toSequence} | ${n.gapMs} | ${n.fromEventType} -> ${n.toEventType} |`):["| 0 | 0 | 0 | none |"]].join(`
2454
2454
  `)}function B5(t){let e=[`## Audit Replay ${t.traceId}`,"",`- Started: \`${t.startedAt}\``,`- Ended: \`${t.endedAt}\``,`- Duration: \`${t.durationMs}\` ms`,""];for(let n of t.steps){let r=[n.actor,n.riskLevel,n.status].filter(Boolean).join(" | ");e.push(`- **#${n.sequence} ${n.title}**${r?` _(${r})_`:""}`),n.detail&&e.push(` - ${n.detail}`)}return e.join(`
@@ -2568,7 +2568,7 @@ ${e.result.error??""}`;if(!woe(e.toolName,e.input,n))return[];let r=voe(e.toolNa
2568
2568
  `).length!==t.endLine-t.startLine+1&&n.push(`excerpt ${t?.excerptId} line span does not match text`)}function Lae(t,e){Vs(t?.providerId,"model providerId",e),bn(t?.model,"model",e,512),t?.connectionId!==void 0&&Vs(t.connectionId,"model connectionId",e)}function $ae(t,e){(!Number.isSafeInteger(t?.inputTokens)||t.inputTokens<0)&&e.push("usage.inputTokens must be a non-negative integer"),(!Number.isSafeInteger(t?.outputTokens)||t.outputTokens<0)&&e.push("usage.outputTokens must be a non-negative integer")}function ug(t,e,n){(t?.algorithm!=="sha256"||!/^[a-f0-9]{64}$/u.test(t?.value??""))&&n.push(`${e} must be a lowercase SHA-256 digest`)}function Vs(t,e,n){(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u.test(t))&&n.push(`${e} is invalid`)}function bn(t,e,n,r){(typeof t!="string"||!t.trim()||t.length>r||Je(t,{allowTab:!0,allowLineBreaks:!0}))&&n.push(`${e} must be non-empty bounded text`)}function QL(t,e,n){(typeof t!="string"||!Number.isFinite(Date.parse(t))||new Date(t).toISOString()!==t)&&n.push(`${e} must be an ISO-8601 UTC timestamp`)}function Xae(t,e,n){(typeof t!="string"||t.length>253||!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(t))&&n.push(`${e} is invalid`)}function Bae(t,e){(typeof t!="string"||t.length>2048||t.startsWith("/")||t.endsWith("/")||t.split("/").some(n=>!n||n==="."||n===".."))&&e.push("repository name is invalid")}function t$(t,e,n){(typeof t!="string"||t.length>4096||t.startsWith("/")||/^[A-Za-z]:[\\/]/u.test(t)||t.includes("\\")||t.split("/").some(r=>!r||r==="."||r===".."))&&n.push(`${e} must be repository-relative`)}function Uae(t,e,n){try{let r=new URL(String(t));(r.protocol!=="https:"||r.username||r.password)&&n.push(`${e} must be credential-free HTTPS`)}catch{n.push(`${e} is invalid`)}}function ZL(t){return Number.isSafeInteger(t)&&(t??-1)>=0?t:0}function n$(t){return{algorithm:"sha256",value:Pe(t).value}}function Fae(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1}function jae(t){return t==="info"||t==="low"||t==="medium"||t==="high"||t==="critical"}var Hae="xeno.recipe.v1",mt=class extends Error{constructor(n){super(`XENO recipe is invalid: ${n.join("; ")}`);this.issues=n;this.name="XenoRecipeValidationError"}issues;code="XENO_RECIPE_INVALID"};function a2e(t){let e=gi(t,"recipe",["schemaVersion","recipeId","name","description","version","modes","inputs","requiredSecretRefs","authority","budget","steps","provenance"]),n=gi(e.authority,"authority",["permissionMode","externalActions","network"]),r=gi(e.budget,"budget",["maxAgents","maxConcurrency","maxTotalTokens","timeoutMs"]),o={schemaVersion:e.schemaVersion,recipeId:Qe(e.recipeId,"recipeId"),name:Qe(e.name,"name"),description:Qe(e.description,"description"),version:Tl(e.version,"version"),modes:fi(e.modes,"modes").map(i=>i),inputs:fi(e.inputs,"inputs").map((i,s)=>Vae(i,s)),requiredSecretRefs:fi(e.requiredSecretRefs,"requiredSecretRefs").map(i=>Qe(i,"secret ref")),authority:{permissionMode:n.permissionMode,externalActions:n.externalActions,network:n.network},budget:{maxAgents:Tl(r.maxAgents,"budget.maxAgents"),maxConcurrency:Tl(r.maxConcurrency,"budget.maxConcurrency"),maxTotalTokens:Tl(r.maxTotalTokens,"budget.maxTotalTokens"),timeoutMs:Tl(r.timeoutMs,"budget.timeoutMs")},steps:fi(e.steps,"steps").map((i,s)=>zae(i,s)),...e.provenance!==void 0?{provenance:Gae(e.provenance)}:{}};return mg(o),o}function mg(t){let e=[];t?.schemaVersion!==Hae&&e.push("schemaVersion must be xeno.recipe.v1"),pg(t?.recipeId,"recipeId",e),vr(t?.name,"name",e,256),vr(t?.description,"description",e,8e3),(!Number.isSafeInteger(t?.version)||t.version<1||t.version>1e6)&&e.push("version must be a positive bounded integer"),(!Array.isArray(t?.modes)||t.modes.length<1)&&e.push("modes must contain at least one execution mode");let n=new Set;for(let s of t?.modes??[])s!=="interactive"&&s!=="headless"&&s!=="ci"&&e.push(`unsupported recipe mode ${String(s)}`),n.has(s)&&e.push(`duplicate recipe mode ${s}`),n.add(s);rce(t?.authority?.permissionMode)||e.push("authority.permissionMode is invalid"),t?.authority?.externalActions!=="deny"&&t?.authority?.externalActions!=="approval-required"&&e.push("authority.externalActions is invalid"),t?.authority?.network!=="deny"&&t?.authority?.network!=="environment-policy"&&e.push("authority.network is invalid"),Wae(t?.budget,e);let r=new Set;for(let s of t?.inputs??[]){if(tce(s?.name,e),r.has(s.name)&&e.push(`duplicate input ${s.name}`),r.add(s.name),vr(s?.description,`input ${s.name} description`,e,2e3),typeof s?.required!="boolean"&&e.push(`input ${s.name} required must be boolean`),s?.default!==void 0&&vr(s.default,`input ${s.name} default`,e,32e3),s?.required&&s?.default!==void 0&&e.push(`required input ${s.name} cannot define a default`),s?.enum!==void 0){(!Array.isArray(s.enum)||s.enum.length<1||s.enum.length>256)&&e.push(`input ${s.name} enum is invalid`);for(let a of s.enum??[])vr(a,`input ${s.name} enum value`,e,2e3);s.default!==void 0&&!s.enum.includes(s.default)&&e.push(`input ${s.name} default is outside its enum`)}if(s?.pattern!==void 0){vr(s.pattern,`input ${s.name} pattern`,e,1e3);try{new RegExp(s.pattern,"u")}catch{e.push(`input ${s.name} pattern is invalid`)}}}let o=new Set;for(let s of t?.requiredSecretRefs??[])/^[A-Z_][A-Z0-9_]{0,127}$/u.test(s)||e.push(`required secret ref ${s} is invalid`),o.has(s)&&e.push(`duplicate secret ref ${s}`),o.add(s);(!Array.isArray(t?.steps)||t.steps.length<1||t.steps.length>256)&&e.push("steps must contain 1 through 256 records"),Array.isArray(t?.steps)&&t.steps.length>(t?.budget?.maxAgents??0)&&e.push("budget.maxAgents must cover every recipe step");let i=new Map;for(let s of t?.steps??[]){pg(s?.id,"step id",e),i.has(s.id)&&e.push(`duplicate step ${s.id}`),i.set(s.id,s),vr(s?.title,`step ${s.id} title`,e,2e3),s?.kind!=="agent"&&s?.kind!=="verification"&&e.push(`step ${s.id} kind is invalid`),vr(s?.prompt,`step ${s.id} prompt`,e,128e3),s?.agentProfile!==void 0&&pg(s.agentProfile,`step ${s.id} agentProfile`,e);for(let a of s?.dependsOn??[])pg(a,`step ${s.id} dependency`,e);s?.approval&&vr(s.approval.message,`step ${s.id} approval message`,e,8e3);for(let a of s?.expectedArtifacts??[])nce(a,`step ${s.id} expected artifact`,e);for(let a of Zae(s?.prompt??""))r.has(a)||e.push(`step ${s.id} references unknown input ${a}`);/\{\{\s*(?:secret|env)[.:]/iu.test(s?.prompt??"")&&e.push(`step ${s.id} cannot interpolate secrets into prompts`)}for(let s of t?.steps??[])for(let a of s.dependsOn??[])i.has(a)||e.push(`step ${s.id} depends on unknown step ${a}`),a===s.id&&e.push(`step ${s.id} cannot depend on itself`);if(Jae(t?.steps??[],e),e.length>0)throw new mt([...new Set(e)])}function c2e(t,e){if(mg(t),!t.modes.includes(e.mode))throw new mt([`recipe does not allow ${e.mode} mode`]);let n=e.inputs??{},r=new Map(t.inputs.map(a=>[a.name,a])),o=Object.keys(n).filter(a=>!r.has(a));if(o.length>0)throw new mt(o.map(a=>`unknown recipe input ${a}`));let i={};for(let a of t.inputs){let c=n[a.name]??a.default;if(c===void 0){if(a.required)throw new mt([`required recipe input ${a.name} is missing`]);i[a.name]="";continue}i[a.name]=Yae(a,c)}let s=t.requiredSecretRefs.filter(a=>e.hasSecretRef&&!e.hasSecretRef(a));if(s.length>0)throw new mt(s.map(a=>`required secret reference is unavailable: ${a}`));return{schemaVersion:1,recipeId:t.recipeId,recipeVersion:t.version,recipeFingerprint:qae(t),mode:e.mode,inputs:i,requiredSecretRefs:[...t.requiredSecretRefs],authority:structuredClone(t.authority),budget:structuredClone(t.budget),steps:Kae(t.steps).map(a=>({...structuredClone(a),prompt:Qae(a.prompt,i)}))}}function qae(t){return mg(t),{algorithm:"sha256",value:je(t).value}}function l2e(t){return mg(t),`${Z(t)}
2569
2569
  `}function Vae(t,e){let n=gi(t,`inputs[${e}]`,["name","description","required","default","enum","pattern"]);return{name:Qe(n.name,`inputs[${e}].name`),description:Qe(n.description,`inputs[${e}].description`),required:ece(n.required,`inputs[${e}].required`),...n.default!==void 0?{default:Qe(n.default,`inputs[${e}].default`)}:{},...n.enum!==void 0?{enum:fi(n.enum,`inputs[${e}].enum`).map(r=>Qe(r,"enum value"))}:{},...n.pattern!==void 0?{pattern:Qe(n.pattern,`inputs[${e}].pattern`)}:{}}}function zae(t,e){let n=gi(t,`steps[${e}]`,["id","title","kind","prompt","dependsOn","agentProfile","approval","expectedArtifacts"]),r=n.approval===void 0?void 0:gi(n.approval,`steps[${e}].approval`,["message"]);return{id:Qe(n.id,`steps[${e}].id`),title:Qe(n.title,`steps[${e}].title`),kind:n.kind,prompt:Qe(n.prompt,`steps[${e}].prompt`),...n.dependsOn!==void 0?{dependsOn:fi(n.dependsOn,"dependsOn").map(o=>Qe(o,"dependency"))}:{},...n.agentProfile!==void 0?{agentProfile:Qe(n.agentProfile,"agentProfile")}:{},...r?{approval:{message:Qe(r.message,"approval message")}}:{},...n.expectedArtifacts!==void 0?{expectedArtifacts:fi(n.expectedArtifacts,"expectedArtifacts").map(o=>Qe(o,"expected artifact"))}:{}}}function Gae(t){let e=gi(t,"provenance",["publisherId","source","revision"]);return{publisherId:Qe(e.publisherId,"provenance.publisherId"),...e.source!==void 0?{source:Qe(e.source,"provenance.source")}:{},...e.revision!==void 0?{revision:Qe(e.revision,"provenance.revision")}:{}}}function Wae(t,e){(!Number.isSafeInteger(t?.maxAgents)||t.maxAgents<1||t.maxAgents>256)&&e.push("budget.maxAgents is invalid"),(!Number.isSafeInteger(t?.maxConcurrency)||t.maxConcurrency<1||t.maxConcurrency>64)&&e.push("budget.maxConcurrency is invalid"),t?.maxConcurrency>t?.maxAgents&&e.push("budget.maxConcurrency cannot exceed maxAgents"),(!Number.isSafeInteger(t?.maxTotalTokens)||t.maxTotalTokens<1||t.maxTotalTokens>1e8)&&e.push("budget.maxTotalTokens is invalid"),(!Number.isSafeInteger(t?.timeoutMs)||t.timeoutMs<1e3||t.timeoutMs>10080*60*1e3)&&e.push("budget.timeoutMs is invalid")}function Jae(t,e){let n=new Map(t.map(s=>[s.id,s])),r=new Set,o=new Set,i=s=>{if(!(o.has(s)||!n.has(s))){if(r.has(s)){e.push(`recipe step dependency cycle includes ${s}`);return}r.add(s);for(let a of n.get(s)?.dependsOn??[])i(a);r.delete(s),o.add(s)}};for(let s of t)i(s.id)}function Kae(t){let e=new Map(t.map(o=>[o.id,o])),n=new Map(t.map((o,i)=>[o.id,{step:o,index:i,dependencies:new Set(o.dependsOn??[])}])),r=[];for(;n.size>0;){let o=[...n.values()].filter(({dependencies:i})=>[...i].every(s=>!n.has(s))).sort((i,s)=>i.index-s.index);if(o.length===0)throw new mt(["recipe step dependency graph is cyclic"]);for(let i of o)r.push(e.get(i.step.id)),n.delete(i.step.id)}return r}function Yae(t,e){let n=e.trim();if(n.length>32e3||Je(n,{allowTab:!0,allowLineBreaks:!0}))throw new mt([`input ${t.name} is invalid`]);if(t.enum&&!t.enum.includes(n))throw new mt([`input ${t.name} is outside its enum`]);if(t.pattern&&!new RegExp(t.pattern,"u").test(n))throw new mt([`input ${t.name} does not match its pattern`]);return n}function Qae(t,e){return t.replace(/\{\{\s*input\.([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/gu,(n,r)=>e[r]??"")}function Zae(t){return[...t.matchAll(/\{\{\s*input\.([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/gu)].map(e=>e[1])}function gi(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new mt([`${e} must be an object`]);let r=t,o=Object.keys(r).filter(i=>!n.includes(i));if(o.length>0)throw new mt(o.map(i=>`${e} contains unsupported field ${i}`));return r}function fi(t,e){if(!Array.isArray(t))throw new mt([`${e} must be an array`]);return t}function Qe(t,e){if(typeof t!="string")throw new mt([`${e} must be text`]);return t}function ece(t,e){if(typeof t!="boolean")throw new mt([`${e} must be boolean`]);return t}function Tl(t,e){if(!Number.isSafeInteger(t))throw new mt([`${e} must be an integer`]);return t}function pg(t,e,n){(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u.test(t))&&n.push(`${e} is invalid`)}function tce(t,e){(typeof t!="string"||!/^[A-Za-z_][A-Za-z0-9_-]{0,127}$/u.test(t))&&e.push(`input name ${String(t)} is invalid`)}function vr(t,e,n,r){(typeof t!="string"||!t.trim()||t.length>r||Je(t,{allowTab:!0,allowLineBreaks:!0}))&&n.push(`${e} must be non-empty bounded text`)}function nce(t,e,n){(typeof t!="string"||!t||t.startsWith("/")||/^[A-Za-z]:[\\/]/u.test(t)||t.includes("\\")||t.split("/").some(r=>!r||r==="."||r===".."))&&n.push(`${e} must be workflow-relative`)}function rce(t){return t==="default"||t==="plan"||t==="acceptEdits"||t==="auto"||t==="dontAsk"}import{createInterface as Ice}from"node:readline";import{randomUUID as kce}from"node:crypto";zs();Dc();async function ZA(t){let e=t.runtimeEventBus??new ni,n=[],r=t.captureTraceGraph?new Nc("thread-run"):void 0;e.subscribe(a=>{n.push(a),r?.record(a),t.onRuntimeEvent?.(a)});let{agent:o}=await xr({...t,runtimeEventBus:e,onRuntimeEvent:void 0}),i=()=>o.cancelCurrentTurn();t.signal?.addEventListener("abort",i,{once:!0});let s;try{t.signal?.aborted&&i(),s=await o.run(t.prompt)}finally{t.signal?.removeEventListener("abort",i)}return{output:s,events:n,...r?{traceGraph:r.toGraph()}:{},tokenUsage:o.tokenUsage}}async function*P2e(t){let e=t.runtimeEventBus??new ni,n=[],r=t.captureTraceGraph?new Nc("thread-run-streamed"):void 0,o=[],i,s=!1,a,c;e.subscribe(d=>{n.push(d),r?.record(d),t.onRuntimeEvent?.(d),o.push(d),i?.(),i=void 0});let l=(async()=>{try{let{agent:d}=await xr({...t,runtimeEventBus:e,onRuntimeEvent:void 0}),u=()=>d.cancelCurrentTurn();t.signal?.addEventListener("abort",u,{once:!0});let p;try{t.signal?.aborted&&u(),p=await d.run(t.prompt)}finally{t.signal?.removeEventListener("abort",u)}a={output:p,events:n,...r?{traceGraph:r.toGraph()}:{},tokenUsage:d.tokenUsage}}catch(d){c=d}finally{s=!0,i?.(),i=void 0}})();for(;!s||o.length>0;){let d=o.shift();if(d){yield d;continue}await new Promise(u=>{i=u})}if(await l,c)throw c;return a??{output:"",events:n,...r?{traceGraph:r.toGraph()}:{},tokenUsage:{input:0,output:0,total:0}}}Dc();Rn();import{createHash as gce,randomUUID as hce}from"node:crypto";import{isAbsolute as yce,join as bce,resolve as sE}from"node:path";import{performance as g$}from"node:perf_hooks";import{randomUUID as a$}from"node:crypto";import{closeSync as c$,existsSync as cce,fsyncSync as lce,mkdirSync as l$,openSync as d$,readFileSync as dce,renameSync as u$,statSync as uce,unlinkSync as p$,writeFileSync as m$}from"node:fs";import{dirname as pce,join as f$}from"node:path";var eE=[2,1],s$=["initialize","capabilities.get","thread.start","thread.get","thread.list","thread.resume","thread.archive","thread.delete","turn.start","turn.get","turn.steer","turn.interrupt","events.subscribe","events.unsubscribe","events.poll","events.replay","permission.respond","integrations.list"],J=class extends Error{constructor(n,r,o,i=!1,s="app_server",a){super(r);this.machineCode=n;this.rpcCode=o;this.retryable=i;this.category=s;this.details=a;this.name="AppServerProtocolError"}machineCode;rpcCode;retryable;category;details;toData(){return{code:this.machineCode,retryable:this.retryable,category:this.category,...this.details?{details:this.details}:{}}}};function nE(){return{schemaVersion:2,threads:{},turns:{},permissions:{},idempotency:{},streams:{}}}function mce(t){let e=nE();for(let[n,r]of Object.entries(t.threads??{}))e.threads[n]={...r,schemaVersion:2};for(let[n,r]of Object.entries(t.turns??{}))e.turns[n]={...r,schemaVersion:2,steering:r.steering??[]};for(let[n,r]of Object.entries(t.events??{})){let o=r.map((i,s)=>({...i,protocolVersion:2,schemaVersion:2,streamId:n,sequence:Number.isInteger(i.sequence)&&i.sequence>0?i.sequence:s+1})).sort((i,s)=>i.sequence-s.sequence);e.streams[n]={nextSequence:(o.at(-1)?.sequence??0)+1,prunedThrough:0,events:o}}return e}function fce(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("State root is not an object.");let e=t;if(e.schemaVersion===1)return mce(e);if(e.schemaVersion!==2)throw new Error(`Unsupported state schema version: ${String(e.schemaVersion)}.`);for(let n of["threads","turns","permissions","idempotency","streams"]){let r=e[n];if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`State field ${n} is invalid.`)}return e}function tE(t){return structuredClone(t)}var gg=class{constructor(e,n){this.retention=n;l$(e,{recursive:!0}),this.statePath=f$(e,"state-v2.json"),this.lockPath=f$(e,"state-v2.lock"),this.state=nE(),this.withLock(()=>{this.state=this.load(),this.commit(this.state)})}retention;statePath;lockPath;state;snapshot(){return this.state=this.load(),tE(this.state)}mutate(e,n=new Date){return this.withLock(()=>{this.state=this.load();let r=tE(this.state),o=e(r);return this.prune(r,n),this.commit(r),this.state=r,tE(o)})}reload(){return this.state=this.load(),this.snapshot()}load(){if(!cce(this.statePath))return nE();try{return fce(JSON.parse(dce(this.statePath,"utf8")))}catch{let e=`${this.statePath}.corrupt-${Date.now()}-${a$().slice(0,8)}`;try{u$(this.statePath,e)}catch{}throw new J("APP_SERVER_STATE_CORRUPT","The app-server state is malformed and was quarantined.",-32019,!1,"persistence",{quarantineFile:e.split(/[\\/]/).at(-1)})}}commit(e){l$(pce(this.statePath),{recursive:!0});let n=`${this.statePath}.${process.pid}.${a$()}.tmp`,r=d$(n,"wx",384);try{m$(r,`${JSON.stringify(e,null,2)}
2570
2570
  `,"utf8"),lce(r)}finally{c$(r)}u$(n,this.statePath)}prune(e,n){let r=n.getTime()-this.retention.maxAgeMs;for(let o of Object.values(e.streams)){let i=0;for(;i<o.events.length&&(o.events.length-i>this.retention.maxEvents||Date.parse(o.events[i].timestamp)<r);)i+=1;if(i>0){let s=o.events.splice(0,i);o.prunedThrough=Math.max(o.prunedThrough,s.at(-1)?.sequence??0)}}}withLock(e){let n=Date.now()+5e3,r;for(;r===void 0;)try{r=d$(this.lockPath,"wx",384),m$(r,String(process.pid),"utf8")}catch(o){if(o.code!=="EEXIST")throw o;try{Date.now()-uce(this.lockPath).mtimeMs>3e4&&p$(this.lockPath)}catch{}if(Date.now()>=n)throw new J("APP_SERVER_STATE_LOCKED","The app-server state is busy.",-32023,!0,"persistence");Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5)}try{return e()}finally{c$(r);try{p$(this.lockPath)}catch{}}}};et();var wce=new Set(s$),vce=new Set(["thread.start","thread.resume","thread.archive","thread.delete","turn.start","turn.steer","turn.interrupt","permission.respond"]);function xce(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Ct(t,e){let n=t[e];if(typeof n!="string"||n.trim().length===0)throw new J("APP_SERVER_INVALID_PARAMS",`${e} is required.`,-32602,!1,"validation");return n.trim()}function Xn(t){if(!(typeof t!="number"||!Number.isInteger(t)))return t}function h$(t,e){if(t===void 0)return;let n=Xn(t);if(n===void 0||n<0)throw new J("APP_SERVER_INVALID_PARAMS",`${e} must be a non-negative integer.`,-32602,!1,"validation");return n}function rE(t){if(!t.id?.trim())throw new J("APP_SERVER_UNAUTHORIZED","An authenticated principal is required.",-32011);return{id:t.id.trim(),...t.tenantId?.trim()?{tenantId:t.tenantId.trim()}:{},workspaceRoots:[...new Set((t.workspaceRoots??[]).map(e=>sE(e)))],capabilities:[...new Set(t.capabilities??[])].sort()}}function y$(t){let e=sE(t);return process.platform==="win32"?e.toLowerCase():e}function oE(t,e){let n=y$(t),r=y$(e);return n===r||n.startsWith(`${r}/`)||n.startsWith(`${r}\\`)}function iE(t){return Array.isArray(t)?t.map(iE):!t||typeof t!="object"?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,iE(n)]))}function b$(t){return gce("sha256").update(JSON.stringify(iE(t))).digest("hex")}function Sce(t){return t instanceof J?{code:t.machineCode,message:t.message,retryable:t.retryable}:{code:"TURN_EXECUTION_FAILED",message:t instanceof Error?t.message.slice(0,500):"Turn execution failed.",retryable:!1}}function Ace(t){return/(?:completed|failed|interrupted|deleted|archived|permission\.resolved)$/.test(t.type)}function Ece(t){return/(?:progress|delta|steering)$/.test(t.type)}function Rl(t,e=0){return e>6?"[truncated]":Array.isArray(t)?t.slice(0,100).map(n=>Rl(n,e+1)):!t||typeof t!="object"?typeof t=="string"?t.slice(0,1e3):typeof t=="number"||typeof t=="boolean"||t===null?t:void 0:Object.fromEntries(Object.entries(t).filter(([n])=>!/(?:token|secret|password|credential|authorization|api.?key|prompt|content)/i.test(n)).map(([n,r])=>[n,Rl(r,e+1)]))}var Pl=class t{constructor(e={}){this.options=e;this.retention={maxEvents:Math.max(32,e.eventRetention?.maxEvents??2e3),maxAgeMs:Math.max(6e4,e.eventRetention?.maxAgeMs??1440*60*1e3)},this.maxSubscriptionQueue=Math.max(8,Math.min(4096,e.maxSubscriptionQueue??256)),this.now=e.now??(()=>new Date),this.idFactory=e.idFactory??hce,this.defaultPrincipal=rE(e.defaultPrincipal??{id:"local-stdio",workspaceRoots:[process.cwd()],capabilities:["thread.delete.permanent","integrations.read"]});let n=e.stateDir??bce(xe(),"app-server-v2");this.store=new gg(n,this.retention),this.turnRunner=e.turnRunner??(async({turn:r})=>({accepted:!0,turnId:r.turnId}))}options;static supports(e){return wce.has(e)}retention;store;connections=new Map;subscriptions=new Map;activeTurns=new Map;permissionWaiters=new Map;maxSubscriptionQueue;now;idFactory;turnRunner;defaultPrincipal;stopping=!1;supports(e){return t.supports(e)}capabilities(){return{"protocol.v1":!0,"protocol.v2":!0,"threads.persistent":!0,"turns.steer":!0,"turns.interrupt":!0,"events.replay":!0,"events.atLeastOnce":!0,"permissions.respond":!0,"integrations.metadata":!0,"subscriptions.maxQueue":this.maxSubscriptionQueue,"events.maxRetained":this.retention.maxEvents}}async handle(e,n,r={transport:"test"}){if(!this.supports(e))return{handled:!1};let o=g$.now(),i="success",s;oe("xeno.app_server.method_calls",1,{component:"app_server_v2",method:e,transport:r.transport});try{let a=xce(n);if(e==="initialize")return{handled:!0,result:this.initialize(a,r)};let c=this.requireConnection(r);if(e==="capabilities.get")return{handled:!0,result:{appProtocolVersion:c.protocolVersion,capabilities:this.capabilities()}};if(c.protocolVersion!==2)throw new J("APP_SERVER_VERSION_UNSUPPORTED","This method requires app protocol v2.",-32010);return{handled:!0,result:await this.handleV2Method(e,a,c)}}catch(a){throw i="error",s=a instanceof J?a.machineCode:a instanceof Error?a.name:"unknown_error",a}finally{oe("xeno.app_server.method_results",1,{component:"app_server_v2",method:e,transport:r.transport,outcome:i,...s?{error_code:s}:{}}),Oe("xeno.app_server.method_duration_ms",g$.now()-o,{component:"app_server_v2",method:e,transport:r.transport,outcome:i})}}stop(){this.stopping=!0;for(let e of this.activeTurns.values())e.abort();this.activeTurns.clear();for(let e of this.permissionWaiters.values())clearTimeout(e.timer),e.resolve("deny");this.permissionWaiters.clear();for(let e of this.subscriptions.values())e.closed=!0}subscriptionSnapshots(){return[...this.subscriptions.values()].map(e=>({subscriptionId:e.subscriptionId,connectionId:e.connectionId,streamId:e.streamId,queuedEvents:e.queue.length,droppedEvents:e.droppedEvents,degraded:e.degraded,closed:e.closed}))}initialize(e,n){let r=e,o=Array.isArray(r.protocolVersions)?r.protocolVersions.filter(c=>Number.isInteger(c)):Number.isInteger(r.appProtocolVersion)?[r.appProtocolVersion]:[2],i=eE.find(c=>o.includes(c));if(!i)throw new J("APP_SERVER_VERSION_UNSUPPORTED","Client and server app protocol versions do not overlap.",-32010,!1,"protocol",{requested:o,supported:[...eE]});let s=rE(n.principal??this.defaultPrincipal);if(i===1){let c=`connection_${this.idFactory()}`;return this.connections.set(c,{connectionId:c,principal:s,protocolVersion:1,client:r.client,createdAt:this.now().toISOString()}),n.connectionId=c,{appProtocolVersion:1,connectionId:c,capabilities:{"protocol.v1":!0}}}let a=`connection_${this.idFactory()}`;return this.connections.set(a,{connectionId:a,principal:s,protocolVersion:2,client:r.client,createdAt:this.now().toISOString()}),n.connectionId=a,{appProtocolVersion:2,connectionId:a,principal:{id:s.id,...s.tenantId?{tenantId:s.tenantId}:{}},capabilities:this.capabilities(),eventRetention:this.retention}}requireConnection(e){let n=e.connectionId?.trim(),r=n?this.connections.get(n):void 0;if(!r)throw new J("APP_SERVER_INITIALIZATION_REQUIRED","Call initialize and provide its connection identity.",-32012,!1,"protocol");if(e.principal&&rE(e.principal).id!==r.principal.id)throw new J("APP_SERVER_UNAUTHORIZED","Connection principal mismatch.",-32011);return r}async handleV2Method(e,n,r){switch(e){case"thread.start":return this.startThread(n,r);case"thread.get":return this.getThread(n,r);case"thread.list":return this.listThreads(n,r);case"thread.resume":return this.mutateThreadStatus("resume",n,r);case"thread.archive":return this.mutateThreadStatus("archive",n,r);case"thread.delete":return this.deleteThread(n,r);case"turn.start":return this.startTurn(n,r);case"turn.get":return this.getTurn(n,r);case"turn.steer":return this.steerTurn(n,r);case"turn.interrupt":return this.interruptTurn(n,r);case"events.subscribe":return this.subscribe(n,r);case"events.unsubscribe":return this.unsubscribe(n,r);case"events.poll":return this.poll(n,r);case"events.replay":return this.replay(n,r);case"permission.respond":return this.respondPermission(n,r);case"integrations.list":return this.listIntegrations(r);default:throw new J("APP_SERVER_METHOD_UNKNOWN",`Unknown v2 method: ${e}`,-32601)}}startThread(e,n){let r=this.authorizeWorkspace(typeof e.workspaceRoot=="string"?e.workspaceRoot:n.principal.workspaceRoots[0],n.principal),o=this.now().toISOString(),i=this.idempotentMutation("thread.start",e,n,(s,a)=>{let c=`thread_${this.idFactory()}`,l={schemaVersion:2,threadId:c,streamId:`stream_${c}`,principalId:n.principal.id,...n.principal.tenantId?{tenantId:n.principal.tenantId}:{},workspaceRoot:r,...typeof e.title=="string"&&e.title.trim()?{title:e.title.trim().slice(0,200)}:{},status:"active",version:1,createdAt:o,updatedAt:o};return s.threads[c]=l,a.push(this.appendEvent(s,l,"thread.started",{version:l.version})),l});return this.publishMany(i.events),i.result}getThread(e,n){return this.requireThread(Ct(e,"threadId"),n,{allowDeleted:e.includeDeleted===!0})}listThreads(e,n){let r=e.includeArchived===!0,o=e.includeDeleted===!0;return Object.values(this.store.snapshot().threads).filter(i=>this.ownsThread(i,n.principal)).filter(i=>r||i.status!=="archived").filter(i=>o||i.status!=="deleted").sort((i,s)=>s.updatedAt.localeCompare(i.updatedAt))}mutateThreadStatus(e,n,r){let o=Ct(n,"threadId"),i=this.idempotentMutation(`thread.${e}`,n,r,(s,a)=>{let c=this.requireThreadFromState(s,o,r,{allowDeleted:!1});if(this.assertVersion(c.version,Xn(n.threadVersion),"thread"),e==="archive"&&c.status==="archived"||e==="resume"&&c.status==="active")return c;let l=this.now().toISOString(),d={...c,status:e==="archive"?"archived":"active",version:c.version+1,updatedAt:l,...e==="archive"?{archivedAt:l}:{archivedAt:void 0}};return s.threads[o]=d,a.push(this.appendEvent(s,d,`thread.${e==="archive"?"archived":"resumed"}`,{version:d.version})),d});return this.publishMany(i.events),i.result}deleteThread(e,n){let r=Ct(e,"threadId"),o=this.idempotentMutation("thread.delete",e,n,(i,s)=>{let a=this.requireThreadFromState(i,r,n,{allowDeleted:!0});if(this.assertVersion(a.version,Xn(e.threadVersion),"thread"),e.permanent===!0){if(!n.principal.capabilities.includes("thread.delete.permanent"))throw new J("APP_SERVER_UNAUTHORIZED","Permanent thread deletion is not permitted.",-32011);if(a.legalHold)throw new J("APP_SERVER_LEGAL_HOLD","Thread is under legal hold.",-32016);delete i.threads[r];for(let u of Object.values(i.turns))u.threadId===r&&delete i.turns[u.turnId];for(let u of Object.values(i.permissions))u.threadId===r&&delete i.permissions[u.requestId];return delete i.streams[a.streamId],{threadId:r,permanentlyDeleted:!0}}if(a.status==="deleted")return a;let l=this.now().toISOString(),d={...a,status:"deleted",version:a.version+1,updatedAt:l,deletedAt:l};return i.threads[r]=d,s.push(this.appendEvent(i,d,"thread.deleted",{version:d.version})),d});return this.publishMany(o.events),o.result}startTurn(e,n){let r=Ct(e,"threadId"),o=Ct(e,"input"),i=!1,s=this.idempotentMutation("turn.start",e,n,(c,l)=>{let d=this.requireThreadFromState(c,r,n,{allowDeleted:!1});if(d.status!=="active")throw new J("THREAD_NOT_ACTIVE","Thread must be active to start a turn.",-32013);let u=Object.values(c.turns).find(g=>g.threadId===r&&["queued","running","needs_permission"].includes(g.status));if(u)throw new J("TURN_ALREADY_ACTIVE","A thread can have only one active turn.",-32015,!0,"concurrency",{turnId:u.turnId});this.assertVersion(d.version,Xn(e.threadVersion),"thread");let p=this.now().toISOString(),m=`turn_${this.idFactory()}`,f={schemaVersion:2,turnId:m,threadId:r,principalId:n.principal.id,connectionId:n.connectionId,status:e.defer===!0?"queued":"running",version:1,input:o,steering:[],createdAt:p,updatedAt:p,...e.defer===!0?{}:{startedAt:p}};return c.turns[m]=f,c.threads[r]={...d,version:d.version+1,updatedAt:p},l.push(this.appendEvent(c,d,"turn.started",{status:f.status},m)),i=!0,f});this.publishMany(s.events);let a=s.result;return i&&a.status==="running"&&queueMicrotask(()=>{this.executeTurn(a.turnId)}),a}getTurn(e,n){let r=this.store.snapshot().turns[Ct(e,"turnId")];if(!r)throw new J("TURN_NOT_FOUND","Turn not found.",-32014);return this.requireThread(r.threadId,n,{allowDeleted:!1}),r}steerTurn(e,n){let r=Ct(e,"turnId"),o=Ct(e,"input"),i=this.idempotentMutation("turn.steer",e,n,(s,a)=>{let c=this.requireTurnFromState(s,r,n);if(this.assertVersion(c.version,Xn(e.turnVersion),"turn"),!["queued","running","needs_permission"].includes(c.status))throw new J("TURN_NOT_RUNNING","Only an active turn can be steered.",-32015);let l=this.now().toISOString(),d={...c,version:c.version+1,updatedAt:l,steering:[...c.steering,{id:`steer_${this.idFactory()}`,text:o,createdAt:l}]};s.turns[r]=d;let u=s.threads[c.threadId];return a.push(this.appendEvent(s,u,"turn.steering",{count:d.steering.length},r)),d});return this.publishMany(i.events),i.result}interruptTurn(e,n){let r=Ct(e,"turnId"),o=this.idempotentMutation("turn.interrupt",e,n,(i,s)=>{let a=this.requireTurnFromState(i,r,n);if(this.assertVersion(a.version,Xn(e.turnVersion),"turn"),["completed","failed","interrupted"].includes(a.status))return a;let c=this.now().toISOString(),l={...a,status:"interrupted",version:a.version+1,updatedAt:c,completedAt:c};i.turns[r]=l;let d=i.threads[a.threadId];return s.push(this.appendEvent(i,d,"turn.interrupted",{},r)),l});return this.activeTurns.get(r)?.abort(),this.publishMany(o.events),o.result}subscribe(e,n){let r=this.resolveAuthorizedStream(e,n),o=h$(e.afterSequence,"afterSequence")??0,i=this.replayStream(r,o,Xn(e.limit)??100,n),s=`subscription_${this.idFactory()}`,a=Math.max(8,Math.min(this.maxSubscriptionQueue,Xn(e.maxQueue)??this.maxSubscriptionQueue));return this.subscriptions.set(s,{subscriptionId:s,connectionId:n.connectionId,principalId:n.principal.id,streamId:r,queue:[],maxQueue:a,droppedEvents:0,degraded:!1,closed:!1}),{subscriptionId:s,streamId:r,maxQueue:a,replay:i}}unsubscribe(e,n){let r=this.requireSubscription(Ct(e,"subscriptionId"),n);return r.closed=!0,this.subscriptions.delete(r.subscriptionId),{unsubscribed:!0}}poll(e,n){let r=this.requireSubscription(Ct(e,"subscriptionId"),n);if(this.threadForStream(r.streamId,n).status==="deleted")throw r.closed=!0,this.subscriptions.delete(r.subscriptionId),new J("APP_SERVER_UNAUTHORIZED","Event access has been revoked.",-32011);let i=Math.max(1,Math.min(256,Xn(e.limit)??100)),s=r.queue.splice(0,i);return{subscriptionId:r.subscriptionId,events:s,degraded:r.degraded,droppedEvents:r.droppedEvents,closed:r.closed}}replay(e,n){let r=this.resolveAuthorizedStream(e,n);return this.replayStream(r,h$(e.afterSequence,"afterSequence")??0,Xn(e.limit)??100,n)}replayStream(e,n,r,o){if(this.threadForStream(e,o).status==="deleted")throw new J("APP_SERVER_UNAUTHORIZED","Event access has been revoked.",-32011);let s=this.store.snapshot().streams[e]??{nextSequence:1,prunedThrough:0,events:[]};if(n<s.prunedThrough)throw oe("xeno.app_server.cursor_expirations",1,{component:"app_server_v2",operation:"replay",reason:"cursor_expired"}),new J("EVENT_CURSOR_EXPIRED","The requested event cursor is older than retained history.",-32018,!1,"replay",{prunedThrough:s.prunedThrough});let a=Math.max(1,Math.min(256,r)),c=s.events.filter(d=>d.sequence>n).slice(0,a);Oe("xeno.app_server.replay_events",c.length,{component:"app_server_v2",operation:"replay"});let l=new Set;for(let d of c){let u=`${d.streamId}:${d.sequence}`;if(l.has(u))throw new J("APP_SERVER_EVENT_DUPLICATE","Duplicate retained event detected.",-32019);l.add(u)}return{streamId:e,events:c,nextCursor:c.at(-1)?.sequence??n,hasMore:s.events.some(d=>d.sequence>(c.at(-1)?.sequence??n)),delivery:"at-least-once"}}respondPermission(e,n){let r=Ct(e,"requestId"),o=Ct(e,"response");if(!["allow","always","deny"].includes(o))throw new J("APP_SERVER_INVALID_PARAMS","Permission response is invalid.",-32602);let i=this.lookupIdempotentMutation("permission.respond",e,n);if(i.found)return i.result;let s=this.store.snapshot().permissions[r];if(!s||s.status!=="pending")throw new J("PERMISSION_RESPONSE_STALE","Permission request is not active.",-32017);if(s.principalId!==n.principal.id||s.connectionId!==n.connectionId)throw new J("APP_SERVER_UNAUTHORIZED","Permission request ownership mismatch.",-32011);if(Date.parse(s.expiresAt)<=this.now().getTime())throw this.store.mutate(l=>{let d=l.permissions[r];d?.status==="pending"&&(l.permissions[r]={...d,status:"expired"})},this.now()),new J("PERMISSION_RESPONSE_STALE","Permission request has expired.",-32017);let a=this.idempotentMutation("permission.respond",e,n,(l,d)=>{let u=l.permissions[r];if(!u)throw new J("PERMISSION_RESPONSE_STALE","Permission request is not active.",-32017);let p=this.now().toISOString(),m={...u,status:o==="deny"?"denied":"allowed",response:o,respondedAt:p};l.permissions[r]=m;let f=l.threads[u.threadId];return d.push(this.appendEvent(l,f,"permission.resolved",{requestId:r,response:o},u.turnId)),m}),c=this.permissionWaiters.get(r);return c&&(clearTimeout(c.timer),this.permissionWaiters.delete(r),c.resolve(o)),this.publishMany(a.events),a.result}async listIntegrations(e){return e.principal.capabilities.includes("integrations.read")?(await this.options.integrations?.()??[]).filter(r=>(r.requiredCapabilities??[]).every(o=>e.principal.capabilities.includes(o))).filter(r=>!r.workspaceRoot||e.principal.workspaceRoots.some(o=>oE(r.workspaceRoot,o))).map(r=>({id:r.id,kind:r.kind,name:r.name,...r.description?{description:r.description.slice(0,500)}:{},status:r.status,...r.workspaceRoot?{workspaceRoot:r.workspaceRoot}:{},requiredCapabilities:[...r.requiredCapabilities??[]],metadata:Rl(r.metadata??{})})):[]}async executeTurn(e){let n=this.store.snapshot(),r=n.turns[e],o=r?n.threads[r.threadId]:void 0;if(!r||!o||r.status!=="running")return;let i=new AbortController;this.activeTurns.set(e,i);let s=new Set;try{let a=await this.turnRunner({thread:o,turn:r,signal:i.signal,emit:(l,d={})=>{if(this.stopping)return;let u=this.store.mutate(p=>{let m=p.threads[o.threadId];return m?this.appendEvent(p,m,l,Rl(d),e):null},this.now());u&&this.publish(u)},takeSteering:()=>{let l=this.store.snapshot().turns[e];if(!l)return[];let d=l.steering.filter(u=>!s.has(u.id));return d.forEach(u=>s.add(u.id)),d},requestPermission:l=>this.createPermissionRequest(e,l)});if(this.stopping)return;let c=this.store.mutate(l=>{let d=l.turns[e];if(!d||d.status==="interrupted")return[];let u=this.now().toISOString();return l.turns[e]={...d,status:"completed",version:d.version+1,updatedAt:u,completedAt:u,result:Rl(a)},[this.appendEvent(l,l.threads[d.threadId],"turn.completed",{},e)]},this.now());this.publishMany(c)}catch(a){if(this.stopping)return;let c=this.store.mutate(l=>{let d=l.turns[e];if(!d||d.status==="interrupted")return[];let u=this.now().toISOString(),p=Sce(a);return l.turns[e]={...d,status:"failed",version:d.version+1,updatedAt:u,completedAt:u,error:p},[this.appendEvent(l,l.threads[d.threadId],"turn.failed",{code:p.code},e)]},this.now());this.publishMany(c)}finally{this.activeTurns.delete(e)}}createPermissionRequest(e,n){let r=this.now(),o=Math.max(1e3,Math.min(10*6e4,n.expiresInMs??6e4)),i=this.store.mutate(s=>{let a=s.turns[e];if(!a)throw new J("TURN_NOT_FOUND","Turn not found.",-32014);let c=`permission_${this.idFactory()}`,l={schemaVersion:2,requestId:c,threadId:a.threadId,turnId:e,principalId:a.principalId,connectionId:a.connectionId,permission:n.permission.slice(0,200),...n.resource?{resource:n.resource.slice(0,500)}:{},status:"pending",createdAt:r.toISOString(),expiresAt:new Date(r.getTime()+o).toISOString()};s.permissions[c]=l,s.turns[e]={...a,status:"needs_permission",version:a.version+1,updatedAt:l.createdAt};let d=this.appendEvent(s,s.threads[a.threadId],"permission.requested",{requestId:c,permission:l.permission,...l.resource?{resource:l.resource}:{},expiresAt:l.expiresAt},e);return{permission:l,event:d}},r);return this.publish(i.event),new Promise(s=>{let a=setTimeout(()=>{if(this.stopping){s("deny");return}this.permissionWaiters.delete(i.permission.requestId);let c=this.store.mutate(l=>{let d=l.permissions[i.permission.requestId];if(!d||d.status!=="pending")return null;l.permissions[d.requestId]={...d,status:"expired"};let u=l.turns[d.turnId];return u?.status==="needs_permission"&&(l.turns[d.turnId]={...u,status:"running",version:u.version+1,updatedAt:this.now().toISOString()}),this.appendEvent(l,l.threads[d.threadId],"permission.expired",{requestId:d.requestId},d.turnId)},this.now());c&&this.publish(c),s("deny")},o);a.unref?.(),this.permissionWaiters.set(i.permission.requestId,{resolve:s,timer:a})})}idempotentMutation(e,n,r,o){if(!vce.has(e))throw new Error(`Method ${e} is not registered as a mutation.`);let i=typeof n.idempotencyKey=="string"?n.idempotencyKey.trim():"",s={...n};delete s.idempotencyKey;let a=b$(s),c=i?`${r.principal.id}:${e}:${i}`:"";return this.store.mutate(l=>{if(c){let p=l.idempotency[c];if(p){if(p.fingerprint!==a)throw new J("IDEMPOTENCY_KEY_REUSED","The idempotency key was already used with different parameters.",-32020);return{result:p.result,events:[]}}}let d=[],u=o(l,d);return c&&(l.idempotency[c]={fingerprint:a,result:u,createdAt:this.now().toISOString()}),{result:u,events:d}},this.now())}lookupIdempotentMutation(e,n,r){let o=typeof n.idempotencyKey=="string"?n.idempotencyKey.trim():"";if(!o)return{found:!1};let i={...n};delete i.idempotencyKey;let s=b$(i),a=`${r.principal.id}:${e}:${o}`,c=this.store.snapshot().idempotency[a];if(!c)return{found:!1};if(c.fingerprint!==s)throw new J("IDEMPOTENCY_KEY_REUSED","The idempotency key was already used with different parameters.",-32020);return{found:!0,result:c.result}}appendEvent(e,n,r,o,i){let s=e.streams[n.streamId]??{nextSequence:1,prunedThrough:0,events:[]};e.streams[n.streamId]=s;let a={protocolVersion:2,schemaVersion:2,streamId:n.streamId,sequence:s.nextSequence,eventId:`event_${this.idFactory()}`,threadId:n.threadId,...i?{turnId:i}:{},type:r,timestamp:this.now().toISOString(),payload:o};return s.nextSequence+=1,s.events.push(a),a}publishMany(e){for(let n of e)this.publish(n)}publish(e){for(let n of this.subscriptions.values()){if(n.closed||n.streamId!==e.streamId)continue;if(n.queue.length<n.maxQueue){n.queue.push(e);continue}if(n.degraded=!0,oe("xeno.app_server.subscription_backpressure",1,{component:"app_server_v2",queue:"subscription",state:"degraded"}),Ece(e)){let o=-1;for(let i=n.queue.length-1;i>=0;i-=1){let s=n.queue[i];if(s.type===e.type&&s.turnId===e.turnId){o=i;break}}o>=0?n.queue[o]=e:(n.droppedEvents+=1,oe("xeno.app_server.subscription_dropped_events",1,{component:"app_server_v2",reason:"coalescing_unavailable"}));continue}let r=n.queue.findIndex(o=>!Ace(o));if(r>=0){n.queue.splice(r,1),n.queue.push(e),n.droppedEvents+=1,oe("xeno.app_server.subscription_dropped_events",1,{component:"app_server_v2",reason:"terminal_priority"});continue}n.closed=!0,n.queue=[],n.droppedEvents+=1,oe("xeno.app_server.subscription_closures",1,{component:"app_server_v2",reason:"irrecoverable_backpressure"})}}authorizeWorkspace(e,n){if(typeof e!="string"||!e.trim()||!yce(e))throw new J("APP_SERVER_UNAUTHORIZED","A permitted workspace is required.",-32011);let r=sE(e);if(!n.workspaceRoots.some(o=>oE(r,o)))throw new J("APP_SERVER_UNAUTHORIZED","Workspace is outside the principal boundary.",-32011);return r}ownsThread(e,n){return e.principalId===n.id&&(e.tenantId??"")===(n.tenantId??"")&&n.workspaceRoots.some(r=>oE(e.workspaceRoot,r))}requireThread(e,n,r){return this.requireThreadFromState(this.store.snapshot(),e,n,r)}requireThreadFromState(e,n,r,o){let i=e.threads[n];if(!i||!this.ownsThread(i,r.principal)||!o.allowDeleted&&i.status==="deleted")throw new J("APP_SERVER_UNAUTHORIZED","Thread is not available to this principal.",-32011);return i}requireTurnFromState(e,n,r){let o=e.turns[n];if(!o)throw new J("TURN_NOT_FOUND","Turn not found.",-32014);return this.requireThreadFromState(e,o.threadId,r,{allowDeleted:!1}),o}assertVersion(e,n,r){if(n!==void 0&&n!==e)throw new J("APP_SERVER_VERSION_CONFLICT",`The ${r} version is stale.`,-32021,!0,"concurrency",{expected:n,actual:e})}resolveAuthorizedStream(e,n){if(typeof e.threadId=="string")return this.requireThread(e.threadId,n,{allowDeleted:!0}).streamId;let r=Ct(e,"streamId");return this.threadForStream(r,n),r}threadForStream(e,n){let r=Object.values(this.store.snapshot().threads).find(o=>o.streamId===e);if(!r||!this.ownsThread(r,n.principal))throw new J("APP_SERVER_UNAUTHORIZED","Event stream is not available.",-32011);return r}requireSubscription(e,n){let r=this.subscriptions.get(e);if(!r||r.connectionId!==n.connectionId||r.principalId!==n.principal.id)throw new J("APP_SERVER_UNAUTHORIZED","Subscription is not available.",-32011);if(r.closed)throw new J("APP_SERVER_BACKPRESSURE","Subscription was closed because the client could not keep up.",-32022,!0,"backpressure");return r}};var hi=class extends Error{constructor(n,r,o){super(n);this.rpcCode=r;this.data=o;this.name="AppServerRemoteError"}rpcCode;data},w$=class{constructor(e){this.transport=e}transport;connectionId;async initialize(e={protocolVersions:[2]}){let n=await this.transport.request({method:"initialize",params:e});if(!n||typeof n!="object"||n.appProtocolVersion!==2)throw new hi("Server did not negotiate app protocol v2.",-32010,{code:"APP_SERVER_VERSION_UNSUPPORTED",retryable:!1,category:"protocol"});let r=n;return this.connectionId=r.connectionId,r}async call(e,n){if(!this.connectionId)throw new hi("Call initialize before stateful methods.",-32012,{code:"APP_SERVER_INITIALIZATION_REQUIRED",retryable:!1,category:"protocol"});return await this.transport.request({method:e,params:n,connectionId:this.connectionId})}getConnectionId(){return this.connectionId}};function V2e(t){let e=t.fetch??globalThis.fetch,n=0;return{async request(r){let o=await e(new URL("/rpc",t.url),{method:"POST",headers:{authorization:`Bearer ${t.bearerToken}`,"content-type":"application/json",...r.connectionId?{"x-xeno-connection-id":r.connectionId}:{}},body:JSON.stringify({jsonrpc:"2.0",id:++n,method:r.method,params:r.params})});if(!o.ok)throw new hi(`HTTP app-server request failed with status ${o.status}.`,o.status);let s=(await o.json()).messages?.[0];if(!s)throw new hi("App server returned no JSON-RPC message.",-32603);if(s.error)throw new hi(s.error.message,s.error.code,s.error.data);return s.result}}}var aE=class{constructor(e={}){this.options=e;this.execManager=e.execManager??dp,this.ownerId=e.ownerId??`app-server-${kce()}`;let n=e.defaultAgentOptions?.cwd??process.cwd();this.v2Options={...e.v2,defaultPrincipal:e.v2?.defaultPrincipal??{id:this.ownerId,workspaceRoots:[n],capabilities:["thread.delete.permanent","integrations.read"]},turnRunner:e.v2?.turnRunner??(async r=>ZA({...this.options.defaultAgentOptions,prompt:r.turn.input,signal:r.signal,...this.options.defaultAgentOptions?.permissionEngine?{permissionEngine:this.options.defaultAgentOptions.permissionEngine.fork(async o=>r.requestPermission({permission:o.toolName,resource:o.filePath??o.directory??o.commandPrefix??o.detail}))}:{permissionPrompt:async o=>r.requestPermission({permission:o.toolName,resource:o.filePath??o.directory??o.commandPrefix??o.detail})},onPermissionRequest:async o=>{let i=await r.requestPermission({permission:o.toolName,resource:o.path||o.directory||o.reason});return{granted:i!=="deny",...i==="always"?{allowedDirectory:o.directory}:{}}},onRuntimeEvent:o=>r.emit("runtime.event",{eventType:o.type,timestamp:o.timestamp,sequence:o.sequence},{coalescible:/delta|progress/.test(o.type)})}))}}options;stopping=!1;execManager;ownerId;v2Runtime;v2Options;async start(e=process.stdin,n=process.stdout){let r=Ice({input:e,crlfDelay:1/0}),o={transport:"stdio",principal:this.options.v2?.defaultPrincipal??{id:this.ownerId,workspaceRoots:[this.options.defaultAgentOptions?.cwd??process.cwd()],capabilities:["thread.delete.permanent","integrations.read"]}};this.write(n,{jsonrpc:"2.0",method:"server.ready",params:{name:"xeno-app-server",protocolVersion:1,protocolVersions:[2,1],ownerId:this.ownerId,capabilities:{"exec.pty":this.execManager.getPtyCapability(),"exec.resize":!0}}});try{for await(let i of r){if(this.stopping)break;let s=i.trim();if(!s)continue;let a;try{a=JSON.parse(s)}catch(c){this.write(n,this.error(null,-32700,"Parse error",c));continue}await this.handleRequest(a,n,o)}}finally{this.stop()}}stop(){this.stopping||(this.stopping=!0,this.v2Runtime?.stop(),this.execManager.terminateOwner(this.ownerId,{force:!0}))}async handleJsonRpcRequest(e,n={transport:"test"}){let r=[],o={write(i){for(let s of i.split(/\r?\n/)){let a=s.trim();a&&r.push(JSON.parse(a))}return!0}};return await this.handleRequest(e,o,n),r}getSubscriptionSnapshots(){return this.v2Runtime?.subscriptionSnapshots()??[]}async handleRequest(e,n,r){try{if(Pl.supports(e.method)){let o=await this.appServerV2().handle(e.method,e.params,r);if(o.handled){this.write(n,this.success(e.id??null,o.result));return}}if(e.method==="health"){this.write(n,this.success(e.id??null,{ok:!0}));return}if(e.method==="exec.start"){let o=po(e.params),i=typeof o.command=="string"?o.command:"";if(!i.trim()){this.write(n,this.error(e.id??null,-32602,"exec.start requires params.command"));return}this.write(n,this.success(e.id??null,this.execManager.start(i,{cwd:typeof o.cwd=="string"?o.cwd:void 0,timeoutMs:mo(o.timeoutMs),maxOutputBytes:mo(o.maxOutputBytes),env:Tce(o.env),tty:o.tty===!0,cols:mo(o.cols),rows:mo(o.rows),ownerSessionId:this.ownerId,origin:"app_server"})));return}if(e.method==="exec.write"){let o=po(e.params),i=typeof o.processId=="string"?o.processId:"",s=typeof o.text=="string"?o.text:"";if(!this.isOwned(i)){this.write(n,this.error(e.id??null,-32004,"Process not found"));return}this.write(n,this.success(e.id??null,{ok:this.execManager.writeStdin(i,s,{source:"app_server"})}));return}if(e.method==="exec.output"){let o=po(e.params),i=typeof o.processId=="string"?o.processId:"";if(!this.isOwned(i)){this.write(n,this.error(e.id??null,-32004,"Process not found"));return}this.write(n,this.success(e.id??null,this.execManager.readOutput(i)));return}if(e.method==="exec.output.delta"){let o=po(e.params),i=typeof o.processId=="string"?o.processId:"";if(!this.isOwned(i)){this.write(n,this.error(e.id??null,-32004,"Process not found"));return}this.write(n,this.success(e.id??null,this.execManager.readOutputDelta(i,Rce(o.cursor)??0,{maxChunks:mo(o.maxChunks),maxBytes:mo(o.maxBytes)})));return}if(e.method==="exec.terminate"){let o=po(e.params),i=typeof o.processId=="string"?o.processId:"";if(!this.isOwned(i)){this.write(n,this.error(e.id??null,-32004,"Process not found"));return}this.write(n,this.success(e.id??null,{ok:this.execManager.terminate(i)}));return}if(e.method==="exec.resize"){let o=po(e.params),i=typeof o.processId=="string"?o.processId:"";if(!this.isOwned(i)){this.write(n,this.error(e.id??null,-32004,"Process not found"));return}let s=mo(o.cols),a=mo(o.rows);if(!s||!a){this.write(n,this.error(e.id??null,-32602,"INVALID_SIZE: exec.resize requires positive cols and rows"));return}let c=this.execManager.get(i);if(c.status!=="running"){this.write(n,this.error(e.id??null,-32005,`TASK_NOT_RUNNING: ${c.status}`));return}if(!c.interactive){this.write(n,this.error(e.id??null,-32006,"TASK_NOT_INTERACTIVE: process is pipe-backed"));return}if(!this.execManager.resize(i,s,a)){this.write(n,this.error(e.id??null,-32602,"INVALID_SIZE: terminal dimensions are outside supported bounds"));return}this.write(n,this.success(e.id??null,{ok:!0}));return}if(e.method==="exec.list"){this.write(n,this.success(e.id??null,this.execManager.list({ownerSessionId:this.ownerId})));return}if(e.method==="thread.run"){let o=po(e.params),i=typeof o.prompt=="string"?o.prompt:"";if(!i.trim()){this.write(n,this.error(e.id??null,-32602,"thread.run requires params.prompt"));return}let s=po(o.options),a=await ZA({...this.options.defaultAgentOptions,...s,prompt:i,onRuntimeEvent:c=>{this.write(n,{jsonrpc:"2.0",method:"runtime.event",params:c})}});this.write(n,this.success(e.id??null,a));return}if(e.method==="server.stop"){this.write(n,this.success(e.id??null,{ok:!0})),this.stop();return}this.write(n,this.error(e.id??null,-32601,`Unknown method: ${e.method}`))}catch(o){if(o instanceof J){this.write(n,this.error(e.id??null,o.rpcCode,o.message,o.toData()));return}let i=o instanceof Error?o.message:String(o);this.write(n,this.error(e.id??null,-32e3,i))}}success(e,n){return{jsonrpc:"2.0",id:e,result:n}}appServerV2(){return this.v2Runtime??=new Pl(this.v2Options),this.v2Runtime}isOwned(e){return this.execManager.get(e)?.ownerSessionId===this.ownerId}error(e,n,r,o){return{jsonrpc:"2.0",id:e,error:{code:n,message:r,...o?{data:Pce(o)}:{}}}}write(e,n){e.write(`${JSON.stringify(n)}
2571
- `)}};function po(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Tce(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=Object.entries(t).filter(n=>typeof n[0]=="string"&&(typeof n[1]=="string"||n[1]===void 0));return Object.fromEntries(e)}function mo(t){let e=typeof t=="number"?t:Number.parseInt(String(t??""),10);if(!(!Number.isFinite(e)||e<=0))return Math.floor(e)}function Rce(t){let e=typeof t=="number"?t:Number.parseInt(String(t??""),10);if(!(!Number.isFinite(e)||e<0))return Math.floor(e)}function Pce(t){return t instanceof Error?{name:t.name,message:t.message}:t&&typeof t=="object"&&!Array.isArray(t)?t:{value:String(t)}}Ha();nc();Ji();bt();Ze();tt();ns();import*as go from"path";import*as cE from"os";import*as fo from"fs";var Cce=1e4,_ce=6e4,Mce="session.lock",Oce="lock.json",Gs=new Map;function lE(t,e){return t!=null&&t.pid===e.pid&&t.hostname===e.hostname&&t.processStartedAt===e.processStartedAt&&t.acquiredAt===e.acquiredAt}function Nce(){for(let[t,e]of Gs)try{let n=ee(fo.readFileSync(t,"utf8"),null);lE(n,e)&&fo.unlinkSync(t)}catch{}Gs.clear()}Kr(Nce);var ho=class t{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=go.join(e,Mce),this.legacyLockPath=go.join(e,Oce),this.sessionId=go.basename(e)}async acquire(){let e=new Date().toISOString(),n={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:cE.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:qn,acquiredAt:e,updatedAt:e,heartbeat:e},r=go.dirname(this.lockPath);await fo.promises.mkdir(r,{recursive:!0});let o=await this.findExistingLockPath();if(o){if(!await this.isStalePath(o)){let s=await this.readLockAt(o);throw new Error(`Session ${this.sessionId} is already locked by PID ${s?.pid} on ${s?.hostname}`)}await Vn(o)}try{await fo.promises.writeFile(this.lockPath,JSON.stringify(n,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=n,Gs.set(this.lockPath,n)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let c=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${c?.pid} on ${c?.hostname}`)}await Vn(this.lockPath);try{await fo.promises.writeFile(this.lockPath,JSON.stringify(n,null,2),{flag:"wx",encoding:"utf-8"})}catch(c){throw c.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):c}this.acquiredOwner=n,Gs.set(this.lockPath,n)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;Gs.delete(this.lockPath);let n=await this.readLockAt(this.lockPath);lE(n,e)&&await Vn(this.lockPath)}async isLocked(){let e=await this.findExistingLockPath();return e?!await this.isStalePath(e):!1}async isStale(){let e=await this.findExistingLockPath();return e?this.isStalePath(e):!1}async isStalePath(e){let n=await this.readLockAt(e);if(!n)return!1;if(n.hostname===cE.hostname())try{process.kill(n.pid,0)}catch(i){if(i.code!=="EPERM")return!0}let r=new Date(n.heartbeat).getTime();return Date.now()-r>_ce}startHeartbeat(e=Cce){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(n){let r=n instanceof Error?n.message:String(n);if(n?.code==="ENOENT"){K("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}K(`SessionLock: Failed to update heartbeat: ${r}`)}},e),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let e=await this.readLockAt(this.lockPath),n=this.acquiredOwner;if(!(!e||!n)){if(!lE(e,n)){this.acquiredOwner=void 0,Gs.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await he(this.lockPath,JSON.stringify(e,null,2))}}async readLock(){let e=await this.findExistingLockPath();return e?this.readLockAt(e):null}async readLockAt(e){let n=await pe(e);return n?ee(n,null):null}async findExistingLockPath(){return await pe(this.lockPath)?this.lockPath:await pe(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let n=await od(e),r=[];for(let o of n){let i=new t(o);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await Vn(a),r.push(go.basename(o))}}return r}};Ru();bt();Ze();nc();Ji();import*as yg from"path";Ru();Ha();vo();tc();tt();Ji();nc();function Dce(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e.type==="text"?typeof e.text=="string":e.type==="tool_use"?typeof e.id=="string"&&typeof e.name=="string"&&!!e.input&&typeof e.input=="object"&&!Array.isArray(e.input):e.type==="tool_result"?typeof e.tool_use_id=="string"&&typeof e.content=="string":!1}function Lce(t){if(!t||typeof t!="object")return!1;let e=t;return(e.role==="user"||e.role==="assistant")&&(typeof e.content=="string"||Array.isArray(e.content)&&e.content.every(Dce))}function v$(t){return JSON.stringify({role:t.role,content:t.content})}function Sr(t,e){return t.length>e.length?!1:t.every((n,r)=>v$(n)===v$(e[r]))}function $ce(t,e){return Sr(t,e)?e.slice(t.length):[]}function Xce(t){return{role:"user",content:Array.from(t,n=>({type:"tool_result",tool_use_id:n,content:"Tool execution was interrupted before a durable result was recorded. Retry if the operation is still required.",is_error:!0,retryable:!0}))}}function Cl(t){let e=[],n=[],r=[],o=new Set,i=()=>{if(o.size===0)return;let s=Array.from(o),a=Xce(s);e.push(a),n.push(a),r.push(...s),o.clear()};for(let s of t){let a=Array.isArray(s.content)?s.content:[],c=new Set(a.filter(d=>d.type==="tool_result").map(d=>d.tool_use_id)),l=typeof s.content=="string"||a.some(d=>d.type!=="tool_result");if(o.size>0&&(s.role==="assistant"||l)&&i(),e.push(s),s.role==="assistant")for(let d of a)d.type==="tool_use"&&d.id&&o.add(d.id);else for(let d of c)o.delete(d)}return i(),{messages:e,repairs:n,interruptedToolUseIds:r}}async function hg(t,e){let n=new jt(t),r=await n.readValidated(),o=r.issues.map(b=>({code:b.code,detail:b.detail})),i=r.events.filter(b=>n.isMessageEvent(b)).map(b=>({...b.data,id:b.data.id??b.id})),s=[],a=!1;for(let b of r.events){if(n.isMessageEvent(b)){s.push({...b.data,id:b.data.id??b.id});continue}if(b.type!=="context_compressed")continue;let w=b.data.activeContextMessages;if(w!==void 0){if(!Array.isArray(w)||!w.every(Lce)){o.push({code:"invalid_compaction_snapshot",detail:`Ignored invalid resident-context snapshot from transcript event ${b.id}.`});continue}s=structuredClone(w),a=!0}}let c=Cl(i),l=Cl(s);for(let b of l.interruptedToolUseIds)o.push({code:"interrupted_tool_call",detail:`Recovered interrupted tool call ${b} without discarding later messages.`});let d=l.messages,u=c.messages,p=d.length>0?"transcript":"empty",m,f=p==="transcript"?l.repairs:[],g=new Nt(t),h=[];for(let b of await g.list()){let w;try{w=(await g.restore(b.id)).messages}catch{continue}if(w.length!==0){if(d.length===0){h.push({id:b.id,messages:w});continue}if(a){w.length>s.length&&Sr(s,w)?h.push({id:b.id,messages:w}):!Sr(w,s)&&!Sr(s,w)&&o.push({code:"divergent_checkpoint",detail:`Preserved divergent checkpoint ${b.id}; it was not selected as the active branch.`});continue}if(w.length>i.length&&Sr(i,w)){h.push({id:b.id,messages:w});continue}!Sr(w,i)&&!Sr(i,w)&&o.push({code:"divergent_checkpoint",detail:`Preserved divergent checkpoint ${b.id}; it was not selected as the active branch.`})}}h.sort((b,w)=>w.messages.length-b.messages.length);let y=h[0];if(y){let b=Cl(y.messages);d=b.messages,u=a?[...c.messages,...$ce(s,y.messages)]:b.messages,f=b.repairs,p="checkpoint",m=y.id,o.push({code:"checkpoint_fallback",detail:i.length>0?`Checkpoint ${y.id} extends the valid transcript prefix to ${y.messages.length} messages.`:`Recovered ${y.messages.length} messages from checkpoint ${y.id}.`});for(let w of b.interruptedToolUseIds)o.push({code:"interrupted_tool_call",detail:`Recovered interrupted tool call ${w} from checkpoint ${y.id}.`});for(let w of h.slice(1))!Sr(w.messages,y.messages)&&!Sr(y.messages,w.messages)&&o.push({code:"divergent_checkpoint",detail:`Preserved divergent checkpoint ${w.id}; deterministic recovery selected ${y.id}.`})}return e?.metadataMessageCount!==void 0&&e.metadataMessageCount!==d.length&&o.push({code:"stale_metadata",detail:`Metadata recorded ${e.metadataMessageCount} messages; durable recovery found ${d.length} active context messages.`}),{messages:d,transcriptMessages:u,source:p,...m?{sourceId:m}:{},issues:o,repairMessages:f,transcriptEventCount:r.events.length,latestTimestamp:r.events.at(-1)?.timestamp}}qy();var yi=class t{sessionDir;_meta;_transcript;_checkpoints;_lock;_recovery;_detachedForHandoff=!1;constructor(e,n,r,o,i,s){this.sessionDir=e,this._meta=n,this._transcript=r,this._checkpoints=o,this._lock=i,this._recovery=s}static async create(e){Xo(e.executionMode);let n=e.role??"default",r=$r(n),o=Rt.getSessionDir(r),i=null,s=null;try{await en(o);let a={id:r,role:n,status:"creating",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),lastActivity:new Date().toISOString(),workingDirectory:e.workingDirectory,model:e.model,...e.executionMode!==void 0?{executionMode:e.executionMode}:{},parentSession:e.parentSession,...e.hostBinding?{hostBinding:structuredClone(e.hostBinding)}:{},checkpoints:[],messageCount:0,tokenUsage:{input:0,output:0,total:0},formatVersion:1},c=yg.join(o,"meta.json");await he(c,JSON.stringify(a,null,2)),s=new jt(o);let l=new Nt(o);i=new ho(o),await i.acquire(),i.startHeartbeat(),await s.append({type:"session_start",data:{sessionId:r,role:n,workingDirectory:e.workingDirectory,model:e.model,formatVersion:1}});let d=new t(o,a,s,l,i,{messages:[],transcriptMessages:[],source:"empty",issues:[],repairMessages:[],transcriptEventCount:1});return await d.updateMeta({status:"active"}),d}catch(a){if(i)try{i.stopHeartbeat(),await i.release()}catch(c){K("Error releasing lock during cleanup",c)}throw a}}static async resume(e){let n=Rt.getSessionDir(e.sessionId),r=null,o=null;try{let i=yg.join(n,"meta.json"),s=await pe(i);if(!s)throw new Error(`SessionManager: Session not found: ${e.sessionId}`);let a=ee(s,null);if(!a)throw new Error(`SessionManager: Invalid session metadata: ${e.sessionId}`);Xo(a.executionMode),a.formatVersion=dE(a),o=new jt(n),await o.initialize();let c=new Nt(n);r=new ho(n),await r.acquire(),r.startHeartbeat();let l;if(e.fromCheckpoint){let{info:u,messages:p}=await c.restore(e.fromCheckpoint);a.messageCount=u.messageCount,await o.append({type:"checkpoint",data:{id:e.fromCheckpoint,trigger:"manual",messageCount:u.messageCount}}),l={messages:p,transcriptMessages:p,source:"checkpoint",sourceId:e.fromCheckpoint,issues:[],repairMessages:[],transcriptEventCount:o.getSequence()}}else l=await hg(n,{metadataMessageCount:a.messageCount}),a.messageCount=l.messages.length;let d=new t(n,a,o,c,r,l);return await d.updateMeta({status:"active",lastActivity:new Date().toISOString()}),d}catch(i){if(r)try{r.stopHeartbeat(),await r.release()}catch(s){K("Error releasing lock during cleanup",s)}throw i}}get meta(){return{...this._meta}}get transcript(){return this._transcript}get checkpoints(){return this._checkpoints}get recovery(){return{...this._recovery,messages:[...this._recovery.messages],transcriptMessages:[...this._recovery.transcriptMessages],repairMessages:[...this._recovery.repairMessages],issues:[...this._recovery.issues]}}async detachForHandoff(){this._detachedForHandoff||(await this._transcript.flush(),this._lock.stopHeartbeat(),await this._lock.release(),this._detachedForHandoff=!0)}get detachedForHandoff(){return this._detachedForHandoff}async updateMeta(e){if(Xo(e.executionMode),this._detachedForHandoff)throw new Error(`Session ${this._meta.id} is detached after execution handoff`);this._meta={...this._meta,...e,updatedAt:new Date().toISOString()};let n=yg.join(this.sessionDir,"meta.json"),r=3,o=null;for(let i=0;i<r;i++)try{await he(n,JSON.stringify(this._meta,null,2));return}catch(s){o=s instanceof Error?s:new Error(String(s)),fe(`Failed to write session metadata (attempt ${i+1}/${r}): ${o.message}`),i<r-1&&await new Promise(a=>setTimeout(a,Math.pow(2,i)*100))}K(`Failed to write session metadata after ${r} attempts. Session will continue but metadata may be stale.`)}async end(e="completed"){await this._transcript.append({type:"session_end",data:{reason:e==="completed"?"completed":"user_exit",messageCount:this._meta.messageCount,totalTokens:this._meta.tokenUsage.total}}),await this._transcript.flush(),await this.updateMeta({status:e}),this._lock.stopHeartbeat(),await this._lock.release()}async recordUserMessage(e){await this._transcript.append({type:"user_message",data:{role:"user",content:e}}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()})}async recordDirectShellResult(e){let n=ku(e);return await this._transcript.append({type:"user_message",data:n}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()}),n}async recordAssistantMessage(e,n){await this._transcript.append({type:"assistant_message",data:{role:"assistant",content:e},tokenCount:n}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()})}async recordTokenUsage(e,n){let r={input:this._meta.tokenUsage.input+e,output:this._meta.tokenUsage.output+n,total:this._meta.tokenUsage.total+e+n};await this.updateMeta({tokenUsage:r})}async recordDelegationSummary(e){await this._transcript.append({type:"delegation_summary",data:e}),await this.updateMeta({lastActivity:new Date().toISOString()})}async updateMessageCount(e){e!==this._meta.messageCount&&await this.updateMeta({messageCount:e,lastActivity:new Date().toISOString()})}};function dE(t){let e=t?.formatVersion;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}tc();Wy();Tt();Be();import{randomUUID as wg}from"node:crypto";import{spawn as Bce}from"node:child_process";import{mkdir as Ml,readFile as _l,readdir as x$,realpath as vg,rm as bg,stat as Uce,unlink as S$,writeFile as uE}from"node:fs/promises";import{tmpdir as Fce}from"node:os";import ke from"node:path";var pE=2,A$=400,mE=80,gE=12,E$=3e4,fE=64*1024*1024;function I$(t){let e=t.replace(/\r\n/g,`
2571
+ `)}};function po(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Tce(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=Object.entries(t).filter(n=>typeof n[0]=="string"&&(typeof n[1]=="string"||n[1]===void 0));return Object.fromEntries(e)}function mo(t){let e=typeof t=="number"?t:Number.parseInt(String(t??""),10);if(!(!Number.isFinite(e)||e<=0))return Math.floor(e)}function Rce(t){let e=typeof t=="number"?t:Number.parseInt(String(t??""),10);if(!(!Number.isFinite(e)||e<0))return Math.floor(e)}function Pce(t){return t instanceof Error?{name:t.name,message:t.message}:t&&typeof t=="object"&&!Array.isArray(t)?t:{value:String(t)}}Ha();nc();Ji();bt();Ze();tt();ns();import*as go from"path";import*as cE from"os";import*as fo from"fs";var Cce=1e4,_ce=6e4,Mce="session.lock",Oce="lock.json",Gs=new Map;function lE(t,e){return t!=null&&t.pid===e.pid&&t.hostname===e.hostname&&t.processStartedAt===e.processStartedAt&&t.acquiredAt===e.acquiredAt}function Nce(){for(let[t,e]of Gs)try{let n=ee(fo.readFileSync(t,"utf8"),null);lE(n,e)&&fo.unlinkSync(t)}catch{}Gs.clear()}Kr(Nce);var ho=class t{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=go.join(e,Mce),this.legacyLockPath=go.join(e,Oce),this.sessionId=go.basename(e)}async acquire(){let e=new Date().toISOString(),n={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:cE.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:qn,acquiredAt:e,updatedAt:e,heartbeat:e},r=go.dirname(this.lockPath);await fo.promises.mkdir(r,{recursive:!0});let o=await this.findExistingLockPath();if(o){if(!await this.isStalePath(o)){let s=await this.readLockAt(o);throw new Error(`Session ${this.sessionId} is already locked by PID ${s?.pid} on ${s?.hostname}`)}await Vn(o)}try{await fo.promises.writeFile(this.lockPath,JSON.stringify(n,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=n,Gs.set(this.lockPath,n)}catch(i){if(i.code==="EEXIST"){if(!await this.isStalePath(this.lockPath)){let c=await this.readLockAt(this.lockPath);throw new Error(`Session ${this.sessionId} is already locked by PID ${c?.pid} on ${c?.hostname}`)}await Vn(this.lockPath);try{await fo.promises.writeFile(this.lockPath,JSON.stringify(n,null,2),{flag:"wx",encoding:"utf-8"})}catch(c){throw c.code==="EEXIST"?new Error(`Session ${this.sessionId} lock was acquired by another process during stale recovery`):c}this.acquiredOwner=n,Gs.set(this.lockPath,n)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;Gs.delete(this.lockPath);let n=await this.readLockAt(this.lockPath);lE(n,e)&&await Vn(this.lockPath)}async isLocked(){let e=await this.findExistingLockPath();return e?!await this.isStalePath(e):!1}async isStale(){let e=await this.findExistingLockPath();return e?this.isStalePath(e):!1}async isStalePath(e){let n=await this.readLockAt(e);if(!n)return!1;if(n.hostname===cE.hostname())try{return process.kill(n.pid,0),!1}catch(i){return i.code!=="EPERM"}let r=new Date(n.heartbeat).getTime();return Date.now()-r>_ce}startHeartbeat(e=Cce){this.heartbeatTimer&&this.stopHeartbeat(),this.heartbeatTimer=setInterval(async()=>{try{await this.updateHeartbeat()}catch(n){let r=n instanceof Error?n.message:String(n);if(n?.code==="ENOENT"){K("SessionLock: Session directory removed, stopping heartbeat"),this.stopHeartbeat();return}K(`SessionLock: Failed to update heartbeat: ${r}`)}},e),this.heartbeatTimer.unref()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async updateHeartbeat(){let e=await this.readLockAt(this.lockPath),n=this.acquiredOwner;if(!(!e||!n)){if(!lE(e,n)){this.acquiredOwner=void 0,Gs.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await he(this.lockPath,JSON.stringify(e,null,2))}}async readLock(){let e=await this.findExistingLockPath();return e?this.readLockAt(e):null}async readLockAt(e){let n=await pe(e);return n?ee(n,null):null}async findExistingLockPath(){return await pe(this.lockPath)?this.lockPath:await pe(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let n=await od(e),r=[];for(let o of n){let i=new t(o);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await Vn(a),r.push(go.basename(o))}}return r}};Ru();bt();Ze();nc();Ji();import*as yg from"path";Ru();Ha();vo();tc();tt();Ji();nc();function Dce(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e.type==="text"?typeof e.text=="string":e.type==="tool_use"?typeof e.id=="string"&&typeof e.name=="string"&&!!e.input&&typeof e.input=="object"&&!Array.isArray(e.input):e.type==="tool_result"?typeof e.tool_use_id=="string"&&typeof e.content=="string":!1}function Lce(t){if(!t||typeof t!="object")return!1;let e=t;return(e.role==="user"||e.role==="assistant")&&(typeof e.content=="string"||Array.isArray(e.content)&&e.content.every(Dce))}function v$(t){return JSON.stringify({role:t.role,content:t.content})}function Sr(t,e){return t.length>e.length?!1:t.every((n,r)=>v$(n)===v$(e[r]))}function $ce(t,e){return Sr(t,e)?e.slice(t.length):[]}function Xce(t){return{role:"user",content:Array.from(t,n=>({type:"tool_result",tool_use_id:n,content:"Tool execution was interrupted before a durable result was recorded. Retry if the operation is still required.",is_error:!0,retryable:!0}))}}function Cl(t){let e=[],n=[],r=[],o=new Set,i=()=>{if(o.size===0)return;let s=Array.from(o),a=Xce(s);e.push(a),n.push(a),r.push(...s),o.clear()};for(let s of t){let a=Array.isArray(s.content)?s.content:[],c=new Set(a.filter(d=>d.type==="tool_result").map(d=>d.tool_use_id)),l=typeof s.content=="string"||a.some(d=>d.type!=="tool_result");if(o.size>0&&(s.role==="assistant"||l)&&i(),e.push(s),s.role==="assistant")for(let d of a)d.type==="tool_use"&&d.id&&o.add(d.id);else for(let d of c)o.delete(d)}return i(),{messages:e,repairs:n,interruptedToolUseIds:r}}async function hg(t,e){let n=new jt(t),r=await n.readValidated(),o=r.issues.map(b=>({code:b.code,detail:b.detail})),i=r.events.filter(b=>n.isMessageEvent(b)).map(b=>({...b.data,id:b.data.id??b.id})),s=[],a=!1;for(let b of r.events){if(n.isMessageEvent(b)){s.push({...b.data,id:b.data.id??b.id});continue}if(b.type!=="context_compressed")continue;let w=b.data.activeContextMessages;if(w!==void 0){if(!Array.isArray(w)||!w.every(Lce)){o.push({code:"invalid_compaction_snapshot",detail:`Ignored invalid resident-context snapshot from transcript event ${b.id}.`});continue}s=structuredClone(w),a=!0}}let c=Cl(i),l=Cl(s);for(let b of l.interruptedToolUseIds)o.push({code:"interrupted_tool_call",detail:`Recovered interrupted tool call ${b} without discarding later messages.`});let d=l.messages,u=c.messages,p=d.length>0?"transcript":"empty",m,f=p==="transcript"?l.repairs:[],g=new Nt(t),h=[];for(let b of await g.list()){let w;try{w=(await g.restore(b.id)).messages}catch{continue}if(w.length!==0){if(d.length===0){h.push({id:b.id,messages:w});continue}if(a){w.length>s.length&&Sr(s,w)?h.push({id:b.id,messages:w}):!Sr(w,s)&&!Sr(s,w)&&o.push({code:"divergent_checkpoint",detail:`Preserved divergent checkpoint ${b.id}; it was not selected as the active branch.`});continue}if(w.length>i.length&&Sr(i,w)){h.push({id:b.id,messages:w});continue}!Sr(w,i)&&!Sr(i,w)&&o.push({code:"divergent_checkpoint",detail:`Preserved divergent checkpoint ${b.id}; it was not selected as the active branch.`})}}h.sort((b,w)=>w.messages.length-b.messages.length);let y=h[0];if(y){let b=Cl(y.messages);d=b.messages,u=a?[...c.messages,...$ce(s,y.messages)]:b.messages,f=b.repairs,p="checkpoint",m=y.id,o.push({code:"checkpoint_fallback",detail:i.length>0?`Checkpoint ${y.id} extends the valid transcript prefix to ${y.messages.length} messages.`:`Recovered ${y.messages.length} messages from checkpoint ${y.id}.`});for(let w of b.interruptedToolUseIds)o.push({code:"interrupted_tool_call",detail:`Recovered interrupted tool call ${w} from checkpoint ${y.id}.`});for(let w of h.slice(1))!Sr(w.messages,y.messages)&&!Sr(y.messages,w.messages)&&o.push({code:"divergent_checkpoint",detail:`Preserved divergent checkpoint ${w.id}; deterministic recovery selected ${y.id}.`})}return e?.metadataMessageCount!==void 0&&e.metadataMessageCount!==d.length&&o.push({code:"stale_metadata",detail:`Metadata recorded ${e.metadataMessageCount} messages; durable recovery found ${d.length} active context messages.`}),{messages:d,transcriptMessages:u,source:p,...m?{sourceId:m}:{},issues:o,repairMessages:f,transcriptEventCount:r.events.length,latestTimestamp:r.events.at(-1)?.timestamp}}qy();var yi=class t{sessionDir;_meta;_transcript;_checkpoints;_lock;_recovery;_detachedForHandoff=!1;constructor(e,n,r,o,i,s){this.sessionDir=e,this._meta=n,this._transcript=r,this._checkpoints=o,this._lock=i,this._recovery=s}static async create(e){Xo(e.executionMode);let n=e.role??"default",r=$r(n),o=Rt.getSessionDir(r),i=null,s=null;try{await en(o);let a={id:r,role:n,status:"creating",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),lastActivity:new Date().toISOString(),workingDirectory:e.workingDirectory,model:e.model,...e.executionMode!==void 0?{executionMode:e.executionMode}:{},parentSession:e.parentSession,...e.hostBinding?{hostBinding:structuredClone(e.hostBinding)}:{},checkpoints:[],messageCount:0,tokenUsage:{input:0,output:0,total:0},formatVersion:1},c=yg.join(o,"meta.json");await he(c,JSON.stringify(a,null,2)),s=new jt(o);let l=new Nt(o);i=new ho(o),await i.acquire(),i.startHeartbeat(),await s.append({type:"session_start",data:{sessionId:r,role:n,workingDirectory:e.workingDirectory,model:e.model,formatVersion:1}});let d=new t(o,a,s,l,i,{messages:[],transcriptMessages:[],source:"empty",issues:[],repairMessages:[],transcriptEventCount:1});return await d.updateMeta({status:"active"}),d}catch(a){if(i)try{i.stopHeartbeat(),await i.release()}catch(c){K("Error releasing lock during cleanup",c)}throw a}}static async resume(e){let n=Rt.getSessionDir(e.sessionId),r=null,o=null;try{let i=yg.join(n,"meta.json"),s=await pe(i);if(!s)throw new Error(`SessionManager: Session not found: ${e.sessionId}`);let a=ee(s,null);if(!a)throw new Error(`SessionManager: Invalid session metadata: ${e.sessionId}`);Xo(a.executionMode),a.formatVersion=dE(a),o=new jt(n),await o.initialize();let c=new Nt(n);r=new ho(n),await r.acquire(),r.startHeartbeat();let l;if(e.fromCheckpoint){let{info:u,messages:p}=await c.restore(e.fromCheckpoint);a.messageCount=u.messageCount,await o.append({type:"checkpoint",data:{id:e.fromCheckpoint,trigger:"manual",messageCount:u.messageCount}}),l={messages:p,transcriptMessages:p,source:"checkpoint",sourceId:e.fromCheckpoint,issues:[],repairMessages:[],transcriptEventCount:o.getSequence()}}else l=await hg(n,{metadataMessageCount:a.messageCount}),a.messageCount=l.messages.length;let d=new t(n,a,o,c,r,l);return await d.updateMeta({status:"active",lastActivity:new Date().toISOString()}),d}catch(i){if(r)try{r.stopHeartbeat(),await r.release()}catch(s){K("Error releasing lock during cleanup",s)}throw i}}get meta(){return{...this._meta}}get transcript(){return this._transcript}get checkpoints(){return this._checkpoints}get recovery(){return{...this._recovery,messages:[...this._recovery.messages],transcriptMessages:[...this._recovery.transcriptMessages],repairMessages:[...this._recovery.repairMessages],issues:[...this._recovery.issues]}}async detachForHandoff(){this._detachedForHandoff||(await this._transcript.flush(),this._lock.stopHeartbeat(),await this._lock.release(),this._detachedForHandoff=!0)}get detachedForHandoff(){return this._detachedForHandoff}async updateMeta(e){if(Xo(e.executionMode),this._detachedForHandoff)throw new Error(`Session ${this._meta.id} is detached after execution handoff`);this._meta={...this._meta,...e,updatedAt:new Date().toISOString()};let n=yg.join(this.sessionDir,"meta.json"),r=3,o=null;for(let i=0;i<r;i++)try{await he(n,JSON.stringify(this._meta,null,2));return}catch(s){o=s instanceof Error?s:new Error(String(s)),fe(`Failed to write session metadata (attempt ${i+1}/${r}): ${o.message}`),i<r-1&&await new Promise(a=>setTimeout(a,Math.pow(2,i)*100))}K(`Failed to write session metadata after ${r} attempts. Session will continue but metadata may be stale.`)}async end(e="completed"){await this._transcript.append({type:"session_end",data:{reason:e==="completed"?"completed":"user_exit",messageCount:this._meta.messageCount,totalTokens:this._meta.tokenUsage.total}}),await this._transcript.flush(),await this.updateMeta({status:e}),this._lock.stopHeartbeat(),await this._lock.release()}async recordUserMessage(e){await this._transcript.append({type:"user_message",data:{role:"user",content:e}}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()})}async recordDirectShellResult(e){let n=ku(e);return await this._transcript.append({type:"user_message",data:n}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()}),n}async recordAssistantMessage(e,n){await this._transcript.append({type:"assistant_message",data:{role:"assistant",content:e},tokenCount:n}),await this.updateMeta({messageCount:this._meta.messageCount+1,lastActivity:new Date().toISOString()})}async recordTokenUsage(e,n){let r={input:this._meta.tokenUsage.input+e,output:this._meta.tokenUsage.output+n,total:this._meta.tokenUsage.total+e+n};await this.updateMeta({tokenUsage:r})}async recordDelegationSummary(e){await this._transcript.append({type:"delegation_summary",data:e}),await this.updateMeta({lastActivity:new Date().toISOString()})}async updateMessageCount(e){e!==this._meta.messageCount&&await this.updateMeta({messageCount:e,lastActivity:new Date().toISOString()})}};function dE(t){let e=t?.formatVersion;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}tc();Wy();Tt();Be();import{randomUUID as wg}from"node:crypto";import{spawn as Bce}from"node:child_process";import{mkdir as Ml,readFile as _l,readdir as x$,realpath as vg,rm as bg,stat as Uce,unlink as S$,writeFile as uE}from"node:fs/promises";import{tmpdir as Fce}from"node:os";import ke from"node:path";var pE=2,A$=400,mE=80,gE=12,E$=3e4,fE=64*1024*1024;function I$(t){let e=t.replace(/\r\n/g,`
2572
2572
  `).replace(/\r/g,`
2573
2573
  `);if(e.length===0)return[];let n=e.endsWith(`
2574
2574
  `)?e.slice(0,-1):e;return n.length===0?[]:n.split(`