@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.cjs CHANGED
@@ -2448,7 +2448,7 @@ try {
2448
2448
 
2449
2449
  ---
2450
2450
 
2451
- `));let h=t.systemPrompt??tT({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(()=>(Aw(),bU)),{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??GR,4096)),maxIterations:Math.max(3,Math.min(t.maxIterations??WR,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??Tn({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 yi({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??GR,maxIterations:t.maxIterations??WR,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 wU,GR,WR,bl=T(()=>{"use strict";wU=require("node:process");Ko();eo();Hy();nT();Zy();zd();yb();fi();GR=8192,WR=50});var mle={};sC(mle,{AGENT_DAEMON_PROTOCOL_VERSION:()=>pl,AGENT_EFFORT_LEVELS:()=>Ov,AGENT_PERMISSION_MODES:()=>Nv,AGENT_PROFILE_EXTERNAL_ACTIONS:()=>Gl,ARCHITECT_CAPABILITIES:()=>tj,ARCHITECT_TOOL_NAMES:()=>ej,AgentDaemonClient:()=>eR,AgentDaemonServer:()=>ZT,AgentDebugger:()=>Cv,AgentDefinitionLoader:()=>Rm,AgentDefinitionResolver:()=>Uv,AgentEvaluator:()=>_v,AgentEventStore:()=>Ap,AgentHookRunner:()=>If,AgentInterruptedError:()=>Bn,AgentLoop:()=>yi,AgentProfileValidationError:()=>jr,AgentProtocol:()=>Bw,AgentRegistry:()=>Xw,AgentRunController:()=>QT,AgentRunError:()=>jy,AgentRunStore:()=>Ep,AppAgentFactory:()=>ym,AppContextInjector:()=>sa,AppContextManager:()=>Ni,AppServerProtocolError:()=>W,AppServerRemoteError:()=>Ri,AuditLogger:()=>ha,AutoCheckpointHandler:()=>qy,AutoMemory:()=>hA,AutoPermissionClassifier:()=>lb,BUILT_IN_XENO_PROVIDER_PRESETS:()=>Sj,BackgroundProcessManager:()=>ou,COMPAT_TOOL_ALIASES:()=>fA,CONFIG_VERSION:()=>PS,CheckpointManager:()=>dn,CliGovernedAutomationRuntime:()=>df,CodeValidator:()=>Pv,CommandHookRunner:()=>Pf,CompletionGuardRegistry:()=>el,ContainmentApprovalError:()=>pe,ContainmentCertificationError:()=>ue,ContextManager:()=>dp,ConversationStore:()=>jw,CrossAppRouter:()=>$w,CrossAppRouterError:()=>ra,DEFAULT_API_KEY:()=>Yn,DEFAULT_IMAGE_MODEL:()=>oh,DEFAULT_MEMORY_BUDGETS:()=>ZS,DEFAULT_MODEL:()=>os,DEFAULT_PROMPT_SECTIONS_TOKEN_BUDGET:()=>pp,DEFAULT_PROTECTED_STATE_KEY_NAME:()=>p5,DEFAULT_PROTECTED_STATE_SERVICE:()=>u5,DEFAULT_SUBAGENT_BRANCH_POLICY:()=>Gy,DEFAULT_SUBAGENT_REMOTE_MCP_BY_ROLE:()=>Jy,DEFAULT_SUBAGENT_ROLES:()=>rl,DEFAULT_SUBAGENT_ROLE_PRECEDENCE:()=>Wy,DEFAULT_SUBAGENT_TEAM_PRESET:()=>Xs,DIRECT_SHELL_CONTEXT_WARNING:()=>ig,DOCS_CAPABILITIES:()=>lj,DOCS_TOOL_NAMES:()=>cj,DualLLMProvider:()=>El,DurableXenoCapabilityLeaseRegistry:()=>IT,DurableXenoCoordinationStore:()=>Lp,ENGINE_CAPABILITIES:()=>ij,ENGINE_TOOL_NAMES:()=>oj,ElectronAgentBridge:()=>Lw,EpisodicStore:()=>sl,ExecutionGovernance:()=>fl,ExecutionSecurityError:()=>Vn,FALLBACK_MODELS:()=>cM,FileQuotaAuthority:()=>rC,FileXenoArtifactRepository:()=>hd,FileXenoProviderConnectionStore:()=>tC,FileXenoShareRegistry:()=>TR,HIGH_RISK_PERMISSIONS:()=>zP,HookRunner:()=>Tf,HookRuntime:()=>Rf,HttpHookRunner:()=>Cf,IDENTITY_PATHS:()=>ko,IdentityLoader:()=>Bs,IdentityResolver:()=>Us,InMemoryXenoArtifactRepository:()=>Ra,InMemoryXenoCapabilityLeaseRegistry:()=>hr,InMemoryXenoTelemetryCollector:()=>GS,InteractiveChatTurnGovernance:()=>jb,InteractiveTurnGovernance:()=>Vs,JsonSchemaCompilationError:()=>ls,LlmClient:()=>Vc,LocalLLMProvider:()=>aa,LogLevel:()=>lA,MANIFEST_FILENAME:()=>mm,MAX_CONTAINMENT_APPROVAL_AGE_MS:()=>VX,MAX_CONTAINMENT_CERTIFICATION_BYTES:()=>ix,MAX_CONTAINMENT_CERTIFICATION_LIFETIME_MS:()=>KC,MAX_DIRECT_SHELL_OUTPUT_CHARS:()=>dA,MCPHttpTransportError:()=>Ke,MCPManager:()=>tv,MCPOAuthClient:()=>Kw,MCPServer:()=>nv,MCP_APPS_EXTENSION_ID:()=>oa,MCP_APP_MIME_TYPE:()=>dm,MCP_APP_RESOURCE_SCHEME:()=>wF,MCP_PROTOCOL_VERSION:()=>$r,MCP_SUPPORTED_PROTOCOL_VERSIONS:()=>Gw,MEMORY_FILES:()=>eA,MOTION_CAPABILITIES:()=>wj,MOTION_SYSTEM_PROMPT:()=>mP,MOTION_TOOL_NAMES:()=>bj,MemoryManager:()=>ao,MessageFlow:()=>Wc,ModelProviderRegistry:()=>Ld,MonitorManager:()=>oR,MonitorStopTool:()=>sR,MonitorTool:()=>iR,NOTES_CAPABILITIES:()=>gj,NOTES_TOOL_NAMES:()=>fj,OtelExporter:()=>cR,PIXEL_CAPABILITIES:()=>yj,PIXEL_SYSTEM_PROMPT:()=>pP,PIXEL_TOOL_NAMES:()=>hj,PROCESS_TREE_ADAPTERS:()=>Bj,PROJECT_STATE_VERSION:()=>Y_,PermissionEngine:()=>rn,PluginEventBus:()=>Ll,PluginHost:()=>Xl,PluginManager:()=>UF,PluginMarketplace:()=>mv,PluginSandbox:()=>Nl,PluginSettingsManager:()=>sv,PluginToolBuilder:()=>iv,ProfileManager:()=>qS,PromptHookRunner:()=>Ef,PromptSectionRegistry:()=>Zc,ProtectedFileWriteError:()=>Cn,ProviderError:()=>ge,QueryLifecycle:()=>Jc,QuotaAcknowledgementError:()=>Uy,QuotaError:()=>we,REQUIRED_CONTAINMENT_CONFORMANCE_CHECKS:()=>Ql,SDK_DEFAULT_MAX_ITERATIONS:()=>WR,SDK_DEFAULT_MAX_TOKENS:()=>GR,SDK_VERSION:()=>pr,SESSION_FORMAT_VERSION:()=>ql,SHEETS_CAPABILITIES:()=>uj,SHEETS_TOOL_NAMES:()=>dj,SLIDES_CAPABILITIES:()=>mj,SLIDES_TOOL_NAMES:()=>pj,SOUND_CAPABILITIES:()=>xj,SOUND_SYSTEM_PROMPT:()=>fP,SOUND_TOOL_NAMES:()=>vj,SSETransport:()=>Li,SUBAGENT_ROLE_ALIASES:()=>tX,SUBAGENT_TEAM_PRESETS:()=>nX,ScreenCapture:()=>Nw,SessionLock:()=>Oo,SessionLockManager:()=>Oo,SessionManager:()=>Oi,SessionRegistry:()=>en,SkillStore:()=>al,SoulEngine:()=>sb,SqliteAutomationExecutionJournal:()=>rf,SqliteCapabilityLeasePersistence:()=>db,StdioTransport:()=>Cl,StreamableHTTPTransport:()=>Pl,THREE_D_CAPABILITIES:()=>rj,THREE_D_TOOL_NAMES:()=>nj,TOOL_OPERATION_SCHEMA_VERSION:()=>tu,TaskListManager:()=>Ps,ToolFailureLoopGuard:()=>Yc,ToolMiddlewareRegistry:()=>Qc,ToolOperationManager:()=>Ug,ToolOrchestrator:()=>ep,ToolRegistry:()=>Cs,ToolSchemaProjectionError:()=>Et,TranscriptWriter:()=>Sn,TurnDiffTracker:()=>xk,TurnRestoreManager:()=>na,UNBOUNDED_OPERATION_CONTINUATION_LIMIT:()=>nu,UnifiedExecError:()=>Ar,UnifiedExecManager:()=>Fg,UsageAccumulator:()=>Pb,UsageLedger:()=>aR,VectorMemoryStore:()=>ei,WEB_CONTEXT_CONTRACT_VERSION:()=>hE,WEB_CONTEXT_TOOL_RESULT_SCHEMA:()=>sh,WORKFLOW_CAPABILITIES:()=>aj,WORKFLOW_TOOL_NAMES:()=>sj,WorkflowPlanner:()=>ml,WorkflowRuntime:()=>rR,WorkflowStore:()=>Rb,WorkspaceIndex:()=>Dw,XENO_AGENT_PROFILE_SCHEMA_VERSION:()=>Mm,XENO_API_BASE:()=>vr,XENO_APP_PROTOCOL_V2_METHODS:()=>JR,XENO_APP_PROTOCOL_VERSIONS:()=>Iw,XENO_ARTIFACT_ACTOR_KINDS:()=>_x,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION:()=>Jx,XENO_ARTIFACT_SCHEMA_VERSION:()=>Ae,XENO_ARTIFACT_SENSITIVITIES:()=>Cx,XENO_ARTIFACT_STATES:()=>Px,XENO_AUTOMATION_OPERATIONS:()=>va,XENO_AUTOMATION_PROTOCOL_VERSION:()=>Hr,XENO_BROWSER_CONTROL_PLANE_OPERATIONS:()=>gd,XENO_BUILTIN_ARTIFACT_KINDS:()=>Rx,XENO_CAPABILITY_LEASE_SCHEMA_VERSION:()=>Kx,XENO_CONTAINMENT_APPROVAL_SCHEMA:()=>ub,XENO_CONTAINMENT_CERTIFICATION_SCHEMA:()=>Dm,XENO_CONTAINMENT_CONFORMANCE_SCHEMA:()=>ZX,XENO_CONTAINMENT_REVIEWER_TRUST_STORE_SCHEMA:()=>pb,XENO_CONTROL_ROOM_SCHEMA_VERSION:()=>_b,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION:()=>Np,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION:()=>rw,XENO_COORDINATION_SCHEMA_VERSION:()=>Co,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION:()=>Dp,XENO_DEFLATE_CODEC_NAME:()=>yM,XENO_DEFLATE_CODEC_VERSION:()=>bM,XENO_EVIDENCE_EDGE_TYPES:()=>ad,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION:()=>id,XENO_EVIDENCE_NODE_TYPES:()=>sd,XENO_GIF_ANIMATION_POLICY:()=>n2,XENO_GIF_CODEC_NAME:()=>e2,XENO_GIF_CODEC_VERSION:()=>t2,XENO_HANDOFF_SCHEMA_VERSION:()=>Zb,XENO_HOSTED_CONTROL_SCHEMA_VERSION:()=>LR,XENO_HOSTED_ENVIRONMENT_SCHEMA_VERSION:()=>Xp,XENO_HOSTED_EVENT_SCHEMA_VERSION:()=>sw,XENO_HOSTED_EXECUTION_ADAPTER_CERTIFICATION_SCHEMA:()=>Up,XENO_HOSTED_EXECUTION_ADAPTER_MAX_CERTIFICATE_LIFETIME_MS:()=>VB,XENO_HOSTED_EXECUTION_ADAPTER_PROTOCOL_VERSION:()=>_R,XENO_HOSTED_EXECUTION_PROTOCOL_VERSION:()=>JB,XENO_HOSTED_EXECUTION_TOOL_NAMES:()=>KB,XENO_HOSTED_RESULT_SCHEMA_VERSION:()=>$R,XENO_HOSTED_RUN_SCHEMA_VERSION:()=>rie,XENO_HOSTED_TRIGGER_SCHEMA_VERSION:()=>oie,XENO_JPEG_CODEC_NAME:()=>u2,XENO_JPEG_CODEC_VERSION:()=>p2,XENO_MXC_ADAPTER_NAME:()=>Um,XENO_MXC_POLICY_VERSION:()=>px,XENO_MXC_VERSION:()=>Vo,XENO_ORACLE_REPORT_SCHEMA_VERSION:()=>HR,XENO_PLUGIN_LOCK_FILENAME:()=>fm,XENO_PLUGIN_LOCK_SCHEMA_VERSION:()=>$l,XENO_PLUGIN_SIGNATURE_FILENAME:()=>ia,XENO_PLUGIN_SIGNATURE_SCHEMA_VERSION:()=>cv,XENO_PROVIDER_CATALOG_SCHEMA_VERSION:()=>QP,XENO_PROVIDER_CONNECTION_STORE_SCHEMA_VERSION:()=>Ev,XENO_RASTER_CODEC_NAME:()=>di,XENO_RASTER_CODEC_VERSION:()=>Oh,XENO_RASTER_PREVIEW_FORMATS:()=>oI,XENO_RECIPE_SCHEMA_VERSION:()=>hU,XENO_REPOSITORY_INDEX_SCHEMA_VERSION:()=>Vb,XENO_REVIEW_DIMENSIONS:()=>__,XENO_REVIEW_EVIDENCE_KINDS:()=>M_,XENO_REVIEW_REPORT_SCHEMA_VERSION:()=>bS,XENO_RT_DEFAULT_URL:()=>Uf,XENO_SECURE_EXECUTION_CONTRACT_SCHEMA_VERSION:()=>xx,XENO_SHARE_REGISTRY_SCHEMA_VERSION:()=>Op,XENO_SHARE_SCHEMA_VERSION:()=>Qb,XENO_SKILL_SCHEMA_VERSION:()=>qs,XENO_SOURCE_RESEARCH_SCHEMA_VERSION:()=>zR,XENO_SPEC_EXECUTION_SCHEMA_VERSION:()=>xd,XENO_SPEC_SCHEMA_VERSION:()=>Xa,XENO_SVG_RENDERER_NAME:()=>L2,XENO_SVG_RENDERER_VERSION:()=>$2,XENO_TELEMETRY_SCHEMA_VERSION:()=>mM,XENO_VP8_CODEC_NAME:()=>aN,XENO_VP8_CODEC_VERSION:()=>cN,XENO_WEBP_ANIMATION_POLICY:()=>hN,XENO_WEBP_CODEC_NAME:()=>fN,XENO_WEBP_CODEC_VERSION:()=>gN,XenoAppServer:()=>Rw,XenoAppServerV2Client:()=>rP,XenoArtifactRepositoryError:()=>F,XenoArtifactReviewService:()=>La,XenoArtifactStateTransitionError:()=>Jm,XenoArtifactValidationError:()=>Ki,XenoAuthError:()=>Fa,XenoAutomationError:()=>L,XenoBrowserControlPlaneAdapter:()=>Oa,XenoCapabilityLeaseError:()=>Re,XenoControlRoomValidationError:()=>He,XenoCoordinationError:()=>_,XenoDiffParseError:()=>Dt,XenoEvidenceGraphBuilder:()=>sS,XenoEvidenceGraphValidationError:()=>mf,XenoExecutionLeaseSession:()=>CR,XenoGovernedAutomationExecutor:()=>fd,XenoHostGovernedAutomationRuntime:()=>df,XenoLoopbackAutomationAdapter:()=>Fx,XenoMultiAgentReviewCoordinator:()=>yS,XenoOracleCoordinator:()=>UR,XenoOracleValidationError:()=>Nn,XenoProviderCatalog:()=>Ul,XenoRecipeValidationError:()=>Rt,XenoRepositoryIndexFileStore:()=>SR,XenoReviewValidationError:()=>vt,XenoRuntimeEventBus:()=>gi,XenoSecureExecutionContractError:()=>ot,XenoSourceResearchValidationError:()=>ki,XenoSpecLifecycleService:()=>pS,XenoSpecValidationError:()=>wt,XenoTraceGraphRecorder:()=>Uc,acquireControlPlaneLock:()=>Gn,activateSessionRuntime:()=>Aae,addProjectAllowedDirectory:()=>MS,addProjectAllowedTool:()=>_S,agentDefinitionFromProfile:()=>MH,agentProfileFromDefinition:()=>UC,appendBoundedShellOutput:()=>Jg,appendGuidanceToResult:()=>zk,approveMcpServer:()=>Vw,areSignalHandlersInstalled:()=>i6,artifactCompareTool:()=>zD,askUserTool:()=>N1,assertDirectEndpointResolution:()=>Ay,assertPersistedXenoCapabilityLease:()=>Wn,assertRequiredXenoAutomationEvidence:()=>md,assertSupportedMcpProtocolVersion:()=>Ww,assertUsableXenoApiKey:()=>US,assertValidMcpAppResource:()=>Zw,assertValidXenoArtifact:()=>it,assertValidXenoAutomationAdapterManifest:()=>od,assertValidXenoAutomationRequest:()=>Ix,assertValidXenoEvidenceGraph:()=>Da,assertValidXenoHostedExecutionJob:()=>Eie,assertValidXenoOracleReport:()=>yw,assertValidXenoRecipeDefinition:()=>zp,assertValidXenoReviewPack:()=>wS,assertValidXenoReviewReport:()=>Ad,assertValidXenoReviewTarget:()=>vS,assertValidXenoSecureExecutionContract:()=>Vm,assertValidXenoSourceResearchReport:()=>vw,assertValidXenoSpecDocument:()=>wf,assertValidXenoSpecExecution:()=>hS,assertXenoArtifactStateTransition:()=>ud,assertXenoAutomationAdapterConformant:()=>Kq,assertXenoAutomationAuthority:()=>Wm,auditRiskLevelForTool:()=>QU,authorizeShellExecution:()=>Xg,backgroundProcessManager:()=>ae,bashTool:()=>R1,benchmarkCodingTools:()=>iee,bridgeXenoTelemetryToOpenTelemetry:()=>O4,buildAtomicMessageGroups:()=>$k,buildAuditReplayReport:()=>yC,buildAuditTraceReport:()=>hC,buildContainedProcessSpec:()=>l0,buildContractLedgerGuidance:()=>$b,buildDefaultSubagentTasks:()=>Aee,buildDelegatedRoleSystemPrompt:()=>pT,buildHookEnvironment:()=>IS,buildLinuxBubblewrapProcessSpec:()=>Nm,buildLspDefinitionReport:()=>VI,buildLspDiagnosticsReport:()=>qI,buildLspDoctorReport:()=>YD,buildLspHoverReport:()=>GI,buildLspReferencesReport:()=>zI,buildMotionSystemPrompt:()=>Sl,buildPixelSystemPrompt:()=>xl,buildProcessHardenedProcessSpec:()=>c0,buildProjectBudgetFinalizationGuidance:()=>Y5,buildProjectExecutionGuidance:()=>Ub,buildProjectExecutionProfile:()=>Bb,buildPromptMemoryContext:()=>xae,buildSecuredProcessSpec:()=>Aa,buildSoundSystemPrompt:()=>Al,buildSystemPrompt:()=>tT,buildToolFailureGuardResult:()=>Xy,buildXenoArtifactReviewAnchor:()=>uS,buildXenoAutomationCapabilityUse:()=>kx,buildXenoRepositoryIndex:()=>gB,buildXenoRepositoryIndexWithEmbeddings:()=>Wre,buildXenoSecureExecutionContract:()=>Sx,cachedModelContextWindow:()=>FS,calculateCost:()=>Uw,canTransitionXenoArtifactState:()=>I0,canXenoRasterPreview:()=>Nh,canonicalPayload:()=>cl,canonicalizeArtifactJson:()=>Q,canonicalizeMcpResourceUri:()=>Rl,canonicalizeSecurityPath:()=>bn,canonicalizeToolName:()=>z,checkSandbox:()=>ZL,classifyProviderHttpError:()=>xy,cleanupReadImagePreviews:()=>hI,cleanupSessionRuntime:()=>Iae,clearMcpServerApproval:()=>cF,clearProjectAllowedTools:()=>q3,clearProjectLastSessionSummary:()=>z3,clearProjectMcpApproval:()=>OS,clearProjectMcpApprovals:()=>DS,clipXenoAnsi:()=>vX,coerceSubagentRole:()=>Ky,coerceSubagentTeamPreset:()=>rX,compileAgentProfile:()=>$C,compileJsonSchema:()=>fg,compileToolInputSchema:()=>oc,compileXenoRecipe:()=>ose,compileXenoSkillActivation:()=>Nte,configureImageGeneration:()=>F1,configureSearch:()=>th,configureSearchPermissionProfile:()=>nh,configureXenoAnsi:()=>gX,containmentApprovalSigningPayload:()=>zX,containmentCertificationSigningPayload:()=>YC,copyTextToClipboard:()=>WU,create3DTools:()=>hv,createAgentDefinitionFile:()=>SH,createAgentDefinitionPromptSection:()=>bH,createAgentRunId:()=>B5,createAppServerV2HttpTransport:()=>_se,createArchitectTools:()=>gv,createArtifactCompareTool:()=>Cu,createAskUserTool:()=>du,createAudioTools:()=>Ow,createAuditBackedPermissionEngine:()=>wae,createBashTool:()=>au,createBenchBashMiddleware:()=>qb,createCliAutomationAuditSink:()=>i8,createCliGovernedAutomationRuntime:()=>o8,createCommandBackedProtectedStateStore:()=>f5,createDefaultToolRegistry:()=>Tn,createDelegatedXenoAgent:()=>Sw,createDirectProvider:()=>_y,createDirectShellMessage:()=>Fd,createDispatchAgentTool:()=>cu,createDocsTools:()=>wv,createEd25519Signer:()=>EX,createEditTool:()=>Yd,createElfAnalyzeTool:()=>ku,createEngineTools:()=>yv,createGcodeAnalyzeTool:()=>Tu,createGenerateImageTool:()=>pu,createGlobTool:()=>Qd,createGovernanceExtensions:()=>Fre,createGrepTool:()=>Zd,createHtmlSanitizerAuditTool:()=>Ru,createImageTools:()=>_w,createLsTool:()=>$u,createLspDefinitionTool:()=>Ou,createLspDiagnosticsTool:()=>Lu,createLspHoverTool:()=>Du,createLspReferencesTool:()=>Nu,createMcpAppCapabilities:()=>MP,createMcpAppExtensionCapabilities:()=>vF,createMcpPkcePair:()=>IP,createMcpPromptRegisteredTool:()=>jP,createMcpRegisteredTool:()=>FP,createMcpResourceRegisteredTool:()=>HP,createMemoryProtectedStateStore:()=>vte,createMemoryReadTool:()=>Xu,createMemoryWriteTool:()=>Bu,createNotebookEditTool:()=>Fu,createNotebookReadTool:()=>Uu,createNotesTools:()=>Sv,createOllamaNativeProvider:()=>My,createOsProtectedStateStore:()=>g5,createProtectedStateEnvelopeCipher:()=>xte,createQuotaGovernedProvider:()=>BZ,createReadImageTool:()=>Au,createReadTool:()=>Jd,createSheetsTools:()=>vv,createSlidesTools:()=>xv,createSpeechRecognizer:()=>oF,createSqliteAnalyzeTool:()=>Nc,createTaskInputTool:()=>qu,createTaskListTools:()=>ly,createTaskOutputTool:()=>ju,createTaskStopTool:()=>Hu,createThinkTool:()=>lu,createToolAlias:()=>io,createToolRuntimeContext:()=>Wd,createUnavailableProtectedStateStore:()=>dl,createVideoTools:()=>Mw,createWebContextFetchTool:()=>ch,createWebContextRequestFactory:()=>J1,createWebContextSearchTool:()=>ah,createWebSearchTool:()=>B1,createWindowsDpapiProtectedCipher:()=>wte,createWindowsDpapiProtectedFileStore:()=>m5,createWorkflowTools:()=>bv,createWriteTool:()=>Kd,createXenoAgent:()=>Nr,createXenoAutomationConformanceReport:()=>X0,createXenoGovernedAutomationTools:()=>Zx,createXenoHostAutomationAuditSink:()=>i8,createXenoHostGovernedAutomationRuntime:()=>o8,createXenoHostedControlCommand:()=>tU,createXenoHostedEnvironmentManifest:()=>iie,createXenoHostedEvent:()=>sie,createXenoHostedExecutionBoundaryReceipt:()=>YB,createXenoHostedRunResult:()=>nU,createXenoRasterPreview:()=>Dh,createXenoSecureShare:()=>Moe,createXenoSessionHandoff:()=>Noe,createXenoShareSigningIdentity:()=>_oe,createXenoSkillTool:()=>Ote,createXenoSourceResearchExcerpt:()=>qie,createXenoSourceResearchReport:()=>Hie,currentExecutionAdapterStatus:()=>uq,decodeJwtPayload:()=>$f,decodeXenoBmp:()=>Lh,decodeXenoGif:()=>lh,decodeXenoGifAnimation:()=>o2,decodeXenoJpeg:()=>hh,decodeXenoNetpbm:()=>$h,decodeXenoPng:()=>sI,decodeXenoSvg:()=>Y2,decodeXenoVp8:()=>wu,decodeXenoWebp:()=>Ch,defaultToolRuntimeContext:()=>j,defaultXenoReviewPack:()=>V8,deflateXenoZlib:()=>Va,deleteSession:()=>y4,denyMcpServer:()=>zw,deriveHostedIdempotencyKey:()=>lie,describeXenoAutomationOperation:()=>hn,detectLanguage:()=>Rv,detectPluginRepositorySignals:()=>jF,detectRepositoryDocumentKind:()=>hB,detectRepositoryLanguage:()=>xR,detectXenoSpecDrift:()=>B8,deterministicReduce:()=>aT,digestMessages:()=>Dk,directProviderConfigFromConnection:()=>Jce,discoverXenoSkills:()=>Ite,dispatchAgentTool:()=>M1,editTool:()=>SO,elfAnalyzeTool:()=>ED,emitXenoTelemetry:()=>Jf,encodeXenoPngRgb:()=>Cc,enforceShellCommandPolicy:()=>yy,enforceToolPolicy:()=>Zu,ensureConfigDir:()=>Ua,ensureDurableMessageIds:()=>Ny,ensureProjectStateDir:()=>nM,estimateFullRequestBudget:()=>Lk,evaluateContainmentUiRestrictions:()=>t5,evaluatePermissionProfileNetworkUrl:()=>br,evaluateXenoCapabilityEligibility:()=>e_,executeXenoCoordinationAction:()=>nie,extractJsonObject:()=>ob,extractToolPath:()=>_s,findXenoSkill:()=>GT,fingerprintXenoSecureExecutionContract:()=>dq,forgetRecentSession:()=>aA,forgetRecentSessionById:()=>Ja,formatBoundedShellOutput:()=>nr,formatCost:()=>zU,formatDirectShellContext:()=>Qa,formatJsonSchemaErrors:()=>gg,formatModelList:()=>c4,formatPromptContextBreakdown:()=>vae,gcodeAnalyzeTool:()=>CD,generateImageTool:()=>q1,generateSessionId:()=>no,getAgentHome:()=>M3,getAgentRunDir:()=>tne,getAgentRunStoreDir:()=>ene,getAvailableModels:()=>Ff,getBenchmarkComputeBudgetHintForCommand:()=>Dg,getBenchmarkForegroundTimeoutForCommand:()=>Ng,getBestExecutionSecurityStatus:()=>wx,getChatModels:()=>a4,getConfigDir:()=>Zr,getDefaultProviderRegistry:()=>zf,getExecutionSecurityCapabilityReport:()=>i0,getExecutionSecurityStatus:()=>Vr,getGlobIgnores:()=>OA,getGrepIgnores:()=>DA,getHighRiskPermissions:()=>OF,getImageGenerationConfig:()=>j1,getJwtExpiry:()=>Xf,getLinuxBubblewrapCapability:()=>Kl,getLogLevel:()=>MM,getManagedConfigPath:()=>eM,getMcpAppMetadata:()=>um,getMcpAppResourceUri:()=>Ml,getMcpApprovalDecision:()=>lF,getMcpAuthorizationServerMetadataUrls:()=>EP,getMcpPromptToolName:()=>XP,getMcpProtectedResourceMetadataUrls:()=>AP,getMcpResourceToolName:()=>BP,getMcpToolName:()=>$P,getModelName:()=>ja,getMxcContainmentProbe:()=>Go,getMxcNativeAssetDescriptor:()=>fx,getMxcWindowsHostPreparationDescriptor:()=>gx,getMxcWindowsHostPreparationHelperArchitecture:()=>hx,getPermissionProfile:()=>Af,getPersistentShellSession:()=>Yg,getPersistentShellSpawnSpec:()=>eE,getProcessContainmentStatus:()=>s0,getProjectAgentDefinitionDirs:()=>_C,getProjectAgentDefinitionsDir:()=>MC,getProjectLastSessionSummary:()=>V3,getProjectMcpApproval:()=>Nf,getProjectStatePath:()=>Mf,getReadImagePreviewCapability:()=>jN,getRecentSessionsIndexPath:()=>Yo,getSubagentTeamPresetDefinition:()=>oX,getToolRiskLevel:()=>n$,getUserAgentDefinitionsDir:()=>Fv,gitBranchTool:()=>cy,gitCommitTool:()=>ay,gitDiffTool:()=>iy,gitLogTool:()=>sy,gitStatusTool:()=>oy,globTool:()=>CO,grepTool:()=>LO,gzipXeno:()=>za,hasProjectOnboardingCompleted:()=>U3,hasXenoTelemetrySubscribers:()=>C4,hashContainmentConformanceReport:()=>hte,hashPluginManifest:()=>lv,hashPluginTree:()=>GP,hookResultStatus:()=>Ln,hostedEnvironmentIdentity:()=>cie,htmlSanitizerAuditTool:()=>ND,importLegacyXenoSkill:()=>kte,inflateXenoZlib:()=>Bd,initializeSessionRuntime:()=>Sae,inspectCliAutomationStatus:()=>s8,inspectRuntimeManifests:()=>yae,inspectSecurityPath:()=>jo,inspectSystemPrompt:()=>bae,inspectXenoHostAutomationStatus:()=>s8,inspectXenoRepositoryFreshness:()=>Yre,inspectXenoRepositorySymbol:()=>Kre,installSignalHandlers:()=>o6,invalidateAllObservedFiles:()=>Zg,invokeXenoSkill:()=>_5,isChatModel:()=>jS,isDangerousCommand:()=>Og,isDirectShellMessage:()=>jd,isExpiredJwt:()=>Q3,isExplicitResearchPrompt:()=>Hb,isJwt:()=>Lf,isLocalModel:()=>Md,isMcpAppResourceUri:()=>OP,isMcpOAuthTokenExpired:()=>mF,isMcpToolVisibleToApp:()=>Qw,isMcpToolVisibleToModel:()=>Yw,isNotBeforeJwt:()=>sM,isPathWithinAllowed:()=>qn,isQuotaControlError:()=>tl,isScreenCaptureAvailable:()=>UU,isSensitiveEnvironmentKey:()=>Sa,isSimpleInformationalPrompt:()=>Cp,isSpeechRecognitionAvailable:()=>iF,isSupportedMcpProtocolVersion:()=>om,isToolAllowedByXenoSkillActivation:()=>Dte,isUncOrDevicePath:()=>Jl,isValidAgentDefinitionName:()=>jv,isValidModel:()=>i4,isValidSessionId:()=>VS,isWorkspaceTrusted:()=>X3,isXenoAutomationOperation:()=>Om,legacyAgentArtifactToXenoArtifact:()=>r3,listBuiltInAgentProfiles:()=>_H,listPermissionProfiles:()=>V_,listProjectAllowedTools:()=>j3,listProjectMcpApprovals:()=>NS,listSessions:()=>h4,loadConfig:()=>$S,loadConfiguredMcpServers:()=>qw,loadMcpConfigFile:()=>rm,loadProjectConfig:()=>Od,loadProjectState:()=>xn,loadRecentSessionsIndex:()=>oo,loadSession:()=>g4,loadUserConfig:()=>rM,loadXenoSkill:()=>zT,lookupRecentSession:()=>Ud,lsTool:()=>uL,lspDefinitionTool:()=>sL,lspDiagnosticsTool:()=>iL,lspHoverTool:()=>aL,lspReferencesTool:()=>cL,matchPermissionRule:()=>BX,matchesMcpRegistryEntryPolicy:()=>kF,materializeXenoAutomationEvidence:()=>Qm,mcpInputSchemaToToolSchema:()=>UP,memoryReadTool:()=>gL,memoryWriteTool:()=>hL,mergeConfigs:()=>p4,mxcWarningsRequireWindowsHostPreparation:()=>mx,normalizeDirectShellResultRecord:()=>Ya,normalizeHookDecision:()=>Id,normalizeMcpAppVisibility:()=>_l,normalizePermissionProfileName:()=>Td,normalizeQuotaScope:()=>Cr,normalizeRepositoryRelativePath:()=>E_,normalizeSourceText:()=>bw,normalizeSubagentBranchPolicy:()=>Yy,normalizeWorkingDirectory:()=>Wa,normalizeXenoHostedControlAcknowledgement:()=>Oie,notebookEditTool:()=>SL,notebookReadTool:()=>xL,openSqliteAutomationExecutionJournal:()=>Jq,openSqliteCapabilityLeasePersistence:()=>Zee,parseContainmentReviewerTrustStore:()=>GX,parseMcpWwwAuthenticate:()=>lm,parsePermissionRule:()=>ET,parseRetryAfter:()=>vy,parseSessionId:()=>qf,parseShellPathReferences:()=>hk,parseSubagentRemoteMcpPolicy:()=>gee,parseSubagentRoleList:()=>pee,parseUnifiedDiff:()=>cS,parseXenoAnsi:()=>il,parseXenoRecipeDefinition:()=>rse,pending:()=>Jr,persistXenoAutomationEvidence:()=>Pa,planXenoControlRoomAction:()=>sne,pluginInfoRelevanceCandidate:()=>qF,pluginListingRelevanceCandidate:()=>VF,pluginSignaturePayload:()=>WP,preflightLocalModel:()=>o4,prepareMxcWindowsHost:()=>t0,probeXenoProvider:()=>Gce,projectToolDefinitionsForProvider:()=>Ns,projectToolSchemaForProvider:()=>Ek,projectXenoControlRoom:()=>ine,providerCapabilityError:()=>Ds,providerProtocolError:()=>ce,publicKeyFingerprint:()=>kR,publishPlugin:()=>KF,quotaAncestors:()=>mp,quotaInteger:()=>je,quotaScopeKey:()=>_r,quotaText:()=>Rn,rankPluginRelevance:()=>HF,readCliAutomationEnvironment:()=>oS,readImageTool:()=>HN,readManifestFromDisk:()=>$i,readPluginDetachedSignature:()=>JP,readPluginSupplyChainLockfile:()=>uv,readSessionFormatVersion:()=>Cw,readTool:()=>bO,readXenoApiKey:()=>jU,readXenoHostAutomationEnvironment:()=>oS,recordRecentSession:()=>Qo,recordXenoCounter:()=>re,recordXenoEvent:()=>_4,recordXenoHistogram:()=>Le,recoverSessionMessages:()=>Kp,redactXenoShareValue:()=>ER,registerShutdownCleanup:()=>fo,registry:()=>uy,removeMcpServerConfig:()=>aF,removeProjectAllowedTool:()=>H3,renderAgentDefinition:()=>xH,renderAgentDefinitions:()=>vH,renderAuditReplayMarkdown:()=>xC,renderAuditReplayReport:()=>SC,renderAuditTraceMarkdown:()=>vC,renderAuditTraceReport:()=>wC,renderAuditTraceSummaries:()=>bC,renderCliAutomationStatus:()=>E8,renderCodingBenchmarkMarkdown:()=>aee,renderCodingBenchmarkReport:()=>see,renderContinuationIncompleteStatus:()=>e6,renderLspDefinitionReport:()=>tL,renderLspDiagnosticsReport:()=>eL,renderLspDoctorReport:()=>oL,renderLspHoverReport:()=>rL,renderLspReferencesReport:()=>nL,renderToolContinuationInput:()=>ZG,renderXenoHostAutomationStatus:()=>E8,renderXenoSkillCatalog:()=>Tte,repairInterruptedToolCalls:()=>vl,repairToolExchangeHistory:()=>Bk,requestBackground:()=>T1,requiresSecuredProcessLaunch:()=>zr,resetAllPersistentShellSessions:()=>A1,resetBashBenchmarkGuards:()=>WO,resetImageGenerationConfig:()=>H1,resetMcpServerApprovals:()=>dF,resetMxcContainmentProbe:()=>yx,resetPersistentShellSession:()=>Qg,resetXenoAnsiPolicy:()=>hX,resetXenoTelemetryCardinalityForTests:()=>N4,resizeXenoRaster:()=>aI,resolveAgentDefinition:()=>gH,resolveAgentProfile:()=>OH,resolveAgentToolPolicy:()=>Pm,resolveBuiltInAgentProfile:()=>BC,resolveCommandOnPath:()=>ks,resolveContainmentConformanceTemporaryRoot:()=>e5,resolveDelegatedExecutionMode:()=>oT,resolveExecutionSecurityLevel:()=>td,resolveExecutionTrustMode:()=>qm,resolveInteractiveTurnMaxIterations:()=>dB,resolveLocalRuntimeUrl:()=>is,resolveModelContextTokens:()=>Vf,resolvePermissionProfile:()=>z_,resolveShellInvocation:()=>m1,resolveSubagentRemoteMcpAccess:()=>yee,resolveSubagentWorkflowAnswer:()=>fT,resolveXenoAutomationEvidencePolicy:()=>Tx,resolveXenoSdkApiKey:()=>Z3,runAgentHook:()=>_d,runCommandHook:()=>kd,runContainmentConformanceSuite:()=>ote,runDelegatedXenoTurn:()=>fae,runDelegationPlan:()=>iT,runDurableAutomation:()=>Lx,runHookDefinition:()=>kf,runHooks:()=>_f,runHttpHook:()=>Rd,runPromptHook:()=>Cd,runSubagentWorkflow:()=>gT,runXenoThread:()=>Ew,runXenoThreadStreamed:()=>Sse,sanitizeEnvironment:()=>qo,sanitizeXenoTelemetryAttributes:()=>fM,saveConfig:()=>G3,saveMcpConfigFile:()=>Hw,saveProjectState:()=>Of,saveSession:()=>f4,scaffoldPlugin:()=>WF,scanAgentDefinitions:()=>Hv,scoreMemories:()=>vZ,scorePluginRelevance:()=>KP,searchXenoRepositoryIndex:()=>Jre,selectXenoProviderRoute:()=>Wce,serializeXenoRecipe:()=>ise,setLogLevel:()=>_M,setProjectLastSessionSummary:()=>LS,setProjectMcpApproval:()=>Df,setProjectOnboardingCompleted:()=>F3,setWorkspaceTrusted:()=>B3,setupAIHandlers:()=>FU,sha256ArtifactBytes:()=>Me,sha256ArtifactJson:()=>ze,shouldEnableExecutionGovernance:()=>Pp,shouldSourceShellProfile:()=>su,shouldUseIsolatedStdinForCommand:()=>eu,signSharePayload:()=>AB,sqliteAnalyzeTool:()=>RI,stripXenoAnsi:()=>bT,subscribeXenoTelemetry:()=>WS,summarizeAuditInputRecord:()=>ZU,summarizeAuditTraces:()=>Am,summarizeRuntimeInput:()=>hy,summarizeSubagentResults:()=>mT,summarizeXenoArtifactReview:()=>Ym,syncMcpToolsToRegistry:()=>PF,synthesizeSkill:()=>ib,taskInputTool:()=>CL,taskOutputTool:()=>kL,taskStopTool:()=>TL,testPlugin:()=>JF,thinkTool:()=>O1,toAgentDefinitionMetadata:()=>wH,toLLMProvider:()=>rT,toolEvidenceToXenoArtifact:()=>i3,toolOperationManager:()=>G,toolRiskLevel:()=>ec,turnDiffSummaryToXenoArtifact:()=>a3,unifiedDiffToXenoArtifact:()=>lS,unifiedExecManager:()=>ru,updateProjectState:()=>wr,upsertMcpServerConfig:()=>sF,validateAgentDefinition:()=>OC,validateCapabilityLeaseRequest:()=>Yx,validateCapabilityMutationReceipt:()=>kT,validateDelegationPlan:()=>Z$,validateDirectEndpoint:()=>Ls,validateExecutionSecurityPolicy:()=>Gi,validateJsonSchema:()=>YM,validateManifest:()=>ov,validateMcpAppResource:()=>NP,validateToolContinuationGoal:()=>mc,validateXenoArtifact:()=>E0,validateXenoArtifactReviewEvent:()=>Km,validateXenoControlRoomSnapshot:()=>q5,validateXenoEvidenceGraph:()=>g_,validateXenoRepositoryIndex:()=>zs,validateXenoSdkApiKey:()=>e4,validateXenoSecureExecutionContract:()=>f0,validateXenoSpecDocument:()=>k_,verifyContainmentCertification:()=>cx,verifyContainmentCertificationApproval:()=>tte,verifyPluginSupplyChain:()=>dv,verifySignature:()=>xT,verifySoulRecord:()=>IX,verifyXenoHostedControlCommand:()=>Mie,verifyXenoHostedEnvironmentManifest:()=>cw,verifyXenoHostedEventChain:()=>aie,verifyXenoHostedExecutionAdapterCertification:()=>xie,verifyXenoHostedExecutionJob:()=>QB,verifyXenoHostedRunResult:()=>Nie,verifyXenoHostedWebhook:()=>bie,verifyXenoSecureShare:()=>Ooe,verifyXenoSessionHandoff:()=>Doe,webFetchTool:()=>ih,webSearchTool:()=>rh,windowsDpapiProtect:()=>FT,windowsDpapiUnprotect:()=>jT,withXenoTelemetrySpan:()=>M4,wrapXenoAnsi:()=>xX,writePluginSupplyChainLockfile:()=>pv,writeTool:()=>vO,xenoAnsi:()=>ol,xenoAnsiVisibleWidth:()=>wT,xenoArtifactToDiffDocument:()=>dS,xenoArtifactToLegacyAgentArtifact:()=>o3,xenoArtifactToOracleReport:()=>Bie,xenoArtifactToReviewReport:()=>G8,xenoArtifactToSourceResearchReport:()=>zie,xenoArtifactToSpecDocument:()=>fS,xenoArtifactToSpecExecution:()=>T_,xenoArtifactToToolEvidence:()=>s3,xenoArtifactToTurnDiffSummary:()=>c3,xenoHostedExecutionAdapterSigningPayload:()=>vie,xenoOracleReportToArtifact:()=>Xie,xenoRecipeFingerprint:()=>yU,xenoReviewReportToArtifact:()=>z8,xenoReviewReportToGitHubComments:()=>W8,xenoSourceResearchReportToArtifact:()=>Vie,xenoSpecArtifactIds:()=>$a,xenoSpecExecutionToArtifact:()=>gS,xenoSpecToArtifactBundle:()=>mS});module.exports=Xj(mle);Fi();var pr="0.9.31";var pC=require("node:crypto");zt();yt();var ha=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=(0,pC.randomUUID)(),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 ga(this.filePath,JSON.stringify(r))}),await this.writeQueue,n}async read(e){let n=await ye(this.filePath);if(!n)return[];let r=Hi(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 xe(e,JSON.stringify(n,null,2)),n.length}async flush(){await this.writeQueue}};function Jj(t,e){return e.endedAt.localeCompare(t.endedAt)}function Lv(t,e){t.set(e,(t.get(e)??0)+1)}function Bv(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 mC(t){return t.filter(e=>e.tool_name||e.event_type.startsWith("tool_")).length}function fC(t){return t.filter(e=>e.event_type==="permission_decision").length}function gC(t){return t.filter(e=>e.status==="error"||e.event_type.endsWith("_failed")).length}function $v(t){return t.split(/[_\s-]+/).filter(e=>e.length>0).map(e=>e[0].toUpperCase()+e.slice(1)).join(" ")}function Xv(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 Kj(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 Yj(t){let e=$v(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=`${$v(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=Xv(t.metadata)}else t.event_type==="delegation_started"?(e="Delegation started",n=Xv(t.metadata)):t.tool_name?e=`${$v(t.event_type)}: ${t.tool_name}`:n||(n=Xv(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 Am(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:Bv(s,a),toolEvents:mC(i),permissionEvents:fC(i),errorEvents:gC(i),lastEventType:i[i.length-1]?.event_type??"unknown"})}return n.sort(Jj)}function hC(t,e){let n=Am(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(Lv(i,u.event_type),Lv(a,u.actor),Lv(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:Bv(l,d),toolEvents:mC(o),permissionEvents:fC(o),deniedPermissions:o.filter(u=>u.event_type==="permission_decision"&&u.decision==="deny").length,errorEvents:gC(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:Kj(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 yC(t,e){let n=Am(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:Bv(i,s),steps:o.map(Yj)}}function bC(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??tT({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(()=>(Aw(),bU)),{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??GR,4096)),maxIterations:Math.max(3,Math.min(t.maxIterations??WR,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??Tn({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 yi({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??GR,maxIterations:t.maxIterations??WR,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 wU,GR,WR,bl=T(()=>{"use strict";wU=require("node:process");Ko();eo();Hy();nT();Zy();zd();yb();fi();GR=8192,WR=50});var mle={};sC(mle,{AGENT_DAEMON_PROTOCOL_VERSION:()=>pl,AGENT_EFFORT_LEVELS:()=>Ov,AGENT_PERMISSION_MODES:()=>Nv,AGENT_PROFILE_EXTERNAL_ACTIONS:()=>Gl,ARCHITECT_CAPABILITIES:()=>tj,ARCHITECT_TOOL_NAMES:()=>ej,AgentDaemonClient:()=>eR,AgentDaemonServer:()=>ZT,AgentDebugger:()=>Cv,AgentDefinitionLoader:()=>Rm,AgentDefinitionResolver:()=>Uv,AgentEvaluator:()=>_v,AgentEventStore:()=>Ap,AgentHookRunner:()=>If,AgentInterruptedError:()=>Bn,AgentLoop:()=>yi,AgentProfileValidationError:()=>jr,AgentProtocol:()=>Bw,AgentRegistry:()=>Xw,AgentRunController:()=>QT,AgentRunError:()=>jy,AgentRunStore:()=>Ep,AppAgentFactory:()=>ym,AppContextInjector:()=>sa,AppContextManager:()=>Ni,AppServerProtocolError:()=>W,AppServerRemoteError:()=>Ri,AuditLogger:()=>ha,AutoCheckpointHandler:()=>qy,AutoMemory:()=>hA,AutoPermissionClassifier:()=>lb,BUILT_IN_XENO_PROVIDER_PRESETS:()=>Sj,BackgroundProcessManager:()=>ou,COMPAT_TOOL_ALIASES:()=>fA,CONFIG_VERSION:()=>PS,CheckpointManager:()=>dn,CliGovernedAutomationRuntime:()=>df,CodeValidator:()=>Pv,CommandHookRunner:()=>Pf,CompletionGuardRegistry:()=>el,ContainmentApprovalError:()=>pe,ContainmentCertificationError:()=>ue,ContextManager:()=>dp,ConversationStore:()=>jw,CrossAppRouter:()=>$w,CrossAppRouterError:()=>ra,DEFAULT_API_KEY:()=>Yn,DEFAULT_IMAGE_MODEL:()=>oh,DEFAULT_MEMORY_BUDGETS:()=>ZS,DEFAULT_MODEL:()=>os,DEFAULT_PROMPT_SECTIONS_TOKEN_BUDGET:()=>pp,DEFAULT_PROTECTED_STATE_KEY_NAME:()=>p5,DEFAULT_PROTECTED_STATE_SERVICE:()=>u5,DEFAULT_SUBAGENT_BRANCH_POLICY:()=>Gy,DEFAULT_SUBAGENT_REMOTE_MCP_BY_ROLE:()=>Jy,DEFAULT_SUBAGENT_ROLES:()=>rl,DEFAULT_SUBAGENT_ROLE_PRECEDENCE:()=>Wy,DEFAULT_SUBAGENT_TEAM_PRESET:()=>Xs,DIRECT_SHELL_CONTEXT_WARNING:()=>ig,DOCS_CAPABILITIES:()=>lj,DOCS_TOOL_NAMES:()=>cj,DualLLMProvider:()=>El,DurableXenoCapabilityLeaseRegistry:()=>IT,DurableXenoCoordinationStore:()=>Lp,ENGINE_CAPABILITIES:()=>ij,ENGINE_TOOL_NAMES:()=>oj,ElectronAgentBridge:()=>Lw,EpisodicStore:()=>sl,ExecutionGovernance:()=>fl,ExecutionSecurityError:()=>Vn,FALLBACK_MODELS:()=>cM,FileQuotaAuthority:()=>rC,FileXenoArtifactRepository:()=>hd,FileXenoProviderConnectionStore:()=>tC,FileXenoShareRegistry:()=>TR,HIGH_RISK_PERMISSIONS:()=>zP,HookRunner:()=>Tf,HookRuntime:()=>Rf,HttpHookRunner:()=>Cf,IDENTITY_PATHS:()=>ko,IdentityLoader:()=>Bs,IdentityResolver:()=>Us,InMemoryXenoArtifactRepository:()=>Ra,InMemoryXenoCapabilityLeaseRegistry:()=>hr,InMemoryXenoTelemetryCollector:()=>GS,InteractiveChatTurnGovernance:()=>jb,InteractiveTurnGovernance:()=>Vs,JsonSchemaCompilationError:()=>ls,LlmClient:()=>Vc,LocalLLMProvider:()=>aa,LogLevel:()=>lA,MANIFEST_FILENAME:()=>mm,MAX_CONTAINMENT_APPROVAL_AGE_MS:()=>VX,MAX_CONTAINMENT_CERTIFICATION_BYTES:()=>ix,MAX_CONTAINMENT_CERTIFICATION_LIFETIME_MS:()=>KC,MAX_DIRECT_SHELL_OUTPUT_CHARS:()=>dA,MCPHttpTransportError:()=>Ke,MCPManager:()=>tv,MCPOAuthClient:()=>Kw,MCPServer:()=>nv,MCP_APPS_EXTENSION_ID:()=>oa,MCP_APP_MIME_TYPE:()=>dm,MCP_APP_RESOURCE_SCHEME:()=>wF,MCP_PROTOCOL_VERSION:()=>$r,MCP_SUPPORTED_PROTOCOL_VERSIONS:()=>Gw,MEMORY_FILES:()=>eA,MOTION_CAPABILITIES:()=>wj,MOTION_SYSTEM_PROMPT:()=>mP,MOTION_TOOL_NAMES:()=>bj,MemoryManager:()=>ao,MessageFlow:()=>Wc,ModelProviderRegistry:()=>Ld,MonitorManager:()=>oR,MonitorStopTool:()=>sR,MonitorTool:()=>iR,NOTES_CAPABILITIES:()=>gj,NOTES_TOOL_NAMES:()=>fj,OtelExporter:()=>cR,PIXEL_CAPABILITIES:()=>yj,PIXEL_SYSTEM_PROMPT:()=>pP,PIXEL_TOOL_NAMES:()=>hj,PROCESS_TREE_ADAPTERS:()=>Bj,PROJECT_STATE_VERSION:()=>Y_,PermissionEngine:()=>rn,PluginEventBus:()=>Ll,PluginHost:()=>Xl,PluginManager:()=>UF,PluginMarketplace:()=>mv,PluginSandbox:()=>Nl,PluginSettingsManager:()=>sv,PluginToolBuilder:()=>iv,ProfileManager:()=>qS,PromptHookRunner:()=>Ef,PromptSectionRegistry:()=>Zc,ProtectedFileWriteError:()=>Cn,ProviderError:()=>ge,QueryLifecycle:()=>Jc,QuotaAcknowledgementError:()=>Uy,QuotaError:()=>we,REQUIRED_CONTAINMENT_CONFORMANCE_CHECKS:()=>Ql,SDK_DEFAULT_MAX_ITERATIONS:()=>WR,SDK_DEFAULT_MAX_TOKENS:()=>GR,SDK_VERSION:()=>pr,SESSION_FORMAT_VERSION:()=>ql,SHEETS_CAPABILITIES:()=>uj,SHEETS_TOOL_NAMES:()=>dj,SLIDES_CAPABILITIES:()=>mj,SLIDES_TOOL_NAMES:()=>pj,SOUND_CAPABILITIES:()=>xj,SOUND_SYSTEM_PROMPT:()=>fP,SOUND_TOOL_NAMES:()=>vj,SSETransport:()=>Li,SUBAGENT_ROLE_ALIASES:()=>tX,SUBAGENT_TEAM_PRESETS:()=>nX,ScreenCapture:()=>Nw,SessionLock:()=>Oo,SessionLockManager:()=>Oo,SessionManager:()=>Oi,SessionRegistry:()=>en,SkillStore:()=>al,SoulEngine:()=>sb,SqliteAutomationExecutionJournal:()=>rf,SqliteCapabilityLeasePersistence:()=>db,StdioTransport:()=>Cl,StreamableHTTPTransport:()=>Pl,THREE_D_CAPABILITIES:()=>rj,THREE_D_TOOL_NAMES:()=>nj,TOOL_OPERATION_SCHEMA_VERSION:()=>tu,TaskListManager:()=>Ps,ToolFailureLoopGuard:()=>Yc,ToolMiddlewareRegistry:()=>Qc,ToolOperationManager:()=>Ug,ToolOrchestrator:()=>ep,ToolRegistry:()=>Cs,ToolSchemaProjectionError:()=>Et,TranscriptWriter:()=>Sn,TurnDiffTracker:()=>xk,TurnRestoreManager:()=>na,UNBOUNDED_OPERATION_CONTINUATION_LIMIT:()=>nu,UnifiedExecError:()=>Ar,UnifiedExecManager:()=>Fg,UsageAccumulator:()=>Pb,UsageLedger:()=>aR,VectorMemoryStore:()=>ei,WEB_CONTEXT_CONTRACT_VERSION:()=>hE,WEB_CONTEXT_TOOL_RESULT_SCHEMA:()=>sh,WORKFLOW_CAPABILITIES:()=>aj,WORKFLOW_TOOL_NAMES:()=>sj,WorkflowPlanner:()=>ml,WorkflowRuntime:()=>rR,WorkflowStore:()=>Rb,WorkspaceIndex:()=>Dw,XENO_AGENT_PROFILE_SCHEMA_VERSION:()=>Mm,XENO_API_BASE:()=>vr,XENO_APP_PROTOCOL_V2_METHODS:()=>JR,XENO_APP_PROTOCOL_VERSIONS:()=>Iw,XENO_ARTIFACT_ACTOR_KINDS:()=>_x,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION:()=>Jx,XENO_ARTIFACT_SCHEMA_VERSION:()=>Ae,XENO_ARTIFACT_SENSITIVITIES:()=>Cx,XENO_ARTIFACT_STATES:()=>Px,XENO_AUTOMATION_OPERATIONS:()=>va,XENO_AUTOMATION_PROTOCOL_VERSION:()=>Hr,XENO_BROWSER_CONTROL_PLANE_OPERATIONS:()=>gd,XENO_BUILTIN_ARTIFACT_KINDS:()=>Rx,XENO_CAPABILITY_LEASE_SCHEMA_VERSION:()=>Kx,XENO_CONTAINMENT_APPROVAL_SCHEMA:()=>ub,XENO_CONTAINMENT_CERTIFICATION_SCHEMA:()=>Dm,XENO_CONTAINMENT_CONFORMANCE_SCHEMA:()=>ZX,XENO_CONTAINMENT_REVIEWER_TRUST_STORE_SCHEMA:()=>pb,XENO_CONTROL_ROOM_SCHEMA_VERSION:()=>_b,XENO_COORDINATION_BUDGET_SESSION_SCHEMA_VERSION:()=>Np,XENO_COORDINATION_MANAGED_SESSION_SCHEMA_VERSION:()=>rw,XENO_COORDINATION_SCHEMA_VERSION:()=>Co,XENO_COORDINATION_TURN_SESSION_SCHEMA_VERSION:()=>Dp,XENO_DEFLATE_CODEC_NAME:()=>yM,XENO_DEFLATE_CODEC_VERSION:()=>bM,XENO_EVIDENCE_EDGE_TYPES:()=>ad,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION:()=>id,XENO_EVIDENCE_NODE_TYPES:()=>sd,XENO_GIF_ANIMATION_POLICY:()=>n2,XENO_GIF_CODEC_NAME:()=>e2,XENO_GIF_CODEC_VERSION:()=>t2,XENO_HANDOFF_SCHEMA_VERSION:()=>Zb,XENO_HOSTED_CONTROL_SCHEMA_VERSION:()=>LR,XENO_HOSTED_ENVIRONMENT_SCHEMA_VERSION:()=>Xp,XENO_HOSTED_EVENT_SCHEMA_VERSION:()=>sw,XENO_HOSTED_EXECUTION_ADAPTER_CERTIFICATION_SCHEMA:()=>Up,XENO_HOSTED_EXECUTION_ADAPTER_MAX_CERTIFICATE_LIFETIME_MS:()=>VB,XENO_HOSTED_EXECUTION_ADAPTER_PROTOCOL_VERSION:()=>_R,XENO_HOSTED_EXECUTION_PROTOCOL_VERSION:()=>JB,XENO_HOSTED_EXECUTION_TOOL_NAMES:()=>KB,XENO_HOSTED_RESULT_SCHEMA_VERSION:()=>$R,XENO_HOSTED_RUN_SCHEMA_VERSION:()=>rie,XENO_HOSTED_TRIGGER_SCHEMA_VERSION:()=>oie,XENO_JPEG_CODEC_NAME:()=>u2,XENO_JPEG_CODEC_VERSION:()=>p2,XENO_MXC_ADAPTER_NAME:()=>Um,XENO_MXC_POLICY_VERSION:()=>px,XENO_MXC_VERSION:()=>Vo,XENO_ORACLE_REPORT_SCHEMA_VERSION:()=>HR,XENO_PLUGIN_LOCK_FILENAME:()=>fm,XENO_PLUGIN_LOCK_SCHEMA_VERSION:()=>$l,XENO_PLUGIN_SIGNATURE_FILENAME:()=>ia,XENO_PLUGIN_SIGNATURE_SCHEMA_VERSION:()=>cv,XENO_PROVIDER_CATALOG_SCHEMA_VERSION:()=>QP,XENO_PROVIDER_CONNECTION_STORE_SCHEMA_VERSION:()=>Ev,XENO_RASTER_CODEC_NAME:()=>di,XENO_RASTER_CODEC_VERSION:()=>Oh,XENO_RASTER_PREVIEW_FORMATS:()=>oI,XENO_RECIPE_SCHEMA_VERSION:()=>hU,XENO_REPOSITORY_INDEX_SCHEMA_VERSION:()=>Vb,XENO_REVIEW_DIMENSIONS:()=>__,XENO_REVIEW_EVIDENCE_KINDS:()=>M_,XENO_REVIEW_REPORT_SCHEMA_VERSION:()=>bS,XENO_RT_DEFAULT_URL:()=>Uf,XENO_SECURE_EXECUTION_CONTRACT_SCHEMA_VERSION:()=>xx,XENO_SHARE_REGISTRY_SCHEMA_VERSION:()=>Op,XENO_SHARE_SCHEMA_VERSION:()=>Qb,XENO_SKILL_SCHEMA_VERSION:()=>qs,XENO_SOURCE_RESEARCH_SCHEMA_VERSION:()=>zR,XENO_SPEC_EXECUTION_SCHEMA_VERSION:()=>xd,XENO_SPEC_SCHEMA_VERSION:()=>Xa,XENO_SVG_RENDERER_NAME:()=>L2,XENO_SVG_RENDERER_VERSION:()=>$2,XENO_TELEMETRY_SCHEMA_VERSION:()=>mM,XENO_VP8_CODEC_NAME:()=>aN,XENO_VP8_CODEC_VERSION:()=>cN,XENO_WEBP_ANIMATION_POLICY:()=>hN,XENO_WEBP_CODEC_NAME:()=>fN,XENO_WEBP_CODEC_VERSION:()=>gN,XenoAppServer:()=>Rw,XenoAppServerV2Client:()=>rP,XenoArtifactRepositoryError:()=>F,XenoArtifactReviewService:()=>La,XenoArtifactStateTransitionError:()=>Jm,XenoArtifactValidationError:()=>Ki,XenoAuthError:()=>Fa,XenoAutomationError:()=>L,XenoBrowserControlPlaneAdapter:()=>Oa,XenoCapabilityLeaseError:()=>Re,XenoControlRoomValidationError:()=>He,XenoCoordinationError:()=>_,XenoDiffParseError:()=>Dt,XenoEvidenceGraphBuilder:()=>sS,XenoEvidenceGraphValidationError:()=>mf,XenoExecutionLeaseSession:()=>CR,XenoGovernedAutomationExecutor:()=>fd,XenoHostGovernedAutomationRuntime:()=>df,XenoLoopbackAutomationAdapter:()=>Fx,XenoMultiAgentReviewCoordinator:()=>yS,XenoOracleCoordinator:()=>UR,XenoOracleValidationError:()=>Nn,XenoProviderCatalog:()=>Ul,XenoRecipeValidationError:()=>Rt,XenoRepositoryIndexFileStore:()=>SR,XenoReviewValidationError:()=>vt,XenoRuntimeEventBus:()=>gi,XenoSecureExecutionContractError:()=>ot,XenoSourceResearchValidationError:()=>ki,XenoSpecLifecycleService:()=>pS,XenoSpecValidationError:()=>wt,XenoTraceGraphRecorder:()=>Uc,acquireControlPlaneLock:()=>Gn,activateSessionRuntime:()=>Aae,addProjectAllowedDirectory:()=>MS,addProjectAllowedTool:()=>_S,agentDefinitionFromProfile:()=>MH,agentProfileFromDefinition:()=>UC,appendBoundedShellOutput:()=>Jg,appendGuidanceToResult:()=>zk,approveMcpServer:()=>Vw,areSignalHandlersInstalled:()=>i6,artifactCompareTool:()=>zD,askUserTool:()=>N1,assertDirectEndpointResolution:()=>Ay,assertPersistedXenoCapabilityLease:()=>Wn,assertRequiredXenoAutomationEvidence:()=>md,assertSupportedMcpProtocolVersion:()=>Ww,assertUsableXenoApiKey:()=>US,assertValidMcpAppResource:()=>Zw,assertValidXenoArtifact:()=>it,assertValidXenoAutomationAdapterManifest:()=>od,assertValidXenoAutomationRequest:()=>Ix,assertValidXenoEvidenceGraph:()=>Da,assertValidXenoHostedExecutionJob:()=>Eie,assertValidXenoOracleReport:()=>yw,assertValidXenoRecipeDefinition:()=>zp,assertValidXenoReviewPack:()=>wS,assertValidXenoReviewReport:()=>Ad,assertValidXenoReviewTarget:()=>vS,assertValidXenoSecureExecutionContract:()=>Vm,assertValidXenoSourceResearchReport:()=>vw,assertValidXenoSpecDocument:()=>wf,assertValidXenoSpecExecution:()=>hS,assertXenoArtifactStateTransition:()=>ud,assertXenoAutomationAdapterConformant:()=>Kq,assertXenoAutomationAuthority:()=>Wm,auditRiskLevelForTool:()=>QU,authorizeShellExecution:()=>Xg,backgroundProcessManager:()=>ae,bashTool:()=>R1,benchmarkCodingTools:()=>iee,bridgeXenoTelemetryToOpenTelemetry:()=>O4,buildAtomicMessageGroups:()=>$k,buildAuditReplayReport:()=>yC,buildAuditTraceReport:()=>hC,buildContainedProcessSpec:()=>l0,buildContractLedgerGuidance:()=>$b,buildDefaultSubagentTasks:()=>Aee,buildDelegatedRoleSystemPrompt:()=>pT,buildHookEnvironment:()=>IS,buildLinuxBubblewrapProcessSpec:()=>Nm,buildLspDefinitionReport:()=>VI,buildLspDiagnosticsReport:()=>qI,buildLspDoctorReport:()=>YD,buildLspHoverReport:()=>GI,buildLspReferencesReport:()=>zI,buildMotionSystemPrompt:()=>Sl,buildPixelSystemPrompt:()=>xl,buildProcessHardenedProcessSpec:()=>c0,buildProjectBudgetFinalizationGuidance:()=>Y5,buildProjectExecutionGuidance:()=>Ub,buildProjectExecutionProfile:()=>Bb,buildPromptMemoryContext:()=>xae,buildSecuredProcessSpec:()=>Aa,buildSoundSystemPrompt:()=>Al,buildSystemPrompt:()=>tT,buildToolFailureGuardResult:()=>Xy,buildXenoArtifactReviewAnchor:()=>uS,buildXenoAutomationCapabilityUse:()=>kx,buildXenoRepositoryIndex:()=>gB,buildXenoRepositoryIndexWithEmbeddings:()=>Wre,buildXenoSecureExecutionContract:()=>Sx,cachedModelContextWindow:()=>FS,calculateCost:()=>Uw,canTransitionXenoArtifactState:()=>I0,canXenoRasterPreview:()=>Nh,canonicalPayload:()=>cl,canonicalizeArtifactJson:()=>Q,canonicalizeMcpResourceUri:()=>Rl,canonicalizeSecurityPath:()=>bn,canonicalizeToolName:()=>z,checkSandbox:()=>ZL,classifyProviderHttpError:()=>xy,cleanupReadImagePreviews:()=>hI,cleanupSessionRuntime:()=>Iae,clearMcpServerApproval:()=>cF,clearProjectAllowedTools:()=>q3,clearProjectLastSessionSummary:()=>z3,clearProjectMcpApproval:()=>OS,clearProjectMcpApprovals:()=>DS,clipXenoAnsi:()=>vX,coerceSubagentRole:()=>Ky,coerceSubagentTeamPreset:()=>rX,compileAgentProfile:()=>$C,compileJsonSchema:()=>fg,compileToolInputSchema:()=>oc,compileXenoRecipe:()=>ose,compileXenoSkillActivation:()=>Nte,configureImageGeneration:()=>F1,configureSearch:()=>th,configureSearchPermissionProfile:()=>nh,configureXenoAnsi:()=>gX,containmentApprovalSigningPayload:()=>zX,containmentCertificationSigningPayload:()=>YC,copyTextToClipboard:()=>WU,create3DTools:()=>hv,createAgentDefinitionFile:()=>SH,createAgentDefinitionPromptSection:()=>bH,createAgentRunId:()=>B5,createAppServerV2HttpTransport:()=>_se,createArchitectTools:()=>gv,createArtifactCompareTool:()=>Cu,createAskUserTool:()=>du,createAudioTools:()=>Ow,createAuditBackedPermissionEngine:()=>wae,createBashTool:()=>au,createBenchBashMiddleware:()=>qb,createCliAutomationAuditSink:()=>i8,createCliGovernedAutomationRuntime:()=>o8,createCommandBackedProtectedStateStore:()=>f5,createDefaultToolRegistry:()=>Tn,createDelegatedXenoAgent:()=>Sw,createDirectProvider:()=>_y,createDirectShellMessage:()=>Fd,createDispatchAgentTool:()=>cu,createDocsTools:()=>wv,createEd25519Signer:()=>EX,createEditTool:()=>Yd,createElfAnalyzeTool:()=>ku,createEngineTools:()=>yv,createGcodeAnalyzeTool:()=>Tu,createGenerateImageTool:()=>pu,createGlobTool:()=>Qd,createGovernanceExtensions:()=>Fre,createGrepTool:()=>Zd,createHtmlSanitizerAuditTool:()=>Ru,createImageTools:()=>_w,createLsTool:()=>$u,createLspDefinitionTool:()=>Ou,createLspDiagnosticsTool:()=>Lu,createLspHoverTool:()=>Du,createLspReferencesTool:()=>Nu,createMcpAppCapabilities:()=>MP,createMcpAppExtensionCapabilities:()=>vF,createMcpPkcePair:()=>IP,createMcpPromptRegisteredTool:()=>jP,createMcpRegisteredTool:()=>FP,createMcpResourceRegisteredTool:()=>HP,createMemoryProtectedStateStore:()=>vte,createMemoryReadTool:()=>Xu,createMemoryWriteTool:()=>Bu,createNotebookEditTool:()=>Fu,createNotebookReadTool:()=>Uu,createNotesTools:()=>Sv,createOllamaNativeProvider:()=>My,createOsProtectedStateStore:()=>g5,createProtectedStateEnvelopeCipher:()=>xte,createQuotaGovernedProvider:()=>BZ,createReadImageTool:()=>Au,createReadTool:()=>Jd,createSheetsTools:()=>vv,createSlidesTools:()=>xv,createSpeechRecognizer:()=>oF,createSqliteAnalyzeTool:()=>Nc,createTaskInputTool:()=>qu,createTaskListTools:()=>ly,createTaskOutputTool:()=>ju,createTaskStopTool:()=>Hu,createThinkTool:()=>lu,createToolAlias:()=>io,createToolRuntimeContext:()=>Wd,createUnavailableProtectedStateStore:()=>dl,createVideoTools:()=>Mw,createWebContextFetchTool:()=>ch,createWebContextRequestFactory:()=>J1,createWebContextSearchTool:()=>ah,createWebSearchTool:()=>B1,createWindowsDpapiProtectedCipher:()=>wte,createWindowsDpapiProtectedFileStore:()=>m5,createWorkflowTools:()=>bv,createWriteTool:()=>Kd,createXenoAgent:()=>Nr,createXenoAutomationConformanceReport:()=>X0,createXenoGovernedAutomationTools:()=>Zx,createXenoHostAutomationAuditSink:()=>i8,createXenoHostGovernedAutomationRuntime:()=>o8,createXenoHostedControlCommand:()=>tU,createXenoHostedEnvironmentManifest:()=>iie,createXenoHostedEvent:()=>sie,createXenoHostedExecutionBoundaryReceipt:()=>YB,createXenoHostedRunResult:()=>nU,createXenoRasterPreview:()=>Dh,createXenoSecureShare:()=>Moe,createXenoSessionHandoff:()=>Noe,createXenoShareSigningIdentity:()=>_oe,createXenoSkillTool:()=>Ote,createXenoSourceResearchExcerpt:()=>qie,createXenoSourceResearchReport:()=>Hie,currentExecutionAdapterStatus:()=>uq,decodeJwtPayload:()=>$f,decodeXenoBmp:()=>Lh,decodeXenoGif:()=>lh,decodeXenoGifAnimation:()=>o2,decodeXenoJpeg:()=>hh,decodeXenoNetpbm:()=>$h,decodeXenoPng:()=>sI,decodeXenoSvg:()=>Y2,decodeXenoVp8:()=>wu,decodeXenoWebp:()=>Ch,defaultToolRuntimeContext:()=>j,defaultXenoReviewPack:()=>V8,deflateXenoZlib:()=>Va,deleteSession:()=>y4,denyMcpServer:()=>zw,deriveHostedIdempotencyKey:()=>lie,describeXenoAutomationOperation:()=>hn,detectLanguage:()=>Rv,detectPluginRepositorySignals:()=>jF,detectRepositoryDocumentKind:()=>hB,detectRepositoryLanguage:()=>xR,detectXenoSpecDrift:()=>B8,deterministicReduce:()=>aT,digestMessages:()=>Dk,directProviderConfigFromConnection:()=>Jce,discoverXenoSkills:()=>Ite,dispatchAgentTool:()=>M1,editTool:()=>SO,elfAnalyzeTool:()=>ED,emitXenoTelemetry:()=>Jf,encodeXenoPngRgb:()=>Cc,enforceShellCommandPolicy:()=>yy,enforceToolPolicy:()=>Zu,ensureConfigDir:()=>Ua,ensureDurableMessageIds:()=>Ny,ensureProjectStateDir:()=>nM,estimateFullRequestBudget:()=>Lk,evaluateContainmentUiRestrictions:()=>t5,evaluatePermissionProfileNetworkUrl:()=>br,evaluateXenoCapabilityEligibility:()=>e_,executeXenoCoordinationAction:()=>nie,extractJsonObject:()=>ob,extractToolPath:()=>_s,findXenoSkill:()=>GT,fingerprintXenoSecureExecutionContract:()=>dq,forgetRecentSession:()=>aA,forgetRecentSessionById:()=>Ja,formatBoundedShellOutput:()=>nr,formatCost:()=>zU,formatDirectShellContext:()=>Qa,formatJsonSchemaErrors:()=>gg,formatModelList:()=>c4,formatPromptContextBreakdown:()=>vae,gcodeAnalyzeTool:()=>CD,generateImageTool:()=>q1,generateSessionId:()=>no,getAgentHome:()=>M3,getAgentRunDir:()=>tne,getAgentRunStoreDir:()=>ene,getAvailableModels:()=>Ff,getBenchmarkComputeBudgetHintForCommand:()=>Dg,getBenchmarkForegroundTimeoutForCommand:()=>Ng,getBestExecutionSecurityStatus:()=>wx,getChatModels:()=>a4,getConfigDir:()=>Zr,getDefaultProviderRegistry:()=>zf,getExecutionSecurityCapabilityReport:()=>i0,getExecutionSecurityStatus:()=>Vr,getGlobIgnores:()=>OA,getGrepIgnores:()=>DA,getHighRiskPermissions:()=>OF,getImageGenerationConfig:()=>j1,getJwtExpiry:()=>Xf,getLinuxBubblewrapCapability:()=>Kl,getLogLevel:()=>MM,getManagedConfigPath:()=>eM,getMcpAppMetadata:()=>um,getMcpAppResourceUri:()=>Ml,getMcpApprovalDecision:()=>lF,getMcpAuthorizationServerMetadataUrls:()=>EP,getMcpPromptToolName:()=>XP,getMcpProtectedResourceMetadataUrls:()=>AP,getMcpResourceToolName:()=>BP,getMcpToolName:()=>$P,getModelName:()=>ja,getMxcContainmentProbe:()=>Go,getMxcNativeAssetDescriptor:()=>fx,getMxcWindowsHostPreparationDescriptor:()=>gx,getMxcWindowsHostPreparationHelperArchitecture:()=>hx,getPermissionProfile:()=>Af,getPersistentShellSession:()=>Yg,getPersistentShellSpawnSpec:()=>eE,getProcessContainmentStatus:()=>s0,getProjectAgentDefinitionDirs:()=>_C,getProjectAgentDefinitionsDir:()=>MC,getProjectLastSessionSummary:()=>V3,getProjectMcpApproval:()=>Nf,getProjectStatePath:()=>Mf,getReadImagePreviewCapability:()=>jN,getRecentSessionsIndexPath:()=>Yo,getSubagentTeamPresetDefinition:()=>oX,getToolRiskLevel:()=>n$,getUserAgentDefinitionsDir:()=>Fv,gitBranchTool:()=>cy,gitCommitTool:()=>ay,gitDiffTool:()=>iy,gitLogTool:()=>sy,gitStatusTool:()=>oy,globTool:()=>CO,grepTool:()=>LO,gzipXeno:()=>za,hasProjectOnboardingCompleted:()=>U3,hasXenoTelemetrySubscribers:()=>C4,hashContainmentConformanceReport:()=>hte,hashPluginManifest:()=>lv,hashPluginTree:()=>GP,hookResultStatus:()=>Ln,hostedEnvironmentIdentity:()=>cie,htmlSanitizerAuditTool:()=>ND,importLegacyXenoSkill:()=>kte,inflateXenoZlib:()=>Bd,initializeSessionRuntime:()=>Sae,inspectCliAutomationStatus:()=>s8,inspectRuntimeManifests:()=>yae,inspectSecurityPath:()=>jo,inspectSystemPrompt:()=>bae,inspectXenoHostAutomationStatus:()=>s8,inspectXenoRepositoryFreshness:()=>Yre,inspectXenoRepositorySymbol:()=>Kre,installSignalHandlers:()=>o6,invalidateAllObservedFiles:()=>Zg,invokeXenoSkill:()=>_5,isChatModel:()=>jS,isDangerousCommand:()=>Og,isDirectShellMessage:()=>jd,isExpiredJwt:()=>Q3,isExplicitResearchPrompt:()=>Hb,isJwt:()=>Lf,isLocalModel:()=>Md,isMcpAppResourceUri:()=>OP,isMcpOAuthTokenExpired:()=>mF,isMcpToolVisibleToApp:()=>Qw,isMcpToolVisibleToModel:()=>Yw,isNotBeforeJwt:()=>sM,isPathWithinAllowed:()=>qn,isQuotaControlError:()=>tl,isScreenCaptureAvailable:()=>UU,isSensitiveEnvironmentKey:()=>Sa,isSimpleInformationalPrompt:()=>Cp,isSpeechRecognitionAvailable:()=>iF,isSupportedMcpProtocolVersion:()=>om,isToolAllowedByXenoSkillActivation:()=>Dte,isUncOrDevicePath:()=>Jl,isValidAgentDefinitionName:()=>jv,isValidModel:()=>i4,isValidSessionId:()=>VS,isWorkspaceTrusted:()=>X3,isXenoAutomationOperation:()=>Om,legacyAgentArtifactToXenoArtifact:()=>r3,listBuiltInAgentProfiles:()=>_H,listPermissionProfiles:()=>V_,listProjectAllowedTools:()=>j3,listProjectMcpApprovals:()=>NS,listSessions:()=>h4,loadConfig:()=>$S,loadConfiguredMcpServers:()=>qw,loadMcpConfigFile:()=>rm,loadProjectConfig:()=>Od,loadProjectState:()=>xn,loadRecentSessionsIndex:()=>oo,loadSession:()=>g4,loadUserConfig:()=>rM,loadXenoSkill:()=>zT,lookupRecentSession:()=>Ud,lsTool:()=>uL,lspDefinitionTool:()=>sL,lspDiagnosticsTool:()=>iL,lspHoverTool:()=>aL,lspReferencesTool:()=>cL,matchPermissionRule:()=>BX,matchesMcpRegistryEntryPolicy:()=>kF,materializeXenoAutomationEvidence:()=>Qm,mcpInputSchemaToToolSchema:()=>UP,memoryReadTool:()=>gL,memoryWriteTool:()=>hL,mergeConfigs:()=>p4,mxcWarningsRequireWindowsHostPreparation:()=>mx,normalizeDirectShellResultRecord:()=>Ya,normalizeHookDecision:()=>Id,normalizeMcpAppVisibility:()=>_l,normalizePermissionProfileName:()=>Td,normalizeQuotaScope:()=>Cr,normalizeRepositoryRelativePath:()=>E_,normalizeSourceText:()=>bw,normalizeSubagentBranchPolicy:()=>Yy,normalizeWorkingDirectory:()=>Wa,normalizeXenoHostedControlAcknowledgement:()=>Oie,notebookEditTool:()=>SL,notebookReadTool:()=>xL,openSqliteAutomationExecutionJournal:()=>Jq,openSqliteCapabilityLeasePersistence:()=>Zee,parseContainmentReviewerTrustStore:()=>GX,parseMcpWwwAuthenticate:()=>lm,parsePermissionRule:()=>ET,parseRetryAfter:()=>vy,parseSessionId:()=>qf,parseShellPathReferences:()=>hk,parseSubagentRemoteMcpPolicy:()=>gee,parseSubagentRoleList:()=>pee,parseUnifiedDiff:()=>cS,parseXenoAnsi:()=>il,parseXenoRecipeDefinition:()=>rse,pending:()=>Jr,persistXenoAutomationEvidence:()=>Pa,planXenoControlRoomAction:()=>sne,pluginInfoRelevanceCandidate:()=>qF,pluginListingRelevanceCandidate:()=>VF,pluginSignaturePayload:()=>WP,preflightLocalModel:()=>o4,prepareMxcWindowsHost:()=>t0,probeXenoProvider:()=>Gce,projectToolDefinitionsForProvider:()=>Ns,projectToolSchemaForProvider:()=>Ek,projectXenoControlRoom:()=>ine,providerCapabilityError:()=>Ds,providerProtocolError:()=>ce,publicKeyFingerprint:()=>kR,publishPlugin:()=>KF,quotaAncestors:()=>mp,quotaInteger:()=>je,quotaScopeKey:()=>_r,quotaText:()=>Rn,rankPluginRelevance:()=>HF,readCliAutomationEnvironment:()=>oS,readImageTool:()=>HN,readManifestFromDisk:()=>$i,readPluginDetachedSignature:()=>JP,readPluginSupplyChainLockfile:()=>uv,readSessionFormatVersion:()=>Cw,readTool:()=>bO,readXenoApiKey:()=>jU,readXenoHostAutomationEnvironment:()=>oS,recordRecentSession:()=>Qo,recordXenoCounter:()=>re,recordXenoEvent:()=>_4,recordXenoHistogram:()=>Le,recoverSessionMessages:()=>Kp,redactXenoShareValue:()=>ER,registerShutdownCleanup:()=>fo,registry:()=>uy,removeMcpServerConfig:()=>aF,removeProjectAllowedTool:()=>H3,renderAgentDefinition:()=>xH,renderAgentDefinitions:()=>vH,renderAuditReplayMarkdown:()=>xC,renderAuditReplayReport:()=>SC,renderAuditTraceMarkdown:()=>vC,renderAuditTraceReport:()=>wC,renderAuditTraceSummaries:()=>bC,renderCliAutomationStatus:()=>E8,renderCodingBenchmarkMarkdown:()=>aee,renderCodingBenchmarkReport:()=>see,renderContinuationIncompleteStatus:()=>e6,renderLspDefinitionReport:()=>tL,renderLspDiagnosticsReport:()=>eL,renderLspDoctorReport:()=>oL,renderLspHoverReport:()=>rL,renderLspReferencesReport:()=>nL,renderToolContinuationInput:()=>ZG,renderXenoHostAutomationStatus:()=>E8,renderXenoSkillCatalog:()=>Tte,repairInterruptedToolCalls:()=>vl,repairToolExchangeHistory:()=>Bk,requestBackground:()=>T1,requiresSecuredProcessLaunch:()=>zr,resetAllPersistentShellSessions:()=>A1,resetBashBenchmarkGuards:()=>WO,resetImageGenerationConfig:()=>H1,resetMcpServerApprovals:()=>dF,resetMxcContainmentProbe:()=>yx,resetPersistentShellSession:()=>Qg,resetXenoAnsiPolicy:()=>hX,resetXenoTelemetryCardinalityForTests:()=>N4,resizeXenoRaster:()=>aI,resolveAgentDefinition:()=>gH,resolveAgentProfile:()=>OH,resolveAgentToolPolicy:()=>Pm,resolveBuiltInAgentProfile:()=>BC,resolveCommandOnPath:()=>ks,resolveContainmentConformanceTemporaryRoot:()=>e5,resolveDelegatedExecutionMode:()=>oT,resolveExecutionSecurityLevel:()=>td,resolveExecutionTrustMode:()=>qm,resolveInteractiveTurnMaxIterations:()=>dB,resolveLocalRuntimeUrl:()=>is,resolveModelContextTokens:()=>Vf,resolvePermissionProfile:()=>z_,resolveShellInvocation:()=>m1,resolveSubagentRemoteMcpAccess:()=>yee,resolveSubagentWorkflowAnswer:()=>fT,resolveXenoAutomationEvidencePolicy:()=>Tx,resolveXenoSdkApiKey:()=>Z3,runAgentHook:()=>_d,runCommandHook:()=>kd,runContainmentConformanceSuite:()=>ote,runDelegatedXenoTurn:()=>fae,runDelegationPlan:()=>iT,runDurableAutomation:()=>Lx,runHookDefinition:()=>kf,runHooks:()=>_f,runHttpHook:()=>Rd,runPromptHook:()=>Cd,runSubagentWorkflow:()=>gT,runXenoThread:()=>Ew,runXenoThreadStreamed:()=>Sse,sanitizeEnvironment:()=>qo,sanitizeXenoTelemetryAttributes:()=>fM,saveConfig:()=>G3,saveMcpConfigFile:()=>Hw,saveProjectState:()=>Of,saveSession:()=>f4,scaffoldPlugin:()=>WF,scanAgentDefinitions:()=>Hv,scoreMemories:()=>vZ,scorePluginRelevance:()=>KP,searchXenoRepositoryIndex:()=>Jre,selectXenoProviderRoute:()=>Wce,serializeXenoRecipe:()=>ise,setLogLevel:()=>_M,setProjectLastSessionSummary:()=>LS,setProjectMcpApproval:()=>Df,setProjectOnboardingCompleted:()=>F3,setWorkspaceTrusted:()=>B3,setupAIHandlers:()=>FU,sha256ArtifactBytes:()=>Me,sha256ArtifactJson:()=>ze,shouldEnableExecutionGovernance:()=>Pp,shouldSourceShellProfile:()=>su,shouldUseIsolatedStdinForCommand:()=>eu,signSharePayload:()=>AB,sqliteAnalyzeTool:()=>RI,stripXenoAnsi:()=>bT,subscribeXenoTelemetry:()=>WS,summarizeAuditInputRecord:()=>ZU,summarizeAuditTraces:()=>Am,summarizeRuntimeInput:()=>hy,summarizeSubagentResults:()=>mT,summarizeXenoArtifactReview:()=>Ym,syncMcpToolsToRegistry:()=>PF,synthesizeSkill:()=>ib,taskInputTool:()=>CL,taskOutputTool:()=>kL,taskStopTool:()=>TL,testPlugin:()=>JF,thinkTool:()=>O1,toAgentDefinitionMetadata:()=>wH,toLLMProvider:()=>rT,toolEvidenceToXenoArtifact:()=>i3,toolOperationManager:()=>G,toolRiskLevel:()=>ec,turnDiffSummaryToXenoArtifact:()=>a3,unifiedDiffToXenoArtifact:()=>lS,unifiedExecManager:()=>ru,updateProjectState:()=>wr,upsertMcpServerConfig:()=>sF,validateAgentDefinition:()=>OC,validateCapabilityLeaseRequest:()=>Yx,validateCapabilityMutationReceipt:()=>kT,validateDelegationPlan:()=>Z$,validateDirectEndpoint:()=>Ls,validateExecutionSecurityPolicy:()=>Gi,validateJsonSchema:()=>YM,validateManifest:()=>ov,validateMcpAppResource:()=>NP,validateToolContinuationGoal:()=>mc,validateXenoArtifact:()=>E0,validateXenoArtifactReviewEvent:()=>Km,validateXenoControlRoomSnapshot:()=>q5,validateXenoEvidenceGraph:()=>g_,validateXenoRepositoryIndex:()=>zs,validateXenoSdkApiKey:()=>e4,validateXenoSecureExecutionContract:()=>f0,validateXenoSpecDocument:()=>k_,verifyContainmentCertification:()=>cx,verifyContainmentCertificationApproval:()=>tte,verifyPluginSupplyChain:()=>dv,verifySignature:()=>xT,verifySoulRecord:()=>IX,verifyXenoHostedControlCommand:()=>Mie,verifyXenoHostedEnvironmentManifest:()=>cw,verifyXenoHostedEventChain:()=>aie,verifyXenoHostedExecutionAdapterCertification:()=>xie,verifyXenoHostedExecutionJob:()=>QB,verifyXenoHostedRunResult:()=>Nie,verifyXenoHostedWebhook:()=>bie,verifyXenoSecureShare:()=>Ooe,verifyXenoSessionHandoff:()=>Doe,webFetchTool:()=>ih,webSearchTool:()=>rh,windowsDpapiProtect:()=>FT,windowsDpapiUnprotect:()=>jT,withXenoTelemetrySpan:()=>M4,wrapXenoAnsi:()=>xX,writePluginSupplyChainLockfile:()=>pv,writeTool:()=>vO,xenoAnsi:()=>ol,xenoAnsiVisibleWidth:()=>wT,xenoArtifactToDiffDocument:()=>dS,xenoArtifactToLegacyAgentArtifact:()=>o3,xenoArtifactToOracleReport:()=>Bie,xenoArtifactToReviewReport:()=>G8,xenoArtifactToSourceResearchReport:()=>zie,xenoArtifactToSpecDocument:()=>fS,xenoArtifactToSpecExecution:()=>T_,xenoArtifactToToolEvidence:()=>s3,xenoArtifactToTurnDiffSummary:()=>c3,xenoHostedExecutionAdapterSigningPayload:()=>vie,xenoOracleReportToArtifact:()=>Xie,xenoRecipeFingerprint:()=>yU,xenoReviewReportToArtifact:()=>z8,xenoReviewReportToGitHubComments:()=>W8,xenoSourceResearchReportToArtifact:()=>Vie,xenoSpecArtifactIds:()=>$a,xenoSpecExecutionToArtifact:()=>gS,xenoSpecToArtifactBundle:()=>mS});module.exports=Xj(mle);Fi();var pr="0.9.32";var pC=require("node:crypto");zt();yt();var ha=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=(0,pC.randomUUID)(),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 ga(this.filePath,JSON.stringify(r))}),await this.writeQueue,n}async read(e){let n=await ye(this.filePath);if(!n)return[];let r=Hi(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 xe(e,JSON.stringify(n,null,2)),n.length}async flush(){await this.writeQueue}};function Jj(t,e){return e.endedAt.localeCompare(t.endedAt)}function Lv(t,e){t.set(e,(t.get(e)??0)+1)}function Bv(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 mC(t){return t.filter(e=>e.tool_name||e.event_type.startsWith("tool_")).length}function fC(t){return t.filter(e=>e.event_type==="permission_decision").length}function gC(t){return t.filter(e=>e.status==="error"||e.event_type.endsWith("_failed")).length}function $v(t){return t.split(/[_\s-]+/).filter(e=>e.length>0).map(e=>e[0].toUpperCase()+e.slice(1)).join(" ")}function Xv(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 Kj(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 Yj(t){let e=$v(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=`${$v(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=Xv(t.metadata)}else t.event_type==="delegation_started"?(e="Delegation started",n=Xv(t.metadata)):t.tool_name?e=`${$v(t.event_type)}: ${t.tool_name}`:n||(n=Xv(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 Am(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:Bv(s,a),toolEvents:mC(i),permissionEvents:fC(i),errorEvents:gC(i),lastEventType:i[i.length-1]?.event_type??"unknown"})}return n.sort(Jj)}function hC(t,e){let n=Am(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(Lv(i,u.event_type),Lv(a,u.actor),Lv(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:Bv(l,d),toolEvents:mC(o),permissionEvents:fC(o),deniedPermissions:o.filter(u=>u.event_type==="permission_decision"&&u.decision==="deny").length,errorEvents:gC(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:Kj(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 yC(t,e){let n=Am(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:Bv(i,s),steps:o.map(Yj)}}function bC(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 wC(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 vC(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 xC(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(!zne(e.toolName,e.input,n))return[];let r=Gne(e.toolNa
2568
2568
  `).length!==t.endLine-t.startLine+1&&n.push(`excerpt ${t?.excerptId} line span does not match text`)}function Kie(t,e){yl(t?.providerId,"model providerId",e),ur(t?.model,"model",e,512),t?.connectionId!==void 0&&yl(t.connectionId,"model connectionId",e)}function Yie(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 ww(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 yl(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 ur(t,e,n,r){(typeof t!="string"||!t.trim()||t.length>r||dt(t,{allowTab:!0,allowLineBreaks:!0}))&&n.push(`${e} must be non-empty bounded text`)}function pU(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 Qie(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 Zie(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 fU(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 ese(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 mU(t){return Number.isSafeInteger(t)&&(t??-1)>=0?t:0}function gU(t){return{algorithm:"sha256",value:Me(t).value}}function tse(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1}function nse(t){return t==="info"||t==="low"||t==="medium"||t==="high"||t==="critical"}var hU="xeno.recipe.v1",Rt=class extends Error{constructor(n){super(`XENO recipe is invalid: ${n.join("; ")}`);this.issues=n;this.name="XenoRecipeValidationError"}issues;code="XENO_RECIPE_INVALID"};function rse(t){let e=ta(t,"recipe",["schemaVersion","recipeId","name","description","version","modes","inputs","requiredSecretRefs","authority","budget","steps","provenance"]),n=ta(e.authority,"authority",["permissionMode","externalActions","network"]),r=ta(e.budget,"budget",["maxAgents","maxConcurrency","maxTotalTokens","timeoutMs"]),o={schemaVersion:e.schemaVersion,recipeId:gt(e.recipeId,"recipeId"),name:gt(e.name,"name"),description:gt(e.description,"description"),version:Vp(e.version,"version"),modes:ea(e.modes,"modes").map(i=>i),inputs:ea(e.inputs,"inputs").map((i,s)=>sse(i,s)),requiredSecretRefs:ea(e.requiredSecretRefs,"requiredSecretRefs").map(i=>gt(i,"secret ref")),authority:{permissionMode:n.permissionMode,externalActions:n.externalActions,network:n.network},budget:{maxAgents:Vp(r.maxAgents,"budget.maxAgents"),maxConcurrency:Vp(r.maxConcurrency,"budget.maxConcurrency"),maxTotalTokens:Vp(r.maxTotalTokens,"budget.maxTotalTokens"),timeoutMs:Vp(r.timeoutMs,"budget.timeoutMs")},steps:ea(e.steps,"steps").map((i,s)=>ase(i,s)),...e.provenance!==void 0?{provenance:cse(e.provenance)}:{}};return zp(o),o}function zp(t){let e=[];t?.schemaVersion!==hU&&e.push("schemaVersion must be xeno.recipe.v1"),xw(t?.recipeId,"recipeId",e),Mo(t?.name,"name",e,256),Mo(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);bse(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"),lse(t?.budget,e);let r=new Set;for(let s of t?.inputs??[]){if(hse(s?.name,e),r.has(s.name)&&e.push(`duplicate input ${s.name}`),r.add(s.name),Mo(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&&Mo(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??[])Mo(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){Mo(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??[]){xw(s?.id,"step id",e),i.has(s.id)&&e.push(`duplicate step ${s.id}`),i.set(s.id,s),Mo(s?.title,`step ${s.id} title`,e,2e3),s?.kind!=="agent"&&s?.kind!=="verification"&&e.push(`step ${s.id} kind is invalid`),Mo(s?.prompt,`step ${s.id} prompt`,e,128e3),s?.agentProfile!==void 0&&xw(s.agentProfile,`step ${s.id} agentProfile`,e);for(let a of s?.dependsOn??[])xw(a,`step ${s.id} dependency`,e);s?.approval&&Mo(s.approval.message,`step ${s.id} approval message`,e,8e3);for(let a of s?.expectedArtifacts??[])yse(a,`step ${s.id} expected artifact`,e);for(let a of fse(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(dse(t?.steps??[],e),e.length>0)throw new Rt([...new Set(e)])}function ose(t,e){if(zp(t),!t.modes.includes(e.mode))throw new Rt([`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 Rt(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 Rt([`required recipe input ${a.name} is missing`]);i[a.name]="";continue}i[a.name]=pse(a,c)}let s=t.requiredSecretRefs.filter(a=>e.hasSecretRef&&!e.hasSecretRef(a));if(s.length>0)throw new Rt(s.map(a=>`required secret reference is unavailable: ${a}`));return{schemaVersion:1,recipeId:t.recipeId,recipeVersion:t.version,recipeFingerprint:yU(t),mode:e.mode,inputs:i,requiredSecretRefs:[...t.requiredSecretRefs],authority:structuredClone(t.authority),budget:structuredClone(t.budget),steps:use(t.steps).map(a=>({...structuredClone(a),prompt:mse(a.prompt,i)}))}}function yU(t){return zp(t),{algorithm:"sha256",value:ze(t).value}}function ise(t){return zp(t),`${Q(t)}
2569
2569
  `}function sse(t,e){let n=ta(t,`inputs[${e}]`,["name","description","required","default","enum","pattern"]);return{name:gt(n.name,`inputs[${e}].name`),description:gt(n.description,`inputs[${e}].description`),required:gse(n.required,`inputs[${e}].required`),...n.default!==void 0?{default:gt(n.default,`inputs[${e}].default`)}:{},...n.enum!==void 0?{enum:ea(n.enum,`inputs[${e}].enum`).map(r=>gt(r,"enum value"))}:{},...n.pattern!==void 0?{pattern:gt(n.pattern,`inputs[${e}].pattern`)}:{}}}function ase(t,e){let n=ta(t,`steps[${e}]`,["id","title","kind","prompt","dependsOn","agentProfile","approval","expectedArtifacts"]),r=n.approval===void 0?void 0:ta(n.approval,`steps[${e}].approval`,["message"]);return{id:gt(n.id,`steps[${e}].id`),title:gt(n.title,`steps[${e}].title`),kind:n.kind,prompt:gt(n.prompt,`steps[${e}].prompt`),...n.dependsOn!==void 0?{dependsOn:ea(n.dependsOn,"dependsOn").map(o=>gt(o,"dependency"))}:{},...n.agentProfile!==void 0?{agentProfile:gt(n.agentProfile,"agentProfile")}:{},...r?{approval:{message:gt(r.message,"approval message")}}:{},...n.expectedArtifacts!==void 0?{expectedArtifacts:ea(n.expectedArtifacts,"expectedArtifacts").map(o=>gt(o,"expected artifact"))}:{}}}function cse(t){let e=ta(t,"provenance",["publisherId","source","revision"]);return{publisherId:gt(e.publisherId,"provenance.publisherId"),...e.source!==void 0?{source:gt(e.source,"provenance.source")}:{},...e.revision!==void 0?{revision:gt(e.revision,"provenance.revision")}:{}}}function lse(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 dse(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 use(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 Rt(["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 pse(t,e){let n=e.trim();if(n.length>32e3||dt(n,{allowTab:!0,allowLineBreaks:!0}))throw new Rt([`input ${t.name} is invalid`]);if(t.enum&&!t.enum.includes(n))throw new Rt([`input ${t.name} is outside its enum`]);if(t.pattern&&!new RegExp(t.pattern,"u").test(n))throw new Rt([`input ${t.name} does not match its pattern`]);return n}function mse(t,e){return t.replace(/\{\{\s*input\.([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/gu,(n,r)=>e[r]??"")}function fse(t){return[...t.matchAll(/\{\{\s*input\.([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/gu)].map(e=>e[1])}function ta(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw new Rt([`${e} must be an object`]);let r=t,o=Object.keys(r).filter(i=>!n.includes(i));if(o.length>0)throw new Rt(o.map(i=>`${e} contains unsupported field ${i}`));return r}function ea(t,e){if(!Array.isArray(t))throw new Rt([`${e} must be an array`]);return t}function gt(t,e){if(typeof t!="string")throw new Rt([`${e} must be text`]);return t}function gse(t,e){if(typeof t!="boolean")throw new Rt([`${e} must be boolean`]);return t}function Vp(t,e){if(!Number.isSafeInteger(t))throw new Rt([`${e} must be an integer`]);return t}function xw(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 hse(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 Mo(t,e,n,r){(typeof t!="string"||!t.trim()||t.length>r||dt(t,{allowTab:!0,allowLineBreaks:!0}))&&n.push(`${e} must be non-empty bounded text`)}function yse(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 bse(t){return t==="default"||t==="plan"||t==="acceptEdits"||t==="auto"||t==="dontAsk"}var AU=require("node:readline"),EU=require("node:crypto");bl();tp();async function Ew(t){let e=t.runtimeEventBus??new gi,n=[],r=t.captureTraceGraph?new Uc("thread-run"):void 0;e.subscribe(a=>{n.push(a),r?.record(a),t.onRuntimeEvent?.(a)});let{agent:o}=await Nr({...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*Sse(t){let e=t.runtimeEventBus??new gi,n=[],r=t.captureTraceGraph?new Uc("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 Nr({...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}}}tp();var Tw=require("node:crypto"),Ti=require("node:path"),tP=require("node:perf_hooks");xr();var YR=require("node:crypto"),De=require("node:fs"),Gp=require("node:path");var Iw=[2,1],JR=["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"],W=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 QR(){return{schemaVersion:2,threads:{},turns:{},permissions:{},idempotency:{},streams:{}}}function Ase(t){let e=QR();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 Ese(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 Ase(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 KR(t){return structuredClone(t)}var kw=class{constructor(e,n){this.retention=n;(0,De.mkdirSync)(e,{recursive:!0}),this.statePath=(0,Gp.join)(e,"state-v2.json"),this.lockPath=(0,Gp.join)(e,"state-v2.lock"),this.state=QR(),this.withLock(()=>{this.state=this.load(),this.commit(this.state)})}retention;statePath;lockPath;state;snapshot(){return this.state=this.load(),KR(this.state)}mutate(e,n=new Date){return this.withLock(()=>{this.state=this.load();let r=KR(this.state),o=e(r);return this.prune(r,n),this.commit(r),this.state=r,KR(o)})}reload(){return this.state=this.load(),this.snapshot()}load(){if(!(0,De.existsSync)(this.statePath))return QR();try{return Ese(JSON.parse((0,De.readFileSync)(this.statePath,"utf8")))}catch{let e=`${this.statePath}.corrupt-${Date.now()}-${(0,YR.randomUUID)().slice(0,8)}`;try{(0,De.renameSync)(this.statePath,e)}catch{}throw new W("APP_SERVER_STATE_CORRUPT","The app-server state is malformed and was quarantined.",-32019,!1,"persistence",{quarantineFile:e.split(/[\\/]/).at(-1)})}}commit(e){(0,De.mkdirSync)((0,Gp.dirname)(this.statePath),{recursive:!0});let n=`${this.statePath}.${process.pid}.${(0,YR.randomUUID)()}.tmp`,r=(0,De.openSync)(n,"wx",384);try{(0,De.writeFileSync)(r,`${JSON.stringify(e,null,2)}
2570
2570
  `,"utf8"),(0,De.fsyncSync)(r)}finally{(0,De.closeSync)(r)}(0,De.renameSync)(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=(0,De.openSync)(this.lockPath,"wx",384),(0,De.writeFileSync)(r,String(process.pid),"utf8")}catch(o){if(o.code!=="EEXIST")throw o;try{Date.now()-(0,De.statSync)(this.lockPath).mtimeMs>3e4&&(0,De.unlinkSync)(this.lockPath)}catch{}if(Date.now()>=n)throw new W("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{(0,De.closeSync)(r);try{(0,De.unlinkSync)(this.lockPath)}catch{}}}};bt();var Ise=new Set(JR),kse=new Set(["thread.start","thread.resume","thread.archive","thread.delete","turn.start","turn.steer","turn.interrupt","permission.respond"]);function Tse(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function pn(t,e){let n=t[e];if(typeof n!="string"||n.trim().length===0)throw new W("APP_SERVER_INVALID_PARAMS",`${e} is required.`,-32602,!1,"validation");return n.trim()}function Dr(t){if(!(typeof t!="number"||!Number.isInteger(t)))return t}function vU(t,e){if(t===void 0)return;let n=Dr(t);if(n===void 0||n<0)throw new W("APP_SERVER_INVALID_PARAMS",`${e} must be a non-negative integer.`,-32602,!1,"validation");return n}function ZR(t){if(!t.id?.trim())throw new W("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=>(0,Ti.resolve)(e)))],capabilities:[...new Set(t.capabilities??[])].sort()}}function xU(t){let e=(0,Ti.resolve)(t);return process.platform==="win32"?e.toLowerCase():e}function eP(t,e){let n=xU(t),r=xU(e);return n===r||n.startsWith(`${r}/`)||n.startsWith(`${r}\\`)}function nP(t){return Array.isArray(t)?t.map(nP):!t||typeof t!="object"?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,nP(n)]))}function SU(t){return(0,Tw.createHash)("sha256").update(JSON.stringify(nP(t))).digest("hex")}function Rse(t){return t instanceof W?{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 Pse(t){return/(?:completed|failed|interrupted|deleted|archived|permission\.resolved)$/.test(t.type)}function Cse(t){return/(?:progress|delta|steering)$/.test(t.type)}function Wp(t,e=0){return e>6?"[truncated]":Array.isArray(t)?t.slice(0,100).map(n=>Wp(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,Wp(r,e+1)]))}var Jp=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??Tw.randomUUID,this.defaultPrincipal=ZR(e.defaultPrincipal??{id:"local-stdio",workspaceRoots:[process.cwd()],capabilities:["thread.delete.permanent","integrations.read"]});let n=e.stateDir??(0,Ti.join)(Te(),"app-server-v2");this.store=new kw(n,this.retention),this.turnRunner=e.turnRunner??(async({turn:r})=>({accepted:!0,turnId:r.turnId}))}options;static supports(e){return Ise.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=tP.performance.now(),i="success",s;re("xeno.app_server.method_calls",1,{component:"app_server_v2",method:e,transport:r.transport});try{let a=Tse(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 W("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 W?a.machineCode:a instanceof Error?a.name:"unknown_error",a}finally{re("xeno.app_server.method_results",1,{component:"app_server_v2",method:e,transport:r.transport,outcome:i,...s?{error_code:s}:{}}),Le("xeno.app_server.method_duration_ms",tP.performance.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=Iw.find(c=>o.includes(c));if(!i)throw new W("APP_SERVER_VERSION_UNSUPPORTED","Client and server app protocol versions do not overlap.",-32010,!1,"protocol",{requested:o,supported:[...Iw]});let s=ZR(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 W("APP_SERVER_INITIALIZATION_REQUIRED","Call initialize and provide its connection identity.",-32012,!1,"protocol");if(e.principal&&ZR(e.principal).id!==r.principal.id)throw new W("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 W("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(pn(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=pn(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,Dr(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=pn(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,Dr(e.threadVersion),"thread"),e.permanent===!0){if(!n.principal.capabilities.includes("thread.delete.permanent"))throw new W("APP_SERVER_UNAUTHORIZED","Permanent thread deletion is not permitted.",-32011);if(a.legalHold)throw new W("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=pn(e,"threadId"),o=pn(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 W("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 W("TURN_ALREADY_ACTIVE","A thread can have only one active turn.",-32015,!0,"concurrency",{turnId:u.turnId});this.assertVersion(d.version,Dr(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[pn(e,"turnId")];if(!r)throw new W("TURN_NOT_FOUND","Turn not found.",-32014);return this.requireThread(r.threadId,n,{allowDeleted:!1}),r}steerTurn(e,n){let r=pn(e,"turnId"),o=pn(e,"input"),i=this.idempotentMutation("turn.steer",e,n,(s,a)=>{let c=this.requireTurnFromState(s,r,n);if(this.assertVersion(c.version,Dr(e.turnVersion),"turn"),!["queued","running","needs_permission"].includes(c.status))throw new W("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=pn(e,"turnId"),o=this.idempotentMutation("turn.interrupt",e,n,(i,s)=>{let a=this.requireTurnFromState(i,r,n);if(this.assertVersion(a.version,Dr(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=vU(e.afterSequence,"afterSequence")??0,i=this.replayStream(r,o,Dr(e.limit)??100,n),s=`subscription_${this.idFactory()}`,a=Math.max(8,Math.min(this.maxSubscriptionQueue,Dr(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(pn(e,"subscriptionId"),n);return r.closed=!0,this.subscriptions.delete(r.subscriptionId),{unsubscribed:!0}}poll(e,n){let r=this.requireSubscription(pn(e,"subscriptionId"),n);if(this.threadForStream(r.streamId,n).status==="deleted")throw r.closed=!0,this.subscriptions.delete(r.subscriptionId),new W("APP_SERVER_UNAUTHORIZED","Event access has been revoked.",-32011);let i=Math.max(1,Math.min(256,Dr(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,vU(e.afterSequence,"afterSequence")??0,Dr(e.limit)??100,n)}replayStream(e,n,r,o){if(this.threadForStream(e,o).status==="deleted")throw new W("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 re("xeno.app_server.cursor_expirations",1,{component:"app_server_v2",operation:"replay",reason:"cursor_expired"}),new W("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);Le("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 W("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=pn(e,"requestId"),o=pn(e,"response");if(!["allow","always","deny"].includes(o))throw new W("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 W("PERMISSION_RESPONSE_STALE","Permission request is not active.",-32017);if(s.principalId!==n.principal.id||s.connectionId!==n.connectionId)throw new W("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 W("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 W("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=>eP(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:Wp(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,Wp(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:Wp(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=Rse(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 W("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(!kse.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=SU(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 W("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=SU(i),a=`${r.principal.id}:${e}:${o}`,c=this.store.snapshot().idempotency[a];if(!c)return{found:!1};if(c.fingerprint!==s)throw new W("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,re("xeno.app_server.subscription_backpressure",1,{component:"app_server_v2",queue:"subscription",state:"degraded"}),Cse(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,re("xeno.app_server.subscription_dropped_events",1,{component:"app_server_v2",reason:"coalescing_unavailable"}));continue}let r=n.queue.findIndex(o=>!Pse(o));if(r>=0){n.queue.splice(r,1),n.queue.push(e),n.droppedEvents+=1,re("xeno.app_server.subscription_dropped_events",1,{component:"app_server_v2",reason:"terminal_priority"});continue}n.closed=!0,n.queue=[],n.droppedEvents+=1,re("xeno.app_server.subscription_closures",1,{component:"app_server_v2",reason:"irrecoverable_backpressure"})}}authorizeWorkspace(e,n){if(typeof e!="string"||!e.trim()||!(0,Ti.isAbsolute)(e))throw new W("APP_SERVER_UNAUTHORIZED","A permitted workspace is required.",-32011);let r=(0,Ti.resolve)(e);if(!n.workspaceRoots.some(o=>eP(r,o)))throw new W("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=>eP(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 W("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 W("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 W("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=pn(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 W("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 W("APP_SERVER_UNAUTHORIZED","Subscription is not available.",-32011);if(r.closed)throw new W("APP_SERVER_BACKPRESSURE","Subscription was closed because the client could not keep up.",-32022,!0,"backpressure");return r}};var Ri=class extends Error{constructor(n,r,o){super(n);this.rpcCode=r;this.data=o;this.name="AppServerRemoteError"}rpcCode;data},rP=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 Ri("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 Ri("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 _se(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 Ri(`HTTP app-server request failed with status ${o.status}.`,o.status);let s=(await o.json()).messages?.[0];if(!s)throw new Ri("App server returned no JSON-RPC message.",-32603);if(s.error)throw new Ri(s.error.message,s.error.code,s.error.data);return s.result}}}var Rw=class{constructor(e={}){this.options=e;this.execManager=e.execManager??ru,this.ownerId=e.ownerId??`app-server-${(0,EU.randomUUID)()}`;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=>Ew({...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=(0,AU.createInterface)({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(Jp.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=Pi(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:Ci(o.timeoutMs),maxOutputBytes:Ci(o.maxOutputBytes),env:Mse(o.env),tty:o.tty===!0,cols:Ci(o.cols),rows:Ci(o.rows),ownerSessionId:this.ownerId,origin:"app_server"})));return}if(e.method==="exec.write"){let o=Pi(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=Pi(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=Pi(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,Ose(o.cursor)??0,{maxChunks:Ci(o.maxChunks),maxBytes:Ci(o.maxBytes)})));return}if(e.method==="exec.terminate"){let o=Pi(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=Pi(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=Ci(o.cols),a=Ci(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=Pi(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=Pi(o.options),a=await Ew({...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 W){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 Jp(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:Nse(o)}:{}}}}write(e,n){e.write(`${JSON.stringify(n)}
2571
- `)}};function Pi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Mse(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 Ci(t){let e=typeof t=="number"?t:Number.parseInt(String(t??""),10);if(!(!Number.isFinite(e)||e<=0))return Math.floor(e)}function Ose(t){let e=typeof t=="number"?t:Number.parseInt(String(t??""),10);if(!(!Number.isFinite(e)||e<0))return Math.floor(e)}function Nse(t){return t instanceof Error?{name:t.name,message:t.message}:t&&typeof t=="object"&&!Array.isArray(t)?t:{value:String(t)}}Nd();qd();tc();var Mi=Se(require("path"),1),oP=Se(require("os"),1),_i=Se(require("fs"),1);zt();yt();St();fc();var Dse=1e4,Lse=6e4,$se="session.lock",Xse="lock.json",wl=new Map;function iP(t,e){return t!=null&&t.pid===e.pid&&t.hostname===e.hostname&&t.processStartedAt===e.processStartedAt&&t.acquiredAt===e.acquiredAt}function Bse(){for(let[t,e]of wl)try{let n=ee(_i.readFileSync(t,"utf8"),null);iP(n,e)&&_i.unlinkSync(t)}catch{}wl.clear()}fo(Bse);var Oo=class t{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=Mi.join(e,$se),this.legacyLockPath=Mi.join(e,Xse),this.sessionId=Mi.basename(e)}async acquire(){let e=new Date().toISOString(),n={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:oP.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:pr,acquiredAt:e,updatedAt:e,heartbeat:e},r=Mi.dirname(this.lockPath);await _i.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 Fr(o)}try{await _i.promises.writeFile(this.lockPath,JSON.stringify(n,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=n,wl.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 Fr(this.lockPath);try{await _i.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,wl.set(this.lockPath,n)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;wl.delete(this.lockPath);let n=await this.readLockAt(this.lockPath);iP(n,e)&&await Fr(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===oP.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>Lse}startHeartbeat(e=Dse){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(!iP(e,n)){this.acquiredOwner=void 0,wl.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await xe(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 ye(e);return n?ee(n,null):null}async findExistingLockPath(){return await ye(this.lockPath)?this.lockPath:await ye(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let n=await Sm(e),r=[];for(let o of n){let i=new t(o);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await Fr(a),r.push(Mi.basename(o))}}return r}};ag();var Pw=Se(require("path"),1);zt();yt();qd();tc();ag();Nd();Fi();Hd();St();tc();qd();function Use(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 Fse(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(Use))}function IU(t){return JSON.stringify({role:t.role,content:t.content})}function No(t,e){return t.length>e.length?!1:t.every((n,r)=>IU(n)===IU(e[r]))}function jse(t,e){return No(t,e)?e.slice(t.length):[]}function Hse(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 vl(t){let e=[],n=[],r=[],o=new Set,i=()=>{if(o.size===0)return;let s=Array.from(o),a=Hse(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 Kp(t,e){let n=new Sn(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(Fse)){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=vl(i),l=vl(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 dn(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&&No(s,w)?h.push({id:b.id,messages:w}):!No(w,s)&&!No(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&&No(i,w)){h.push({id:b.id,messages:w});continue}!No(w,i)&&!No(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=vl(y.messages);d=b.messages,u=a?[...c.messages,...jse(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))!No(w.messages,y.messages)&&!No(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}}rA();var Oi=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){ss(e.executionMode);let n=e.role??"default",r=no(n),o=en.getSessionDir(r),i=null,s=null;try{await jn(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=Pw.join(o,"meta.json");await xe(c,JSON.stringify(a,null,2)),s=new Sn(o);let l=new dn(o);i=new Oo(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=en.getSessionDir(e.sessionId),r=null,o=null;try{let i=Pw.join(n,"meta.json"),s=await ye(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}`);ss(a.executionMode),a.formatVersion=Cw(a),o=new Sn(n),await o.initialize();let c=new dn(n);r=new Oo(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 Kp(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(ss(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=Pw.join(this.sessionDir,"meta.json"),r=3,o=null;for(let i=0;i<r;i++)try{await xe(n,JSON.stringify(this._meta,null,2));return}catch(s){o=s instanceof Error?s:new Error(String(s)),be(`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=Fd(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 Cw(t){let e=t?.formatVersion;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}Hd();cA();var Yp=require("node:crypto"),DU=require("node:child_process"),me=require("node:fs/promises"),LU=require("node:os"),Pe=Se(require("node:path"),1);ln();Ge();var sP=2,kU=400,aP=80,lP=12,TU=3e4,cP=64*1024*1024;function RU(t){let e=t.replace(/\r\n/g,`
2571
+ `)}};function Pi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Mse(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 Ci(t){let e=typeof t=="number"?t:Number.parseInt(String(t??""),10);if(!(!Number.isFinite(e)||e<=0))return Math.floor(e)}function Ose(t){let e=typeof t=="number"?t:Number.parseInt(String(t??""),10);if(!(!Number.isFinite(e)||e<0))return Math.floor(e)}function Nse(t){return t instanceof Error?{name:t.name,message:t.message}:t&&typeof t=="object"&&!Array.isArray(t)?t:{value:String(t)}}Nd();qd();tc();var Mi=Se(require("path"),1),oP=Se(require("os"),1),_i=Se(require("fs"),1);zt();yt();St();fc();var Dse=1e4,Lse=6e4,$se="session.lock",Xse="lock.json",wl=new Map;function iP(t,e){return t!=null&&t.pid===e.pid&&t.hostname===e.hostname&&t.processStartedAt===e.processStartedAt&&t.acquiredAt===e.acquiredAt}function Bse(){for(let[t,e]of wl)try{let n=ee(_i.readFileSync(t,"utf8"),null);iP(n,e)&&_i.unlinkSync(t)}catch{}wl.clear()}fo(Bse);var Oo=class t{sessionDir;lockPath;legacyLockPath;sessionId;heartbeatTimer;acquiredOwner;constructor(e){this.sessionDir=e,this.lockPath=Mi.join(e,$se),this.legacyLockPath=Mi.join(e,Xse),this.sessionId=Mi.basename(e)}async acquire(){let e=new Date().toISOString(),n={schemaVersion:1,name:`session:${this.sessionId}`,sessionId:this.sessionId,pid:process.pid,hostname:oP.hostname(),processStartedAt:new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString(),version:pr,acquiredAt:e,updatedAt:e,heartbeat:e},r=Mi.dirname(this.lockPath);await _i.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 Fr(o)}try{await _i.promises.writeFile(this.lockPath,JSON.stringify(n,null,2),{flag:"wx",encoding:"utf-8"}),this.acquiredOwner=n,wl.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 Fr(this.lockPath);try{await _i.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,wl.set(this.lockPath,n)}else throw i}}async release(){this.stopHeartbeat();let e=this.acquiredOwner;if(this.acquiredOwner=void 0,!e)return;wl.delete(this.lockPath);let n=await this.readLockAt(this.lockPath);iP(n,e)&&await Fr(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===oP.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>Lse}startHeartbeat(e=Dse){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(!iP(e,n)){this.acquiredOwner=void 0,wl.delete(this.lockPath),this.stopHeartbeat();return}e.heartbeat=new Date().toISOString(),e.updatedAt=e.heartbeat,await xe(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 ye(e);return n?ee(n,null):null}async findExistingLockPath(){return await ye(this.lockPath)?this.lockPath:await ye(this.legacyLockPath)?this.legacyLockPath:null}static async cleanStale(e){let n=await Sm(e),r=[];for(let o of n){let i=new t(o);if(await i.isStale()){let a=await i.findExistingLockPath();a&&await Fr(a),r.push(Mi.basename(o))}}return r}};ag();var Pw=Se(require("path"),1);zt();yt();qd();tc();ag();Nd();Fi();Hd();St();tc();qd();function Use(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 Fse(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(Use))}function IU(t){return JSON.stringify({role:t.role,content:t.content})}function No(t,e){return t.length>e.length?!1:t.every((n,r)=>IU(n)===IU(e[r]))}function jse(t,e){return No(t,e)?e.slice(t.length):[]}function Hse(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 vl(t){let e=[],n=[],r=[],o=new Set,i=()=>{if(o.size===0)return;let s=Array.from(o),a=Hse(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 Kp(t,e){let n=new Sn(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(Fse)){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=vl(i),l=vl(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 dn(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&&No(s,w)?h.push({id:b.id,messages:w}):!No(w,s)&&!No(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&&No(i,w)){h.push({id:b.id,messages:w});continue}!No(w,i)&&!No(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=vl(y.messages);d=b.messages,u=a?[...c.messages,...jse(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))!No(w.messages,y.messages)&&!No(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}}rA();var Oi=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){ss(e.executionMode);let n=e.role??"default",r=no(n),o=en.getSessionDir(r),i=null,s=null;try{await jn(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=Pw.join(o,"meta.json");await xe(c,JSON.stringify(a,null,2)),s=new Sn(o);let l=new dn(o);i=new Oo(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=en.getSessionDir(e.sessionId),r=null,o=null;try{let i=Pw.join(n,"meta.json"),s=await ye(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}`);ss(a.executionMode),a.formatVersion=Cw(a),o=new Sn(n),await o.initialize();let c=new dn(n);r=new Oo(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 Kp(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(ss(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=Pw.join(this.sessionDir,"meta.json"),r=3,o=null;for(let i=0;i<r;i++)try{await xe(n,JSON.stringify(this._meta,null,2));return}catch(s){o=s instanceof Error?s:new Error(String(s)),be(`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=Fd(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 Cw(t){let e=t?.formatVersion;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}Hd();cA();var Yp=require("node:crypto"),DU=require("node:child_process"),me=require("node:fs/promises"),LU=require("node:os"),Pe=Se(require("node:path"),1);ln();Ge();var sP=2,kU=400,aP=80,lP=12,TU=3e4,cP=64*1024*1024;function RU(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(`