brass-runtime 1.12.1 → 1.13.2

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.
@@ -1 +1 @@
1
- 'use strict';var chunk63ODH5W4_cjs=require('../chunk-63ODH5W4.cjs');require('../chunk-T3QEEHK6.cjs');Object.defineProperty(exports,"AGENT_CONFIG_FILE_NAMES",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.fa}});Object.defineProperty(exports,"NodeShell",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ma}});Object.defineProperty(exports,"PROJECT_LOCKFILE_PROBES",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.m}});Object.defineProperty(exports,"PROJECT_PROFILE_PROBES",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.i}});Object.defineProperty(exports,"autoApproveApprovals",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ka}});Object.defineProperty(exports,"canAutoRollback",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.D}});Object.defineProperty(exports,"canRequestPatchRepair",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.x}});Object.defineProperty(exports,"commandForScript",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.r}});Object.defineProperty(exports,"decideNextAction",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.P}});Object.defineProperty(exports,"defaultPermissions",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ja}});Object.defineProperty(exports,"deriveContextSearchQueries",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.e}});Object.defineProperty(exports,"describeCommandDiscovery",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.u}});Object.defineProperty(exports,"describeContextDiscovery",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.f}});Object.defineProperty(exports,"describeLanguagePolicy",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.N}});Object.defineProperty(exports,"describePatchQuality",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.z}});Object.defineProperty(exports,"describeProjectProfile",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.l}});Object.defineProperty(exports,"describeRollbackSafety",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.G}});Object.defineProperty(exports,"discoverNodeWorkspaceRoot",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ta}});Object.defineProperty(exports,"discoverPackageManager",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.p}});Object.defineProperty(exports,"discoverProjectProfile",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.k}});Object.defineProperty(exports,"discoverValidationCommands",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.s}});Object.defineProperty(exports,"emitAgentEvent",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.R}});Object.defineProperty(exports,"emitAgentEvents",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.S}});Object.defineProperty(exports,"errorEventFor",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.W}});Object.defineProperty(exports,"extractLikelyFilePaths",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.d}});Object.defineProperty(exports,"extractPatchPaths",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.I}});Object.defineProperty(exports,"extractUnifiedDiff",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.H}});Object.defineProperty(exports,"goalForAgentPreset",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ha}});Object.defineProperty(exports,"inferUserLanguage",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.L}});Object.defineProperty(exports,"initialAgentState",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.a}});Object.defineProperty(exports,"invokeAction",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.aa}});Object.defineProperty(exports,"isAgentConfigApprovalMode",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.da}});Object.defineProperty(exports,"isAgentConfigLLMProvider",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ea}});Object.defineProperty(exports,"isAgentConfigMode",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ca}});Object.defineProperty(exports,"isAgentPreset",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ga}});Object.defineProperty(exports,"isRedactionEnabled",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.J}});Object.defineProperty(exports,"isTerminal",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.c}});Object.defineProperty(exports,"latestUnappliedPatch",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.C}});Object.defineProperty(exports,"loadNodeAgentConfig",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.pa}});Object.defineProperty(exports,"makeAutoDenyApprovals",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.la}});Object.defineProperty(exports,"makeConfiguredPermissions",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ia}});Object.defineProperty(exports,"makeFakeLLM",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.sa}});Object.defineProperty(exports,"makeGoogleGenerativeAILLM",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ra}});Object.defineProperty(exports,"makeNodeFileSystem",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.na}});Object.defineProperty(exports,"makeNodePatchService",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.oa}});Object.defineProperty(exports,"makeOpenAICompatibleLLM",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.qa}});Object.defineProperty(exports,"nextContextDiscoveryAction",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.h}});Object.defineProperty(exports,"nextProjectProbeAction",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.o}});Object.defineProperty(exports,"nextUnrunValidationCommand",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.t}});Object.defineProperty(exports,"nowMillis",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.Q}});Object.defineProperty(exports,"observationEventFor",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.X}});Object.defineProperty(exports,"observationStatus",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.V}});Object.defineProperty(exports,"parseProjectPackageJson",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.n}});Object.defineProperty(exports,"patchQualitySummary",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.w}});Object.defineProperty(exports,"patchRepairAttemptsUsed",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.v}});Object.defineProperty(exports,"patchValidationStatus",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.y}});Object.defineProperty(exports,"projectProfileProbePending",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.j}});Object.defineProperty(exports,"redactText",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.K}});Object.defineProperty(exports,"reduceAgentState",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.b}});Object.defineProperty(exports,"responseLanguageName",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.M}});Object.defineProperty(exports,"retry",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.Z}});Object.defineProperty(exports,"rollbackSafetySummary",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.A}});Object.defineProperty(exports,"runAgent",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.ba}});Object.defineProperty(exports,"runStatusFor",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.Y}});Object.defineProperty(exports,"shouldContinueRollbackStack",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.E}});Object.defineProperty(exports,"sleep",{enumerable:true,get:function(){return chunk63ODH5W4_cjs._}});Object.defineProperty(exports,"spanishLike",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.O}});Object.defineProperty(exports,"splitCommand",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.q}});Object.defineProperty(exports,"summarizeAgentAction",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.T}});Object.defineProperty(exports,"summarizeAgentObservation",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.U}});Object.defineProperty(exports,"summarizeContextDiscovery",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.g}});Object.defineProperty(exports,"timeout",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.$}});Object.defineProperty(exports,"unappliedPatchStack",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.B}});Object.defineProperty(exports,"workspaceValidationStatus",{enumerable:true,get:function(){return chunk63ODH5W4_cjs.F}});
1
+ 'use strict';var chunk6OUI6UGZ_cjs=require('../chunk-6OUI6UGZ.cjs');require('../chunk-K47BP5A2.cjs');Object.defineProperty(exports,"AGENT_CONFIG_FILE_NAMES",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.fa}});Object.defineProperty(exports,"NodeShell",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ma}});Object.defineProperty(exports,"PROJECT_LOCKFILE_PROBES",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.m}});Object.defineProperty(exports,"PROJECT_PROFILE_PROBES",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.i}});Object.defineProperty(exports,"autoApproveApprovals",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ka}});Object.defineProperty(exports,"canAutoRollback",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.D}});Object.defineProperty(exports,"canRequestPatchRepair",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.x}});Object.defineProperty(exports,"commandForScript",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.r}});Object.defineProperty(exports,"decideNextAction",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.P}});Object.defineProperty(exports,"defaultPermissions",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ja}});Object.defineProperty(exports,"deriveContextSearchQueries",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.e}});Object.defineProperty(exports,"describeCommandDiscovery",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.u}});Object.defineProperty(exports,"describeContextDiscovery",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.f}});Object.defineProperty(exports,"describeLanguagePolicy",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.N}});Object.defineProperty(exports,"describePatchQuality",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.z}});Object.defineProperty(exports,"describeProjectProfile",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.l}});Object.defineProperty(exports,"describeRollbackSafety",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.G}});Object.defineProperty(exports,"discoverNodeWorkspaceRoot",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ta}});Object.defineProperty(exports,"discoverPackageManager",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.p}});Object.defineProperty(exports,"discoverProjectProfile",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.k}});Object.defineProperty(exports,"discoverValidationCommands",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.s}});Object.defineProperty(exports,"emitAgentEvent",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.R}});Object.defineProperty(exports,"emitAgentEvents",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.S}});Object.defineProperty(exports,"errorEventFor",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.W}});Object.defineProperty(exports,"extractLikelyFilePaths",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.d}});Object.defineProperty(exports,"extractPatchPaths",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.I}});Object.defineProperty(exports,"extractUnifiedDiff",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.H}});Object.defineProperty(exports,"goalForAgentPreset",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ha}});Object.defineProperty(exports,"inferUserLanguage",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.L}});Object.defineProperty(exports,"initialAgentState",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.a}});Object.defineProperty(exports,"invokeAction",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.aa}});Object.defineProperty(exports,"isAgentConfigApprovalMode",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.da}});Object.defineProperty(exports,"isAgentConfigLLMProvider",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ea}});Object.defineProperty(exports,"isAgentConfigMode",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ca}});Object.defineProperty(exports,"isAgentPreset",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ga}});Object.defineProperty(exports,"isRedactionEnabled",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.J}});Object.defineProperty(exports,"isTerminal",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.c}});Object.defineProperty(exports,"latestUnappliedPatch",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.C}});Object.defineProperty(exports,"loadNodeAgentConfig",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.pa}});Object.defineProperty(exports,"makeAutoDenyApprovals",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.la}});Object.defineProperty(exports,"makeConfiguredPermissions",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ia}});Object.defineProperty(exports,"makeFakeLLM",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.sa}});Object.defineProperty(exports,"makeGoogleGenerativeAILLM",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ra}});Object.defineProperty(exports,"makeNodeFileSystem",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.na}});Object.defineProperty(exports,"makeNodePatchService",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.oa}});Object.defineProperty(exports,"makeOpenAICompatibleLLM",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.qa}});Object.defineProperty(exports,"nextContextDiscoveryAction",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.h}});Object.defineProperty(exports,"nextProjectProbeAction",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.o}});Object.defineProperty(exports,"nextUnrunValidationCommand",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.t}});Object.defineProperty(exports,"nowMillis",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.Q}});Object.defineProperty(exports,"observationEventFor",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.X}});Object.defineProperty(exports,"observationStatus",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.V}});Object.defineProperty(exports,"parseProjectPackageJson",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.n}});Object.defineProperty(exports,"patchQualitySummary",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.w}});Object.defineProperty(exports,"patchRepairAttemptsUsed",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.v}});Object.defineProperty(exports,"patchValidationStatus",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.y}});Object.defineProperty(exports,"projectProfileProbePending",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.j}});Object.defineProperty(exports,"redactText",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.K}});Object.defineProperty(exports,"reduceAgentState",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.b}});Object.defineProperty(exports,"responseLanguageName",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.M}});Object.defineProperty(exports,"retry",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.Z}});Object.defineProperty(exports,"rollbackSafetySummary",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.A}});Object.defineProperty(exports,"runAgent",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.ba}});Object.defineProperty(exports,"runStatusFor",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.Y}});Object.defineProperty(exports,"shouldContinueRollbackStack",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.E}});Object.defineProperty(exports,"sleep",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs._}});Object.defineProperty(exports,"spanishLike",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.O}});Object.defineProperty(exports,"splitCommand",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.q}});Object.defineProperty(exports,"summarizeAgentAction",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.T}});Object.defineProperty(exports,"summarizeAgentObservation",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.U}});Object.defineProperty(exports,"summarizeContextDiscovery",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.g}});Object.defineProperty(exports,"timeout",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.$}});Object.defineProperty(exports,"unappliedPatchStack",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.B}});Object.defineProperty(exports,"workspaceValidationStatus",{enumerable:true,get:function(){return chunk6OUI6UGZ_cjs.F}});
@@ -1,4 +1,4 @@
1
- import { A as Async, R as Runtime, S as Scope } from '../effect-NSaHksNl.mjs';
1
+ import { A as Async, a3 as Runtime, S as Scope } from '../effect-ISvXPLgc.mjs';
2
2
 
3
3
  type AgentMode = "read-only" | "propose" | "write" | "autonomous";
4
4
  type AgentPackageManager = "npm" | "pnpm" | "yarn" | "bun";
@@ -1,4 +1,4 @@
1
- import { A as Async, R as Runtime, S as Scope } from '../effect-NSaHksNl.js';
1
+ import { A as Async, a3 as Runtime, S as Scope } from '../effect-ISvXPLgc.js';
2
2
 
3
3
  type AgentMode = "read-only" | "propose" | "write" | "autonomous";
4
4
  type AgentPackageManager = "npm" | "pnpm" | "yarn" | "bun";
@@ -1 +1 @@
1
- export{fa as AGENT_CONFIG_FILE_NAMES,ma as NodeShell,m as PROJECT_LOCKFILE_PROBES,i as PROJECT_PROFILE_PROBES,ka as autoApproveApprovals,D as canAutoRollback,x as canRequestPatchRepair,r as commandForScript,P as decideNextAction,ja as defaultPermissions,e as deriveContextSearchQueries,u as describeCommandDiscovery,f as describeContextDiscovery,N as describeLanguagePolicy,z as describePatchQuality,l as describeProjectProfile,G as describeRollbackSafety,ta as discoverNodeWorkspaceRoot,p as discoverPackageManager,k as discoverProjectProfile,s as discoverValidationCommands,R as emitAgentEvent,S as emitAgentEvents,W as errorEventFor,d as extractLikelyFilePaths,I as extractPatchPaths,H as extractUnifiedDiff,ha as goalForAgentPreset,L as inferUserLanguage,a as initialAgentState,aa as invokeAction,da as isAgentConfigApprovalMode,ea as isAgentConfigLLMProvider,ca as isAgentConfigMode,ga as isAgentPreset,J as isRedactionEnabled,c as isTerminal,C as latestUnappliedPatch,pa as loadNodeAgentConfig,la as makeAutoDenyApprovals,ia as makeConfiguredPermissions,sa as makeFakeLLM,ra as makeGoogleGenerativeAILLM,na as makeNodeFileSystem,oa as makeNodePatchService,qa as makeOpenAICompatibleLLM,h as nextContextDiscoveryAction,o as nextProjectProbeAction,t as nextUnrunValidationCommand,Q as nowMillis,X as observationEventFor,V as observationStatus,n as parseProjectPackageJson,w as patchQualitySummary,v as patchRepairAttemptsUsed,y as patchValidationStatus,j as projectProfileProbePending,K as redactText,b as reduceAgentState,M as responseLanguageName,Z as retry,A as rollbackSafetySummary,ba as runAgent,Y as runStatusFor,E as shouldContinueRollbackStack,_ as sleep,O as spanishLike,q as splitCommand,T as summarizeAgentAction,U as summarizeAgentObservation,g as summarizeContextDiscovery,$ as timeout,B as unappliedPatchStack,F as workspaceValidationStatus}from'../chunk-P4IND5C3.js';import'../chunk-63MXGA7P.js';
1
+ export{fa as AGENT_CONFIG_FILE_NAMES,ma as NodeShell,m as PROJECT_LOCKFILE_PROBES,i as PROJECT_PROFILE_PROBES,ka as autoApproveApprovals,D as canAutoRollback,x as canRequestPatchRepair,r as commandForScript,P as decideNextAction,ja as defaultPermissions,e as deriveContextSearchQueries,u as describeCommandDiscovery,f as describeContextDiscovery,N as describeLanguagePolicy,z as describePatchQuality,l as describeProjectProfile,G as describeRollbackSafety,ta as discoverNodeWorkspaceRoot,p as discoverPackageManager,k as discoverProjectProfile,s as discoverValidationCommands,R as emitAgentEvent,S as emitAgentEvents,W as errorEventFor,d as extractLikelyFilePaths,I as extractPatchPaths,H as extractUnifiedDiff,ha as goalForAgentPreset,L as inferUserLanguage,a as initialAgentState,aa as invokeAction,da as isAgentConfigApprovalMode,ea as isAgentConfigLLMProvider,ca as isAgentConfigMode,ga as isAgentPreset,J as isRedactionEnabled,c as isTerminal,C as latestUnappliedPatch,pa as loadNodeAgentConfig,la as makeAutoDenyApprovals,ia as makeConfiguredPermissions,sa as makeFakeLLM,ra as makeGoogleGenerativeAILLM,na as makeNodeFileSystem,oa as makeNodePatchService,qa as makeOpenAICompatibleLLM,h as nextContextDiscoveryAction,o as nextProjectProbeAction,t as nextUnrunValidationCommand,Q as nowMillis,X as observationEventFor,V as observationStatus,n as parseProjectPackageJson,w as patchQualitySummary,v as patchRepairAttemptsUsed,y as patchValidationStatus,j as projectProfileProbePending,K as redactText,b as reduceAgentState,M as responseLanguageName,Z as retry,A as rollbackSafetySummary,ba as runAgent,Y as runStatusFor,E as shouldContinueRollbackStack,_ as sleep,O as spanishLike,q as splitCommand,T as summarizeAgentAction,U as summarizeAgentObservation,g as summarizeContextDiscovery,$ as timeout,B as unappliedPatchStack,F as workspaceValidationStatus}from'../chunk-W6TVAMYC.js';import'../chunk-LTHJNW5A.js';
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkT3QEEHK6_cjs=require('./chunk-T3QEEHK6.cjs'),fs=require('fs'),path=require('path');var Le=e=>({goal:e,phase:"boot",observations:[],errors:[],steps:0});var zt=(e,t)=>{switch(t.type){case "agent.done":return "done";case "agent.error":return e;case "fs.fileRead":case "fs.exists":case "fs.searchResult":return "discovering";case "shell.result":return "validating";case "llm.response":return "planning";case "patch.proposed":return "proposing";case "patch.applied":case "patch.rolledBack":return "validating"}},_e=(e,t)=>{let n=e.steps+1,r=n>=60?"failed":zt(e.phase,t);return {...e,phase:r,observations:[...e.observations,t],errors:t.type==="agent.error"?[...e.errors,t.error]:e.errors,steps:n}},Te=e=>e.phase==="done"||e.phase==="failed"||e.steps>=60;var Ut=["*.ts","*.tsx","*.js","*.jsx","*.mts","*.cts","*.mjs","*.cjs","*.json","*.md","*.yml","*.yaml"];var le=["tsx","jsx","mts","cts","mjs","cjs","json","yaml","html","scss","ts","js","md","yml","css"];[...le].sort((e,t)=>t.length-e.length).join("|");var Wt=new Set(["about","after","agent","because","before","brass","cannot","console","could","describe","error","expect","expected","exit","fail","failed","failing","failure","find","from","goal","have","into","name","node","only","package","please","process","repo","runtime","script","scripts","should","test","tests","that","this","throw","throws","undefined","using","with","previous","user","unrelated","validation","validacion","validaci\xF3n","discovered","remaining","rollback","rollbacks","strategy","proposed","request","relevant","context","summary","latest","patch","applied","configured","package","manager","commands","none","notes","usable","script","found","quality","loop","repairs","attempts","enabled","depth","workspace","inspect","inspection","diagnosis","diagnostic","diagn\xF3stico","plan","technology","stack","deployment","configuration","management","dependencies","observability","plugin","plugins","framework","serverless","commonjs","typescript","javascript","nodejs"]),ie=(e,t)=>e===void 0||!Number.isFinite(e)?t:Math.max(0,Math.floor(e)),H=e=>({enabled:e.goal.context?.enabled??true,maxSearchQueries:ie(e.goal.context?.maxSearchQueries,3),maxFiles:ie(e.goal.context?.maxFiles,4),maxSearchResults:ie(e.goal.context?.maxSearchResults,40),globs:e.goal.context?.globs??Ut,excludeGlobs:e.goal.context?.excludeGlobs??[]}),ce=e=>e.replace(/\\/g,"/"),De=e=>e.replace(/^(?:\.\/)+/,""),Qt=e=>e.replace(/(?:\d+){1,2}$/,""),Kt=new Set([" "," ",`
1
+ 'use strict';var chunkK47BP5A2_cjs=require('./chunk-K47BP5A2.cjs'),fs=require('fs'),path=require('path');var Le=e=>({goal:e,phase:"boot",observations:[],errors:[],steps:0});var zt=(e,t)=>{switch(t.type){case "agent.done":return "done";case "agent.error":return e;case "fs.fileRead":case "fs.exists":case "fs.searchResult":return "discovering";case "shell.result":return "validating";case "llm.response":return "planning";case "patch.proposed":return "proposing";case "patch.applied":case "patch.rolledBack":return "validating"}},_e=(e,t)=>{let n=e.steps+1,r=n>=60?"failed":zt(e.phase,t);return {...e,phase:r,observations:[...e.observations,t],errors:t.type==="agent.error"?[...e.errors,t.error]:e.errors,steps:n}},Te=e=>e.phase==="done"||e.phase==="failed"||e.steps>=60;var Ut=["*.ts","*.tsx","*.js","*.jsx","*.mts","*.cts","*.mjs","*.cjs","*.json","*.md","*.yml","*.yaml"];var le=["tsx","jsx","mts","cts","mjs","cjs","json","yaml","html","scss","ts","js","md","yml","css"];[...le].sort((e,t)=>t.length-e.length).join("|");var Wt=new Set(["about","after","agent","because","before","brass","cannot","console","could","describe","error","expect","expected","exit","fail","failed","failing","failure","find","from","goal","have","into","name","node","only","package","please","process","repo","runtime","script","scripts","should","test","tests","that","this","throw","throws","undefined","using","with","previous","user","unrelated","validation","validacion","validaci\xF3n","discovered","remaining","rollback","rollbacks","strategy","proposed","request","relevant","context","summary","latest","patch","applied","configured","package","manager","commands","none","notes","usable","script","found","quality","loop","repairs","attempts","enabled","depth","workspace","inspect","inspection","diagnosis","diagnostic","diagn\xF3stico","plan","technology","stack","deployment","configuration","management","dependencies","observability","plugin","plugins","framework","serverless","commonjs","typescript","javascript","nodejs"]),ie=(e,t)=>e===void 0||!Number.isFinite(e)?t:Math.max(0,Math.floor(e)),H=e=>({enabled:e.goal.context?.enabled??true,maxSearchQueries:ie(e.goal.context?.maxSearchQueries,3),maxFiles:ie(e.goal.context?.maxFiles,4),maxSearchResults:ie(e.goal.context?.maxSearchResults,40),globs:e.goal.context?.globs??Ut,excludeGlobs:e.goal.context?.excludeGlobs??[]}),ce=e=>e.replace(/\\/g,"/"),De=e=>e.replace(/^(?:\.\/)+/,""),Qt=e=>e.replace(/(?:\d+){1,2}$/,""),Kt=new Set([" "," ",`
2
2
  `,"\r","(","'",'"',"`","<","["]),Zt=new Set([" "," ",`
3
3
  `,"\r",")","'",'"',">",",","]"]),Ht=e=>{let t=0,n=e.length;for(;t<n&&Kt.has(e[t]);)t+=1;for(;n>t&&Zt.has(e[n-1]);)n-=1;return e.slice(t,n)},Jt=new Set(["Node.js","CommonJS.js","TypeScript.ts","JavaScript.js"]),Xt=e=>Jt.has(e),Yt=e=>e.split("/").some(n=>n==="node_modules"||n===".git"||n==="dist"||n==="build"||n==="coverage"||n===".next"||n===".turbo"||n===".cache"),en=e=>le.some(t=>e.toLowerCase().endsWith(`.${t}`)),Ne=(e,t)=>{let n=ce(e).replace(/\/+$/,""),r=Qt(Ht(ce(t.trim())));if(r.startsWith("file://")&&(r=r.slice(7)),r.startsWith(`${n}/`)&&(r=r.slice(n.length+1)),r!==n&&(r=De(r),!(!r||r.startsWith("/")||/^[A-Za-z]:\//.test(r))&&!(r.includes("\0")||r.split("/").includes(".."))&&!Xt(r)&&!Yt(r)&&en(r)))return r},tn=e=>{let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"::DOUBLE_STAR::").replace(/\*/g,"[^/]*").replace(/::DOUBLE_STAR::/g,".*");return new RegExp(`^${t}$`)},Ie=(e,t)=>t.some(n=>tn(De(ce(n))).test(e)),nn=e=>[...e.globs,...e.excludeGlobs.map(t=>`!${t}`)],_=e=>{let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n},rn=e=>e.observations.filter(t=>t.type==="shell.result").map(t=>[t.command.join(" "),t.stdout.slice(-12e3),t.stderr.slice(-12e3)].join(`
4
4
  `)).join(`
@@ -18,8 +18,8 @@ ${dt(e).join(`
18
18
  `)}`:"Failed validation after latest patch: none recorded.","",o?._tag==="PatchError"?`Latest patch error during ${o.operation}: ${String(o.cause)}`:"Latest patch error: none.","","Recent observations:",yt(e)||"No observations yet."].join(`
19
19
  `))},N=e=>e==="write"||e==="autonomous",dr=e=>{let t=we(e).filter(a=>a.type==="shell.result");if(t.length===0)return;let n=V(e),r=te(e.goal),o=n?.type==="patch.rolledBack"?"rollback":r?"aplicar patch":"apply";return [r?`Validaci\xF3n despu\xE9s de ${o}:`:`Validation after latest ${o}:`,...t.map(a=>`- ${a.command.join(" ")} ${r?"termin\xF3 con c\xF3digo":"exited with"} ${a.exitCode}.`)].join(`
20
20
  `)},ut=(e,t)=>{let n=or(e,"llm.response")?.content?.trim()??"No plan was generated.",r=D(e,"llm.response"),o=D(e,"patch.applied"),a=D(e,"patch.rolledBack"),l=D(e,"patch.proposed"),s=dr(e),p=te(e.goal),d=[n];return r?.purpose==="patch"&&r.content.trim()&&d.push("",p?"\xDAltima respuesta de reparaci\xF3n del patch:":"Latest patch repair response:",r.content.trim()),a?d.push("",p?`Patch revertido en: ${a.changedFiles.join(", ")||"(sin archivos reportados)"}`:`Patch rolled back for: ${a.changedFiles.join(", ")||"(no files reported)"}`):o?d.push("",p?`Patch aplicado en: ${o.changedFiles.join(", ")||"(sin archivos reportados)"}`:`Patch applied to: ${o.changedFiles.join(", ")||"(no files reported)"}`):l?d.push("",p?"Patch propuesto, pero no aplicado en este modo.":"Patch extracted and proposed, but not applied in this mode."):t&&d.push("",p?"Hab\xEDa un diff con forma de patch, pero no se materializ\xF3 como observaci\xF3n.":"A patch-shaped diff was present, but it was not materialized as an observation."),s&&d.push("",s),z(e,d.join(`
21
- `).trim())},ur=e=>{let t=D(e,"agent.error")?.error,n=te(e.goal);if(!t)return n?"La ejecuci\xF3n del agente fall\xF3.":"Agent run failed.";switch(t._tag){case "FsError":return n?`El agente se detuvo por un error de filesystem durante ${t.operation}: ${R(e,t.cause)}`:`Agent stopped after a filesystem error during ${t.operation}: ${R(e,t.cause)}`;case "ShellError":return n?`El agente se detuvo por un error ejecutando ${t.command?.join(" ")??t.operation}: ${R(e,t.cause)}`:`Agent stopped after a shell error during ${t.command?.join(" ")??t.operation}: ${R(e,t.cause)}`;case "LLMError":return n?`El agente se detuvo porque fall\xF3 la llamada al modelo: ${R(e,t.cause)}`:`Agent stopped because the model call failed: ${R(e,t.cause)}`;case "PatchError":return n?`El agente se detuvo por un error de patch durante ${t.operation}: ${R(e,t.cause)}`:`Agent stopped after a patch error during ${t.operation}: ${R(e,t.cause)}`;case "PermissionDenied":return n?`El agente se detuvo porque una acci\xF3n fue denegada por policy: ${t.reason}`:`Agent stopped because an action was denied by policy: ${t.reason}`;case "ApprovalRejected":return n?`El agente se detuvo porque se rechaz\xF3 una aprobaci\xF3n: ${t.reason}`:`Agent stopped because an approval was rejected: ${t.reason}`;case "ToolTimeout":return n?`El agente se detuvo porque una tool tard\xF3 m\xE1s de ${t.timeoutMs}ms.`:`Agent stopped because a tool timed out after ${t.timeoutMs}ms.`;case "PathOutsideWorkspace":return n?`El agente bloque\xF3 un path fuera del workspace: ${t.path}`:`Agent blocked a path outside the workspace: ${t.path}`;case "AgentLoopError":return n?`El agente se detuvo por un error del loop: ${t.message}`:`Agent stopped after an agent loop error: ${t.message}`}},gr=e=>{if(e.goal.mode==="read-only")return;let t=P(e).validationCommands,n=X(t,ar(e));return n?{type:"shell.exec",command:n}:void 0},mr=e=>{let t=P(e).validationCommands,n=X(t,Ee(e));return n?{type:"shell.exec",command:n}:void 0},ht=e=>{let t=P(e).validationCommands,n=X(t,we(e));return n?{type:"shell.exec",command:n}:void 0},fr=e=>{for(let t=e.observations.length-1;t>=0;t-=1){let n=e.observations[t];if(!n||n.type!=="llm.response")continue;let r=M(n.content);if(!r)continue;return e.observations.slice(t+1).some(a=>a.type==="patch.applied"||a.type==="patch.proposed")?void 0:{index:t,patch:r}}},yr=e=>{for(let t=e.observations.length-1;t>=0;t-=1){let n=e.observations[t];if(n?.type!=="llm.response")continue;let r=M(n.content);if(r)return r}},hr=e=>{for(let t=e.observations.length-1;t>=0;t-=1){let n=e.observations[t];if(n?.type==="patch.proposed")return n.patch;if(n?.type==="patch.applied"){if(n.patch)return n.patch;let r=e.observations.slice(0,t).reverse().find(o=>o.type==="llm.response"&&!!M(o.content));return r?M(r.content):e.goal.initialPatch}}},Ar=e=>{if(!N(e.goal.mode)||V(e)?.type!=="patch.applied"||!ee(e))return false;let t=P(e).validationCommands;return tt(t,Ee(e)).type==="failed"},br=e=>{if(!N(e.goal.mode)||V(e)?.type!=="patch.applied"||ee(e)||!O(e).onFinalValidationFailure||!ke(e))return false;let n=P(e).validationCommands;return at(n,we(e)).type==="failed"},kr=e=>{if(!N(e.goal.mode)||!ee(e))return false;let t=e.observations.at(-1);return t?.type==="agent.error"&&t.error._tag==="PatchError"},gt=(e,t)=>({type:"llm.complete",purpose:"patch",prompt:pr(e,t)}),mt=(e,t)=>{let n=rt(e);if(n)return {type:"patch.rollback",patch:n.patch,automatic:true,reason:t}},xr=(e,t)=>{if(N(e.goal.mode))return e.goal.initialPatchMode==="rollback"?ne(e,"patch.rolledBack")?void 0:{type:"patch.rollback",patch:t}:ne(e,"patch.applied")?ht(e):{type:"patch.apply",patch:t};if(e.goal.mode==="propose"&&!ne(e,"patch.proposed"))return {type:"patch.propose",patch:t}},At=e=>{if(e.observations.at(-1)?.type==="agent.error")return kr(e)?chunkT3QEEHK6_cjs.f(gt(e,"previous patch failed to apply")):chunkT3QEEHK6_cjs.f({type:"agent.finish",summary:ur(e)});if(!ne(e,"fs.fileRead"))return chunkT3QEEHK6_cjs.f({type:"fs.readFile",path:"package.json"});let n=Ye(e);if(n)return chunkT3QEEHK6_cjs.f(n);let r=e.goal.initialPatch?.trim();if(r){let s=xr(e,r);return s?chunkT3QEEHK6_cjs.f(s):chunkT3QEEHK6_cjs.f({type:"agent.finish",summary:ut(e,r)})}let o=fr(e);if(o){if(N(e.goal.mode))return chunkT3QEEHK6_cjs.f({type:"patch.apply",patch:o.patch});if(e.goal.mode==="propose")return chunkT3QEEHK6_cjs.f({type:"patch.propose",patch:o.patch})}if(!e.observations.find(s=>s.type==="llm.response"&&s.purpose==="plan")){let s=gr(e);if(s)return chunkT3QEEHK6_cjs.f(s);let p=We(e);return p?chunkT3QEEHK6_cjs.f(p):chunkT3QEEHK6_cjs.f({type:"llm.complete",purpose:"plan",prompt:lr(e)})}if(N(e.goal.mode)){if(ot(e)){let s=mt(e,"continuing rollback of generated patch stack");if(s)return chunkT3QEEHK6_cjs.f(s)}if(V(e)?.type==="patch.rolledBack"&&O(e).runValidationAfterRollback){let p=ht(e);if(p)return chunkT3QEEHK6_cjs.f(p)}if(V(e)?.type==="patch.applied"){let s=mr(e);if(s)return chunkT3QEEHK6_cjs.f(s);if(Ar(e))return chunkT3QEEHK6_cjs.f(gt(e,"validation failed after applying the generated patch"));if(br(e)){let p=mt(e,"validation failed after generated patches and no repair attempts remain");if(p)return chunkT3QEEHK6_cjs.f(p)}}}let l=yr(e);return chunkT3QEEHK6_cjs.f({type:"agent.finish",summary:ut(e,l)})};var v=()=>chunkT3QEEHK6_cjs.j((e,t)=>{t({_tag:"Success",value:Date.now()});}),E=e=>chunkT3QEEHK6_cjs.j((t,n)=>{try{t.events?.emit(e);}catch{}n({_tag:"Success",value:void 0});}),Pe=e=>e.reduce((t,n)=>chunkT3QEEHK6_cjs.l(t,()=>E(n)),chunkT3QEEHK6_cjs.f(void 0)),_o=e=>{switch(e.type){case "fs.readFile":return `read ${e.path}`;case "fs.exists":return `check ${e.path}`;case "fs.searchText":return `search "${e.query}"`;case "shell.exec":return e.command.join(" ");case "llm.complete":return `llm.${e.purpose}`;case "patch.propose":return "propose patch";case "patch.apply":return "apply patch";case "patch.rollback":return "rollback patch";case "agent.finish":return "finish";case "agent.fail":return "fail"}},To=e=>{switch(e.type){case "fs.fileRead":return `read ${e.path}`;case "fs.exists":return `${e.exists?"found":"missing"} ${e.path}`;case "fs.searchResult":return `search "${e.query}" (${e.matches.length} matches)`;case "shell.result":return `${e.command.join(" ")} exited ${e.exitCode}`;case "llm.response":return `llm.${e.purpose} responded`;case "patch.proposed":return "patch proposed";case "patch.applied":return `patch applied (${e.changedFiles.join(", ")||"no files reported"})`;case "patch.rolledBack":return `patch rolled back (${e.changedFiles.join(", ")||"no files reported"})`;case "agent.done":return "done";case "agent.error":return `error ${e.error._tag}`}},Oo=e=>{switch(e.type){case "agent.error":return "fail";case "shell.result":return e.exitCode===0?"ok":"warn";default:return "ok"}},bt=(e,t,n,r)=>{switch(n._tag){case "ToolTimeout":return {type:"agent.tool.timeout",action:e,step:t.steps+1,phase:t.phase,timeoutMs:n.timeoutMs,at:r};case "PermissionDenied":return {type:"agent.permission.denied",action:e,step:t.steps+1,phase:t.phase,reason:n.reason,at:r};default:return}},kt=(e,t,n)=>{switch(t.type){case "patch.applied":return {type:"agent.patch.applied",step:e.steps,phase:e.phase,changedFiles:t.changedFiles,automaticRollbackEligible:!!t.patch,at:n};case "patch.rolledBack":return {type:"agent.patch.rolledBack",step:e.steps,phase:e.phase,changedFiles:t.changedFiles,...t.automatic!==void 0?{automatic:t.automatic}:{},...t.reason?{reason:t.reason}:{},at:n};default:return}},xt=e=>e==="done"?"done":"failed";var x=e=>chunkT3QEEHK6_cjs.h(t=>t[e]);var Sr=e=>e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e),vr=e=>{let t=e.length;for(;t>0;){let n=e.charCodeAt(t-1);if(n!==47&&n!==92)break;t-=1;}return t===e.length?e:e.slice(0,t)},Er=e=>e.replace(/^(?:\.[\\/])+/,""),wr=e=>{let t=e.trim();if(!(!t||t.includes("\0")||Sr(t)||t.split(/[\\/]+/).includes("..")))return Er(t)};var U=(e,t)=>{let n=wr(t);return n?chunkT3QEEHK6_cjs.f(`${vr(e)}/${n}`):chunkT3QEEHK6_cjs.g({_tag:"PathOutsideWorkspace",path:t,cwd:e})};var St=(e,t)=>{switch(e.type){case "fs.readFile":return chunkT3QEEHK6_cjs.l(U(t.goal.cwd,e.path),n=>chunkT3QEEHK6_cjs.l(x("fs"),r=>chunkT3QEEHK6_cjs.k(r.readFile(n),o=>({type:"fs.fileRead",path:e.path,content:o}))));case "fs.exists":return chunkT3QEEHK6_cjs.l(U(t.goal.cwd,e.path),n=>chunkT3QEEHK6_cjs.l(x("fs"),r=>chunkT3QEEHK6_cjs.k(r.exists(n),o=>({type:"fs.exists",path:e.path,exists:o}))));case "fs.searchText":return chunkT3QEEHK6_cjs.l(x("fs"),n=>chunkT3QEEHK6_cjs.k(n.searchText(t.goal.cwd,e.query,{globs:e.globs}),r=>({type:"fs.searchResult",query:e.query,matches:r})));case "shell.exec":return chunkT3QEEHK6_cjs.l(x("shell"),n=>chunkT3QEEHK6_cjs.k(n.exec(e.command,{cwd:e.cwd??t.goal.cwd}),r=>({type:"shell.result",command:e.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr})));case "llm.complete":return chunkT3QEEHK6_cjs.l(x("llm"),n=>chunkT3QEEHK6_cjs.k(n.complete({purpose:e.purpose,prompt:e.prompt}),r=>({type:"llm.response",purpose:e.purpose,content:r.content})));case "patch.propose":return chunkT3QEEHK6_cjs.f({type:"patch.proposed",patch:e.patch});case "patch.apply":return chunkT3QEEHK6_cjs.l(x("patch"),n=>chunkT3QEEHK6_cjs.k(n.apply(t.goal.cwd,e.patch),r=>({type:"patch.applied",changedFiles:r.changedFiles,patch:e.patch})));case "patch.rollback":return chunkT3QEEHK6_cjs.l(x("patch"),n=>chunkT3QEEHK6_cjs.k(n.rollback(t.goal.cwd,e.patch),r=>({type:"patch.rolledBack",changedFiles:r.changedFiles,patch:e.patch,...e.automatic!==void 0?{automatic:e.automatic}:{},...e.reason?{reason:e.reason}:{}})));case "agent.finish":return chunkT3QEEHK6_cjs.f({type:"agent.done",summary:e.summary});case "agent.fail":return chunkT3QEEHK6_cjs.g({_tag:"AgentLoopError",message:e.reason})}};var vt=(e,t)=>{let n=r=>chunkT3QEEHK6_cjs.b(e(),o=>r>0&&t.while(o)?n(r-1):chunkT3QEEHK6_cjs.g(o),o=>chunkT3QEEHK6_cjs.f(o));return n(t.times)};var Pr=e=>chunkT3QEEHK6_cjs.j((t,n)=>{let r=setTimeout(()=>n({_tag:"Success",value:void 0}),e);return ()=>clearTimeout(r)}),Et=(e,t,n)=>chunkT3QEEHK6_cjs.V(e,chunkT3QEEHK6_cjs.l(Pr(t),()=>chunkT3QEEHK6_cjs.g({_tag:"ToolTimeout",timeoutMs:t})),n);var wt=e=>e._tag==="LLMError"||e._tag==="ToolTimeout",Rr=e=>{switch(e.type){case "fs.readFile":case "fs.exists":case "fs.searchText":return {timeoutMs:5e3,retries:1,retryable:wt};case "llm.complete":return {timeoutMs:6e4,retries:2,retryable:wt};case "shell.exec":return {timeoutMs:12e4,retries:0,retryable:()=>false};case "patch.propose":case "agent.finish":case "agent.fail":return {timeoutMs:1e3,retries:0,retryable:()=>false};case "patch.apply":case "patch.rollback":return {timeoutMs:15e3,retries:0,retryable:()=>false}}},Cr=(e,t)=>{let n=Rr(e),r=t?.[e.type];return {...n,timeoutMs:r?.timeoutMs!==void 0?Math.max(1,Math.floor(r.timeoutMs)):n.timeoutMs,retries:r?.retries!==void 0?Math.max(0,Math.floor(r.retries)):n.retries}},Pt=(e,t,n)=>chunkT3QEEHK6_cjs.l(chunkT3QEEHK6_cjs.h(r=>r.toolPolicies),r=>{let o=Cr(e,r);return vt(()=>Et(St(e,t),o.timeoutMs,n),{times:o.retries,while:o.retryable})}),Rt=(e,t)=>({_tag:"ApprovalRejected",action:e,reason:t}),Re=(e,t,n,r)=>chunkT3QEEHK6_cjs.l(v(),o=>E({type:"agent.approval.resolved",action:e,step:t.steps+1,phase:t.phase,approved:n,...r?{reason:r}:{},at:o})),jr=(e,t,n)=>{let r=n.defaultAnswer??"reject";return chunkT3QEEHK6_cjs.l(v(),o=>chunkT3QEEHK6_cjs.l(E({type:"agent.approval.requested",action:e,step:t.steps+1,phase:t.phase,reason:n.reason,risk:n.risk,defaultAnswer:r,at:o}),()=>chunkT3QEEHK6_cjs.l(x("approvals"),a=>{if(!a){let l="No approval service configured.";return chunkT3QEEHK6_cjs.l(Re(e,t,false,l),()=>chunkT3QEEHK6_cjs.g(Rt(e,l)))}return chunkT3QEEHK6_cjs.l(a.request({action:e,state:t,reason:n.reason,risk:n.risk,defaultAnswer:r}),l=>{if(l.type==="approved")return chunkT3QEEHK6_cjs.l(Re(e,t,true,void 0),()=>chunkT3QEEHK6_cjs.f(void 0));let s=l.reason??"Approval rejected.";return chunkT3QEEHK6_cjs.l(Re(e,t,false,s),()=>chunkT3QEEHK6_cjs.g(Rt(e,s)))})})))},Ct=(e,t,n)=>chunkT3QEEHK6_cjs.l(x("permissions"),r=>chunkT3QEEHK6_cjs.l(r.check(e,t),o=>o.type==="deny"?chunkT3QEEHK6_cjs.g({_tag:"PermissionDenied",action:e,reason:o.reason}):o.type==="ask"?chunkT3QEEHK6_cjs.l(jr(e,t,o),()=>Pt(e,t,n)):Pt(e,t,n)));var $r=(e,t,n)=>chunkT3QEEHK6_cjs.l(v(),r=>chunkT3QEEHK6_cjs.l(E({type:"agent.action.started",action:e,step:t.steps+1,phase:t.phase,at:r}),()=>chunkT3QEEHK6_cjs.b(Ct(e,t,n),o=>chunkT3QEEHK6_cjs.l(v(),a=>{let l=bt(e,t,o,a),s=[...l?[l]:[],{type:"agent.action.failed",action:e,error:o,step:t.steps+1,phase:t.phase,durationMs:a-r,at:a}];return chunkT3QEEHK6_cjs.l(Pe(s),()=>chunkT3QEEHK6_cjs.f({type:"agent.error",error:o}))}),o=>chunkT3QEEHK6_cjs.l(v(),a=>chunkT3QEEHK6_cjs.l(E({type:"agent.action.completed",action:e,observation:o,step:t.steps+1,phase:t.phase,durationMs:a-r,at:a}),()=>chunkT3QEEHK6_cjs.f(o)))))),Fr=(e,t)=>chunkT3QEEHK6_cjs.l(v(),n=>{let r=kt(e,t,n),o=[{type:"agent.observation.recorded",observation:t,step:e.steps,phase:e.phase,at:n},...r?[r]:[]];return Pe(o)}),jt=(e,t,n)=>Te(e)?chunkT3QEEHK6_cjs.l(v(),r=>chunkT3QEEHK6_cjs.l(E({type:"agent.run.completed",goal:e.goal,status:xt(e.phase),phase:e.phase,steps:e.steps,durationMs:r-n,at:r}),()=>chunkT3QEEHK6_cjs.f(e))):chunkT3QEEHK6_cjs.l(At(e),r=>chunkT3QEEHK6_cjs.l($r(r,e,t),o=>{let a=_e(e,o);return chunkT3QEEHK6_cjs.l(Fr(a,o),()=>jt(a,t,n))})),da=(e,t)=>chunkT3QEEHK6_cjs.T(e,n=>chunkT3QEEHK6_cjs.l(v(),r=>chunkT3QEEHK6_cjs.l(E({type:"agent.run.started",goal:t,at:r}),()=>jt(Le(t),n,r))));var Ce=e=>e==="read-only"||e==="propose"||e==="write"||e==="autonomous",$t=e=>e==="auto"||e==="interactive"||e==="approve"||e==="deny",Ft=e=>e==="fake"||e==="google"||e==="gemini"||e==="openai"||e==="openai-compatible",Mt=[".brass-agent.json","brass-agent.config.json"];var Lt=e=>e==="fix-tests"||e==="inspect"||e==="typecheck"||e==="lint",ma=e=>{switch(e){case "fix-tests":return "fix the failing tests";case "inspect":return "inspect this workspace and summarize the current project state";case "typecheck":return "run typecheck discovery and fix type errors if possible";case "lint":return "run lint discovery and fix lint errors if possible"}};var Mr=["npm test","npm run test*","npm run typecheck","npm run type-check","npm run check-types","npm run tsc","npm run check","npm run *check*","npm run *doctor*","npm run *health*","npm run *verify*","npm run *validate*","npm run repo:check","npm run lint*","pnpm test","pnpm run test*","pnpm run typecheck","pnpm run type-check","pnpm run check-types","pnpm run tsc","pnpm run check","pnpm run *check*","pnpm run *doctor*","pnpm run *health*","pnpm run *verify*","pnpm run *validate*","pnpm run repo:check","pnpm run lint*","yarn test","yarn run test*","yarn run typecheck","yarn run type-check","yarn run check-types","yarn run tsc","yarn run check","yarn run *check*","yarn run *doctor*","yarn run *health*","yarn run *verify*","yarn run *validate*","yarn run repo:check","yarn run lint*","bun run test*","bun run typecheck","bun run type-check","bun run check-types","bun run tsc","bun run check","bun run *check*","bun run *doctor*","bun run *health*","bun run *verify*","bun run *validate*","bun run repo:check","bun run lint*","cargo check","cargo test","cargo fmt --check","cargo clippy","cargo clippy *","git status","git diff","git log"],Ot=e=>e.trim().replace(/\s+/g," "),re=e=>Ot(e.join(" ")),Lr=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Dt=(e,t)=>{let n=re(e),r=Ot(t);return r.includes("*")?new RegExp(`^${r.split("*").map(Lr).join(".*")}$`).test(n):n===r},_t=(e,t)=>!!t?.some(n=>Dt(e,n)),I=()=>({type:"allow"}),G=e=>({type:"deny",reason:e}),W=(e,t,n="reject")=>({type:"ask",reason:e,risk:t,defaultAnswer:n}),_r=e=>e.type==="shell.exec"?e.command.join(" "):e.type,Tr=e=>typeof e=="string"?e:e.pattern,Or=(e,t)=>{let n=t?.find(r=>Dt(e,Tr(r)));if(n)return typeof n=="string"?W(`Run command: ${re(e)}`,"high","reject"):W(n.reason??`Run command: ${re(e)}`,n.risk??"high",n.defaultAnswer??"reject")},Dr=e=>[...e?.inheritDefaults===false?[]:Mr,...e?.allow??[]],je=(e,t)=>{if(_t(e,t?.deny))return G(`Command denied by policy: ${re(e)}`);let n=Or(e,t?.ask);if(n)return n;if(_t(e,Dr(t)))return I()},Nr=e=>e.type==="patch.rollback"?"Reverse-apply a patch to restore the workspace.":"Apply the proposed patch to the workspace.",Tt=(e,t)=>{let n=Nr(e);if(!t)return W(n,"high","reject");let r=typeof t=="string"?t:t.decision??"ask",o=typeof t=="string"?n:t.reason??n,a=typeof t=="string"?"high":t.risk??"high",l=typeof t=="string"?"reject":t.defaultAnswer??"reject";return r==="allow"?I():r==="deny"?G(o):W(o,a,l)},Ir=(e={})=>({check:(t,n)=>{switch(n.goal.mode){case "read-only":return t.type==="fs.readFile"||t.type==="fs.exists"||t.type==="fs.searchText"||t.type==="llm.complete"||t.type==="agent.finish"||t.type==="agent.fail"?chunkT3QEEHK6_cjs.f(I()):chunkT3QEEHK6_cjs.f(G(`Action ${t.type} is not allowed in read-only mode`));case "propose":{if(t.type==="shell.exec"){let r=je(t.command,e.shell);return chunkT3QEEHK6_cjs.f(r??G(`Command not whitelisted: ${t.command.join(" ")}`))}return t.type==="patch.apply"||t.type==="patch.rollback"?chunkT3QEEHK6_cjs.f(G(`${t.type} is not allowed in propose mode; use write mode or --apply.`)):chunkT3QEEHK6_cjs.f(I())}case "write":{if(t.type==="shell.exec"){let r=je(t.command,e.shell);return chunkT3QEEHK6_cjs.f(r??G(`Command not whitelisted: ${t.command.join(" ")}`))}return t.type==="patch.apply"||t.type==="patch.rollback"?chunkT3QEEHK6_cjs.f(Tt(t,e.patchApply)):chunkT3QEEHK6_cjs.f(I())}case "autonomous":{if(t.type==="patch.apply"||t.type==="patch.rollback")return chunkT3QEEHK6_cjs.f(Tt(t,e.patchApply));if(t.type==="shell.exec"){let r=je(t.command,e.shell);return chunkT3QEEHK6_cjs.f(r??W(`Run non-whitelisted command: ${_r(t)}`,"high","reject"))}return chunkT3QEEHK6_cjs.f(I())}}}}),ha=Ir();var ka={request:()=>chunkT3QEEHK6_cjs.f({type:"approved"})},xa=(e="Approval denied by non-interactive policy.")=>({request:()=>chunkT3QEEHK6_cjs.f({type:"rejected",reason:e})});var Gr=new Function("specifier","return import(specifier)"),Nt=e=>{let t=e?.toString;return typeof t=="function"?t.call(e,"utf8"):String(e)},wa={exec:(e,t)=>chunkT3QEEHK6_cjs.j((n,r)=>{let[o,...a]=e;if(!o){r(chunkT3QEEHK6_cjs.u.failCause(chunkT3QEEHK6_cjs.t.fail({_tag:"ShellError",operation:"exec",command:e,cause:new Error("Empty command")})));return}let l="",s="",p=false,d;return Gr("node:child_process").then(({spawn:C})=>{p||(d=C(o,a,{cwd:t.cwd,shell:false,stdio:["pipe","pipe","pipe"]}),d.stdout?.on("data",f=>{l+=Nt(f);}),d.stderr?.on("data",f=>{s+=Nt(f);}),d.on("error",f=>{p||(p=true,r(chunkT3QEEHK6_cjs.u.failCause(chunkT3QEEHK6_cjs.t.fail({_tag:"ShellError",operation:"exec",command:e,cause:f}))));}),d.on("close",f=>{p||(p=true,r(chunkT3QEEHK6_cjs.u.succeed({exitCode:f??1,stdout:l,stderr:s})));}),t.stdin!==void 0?d.stdin?.end(t.stdin):d.stdin?.end());}).catch(C=>{p||(p=true,r(chunkT3QEEHK6_cjs.u.failCause(chunkT3QEEHK6_cjs.t.fail({_tag:"ShellError",operation:"exec",command:e,cause:C}))));}),()=>{p||(p=true,d?.kill?.("SIGTERM"));}})};var It=new Function("specifier","return import(specifier)"),qr=e=>e.split(`
22
- `).filter(Boolean).map(t=>{let[n="",r="0",...o]=t.split(":");return {path:n,line:Number(r),text:o.join(":")}}),ja=e=>({readFile:t=>chunkT3QEEHK6_cjs.Q(async n=>{let{readFile:r}=await It("node:fs/promises");return r(t,{encoding:"utf8",signal:n})},n=>({_tag:"FsError",operation:"readFile",cause:n})),exists:t=>chunkT3QEEHK6_cjs.Q(async n=>{if(n.aborted)return false;let{stat:r}=await It("node:fs/promises");if(n.aborted)return false;try{return await r(t),!0}catch{return false}},n=>({_tag:"FsError",operation:"exists",cause:n})),searchText:(t,n,r)=>chunkT3QEEHK6_cjs.l(e.exec(["rg","--fixed-strings","--line-number","--no-heading","--color","never","--max-count","5",...r?.globs?.flatMap(o=>["--glob",o])??[],"--",n,"."],{cwd:t}),o=>o.exitCode>1?chunkT3QEEHK6_cjs.g({_tag:"FsError",operation:"searchText",cause:o.stderr}):chunkT3QEEHK6_cjs.f(qr(o.stdout)))});var Br=(e,t)=>t.reduce((n,r)=>chunkT3QEEHK6_cjs.l(n,o=>chunkT3QEEHK6_cjs.l(U(e,r),()=>chunkT3QEEHK6_cjs.f([...o,r]))),chunkT3QEEHK6_cjs.f([])),$e=(e,t,n)=>({_tag:"PatchError",operation:e,cause:t,patch:n}),_a=e=>{let t=(n,r,o)=>{let a=M(r)??r.trim(),l=it(a),s=`${a.trim()}
23
- `,p=o?"rollback":"apply";if(!a||!l.length)return chunkT3QEEHK6_cjs.g($e("extract","No unified diff with workspace-scoped paths was found.",r));let d=["git","apply",...o?["--reverse"]:[],"--recount","--whitespace=nowarn","-"],C=["git","apply",...o?["--reverse"]:[],"--check","--recount","--whitespace=nowarn","-"];return chunkT3QEEHK6_cjs.l(Br(n,l),()=>chunkT3QEEHK6_cjs.l(e.exec(C,{cwd:n,stdin:s}),f=>f.exitCode!==0?chunkT3QEEHK6_cjs.g($e(`${p}.check`,f.stderr||f.stdout||`git apply --check exited with ${f.exitCode}`,a)):chunkT3QEEHK6_cjs.l(e.exec(d,{cwd:n,stdin:s}),k=>k.exitCode!==0?chunkT3QEEHK6_cjs.g($e(p,k.stderr||k.stdout||`git apply exited with ${k.exitCode}`,a)):chunkT3QEEHK6_cjs.f({changedFiles:l}))))};return {apply:(n,r)=>t(n,r,false),rollback:(n,r)=>t(n,r,true)}};var oe=new Function("specifier","return import(specifier)"),y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),L=(e,t)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(n=>typeof n!="string")))throw new Error(`${t} must be an array of strings.`)},b=(e,t)=>{if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)))throw new Error(`${t} must be a finite number.`)},S=(e,t)=>{if(e!==void 0&&typeof e!="boolean")throw new Error(`${t} must be a boolean.`)},h=(e,t)=>{if(e!==void 0&&typeof e!="string")throw new Error(`${t} must be a string.`)},Vr=(e,t)=>{if(typeof e!="string"){if(!y(e))throw new Error(`${t} must be a string or object.`);if(h(e.goal,`${t}.goal`),h(e.cwd,`${t}.cwd`),h(e.patchFile,`${t}.patchFile`),h(e.saveRunDir,`${t}.saveRunDir`),e.preset!==void 0&&(typeof e.preset!="string"||!Lt(e.preset)))throw new Error(`${t}.preset must be one of: fix-tests, inspect, typecheck, lint.`);if(e.mode!==void 0&&(typeof e.mode!="string"||!Ce(e.mode)))throw new Error(`${t}.mode must be one of: read-only, propose, write, autonomous.`);if(e.patchFileMode!==void 0&&e.patchFileMode!=="apply"&&e.patchFileMode!=="rollback")throw new Error(`${t}.patchFileMode must be apply or rollback.`);if(e.goal===void 0&&e.preset===void 0&&e.patchFile===void 0)throw new Error(`${t} must include goal, preset, or patchFile.`)}},zr=(e,t)=>{if(!y(e))throw new Error(`Agent config at ${t} must be a JSON object.`);if(e.mode!==void 0&&(typeof e.mode!="string"||!Ce(e.mode)))throw new Error("config.mode must be one of: read-only, propose, write, autonomous.");if(e.approval!==void 0&&(typeof e.approval!="string"||!$t(e.approval)))throw new Error("config.approval must be one of: auto, interactive, approve, deny.");if(e.llm!==void 0){if(!y(e.llm))throw new Error("config.llm must be an object.");if(e.llm.provider!==void 0&&(typeof e.llm.provider!="string"||!Ft(e.llm.provider)))throw new Error("config.llm.provider must be one of: fake, google, gemini, openai, openai-compatible.");if("apiKey"in e.llm)throw new Error("config.llm.apiKey is not supported. Store secrets in environment variables and use config.llm.apiKeyEnv instead.");h(e.llm.model,"config.llm.model"),h(e.llm.endpoint,"config.llm.endpoint"),h(e.llm.baseUrl,"config.llm.baseUrl"),h(e.llm.apiVersion,"config.llm.apiVersion"),h(e.llm.apiKeyEnv,"config.llm.apiKeyEnv"),h(e.llm.systemInstruction,"config.llm.systemInstruction"),h(e.llm.fakeResponse,"config.llm.fakeResponse"),b(e.llm.temperature,"config.llm.temperature"),b(e.llm.topP,"config.llm.topP"),b(e.llm.topK,"config.llm.topK"),b(e.llm.maxOutputTokens,"config.llm.maxOutputTokens");}if(e.project!==void 0){if(!y(e.project))throw new Error("config.project must be an object.");if(e.project.packageManager!==void 0&&(typeof e.project.packageManager!="string"||!["auto","npm","pnpm","yarn","bun"].includes(e.project.packageManager)))throw new Error("config.project.packageManager must be one of: auto, npm, pnpm, yarn, bun.");L(e.project.validationCommands,"config.project.validationCommands"),L(e.project.testScriptNames,"config.project.testScriptNames"),S(e.project.includeTypecheck,"config.project.includeTypecheck"),S(e.project.includeLint,"config.project.includeLint"),b(e.project.maxValidationCommands,"config.project.maxValidationCommands");}if(e.context!==void 0){if(!y(e.context))throw new Error("config.context must be an object.");S(e.context.enabled,"config.context.enabled"),b(e.context.maxSearchQueries,"config.context.maxSearchQueries"),b(e.context.maxFiles,"config.context.maxFiles"),b(e.context.maxSearchResults,"config.context.maxSearchResults"),L(e.context.globs,"config.context.globs"),L(e.context.excludeGlobs,"config.context.excludeGlobs");}if(e.patchQuality!==void 0){if(!y(e.patchQuality))throw new Error("config.patchQuality must be an object.");if(S(e.patchQuality.enabled,"config.patchQuality.enabled"),b(e.patchQuality.maxRepairAttempts,"config.patchQuality.maxRepairAttempts"),typeof e.patchQuality.maxRepairAttempts=="number"&&e.patchQuality.maxRepairAttempts<0)throw new Error("config.patchQuality.maxRepairAttempts must be greater than or equal to 0.")}if(e.rollback!==void 0){if(!y(e.rollback))throw new Error("config.rollback must be an object.");if(S(e.rollback.enabled,"config.rollback.enabled"),S(e.rollback.onFinalValidationFailure,"config.rollback.onFinalValidationFailure"),S(e.rollback.runValidationAfterRollback,"config.rollback.runValidationAfterRollback"),S(e.rollback.allowForSuppliedPatches,"config.rollback.allowForSuppliedPatches"),b(e.rollback.maxRollbackDepth,"config.rollback.maxRollbackDepth"),typeof e.rollback.maxRollbackDepth=="number"&&e.rollback.maxRollbackDepth<0)throw new Error("config.rollback.maxRollbackDepth must be greater than or equal to 0.");if(e.rollback.strategy!==void 0&&e.rollback.strategy!=="last"&&e.rollback.strategy!=="all")throw new Error("config.rollback.strategy must be one of: last, all.")}if(e.redaction!==void 0){if(!y(e.redaction))throw new Error("config.redaction must be an object.");S(e.redaction.enabled,"config.redaction.enabled"),L(e.redaction.additionalPatterns,"config.redaction.additionalPatterns");}if(e.language!==void 0){if(!y(e.language))throw new Error("config.language must be an object.");if(e.language.response!==void 0&&(typeof e.language.response!="string"||!["auto","match-user","en","es","pt","fr","de","it","custom"].includes(e.language.response)))throw new Error("config.language.response must be one of: auto, match-user, en, es, pt, fr, de, it, custom.");h(e.language.custom,"config.language.custom");}if(e.permissions!==void 0){if(!y(e.permissions))throw new Error("config.permissions must be an object.");if(e.permissions.shell!==void 0){if(!y(e.permissions.shell))throw new Error("config.permissions.shell must be an object.");if(S(e.permissions.shell.inheritDefaults,"config.permissions.shell.inheritDefaults"),L(e.permissions.shell.allow,"config.permissions.shell.allow"),L(e.permissions.shell.deny,"config.permissions.shell.deny"),e.permissions.shell.ask!==void 0){if(!Array.isArray(e.permissions.shell.ask))throw new Error("config.permissions.shell.ask must be an array.");for(let[n,r]of e.permissions.shell.ask.entries())if(typeof r!="string"){if(!y(r))throw new Error(`config.permissions.shell.ask[${n}] must be a string or object.`);if(h(r.pattern,`config.permissions.shell.ask[${n}].pattern`),h(r.reason,`config.permissions.shell.ask[${n}].reason`),r.risk!==void 0&&r.risk!=="low"&&r.risk!=="medium"&&r.risk!=="high")throw new Error(`config.permissions.shell.ask[${n}].risk must be one of: low, medium, high.`);if(r.defaultAnswer!==void 0&&r.defaultAnswer!=="approve"&&r.defaultAnswer!=="reject")throw new Error(`config.permissions.shell.ask[${n}].defaultAnswer must be approve or reject.`)}}}if(e.permissions.patchApply!==void 0){let n=e.permissions.patchApply;if(typeof n=="string"){if(n!=="allow"&&n!=="ask"&&n!=="deny")throw new Error("config.permissions.patchApply must be allow, ask, deny, or an object.")}else if(y(n)){if(n.decision!==void 0&&n.decision!=="allow"&&n.decision!=="ask"&&n.decision!=="deny")throw new Error("config.permissions.patchApply.decision must be allow, ask, or deny.");if(h(n.reason,"config.permissions.patchApply.reason"),n.risk!==void 0&&n.risk!=="low"&&n.risk!=="medium"&&n.risk!=="high")throw new Error("config.permissions.patchApply.risk must be one of: low, medium, high.");if(n.defaultAnswer!==void 0&&n.defaultAnswer!=="approve"&&n.defaultAnswer!=="reject")throw new Error("config.permissions.patchApply.defaultAnswer must be approve or reject.")}else throw new Error("config.permissions.patchApply must be allow, ask, deny, or an object.")}}if(e.tools!==void 0){if(!y(e.tools))throw new Error("config.tools must be an object.");for(let[n,r]of Object.entries(e.tools)){if(!y(r))throw new Error(`config.tools.${n} must be an object.`);b(r.timeoutMs,`config.tools.${n}.timeoutMs`),b(r.retries,`config.tools.${n}.retries`);}}if(e.batch!==void 0){if(!y(e.batch))throw new Error("config.batch must be an object.");if(S(e.batch.stopOnFailure,"config.batch.stopOnFailure"),e.batch.goals!==void 0){if(!Array.isArray(e.batch.goals))throw new Error("config.batch.goals must be an array.");e.batch.goals.forEach((n,r)=>Vr(n,`config.batch.goals[${r}]`));}}return e},qt=async e=>{let{stat:t}=await oe("node:fs/promises");try{return (await t(e)).isFile()}catch{return false}},Ur=async e=>{let t=await oe("node:path"),n=t.resolve(e);for(;;){for(let o of Mt){let a=t.join(n,o);if(await qt(a))return a}let r=t.dirname(n);if(r===n)return;n=r;}},Gt=async e=>{let{readFile:t}=await oe("node:fs/promises"),n=String(await t(e,"utf8")).replace(/^\uFEFF/,"");try{return zr(JSON.parse(n),e)}catch(r){throw r instanceof SyntaxError?new Error(`Invalid JSON in agent config ${e}: ${r.message}`):r}},Na=async e=>{if(e.noConfig)return {config:{}};let t=await oe("node:path");if(e.configPath){let r=t.isAbsolute(e.configPath)?e.configPath:t.resolve(e.cwd,e.configPath);if(!await qt(r))throw new Error(`Agent config not found or not a file: ${r}`);return {path:r,config:await Gt(r)}}let n=await Ur(e.cwd);return n?{path:n,config:await Gt(n)}:{config:{}}};var Wr=e=>e?.choices?.[0]?.message?.content??e?.output_text??e?.content?.[0]?.text??JSON.stringify(e),qa=e=>({complete:t=>chunkT3QEEHK6_cjs.Q(async n=>{let r=await fetch(e.endpoint,{method:"POST",signal:n,headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({model:e.model,messages:[{role:"user",content:t.prompt}]})});if(!r.ok)throw new Error(`LLM request failed with ${r.status}`);return {content:Wr(await r.json())}},n=>({_tag:"LLMError",cause:n}))});var Qr="gemini-2.5-flash",Kr="v1beta",Zr="https://generativelanguage.googleapis.com",Hr=e=>{let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)},Jr=e=>e.startsWith("models/")?e:`models/${e}`,Xr=e=>{if(e.endpoint)return e.endpoint;let t=Hr(e.baseUrl??Zr),n=e.apiVersion??Kr,r=Jr(e.model??Qr);return `${t}/${n}/${r}:generateContent`},ae=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Bt=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Yr=(e,t)=>{let n=Bt({temperature:ae(t.temperature),topP:ae(t.topP),topK:ae(t.topK),maxOutputTokens:ae(t.maxOutputTokens),stopSequences:t.stopSequences,responseMimeType:t.responseMimeType,...t.extraGenerationConfig??{}});return Bt({contents:[{role:"user",parts:[{text:e.prompt}]}],systemInstruction:t.systemInstruction?{parts:[{text:t.systemInstruction}]}:void 0,generationConfig:Object.keys(n).length>0?n:void 0})},eo=e=>{let t=e.candidates?.flatMap(o=>o.content?.parts??[]).map(o=>o.text??"").filter(Boolean).join(`
24
- `).trim();if(t)return t;let n=e.promptFeedback?.blockReason;if(n){let o=e.promptFeedback?.blockReasonMessage;throw new Error(`Google Gemini blocked the prompt: ${n}${o?` - ${o}`:""}`)}let r=e.candidates?.[0]?.finishReason;if(r)throw new Error(`Google Gemini returned no text. finishReason=${r}`);if(e.error?.message)throw new Error(`Google Gemini error: ${e.error.message}`);return JSON.stringify(e)},to=async e=>{let t=await e.text();try{return JSON.parse(t).error?.message??t}catch{return t}},za=e=>({complete:t=>chunkT3QEEHK6_cjs.Q(async n=>{let r=await fetch(Xr(e),{method:"POST",signal:n,headers:{"content-type":"application/json","x-goog-api-key":e.apiKey},body:JSON.stringify(Yr({prompt:t.prompt},e))});if(!r.ok){let a=await to(r);throw new Error(`Google Gemini request failed with ${r.status}: ${a}`)}let o=await r.json();return {content:eo(o)}},n=>({_tag:"LLMError",cause:n}))});var no=e=>["Fake LLM response.","",`Purpose: ${e.purpose}`,"Set BRASS_LLM_PROVIDER=google with GEMINI_API_KEY/GOOGLE_API_KEY, or set BRASS_LLM_ENDPOINT and BRASS_LLM_API_KEY for an OpenAI-compatible model.","You can also set BRASS_FAKE_LLM_RESPONSE to provide a deterministic offline response, including a fenced ```diff block."].join(`
25
- `),Qa=(e={})=>({complete:t=>chunkT3QEEHK6_cjs.f({content:typeof e.content=="function"?e.content(t):e.content??no(t)})});var co=[{name:".brass-agent.json",kind:"file"},{name:"brass-agent.config.json",kind:"file"},{name:"package.json",kind:"file"},{name:"pnpm-workspace.yaml",kind:"file"},{name:"turbo.json",kind:"file"},{name:"nx.json",kind:"file"},{name:".git",kind:"directory"}],lo=(e,t)=>{try{let n=fs.statSync(e);return t==="directory"?n.isDirectory():n.isFile()}catch{return false}},po=e=>{for(let t of co){let n=path.join(e,t.name);if(lo(n,t.kind))return {marker:t.name,markerPath:n}}},Ja=(e,t={})=>{let n=path.resolve(e);if(t.enabled===false)return {inputCwd:n,cwd:n,changed:false,disabled:true};if(!fs.existsSync(n))return {inputCwd:n,cwd:n,changed:false};let r=n;for(;;){let o=po(r);if(o)return {inputCwd:n,cwd:r,marker:o.marker,markerPath:o.markerPath,changed:r!==n};let a=path.dirname(r);if(a===r)return {inputCwd:n,cwd:n,changed:false};r=a;}};exports.$=Et;exports.A=O;exports.B=nt;exports.C=rt;exports.D=ke;exports.E=ot;exports.F=at;exports.G=xe;exports.H=M;exports.I=it;exports.J=Hn;exports.K=ct;exports.L=lt;exports.M=rr;exports.N=Se;exports.O=te;exports.P=At;exports.Q=v;exports.R=E;exports.S=Pe;exports.T=_o;exports.U=To;exports.V=Oo;exports.W=bt;exports.X=kt;exports.Y=xt;exports.Z=vt;exports._=Pr;exports.a=Le;exports.aa=Ct;exports.b=_e;exports.ba=da;exports.c=Te;exports.ca=Ce;exports.d=qe;exports.da=$t;exports.e=ze;exports.ea=Ft;exports.f=ue;exports.fa=Mt;exports.g=dn;exports.ga=Lt;exports.h=We;exports.ha=ma;exports.i=Qe;exports.ia=Ir;exports.j=Ke;exports.ja=ha;exports.k=fe;exports.ka=ka;exports.l=ye;exports.la=xa;exports.m=An;exports.ma=wa;exports.n=Xe;exports.na=ja;exports.o=Ye;exports.oa=_a;exports.p=Ze;exports.pa=Na;exports.q=$n;exports.qa=qa;exports.r=J;exports.ra=za;exports.s=P;exports.sa=Qa;exports.t=X;exports.ta=Ja;exports.u=Ae;exports.v=On;exports.w=Y;exports.x=ee;exports.y=tt;exports.z=be;
21
+ `).trim())},ur=e=>{let t=D(e,"agent.error")?.error,n=te(e.goal);if(!t)return n?"La ejecuci\xF3n del agente fall\xF3.":"Agent run failed.";switch(t._tag){case "FsError":return n?`El agente se detuvo por un error de filesystem durante ${t.operation}: ${R(e,t.cause)}`:`Agent stopped after a filesystem error during ${t.operation}: ${R(e,t.cause)}`;case "ShellError":return n?`El agente se detuvo por un error ejecutando ${t.command?.join(" ")??t.operation}: ${R(e,t.cause)}`:`Agent stopped after a shell error during ${t.command?.join(" ")??t.operation}: ${R(e,t.cause)}`;case "LLMError":return n?`El agente se detuvo porque fall\xF3 la llamada al modelo: ${R(e,t.cause)}`:`Agent stopped because the model call failed: ${R(e,t.cause)}`;case "PatchError":return n?`El agente se detuvo por un error de patch durante ${t.operation}: ${R(e,t.cause)}`:`Agent stopped after a patch error during ${t.operation}: ${R(e,t.cause)}`;case "PermissionDenied":return n?`El agente se detuvo porque una acci\xF3n fue denegada por policy: ${t.reason}`:`Agent stopped because an action was denied by policy: ${t.reason}`;case "ApprovalRejected":return n?`El agente se detuvo porque se rechaz\xF3 una aprobaci\xF3n: ${t.reason}`:`Agent stopped because an approval was rejected: ${t.reason}`;case "ToolTimeout":return n?`El agente se detuvo porque una tool tard\xF3 m\xE1s de ${t.timeoutMs}ms.`:`Agent stopped because a tool timed out after ${t.timeoutMs}ms.`;case "PathOutsideWorkspace":return n?`El agente bloque\xF3 un path fuera del workspace: ${t.path}`:`Agent blocked a path outside the workspace: ${t.path}`;case "AgentLoopError":return n?`El agente se detuvo por un error del loop: ${t.message}`:`Agent stopped after an agent loop error: ${t.message}`}},gr=e=>{if(e.goal.mode==="read-only")return;let t=P(e).validationCommands,n=X(t,ar(e));return n?{type:"shell.exec",command:n}:void 0},mr=e=>{let t=P(e).validationCommands,n=X(t,Ee(e));return n?{type:"shell.exec",command:n}:void 0},ht=e=>{let t=P(e).validationCommands,n=X(t,we(e));return n?{type:"shell.exec",command:n}:void 0},fr=e=>{for(let t=e.observations.length-1;t>=0;t-=1){let n=e.observations[t];if(!n||n.type!=="llm.response")continue;let r=M(n.content);if(!r)continue;return e.observations.slice(t+1).some(a=>a.type==="patch.applied"||a.type==="patch.proposed")?void 0:{index:t,patch:r}}},yr=e=>{for(let t=e.observations.length-1;t>=0;t-=1){let n=e.observations[t];if(n?.type!=="llm.response")continue;let r=M(n.content);if(r)return r}},hr=e=>{for(let t=e.observations.length-1;t>=0;t-=1){let n=e.observations[t];if(n?.type==="patch.proposed")return n.patch;if(n?.type==="patch.applied"){if(n.patch)return n.patch;let r=e.observations.slice(0,t).reverse().find(o=>o.type==="llm.response"&&!!M(o.content));return r?M(r.content):e.goal.initialPatch}}},Ar=e=>{if(!N(e.goal.mode)||V(e)?.type!=="patch.applied"||!ee(e))return false;let t=P(e).validationCommands;return tt(t,Ee(e)).type==="failed"},br=e=>{if(!N(e.goal.mode)||V(e)?.type!=="patch.applied"||ee(e)||!O(e).onFinalValidationFailure||!ke(e))return false;let n=P(e).validationCommands;return at(n,we(e)).type==="failed"},kr=e=>{if(!N(e.goal.mode)||!ee(e))return false;let t=e.observations.at(-1);return t?.type==="agent.error"&&t.error._tag==="PatchError"},gt=(e,t)=>({type:"llm.complete",purpose:"patch",prompt:pr(e,t)}),mt=(e,t)=>{let n=rt(e);if(n)return {type:"patch.rollback",patch:n.patch,automatic:true,reason:t}},xr=(e,t)=>{if(N(e.goal.mode))return e.goal.initialPatchMode==="rollback"?ne(e,"patch.rolledBack")?void 0:{type:"patch.rollback",patch:t}:ne(e,"patch.applied")?ht(e):{type:"patch.apply",patch:t};if(e.goal.mode==="propose"&&!ne(e,"patch.proposed"))return {type:"patch.propose",patch:t}},At=e=>{if(e.observations.at(-1)?.type==="agent.error")return kr(e)?chunkK47BP5A2_cjs.f(gt(e,"previous patch failed to apply")):chunkK47BP5A2_cjs.f({type:"agent.finish",summary:ur(e)});if(!ne(e,"fs.fileRead"))return chunkK47BP5A2_cjs.f({type:"fs.readFile",path:"package.json"});let n=Ye(e);if(n)return chunkK47BP5A2_cjs.f(n);let r=e.goal.initialPatch?.trim();if(r){let s=xr(e,r);return s?chunkK47BP5A2_cjs.f(s):chunkK47BP5A2_cjs.f({type:"agent.finish",summary:ut(e,r)})}let o=fr(e);if(o){if(N(e.goal.mode))return chunkK47BP5A2_cjs.f({type:"patch.apply",patch:o.patch});if(e.goal.mode==="propose")return chunkK47BP5A2_cjs.f({type:"patch.propose",patch:o.patch})}if(!e.observations.find(s=>s.type==="llm.response"&&s.purpose==="plan")){let s=gr(e);if(s)return chunkK47BP5A2_cjs.f(s);let p=We(e);return p?chunkK47BP5A2_cjs.f(p):chunkK47BP5A2_cjs.f({type:"llm.complete",purpose:"plan",prompt:lr(e)})}if(N(e.goal.mode)){if(ot(e)){let s=mt(e,"continuing rollback of generated patch stack");if(s)return chunkK47BP5A2_cjs.f(s)}if(V(e)?.type==="patch.rolledBack"&&O(e).runValidationAfterRollback){let p=ht(e);if(p)return chunkK47BP5A2_cjs.f(p)}if(V(e)?.type==="patch.applied"){let s=mr(e);if(s)return chunkK47BP5A2_cjs.f(s);if(Ar(e))return chunkK47BP5A2_cjs.f(gt(e,"validation failed after applying the generated patch"));if(br(e)){let p=mt(e,"validation failed after generated patches and no repair attempts remain");if(p)return chunkK47BP5A2_cjs.f(p)}}}let l=yr(e);return chunkK47BP5A2_cjs.f({type:"agent.finish",summary:ut(e,l)})};var v=()=>chunkK47BP5A2_cjs.j((e,t)=>{t({_tag:"Success",value:Date.now()});}),E=e=>chunkK47BP5A2_cjs.j((t,n)=>{try{t.events?.emit(e);}catch{}n({_tag:"Success",value:void 0});}),Pe=e=>e.reduce((t,n)=>chunkK47BP5A2_cjs.l(t,()=>E(n)),chunkK47BP5A2_cjs.f(void 0)),_o=e=>{switch(e.type){case "fs.readFile":return `read ${e.path}`;case "fs.exists":return `check ${e.path}`;case "fs.searchText":return `search "${e.query}"`;case "shell.exec":return e.command.join(" ");case "llm.complete":return `llm.${e.purpose}`;case "patch.propose":return "propose patch";case "patch.apply":return "apply patch";case "patch.rollback":return "rollback patch";case "agent.finish":return "finish";case "agent.fail":return "fail"}},To=e=>{switch(e.type){case "fs.fileRead":return `read ${e.path}`;case "fs.exists":return `${e.exists?"found":"missing"} ${e.path}`;case "fs.searchResult":return `search "${e.query}" (${e.matches.length} matches)`;case "shell.result":return `${e.command.join(" ")} exited ${e.exitCode}`;case "llm.response":return `llm.${e.purpose} responded`;case "patch.proposed":return "patch proposed";case "patch.applied":return `patch applied (${e.changedFiles.join(", ")||"no files reported"})`;case "patch.rolledBack":return `patch rolled back (${e.changedFiles.join(", ")||"no files reported"})`;case "agent.done":return "done";case "agent.error":return `error ${e.error._tag}`}},Oo=e=>{switch(e.type){case "agent.error":return "fail";case "shell.result":return e.exitCode===0?"ok":"warn";default:return "ok"}},bt=(e,t,n,r)=>{switch(n._tag){case "ToolTimeout":return {type:"agent.tool.timeout",action:e,step:t.steps+1,phase:t.phase,timeoutMs:n.timeoutMs,at:r};case "PermissionDenied":return {type:"agent.permission.denied",action:e,step:t.steps+1,phase:t.phase,reason:n.reason,at:r};default:return}},kt=(e,t,n)=>{switch(t.type){case "patch.applied":return {type:"agent.patch.applied",step:e.steps,phase:e.phase,changedFiles:t.changedFiles,automaticRollbackEligible:!!t.patch,at:n};case "patch.rolledBack":return {type:"agent.patch.rolledBack",step:e.steps,phase:e.phase,changedFiles:t.changedFiles,...t.automatic!==void 0?{automatic:t.automatic}:{},...t.reason?{reason:t.reason}:{},at:n};default:return}},xt=e=>e==="done"?"done":"failed";var x=e=>chunkK47BP5A2_cjs.h(t=>t[e]);var Sr=e=>e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e),vr=e=>{let t=e.length;for(;t>0;){let n=e.charCodeAt(t-1);if(n!==47&&n!==92)break;t-=1;}return t===e.length?e:e.slice(0,t)},Er=e=>e.replace(/^(?:\.[\\/])+/,""),wr=e=>{let t=e.trim();if(!(!t||t.includes("\0")||Sr(t)||t.split(/[\\/]+/).includes("..")))return Er(t)};var U=(e,t)=>{let n=wr(t);return n?chunkK47BP5A2_cjs.f(`${vr(e)}/${n}`):chunkK47BP5A2_cjs.g({_tag:"PathOutsideWorkspace",path:t,cwd:e})};var St=(e,t)=>{switch(e.type){case "fs.readFile":return chunkK47BP5A2_cjs.l(U(t.goal.cwd,e.path),n=>chunkK47BP5A2_cjs.l(x("fs"),r=>chunkK47BP5A2_cjs.k(r.readFile(n),o=>({type:"fs.fileRead",path:e.path,content:o}))));case "fs.exists":return chunkK47BP5A2_cjs.l(U(t.goal.cwd,e.path),n=>chunkK47BP5A2_cjs.l(x("fs"),r=>chunkK47BP5A2_cjs.k(r.exists(n),o=>({type:"fs.exists",path:e.path,exists:o}))));case "fs.searchText":return chunkK47BP5A2_cjs.l(x("fs"),n=>chunkK47BP5A2_cjs.k(n.searchText(t.goal.cwd,e.query,{globs:e.globs}),r=>({type:"fs.searchResult",query:e.query,matches:r})));case "shell.exec":return chunkK47BP5A2_cjs.l(x("shell"),n=>chunkK47BP5A2_cjs.k(n.exec(e.command,{cwd:e.cwd??t.goal.cwd}),r=>({type:"shell.result",command:e.command,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr})));case "llm.complete":return chunkK47BP5A2_cjs.l(x("llm"),n=>chunkK47BP5A2_cjs.k(n.complete({purpose:e.purpose,prompt:e.prompt}),r=>({type:"llm.response",purpose:e.purpose,content:r.content})));case "patch.propose":return chunkK47BP5A2_cjs.f({type:"patch.proposed",patch:e.patch});case "patch.apply":return chunkK47BP5A2_cjs.l(x("patch"),n=>chunkK47BP5A2_cjs.k(n.apply(t.goal.cwd,e.patch),r=>({type:"patch.applied",changedFiles:r.changedFiles,patch:e.patch})));case "patch.rollback":return chunkK47BP5A2_cjs.l(x("patch"),n=>chunkK47BP5A2_cjs.k(n.rollback(t.goal.cwd,e.patch),r=>({type:"patch.rolledBack",changedFiles:r.changedFiles,patch:e.patch,...e.automatic!==void 0?{automatic:e.automatic}:{},...e.reason?{reason:e.reason}:{}})));case "agent.finish":return chunkK47BP5A2_cjs.f({type:"agent.done",summary:e.summary});case "agent.fail":return chunkK47BP5A2_cjs.g({_tag:"AgentLoopError",message:e.reason})}};var vt=(e,t)=>{let n=r=>chunkK47BP5A2_cjs.b(e(),o=>r>0&&t.while(o)?n(r-1):chunkK47BP5A2_cjs.g(o),o=>chunkK47BP5A2_cjs.f(o));return n(t.times)};var Pr=e=>chunkK47BP5A2_cjs.j((t,n)=>{let r=setTimeout(()=>n({_tag:"Success",value:void 0}),e);return ()=>clearTimeout(r)}),Et=(e,t,n)=>chunkK47BP5A2_cjs.ia(e,chunkK47BP5A2_cjs.l(Pr(t),()=>chunkK47BP5A2_cjs.g({_tag:"ToolTimeout",timeoutMs:t})),n);var wt=e=>e._tag==="LLMError"||e._tag==="ToolTimeout",Rr=e=>{switch(e.type){case "fs.readFile":case "fs.exists":case "fs.searchText":return {timeoutMs:5e3,retries:1,retryable:wt};case "llm.complete":return {timeoutMs:6e4,retries:2,retryable:wt};case "shell.exec":return {timeoutMs:12e4,retries:0,retryable:()=>false};case "patch.propose":case "agent.finish":case "agent.fail":return {timeoutMs:1e3,retries:0,retryable:()=>false};case "patch.apply":case "patch.rollback":return {timeoutMs:15e3,retries:0,retryable:()=>false}}},Cr=(e,t)=>{let n=Rr(e),r=t?.[e.type];return {...n,timeoutMs:r?.timeoutMs!==void 0?Math.max(1,Math.floor(r.timeoutMs)):n.timeoutMs,retries:r?.retries!==void 0?Math.max(0,Math.floor(r.retries)):n.retries}},Pt=(e,t,n)=>chunkK47BP5A2_cjs.l(chunkK47BP5A2_cjs.h(r=>r.toolPolicies),r=>{let o=Cr(e,r);return vt(()=>Et(St(e,t),o.timeoutMs,n),{times:o.retries,while:o.retryable})}),Rt=(e,t)=>({_tag:"ApprovalRejected",action:e,reason:t}),Re=(e,t,n,r)=>chunkK47BP5A2_cjs.l(v(),o=>E({type:"agent.approval.resolved",action:e,step:t.steps+1,phase:t.phase,approved:n,...r?{reason:r}:{},at:o})),jr=(e,t,n)=>{let r=n.defaultAnswer??"reject";return chunkK47BP5A2_cjs.l(v(),o=>chunkK47BP5A2_cjs.l(E({type:"agent.approval.requested",action:e,step:t.steps+1,phase:t.phase,reason:n.reason,risk:n.risk,defaultAnswer:r,at:o}),()=>chunkK47BP5A2_cjs.l(x("approvals"),a=>{if(!a){let l="No approval service configured.";return chunkK47BP5A2_cjs.l(Re(e,t,false,l),()=>chunkK47BP5A2_cjs.g(Rt(e,l)))}return chunkK47BP5A2_cjs.l(a.request({action:e,state:t,reason:n.reason,risk:n.risk,defaultAnswer:r}),l=>{if(l.type==="approved")return chunkK47BP5A2_cjs.l(Re(e,t,true,void 0),()=>chunkK47BP5A2_cjs.f(void 0));let s=l.reason??"Approval rejected.";return chunkK47BP5A2_cjs.l(Re(e,t,false,s),()=>chunkK47BP5A2_cjs.g(Rt(e,s)))})})))},Ct=(e,t,n)=>chunkK47BP5A2_cjs.l(x("permissions"),r=>chunkK47BP5A2_cjs.l(r.check(e,t),o=>o.type==="deny"?chunkK47BP5A2_cjs.g({_tag:"PermissionDenied",action:e,reason:o.reason}):o.type==="ask"?chunkK47BP5A2_cjs.l(jr(e,t,o),()=>Pt(e,t,n)):Pt(e,t,n)));var $r=(e,t,n)=>chunkK47BP5A2_cjs.l(v(),r=>chunkK47BP5A2_cjs.l(E({type:"agent.action.started",action:e,step:t.steps+1,phase:t.phase,at:r}),()=>chunkK47BP5A2_cjs.b(Ct(e,t,n),o=>chunkK47BP5A2_cjs.l(v(),a=>{let l=bt(e,t,o,a),s=[...l?[l]:[],{type:"agent.action.failed",action:e,error:o,step:t.steps+1,phase:t.phase,durationMs:a-r,at:a}];return chunkK47BP5A2_cjs.l(Pe(s),()=>chunkK47BP5A2_cjs.f({type:"agent.error",error:o}))}),o=>chunkK47BP5A2_cjs.l(v(),a=>chunkK47BP5A2_cjs.l(E({type:"agent.action.completed",action:e,observation:o,step:t.steps+1,phase:t.phase,durationMs:a-r,at:a}),()=>chunkK47BP5A2_cjs.f(o)))))),Fr=(e,t)=>chunkK47BP5A2_cjs.l(v(),n=>{let r=kt(e,t,n),o=[{type:"agent.observation.recorded",observation:t,step:e.steps,phase:e.phase,at:n},...r?[r]:[]];return Pe(o)}),jt=(e,t,n)=>Te(e)?chunkK47BP5A2_cjs.l(v(),r=>chunkK47BP5A2_cjs.l(E({type:"agent.run.completed",goal:e.goal,status:xt(e.phase),phase:e.phase,steps:e.steps,durationMs:r-n,at:r}),()=>chunkK47BP5A2_cjs.f(e))):chunkK47BP5A2_cjs.l(At(e),r=>chunkK47BP5A2_cjs.l($r(r,e,t),o=>{let a=_e(e,o);return chunkK47BP5A2_cjs.l(Fr(a,o),()=>jt(a,t,n))})),da=(e,t)=>chunkK47BP5A2_cjs.ga(e,n=>chunkK47BP5A2_cjs.l(v(),r=>chunkK47BP5A2_cjs.l(E({type:"agent.run.started",goal:t,at:r}),()=>jt(Le(t),n,r))));var Ce=e=>e==="read-only"||e==="propose"||e==="write"||e==="autonomous",$t=e=>e==="auto"||e==="interactive"||e==="approve"||e==="deny",Ft=e=>e==="fake"||e==="google"||e==="gemini"||e==="openai"||e==="openai-compatible",Mt=[".brass-agent.json","brass-agent.config.json"];var Lt=e=>e==="fix-tests"||e==="inspect"||e==="typecheck"||e==="lint",ma=e=>{switch(e){case "fix-tests":return "fix the failing tests";case "inspect":return "inspect this workspace and summarize the current project state";case "typecheck":return "run typecheck discovery and fix type errors if possible";case "lint":return "run lint discovery and fix lint errors if possible"}};var Mr=["npm test","npm run test*","npm run typecheck","npm run type-check","npm run check-types","npm run tsc","npm run check","npm run *check*","npm run *doctor*","npm run *health*","npm run *verify*","npm run *validate*","npm run repo:check","npm run lint*","pnpm test","pnpm run test*","pnpm run typecheck","pnpm run type-check","pnpm run check-types","pnpm run tsc","pnpm run check","pnpm run *check*","pnpm run *doctor*","pnpm run *health*","pnpm run *verify*","pnpm run *validate*","pnpm run repo:check","pnpm run lint*","yarn test","yarn run test*","yarn run typecheck","yarn run type-check","yarn run check-types","yarn run tsc","yarn run check","yarn run *check*","yarn run *doctor*","yarn run *health*","yarn run *verify*","yarn run *validate*","yarn run repo:check","yarn run lint*","bun run test*","bun run typecheck","bun run type-check","bun run check-types","bun run tsc","bun run check","bun run *check*","bun run *doctor*","bun run *health*","bun run *verify*","bun run *validate*","bun run repo:check","bun run lint*","cargo check","cargo test","cargo fmt --check","cargo clippy","cargo clippy *","git status","git diff","git log"],Ot=e=>e.trim().replace(/\s+/g," "),re=e=>Ot(e.join(" ")),Lr=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Dt=(e,t)=>{let n=re(e),r=Ot(t);return r.includes("*")?new RegExp(`^${r.split("*").map(Lr).join(".*")}$`).test(n):n===r},_t=(e,t)=>!!t?.some(n=>Dt(e,n)),I=()=>({type:"allow"}),G=e=>({type:"deny",reason:e}),W=(e,t,n="reject")=>({type:"ask",reason:e,risk:t,defaultAnswer:n}),_r=e=>e.type==="shell.exec"?e.command.join(" "):e.type,Tr=e=>typeof e=="string"?e:e.pattern,Or=(e,t)=>{let n=t?.find(r=>Dt(e,Tr(r)));if(n)return typeof n=="string"?W(`Run command: ${re(e)}`,"high","reject"):W(n.reason??`Run command: ${re(e)}`,n.risk??"high",n.defaultAnswer??"reject")},Dr=e=>[...e?.inheritDefaults===false?[]:Mr,...e?.allow??[]],je=(e,t)=>{if(_t(e,t?.deny))return G(`Command denied by policy: ${re(e)}`);let n=Or(e,t?.ask);if(n)return n;if(_t(e,Dr(t)))return I()},Nr=e=>e.type==="patch.rollback"?"Reverse-apply a patch to restore the workspace.":"Apply the proposed patch to the workspace.",Tt=(e,t)=>{let n=Nr(e);if(!t)return W(n,"high","reject");let r=typeof t=="string"?t:t.decision??"ask",o=typeof t=="string"?n:t.reason??n,a=typeof t=="string"?"high":t.risk??"high",l=typeof t=="string"?"reject":t.defaultAnswer??"reject";return r==="allow"?I():r==="deny"?G(o):W(o,a,l)},Ir=(e={})=>({check:(t,n)=>{switch(n.goal.mode){case "read-only":return t.type==="fs.readFile"||t.type==="fs.exists"||t.type==="fs.searchText"||t.type==="llm.complete"||t.type==="agent.finish"||t.type==="agent.fail"?chunkK47BP5A2_cjs.f(I()):chunkK47BP5A2_cjs.f(G(`Action ${t.type} is not allowed in read-only mode`));case "propose":{if(t.type==="shell.exec"){let r=je(t.command,e.shell);return chunkK47BP5A2_cjs.f(r??G(`Command not whitelisted: ${t.command.join(" ")}`))}return t.type==="patch.apply"||t.type==="patch.rollback"?chunkK47BP5A2_cjs.f(G(`${t.type} is not allowed in propose mode; use write mode or --apply.`)):chunkK47BP5A2_cjs.f(I())}case "write":{if(t.type==="shell.exec"){let r=je(t.command,e.shell);return chunkK47BP5A2_cjs.f(r??G(`Command not whitelisted: ${t.command.join(" ")}`))}return t.type==="patch.apply"||t.type==="patch.rollback"?chunkK47BP5A2_cjs.f(Tt(t,e.patchApply)):chunkK47BP5A2_cjs.f(I())}case "autonomous":{if(t.type==="patch.apply"||t.type==="patch.rollback")return chunkK47BP5A2_cjs.f(Tt(t,e.patchApply));if(t.type==="shell.exec"){let r=je(t.command,e.shell);return chunkK47BP5A2_cjs.f(r??W(`Run non-whitelisted command: ${_r(t)}`,"high","reject"))}return chunkK47BP5A2_cjs.f(I())}}}}),ha=Ir();var ka={request:()=>chunkK47BP5A2_cjs.f({type:"approved"})},xa=(e="Approval denied by non-interactive policy.")=>({request:()=>chunkK47BP5A2_cjs.f({type:"rejected",reason:e})});var Gr=new Function("specifier","return import(specifier)"),Nt=e=>{let t=e?.toString;return typeof t=="function"?t.call(e,"utf8"):String(e)},wa={exec:(e,t)=>chunkK47BP5A2_cjs.j((n,r)=>{let[o,...a]=e;if(!o){r(chunkK47BP5A2_cjs.u.failCause(chunkK47BP5A2_cjs.t.fail({_tag:"ShellError",operation:"exec",command:e,cause:new Error("Empty command")})));return}let l="",s="",p=false,d;return Gr("node:child_process").then(({spawn:C})=>{p||(d=C(o,a,{cwd:t.cwd,shell:false,stdio:["pipe","pipe","pipe"]}),d.stdout?.on("data",f=>{l+=Nt(f);}),d.stderr?.on("data",f=>{s+=Nt(f);}),d.on("error",f=>{p||(p=true,r(chunkK47BP5A2_cjs.u.failCause(chunkK47BP5A2_cjs.t.fail({_tag:"ShellError",operation:"exec",command:e,cause:f}))));}),d.on("close",f=>{p||(p=true,r(chunkK47BP5A2_cjs.u.succeed({exitCode:f??1,stdout:l,stderr:s})));}),t.stdin!==void 0?d.stdin?.end(t.stdin):d.stdin?.end());}).catch(C=>{p||(p=true,r(chunkK47BP5A2_cjs.u.failCause(chunkK47BP5A2_cjs.t.fail({_tag:"ShellError",operation:"exec",command:e,cause:C}))));}),()=>{p||(p=true,d?.kill?.("SIGTERM"));}})};var It=new Function("specifier","return import(specifier)"),qr=e=>e.split(`
22
+ `).filter(Boolean).map(t=>{let[n="",r="0",...o]=t.split(":");return {path:n,line:Number(r),text:o.join(":")}}),ja=e=>({readFile:t=>chunkK47BP5A2_cjs.da(async n=>{let{readFile:r}=await It("node:fs/promises");return r(t,{encoding:"utf8",signal:n})},n=>({_tag:"FsError",operation:"readFile",cause:n})),exists:t=>chunkK47BP5A2_cjs.da(async n=>{if(n.aborted)return false;let{stat:r}=await It("node:fs/promises");if(n.aborted)return false;try{return await r(t),!0}catch{return false}},n=>({_tag:"FsError",operation:"exists",cause:n})),searchText:(t,n,r)=>chunkK47BP5A2_cjs.l(e.exec(["rg","--fixed-strings","--line-number","--no-heading","--color","never","--max-count","5",...r?.globs?.flatMap(o=>["--glob",o])??[],"--",n,"."],{cwd:t}),o=>o.exitCode>1?chunkK47BP5A2_cjs.g({_tag:"FsError",operation:"searchText",cause:o.stderr}):chunkK47BP5A2_cjs.f(qr(o.stdout)))});var Br=(e,t)=>t.reduce((n,r)=>chunkK47BP5A2_cjs.l(n,o=>chunkK47BP5A2_cjs.l(U(e,r),()=>chunkK47BP5A2_cjs.f([...o,r]))),chunkK47BP5A2_cjs.f([])),$e=(e,t,n)=>({_tag:"PatchError",operation:e,cause:t,patch:n}),_a=e=>{let t=(n,r,o)=>{let a=M(r)??r.trim(),l=it(a),s=`${a.trim()}
23
+ `,p=o?"rollback":"apply";if(!a||!l.length)return chunkK47BP5A2_cjs.g($e("extract","No unified diff with workspace-scoped paths was found.",r));let d=["git","apply",...o?["--reverse"]:[],"--recount","--whitespace=nowarn","-"],C=["git","apply",...o?["--reverse"]:[],"--check","--recount","--whitespace=nowarn","-"];return chunkK47BP5A2_cjs.l(Br(n,l),()=>chunkK47BP5A2_cjs.l(e.exec(C,{cwd:n,stdin:s}),f=>f.exitCode!==0?chunkK47BP5A2_cjs.g($e(`${p}.check`,f.stderr||f.stdout||`git apply --check exited with ${f.exitCode}`,a)):chunkK47BP5A2_cjs.l(e.exec(d,{cwd:n,stdin:s}),k=>k.exitCode!==0?chunkK47BP5A2_cjs.g($e(p,k.stderr||k.stdout||`git apply exited with ${k.exitCode}`,a)):chunkK47BP5A2_cjs.f({changedFiles:l}))))};return {apply:(n,r)=>t(n,r,false),rollback:(n,r)=>t(n,r,true)}};var oe=new Function("specifier","return import(specifier)"),y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),L=(e,t)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(n=>typeof n!="string")))throw new Error(`${t} must be an array of strings.`)},b=(e,t)=>{if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)))throw new Error(`${t} must be a finite number.`)},S=(e,t)=>{if(e!==void 0&&typeof e!="boolean")throw new Error(`${t} must be a boolean.`)},h=(e,t)=>{if(e!==void 0&&typeof e!="string")throw new Error(`${t} must be a string.`)},Vr=(e,t)=>{if(typeof e!="string"){if(!y(e))throw new Error(`${t} must be a string or object.`);if(h(e.goal,`${t}.goal`),h(e.cwd,`${t}.cwd`),h(e.patchFile,`${t}.patchFile`),h(e.saveRunDir,`${t}.saveRunDir`),e.preset!==void 0&&(typeof e.preset!="string"||!Lt(e.preset)))throw new Error(`${t}.preset must be one of: fix-tests, inspect, typecheck, lint.`);if(e.mode!==void 0&&(typeof e.mode!="string"||!Ce(e.mode)))throw new Error(`${t}.mode must be one of: read-only, propose, write, autonomous.`);if(e.patchFileMode!==void 0&&e.patchFileMode!=="apply"&&e.patchFileMode!=="rollback")throw new Error(`${t}.patchFileMode must be apply or rollback.`);if(e.goal===void 0&&e.preset===void 0&&e.patchFile===void 0)throw new Error(`${t} must include goal, preset, or patchFile.`)}},zr=(e,t)=>{if(!y(e))throw new Error(`Agent config at ${t} must be a JSON object.`);if(e.mode!==void 0&&(typeof e.mode!="string"||!Ce(e.mode)))throw new Error("config.mode must be one of: read-only, propose, write, autonomous.");if(e.approval!==void 0&&(typeof e.approval!="string"||!$t(e.approval)))throw new Error("config.approval must be one of: auto, interactive, approve, deny.");if(e.llm!==void 0){if(!y(e.llm))throw new Error("config.llm must be an object.");if(e.llm.provider!==void 0&&(typeof e.llm.provider!="string"||!Ft(e.llm.provider)))throw new Error("config.llm.provider must be one of: fake, google, gemini, openai, openai-compatible.");if("apiKey"in e.llm)throw new Error("config.llm.apiKey is not supported. Store secrets in environment variables and use config.llm.apiKeyEnv instead.");h(e.llm.model,"config.llm.model"),h(e.llm.endpoint,"config.llm.endpoint"),h(e.llm.baseUrl,"config.llm.baseUrl"),h(e.llm.apiVersion,"config.llm.apiVersion"),h(e.llm.apiKeyEnv,"config.llm.apiKeyEnv"),h(e.llm.systemInstruction,"config.llm.systemInstruction"),h(e.llm.fakeResponse,"config.llm.fakeResponse"),b(e.llm.temperature,"config.llm.temperature"),b(e.llm.topP,"config.llm.topP"),b(e.llm.topK,"config.llm.topK"),b(e.llm.maxOutputTokens,"config.llm.maxOutputTokens");}if(e.project!==void 0){if(!y(e.project))throw new Error("config.project must be an object.");if(e.project.packageManager!==void 0&&(typeof e.project.packageManager!="string"||!["auto","npm","pnpm","yarn","bun"].includes(e.project.packageManager)))throw new Error("config.project.packageManager must be one of: auto, npm, pnpm, yarn, bun.");L(e.project.validationCommands,"config.project.validationCommands"),L(e.project.testScriptNames,"config.project.testScriptNames"),S(e.project.includeTypecheck,"config.project.includeTypecheck"),S(e.project.includeLint,"config.project.includeLint"),b(e.project.maxValidationCommands,"config.project.maxValidationCommands");}if(e.context!==void 0){if(!y(e.context))throw new Error("config.context must be an object.");S(e.context.enabled,"config.context.enabled"),b(e.context.maxSearchQueries,"config.context.maxSearchQueries"),b(e.context.maxFiles,"config.context.maxFiles"),b(e.context.maxSearchResults,"config.context.maxSearchResults"),L(e.context.globs,"config.context.globs"),L(e.context.excludeGlobs,"config.context.excludeGlobs");}if(e.patchQuality!==void 0){if(!y(e.patchQuality))throw new Error("config.patchQuality must be an object.");if(S(e.patchQuality.enabled,"config.patchQuality.enabled"),b(e.patchQuality.maxRepairAttempts,"config.patchQuality.maxRepairAttempts"),typeof e.patchQuality.maxRepairAttempts=="number"&&e.patchQuality.maxRepairAttempts<0)throw new Error("config.patchQuality.maxRepairAttempts must be greater than or equal to 0.")}if(e.rollback!==void 0){if(!y(e.rollback))throw new Error("config.rollback must be an object.");if(S(e.rollback.enabled,"config.rollback.enabled"),S(e.rollback.onFinalValidationFailure,"config.rollback.onFinalValidationFailure"),S(e.rollback.runValidationAfterRollback,"config.rollback.runValidationAfterRollback"),S(e.rollback.allowForSuppliedPatches,"config.rollback.allowForSuppliedPatches"),b(e.rollback.maxRollbackDepth,"config.rollback.maxRollbackDepth"),typeof e.rollback.maxRollbackDepth=="number"&&e.rollback.maxRollbackDepth<0)throw new Error("config.rollback.maxRollbackDepth must be greater than or equal to 0.");if(e.rollback.strategy!==void 0&&e.rollback.strategy!=="last"&&e.rollback.strategy!=="all")throw new Error("config.rollback.strategy must be one of: last, all.")}if(e.redaction!==void 0){if(!y(e.redaction))throw new Error("config.redaction must be an object.");S(e.redaction.enabled,"config.redaction.enabled"),L(e.redaction.additionalPatterns,"config.redaction.additionalPatterns");}if(e.language!==void 0){if(!y(e.language))throw new Error("config.language must be an object.");if(e.language.response!==void 0&&(typeof e.language.response!="string"||!["auto","match-user","en","es","pt","fr","de","it","custom"].includes(e.language.response)))throw new Error("config.language.response must be one of: auto, match-user, en, es, pt, fr, de, it, custom.");h(e.language.custom,"config.language.custom");}if(e.permissions!==void 0){if(!y(e.permissions))throw new Error("config.permissions must be an object.");if(e.permissions.shell!==void 0){if(!y(e.permissions.shell))throw new Error("config.permissions.shell must be an object.");if(S(e.permissions.shell.inheritDefaults,"config.permissions.shell.inheritDefaults"),L(e.permissions.shell.allow,"config.permissions.shell.allow"),L(e.permissions.shell.deny,"config.permissions.shell.deny"),e.permissions.shell.ask!==void 0){if(!Array.isArray(e.permissions.shell.ask))throw new Error("config.permissions.shell.ask must be an array.");for(let[n,r]of e.permissions.shell.ask.entries())if(typeof r!="string"){if(!y(r))throw new Error(`config.permissions.shell.ask[${n}] must be a string or object.`);if(h(r.pattern,`config.permissions.shell.ask[${n}].pattern`),h(r.reason,`config.permissions.shell.ask[${n}].reason`),r.risk!==void 0&&r.risk!=="low"&&r.risk!=="medium"&&r.risk!=="high")throw new Error(`config.permissions.shell.ask[${n}].risk must be one of: low, medium, high.`);if(r.defaultAnswer!==void 0&&r.defaultAnswer!=="approve"&&r.defaultAnswer!=="reject")throw new Error(`config.permissions.shell.ask[${n}].defaultAnswer must be approve or reject.`)}}}if(e.permissions.patchApply!==void 0){let n=e.permissions.patchApply;if(typeof n=="string"){if(n!=="allow"&&n!=="ask"&&n!=="deny")throw new Error("config.permissions.patchApply must be allow, ask, deny, or an object.")}else if(y(n)){if(n.decision!==void 0&&n.decision!=="allow"&&n.decision!=="ask"&&n.decision!=="deny")throw new Error("config.permissions.patchApply.decision must be allow, ask, or deny.");if(h(n.reason,"config.permissions.patchApply.reason"),n.risk!==void 0&&n.risk!=="low"&&n.risk!=="medium"&&n.risk!=="high")throw new Error("config.permissions.patchApply.risk must be one of: low, medium, high.");if(n.defaultAnswer!==void 0&&n.defaultAnswer!=="approve"&&n.defaultAnswer!=="reject")throw new Error("config.permissions.patchApply.defaultAnswer must be approve or reject.")}else throw new Error("config.permissions.patchApply must be allow, ask, deny, or an object.")}}if(e.tools!==void 0){if(!y(e.tools))throw new Error("config.tools must be an object.");for(let[n,r]of Object.entries(e.tools)){if(!y(r))throw new Error(`config.tools.${n} must be an object.`);b(r.timeoutMs,`config.tools.${n}.timeoutMs`),b(r.retries,`config.tools.${n}.retries`);}}if(e.batch!==void 0){if(!y(e.batch))throw new Error("config.batch must be an object.");if(S(e.batch.stopOnFailure,"config.batch.stopOnFailure"),e.batch.goals!==void 0){if(!Array.isArray(e.batch.goals))throw new Error("config.batch.goals must be an array.");e.batch.goals.forEach((n,r)=>Vr(n,`config.batch.goals[${r}]`));}}return e},qt=async e=>{let{stat:t}=await oe("node:fs/promises");try{return (await t(e)).isFile()}catch{return false}},Ur=async e=>{let t=await oe("node:path"),n=t.resolve(e);for(;;){for(let o of Mt){let a=t.join(n,o);if(await qt(a))return a}let r=t.dirname(n);if(r===n)return;n=r;}},Gt=async e=>{let{readFile:t}=await oe("node:fs/promises"),n=String(await t(e,"utf8")).replace(/^\uFEFF/,"");try{return zr(JSON.parse(n),e)}catch(r){throw r instanceof SyntaxError?new Error(`Invalid JSON in agent config ${e}: ${r.message}`):r}},Na=async e=>{if(e.noConfig)return {config:{}};let t=await oe("node:path");if(e.configPath){let r=t.isAbsolute(e.configPath)?e.configPath:t.resolve(e.cwd,e.configPath);if(!await qt(r))throw new Error(`Agent config not found or not a file: ${r}`);return {path:r,config:await Gt(r)}}let n=await Ur(e.cwd);return n?{path:n,config:await Gt(n)}:{config:{}}};var Wr=e=>e?.choices?.[0]?.message?.content??e?.output_text??e?.content?.[0]?.text??JSON.stringify(e),qa=e=>({complete:t=>chunkK47BP5A2_cjs.da(async n=>{let r=await fetch(e.endpoint,{method:"POST",signal:n,headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({model:e.model,messages:[{role:"user",content:t.prompt}]})});if(!r.ok)throw new Error(`LLM request failed with ${r.status}`);return {content:Wr(await r.json())}},n=>({_tag:"LLMError",cause:n}))});var Qr="gemini-2.5-flash",Kr="v1beta",Zr="https://generativelanguage.googleapis.com",Hr=e=>{let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)},Jr=e=>e.startsWith("models/")?e:`models/${e}`,Xr=e=>{if(e.endpoint)return e.endpoint;let t=Hr(e.baseUrl??Zr),n=e.apiVersion??Kr,r=Jr(e.model??Qr);return `${t}/${n}/${r}:generateContent`},ae=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Bt=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Yr=(e,t)=>{let n=Bt({temperature:ae(t.temperature),topP:ae(t.topP),topK:ae(t.topK),maxOutputTokens:ae(t.maxOutputTokens),stopSequences:t.stopSequences,responseMimeType:t.responseMimeType,...t.extraGenerationConfig??{}});return Bt({contents:[{role:"user",parts:[{text:e.prompt}]}],systemInstruction:t.systemInstruction?{parts:[{text:t.systemInstruction}]}:void 0,generationConfig:Object.keys(n).length>0?n:void 0})},eo=e=>{let t=e.candidates?.flatMap(o=>o.content?.parts??[]).map(o=>o.text??"").filter(Boolean).join(`
24
+ `).trim();if(t)return t;let n=e.promptFeedback?.blockReason;if(n){let o=e.promptFeedback?.blockReasonMessage;throw new Error(`Google Gemini blocked the prompt: ${n}${o?` - ${o}`:""}`)}let r=e.candidates?.[0]?.finishReason;if(r)throw new Error(`Google Gemini returned no text. finishReason=${r}`);if(e.error?.message)throw new Error(`Google Gemini error: ${e.error.message}`);return JSON.stringify(e)},to=async e=>{let t=await e.text();try{return JSON.parse(t).error?.message??t}catch{return t}},za=e=>({complete:t=>chunkK47BP5A2_cjs.da(async n=>{let r=await fetch(Xr(e),{method:"POST",signal:n,headers:{"content-type":"application/json","x-goog-api-key":e.apiKey},body:JSON.stringify(Yr({prompt:t.prompt},e))});if(!r.ok){let a=await to(r);throw new Error(`Google Gemini request failed with ${r.status}: ${a}`)}let o=await r.json();return {content:eo(o)}},n=>({_tag:"LLMError",cause:n}))});var no=e=>["Fake LLM response.","",`Purpose: ${e.purpose}`,"Set BRASS_LLM_PROVIDER=google with GEMINI_API_KEY/GOOGLE_API_KEY, or set BRASS_LLM_ENDPOINT and BRASS_LLM_API_KEY for an OpenAI-compatible model.","You can also set BRASS_FAKE_LLM_RESPONSE to provide a deterministic offline response, including a fenced ```diff block."].join(`
25
+ `),Qa=(e={})=>({complete:t=>chunkK47BP5A2_cjs.f({content:typeof e.content=="function"?e.content(t):e.content??no(t)})});var co=[{name:".brass-agent.json",kind:"file"},{name:"brass-agent.config.json",kind:"file"},{name:"package.json",kind:"file"},{name:"pnpm-workspace.yaml",kind:"file"},{name:"turbo.json",kind:"file"},{name:"nx.json",kind:"file"},{name:".git",kind:"directory"}],lo=(e,t)=>{try{let n=fs.statSync(e);return t==="directory"?n.isDirectory():n.isFile()}catch{return false}},po=e=>{for(let t of co){let n=path.join(e,t.name);if(lo(n,t.kind))return {marker:t.name,markerPath:n}}},Ja=(e,t={})=>{let n=path.resolve(e);if(t.enabled===false)return {inputCwd:n,cwd:n,changed:false,disabled:true};if(!fs.existsSync(n))return {inputCwd:n,cwd:n,changed:false};let r=n;for(;;){let o=po(r);if(o)return {inputCwd:n,cwd:r,marker:o.marker,markerPath:o.markerPath,changed:r!==n};let a=path.dirname(r);if(a===r)return {inputCwd:n,cwd:n,changed:false};r=a;}};exports.$=Et;exports.A=O;exports.B=nt;exports.C=rt;exports.D=ke;exports.E=ot;exports.F=at;exports.G=xe;exports.H=M;exports.I=it;exports.J=Hn;exports.K=ct;exports.L=lt;exports.M=rr;exports.N=Se;exports.O=te;exports.P=At;exports.Q=v;exports.R=E;exports.S=Pe;exports.T=_o;exports.U=To;exports.V=Oo;exports.W=bt;exports.X=kt;exports.Y=xt;exports.Z=vt;exports._=Pr;exports.a=Le;exports.aa=Ct;exports.b=_e;exports.ba=da;exports.c=Te;exports.ca=Ce;exports.d=qe;exports.da=$t;exports.e=ze;exports.ea=Ft;exports.f=ue;exports.fa=Mt;exports.g=dn;exports.ga=Lt;exports.h=We;exports.ha=ma;exports.i=Qe;exports.ia=Ir;exports.j=Ke;exports.ja=ha;exports.k=fe;exports.ka=ka;exports.l=ye;exports.la=xa;exports.m=An;exports.ma=wa;exports.n=Xe;exports.na=ja;exports.o=Ye;exports.oa=_a;exports.p=Ze;exports.pa=Na;exports.q=$n;exports.qa=qa;exports.r=J;exports.ra=za;exports.s=P;exports.sa=Qa;exports.t=X;exports.ta=Ja;exports.u=Ae;exports.v=On;exports.w=Y;exports.x=ee;exports.y=tt;exports.z=be;
@@ -0,0 +1 @@
1
+ import {r,s as s$1,j,O,fa,N as N$1,z,C as C$1,y as y$1,A,w as w$1,b,d,g,f,v,h,x,u,ea,l,la,t}from'./chunk-LTHJNW5A.js';var C=e=>e._tag==="None"?r:s$1(e.value),m=e=>({_tag:"FromPull",pull:e}),D=(e,a)=>({_tag:"Scoped",acquire:e,release:a}),K=e=>({_tag:"Managed",acquire:e}),Q=(e,a,r=true)=>({_tag:"Merge",left:e,right:a,flip:r}),G={_tag:"Empty"},P=()=>G,Y=e=>({_tag:"Emit",value:e}),w=(e,a)=>({_tag:"Concat",left:e,right:a}),N=e=>({_tag:"Flatten",stream:e});function T(e,a,r,n,t$1){return (o,E,R)=>{if(o._tag,o._tag,o._tag==="Success"){let[i,c]=o.value;E.interrupt();let d=m(e==="L"?B(c,r):B(a,c));return f([i,d])}if(o.cause._tag==="Interrupt")return j((i,c)=>{c(u.failCause(t.interrupt()));});let u$1=o.cause.error;return u$1._tag==="None"?s(e==="L"?r:a):g(u$1)}}function B(e,a,r,n){let o=T("L",e,a),E=T("R",e,a);return j((R,u)=>{let i=O(),c=new fa(i),d=la(s(e),s(a),c,o,E);c.fork(d).join(A=>{c.close(A),u(A);});})}function Ae(e,a){return m(B(e,a))}function s(e){switch(e._tag){case "Empty":return w$1(r);case "Emit":return y$1(A(e.value,a=>s$1(a)),a=>[a,G]);case "FromPull":return e.pull;case "Concat":return C$1(y$1(s(e.left),([a,r])=>[a,w(r,e.right)]),()=>s(e.right));case "Flatten":return z(s(e.stream),([a,r])=>C$1(y$1(s(a),([n,t])=>[n,w(t,N(r))]),()=>s(N(r))));case "Merge":return B(e.left,e.right,e.flip);case "Scoped":return j((a,r)=>{let n=O(),t=new fa(n);N$1()?.addFinalizer(u=>{try{t.close(u);}catch{}});let E=u=>{if(u._tag==="Failure"){let i=u.cause.error;if(i&&typeof i=="object"&&i._tag==="None"){t.close({_tag:"Success",value:void 0});return}}t.close(u);},R=u$1=>m(j((i,c)=>{let d=s(u$1);ea(d,i,A=>{let l=u.failCause(A);E(l),c(l);},([A,l])=>{c(u.succeed([A,R(l)]));});}));t.fork(e.acquire).join(u=>{if(u._tag==="Failure"){E(u),r({_tag:"Failure",cause:{_tag:"Fail",error:s$1(u.cause.error)}});return}t.addFinalizer(c=>e.release(c));let i=u.value;O().fork(s(R(i))).join(r);});});case "Managed":return j((a,r)=>{let n=O(),t=new fa(n);N$1()?.addFinalizer(E=>{try{t.close(E);}catch{}});let o=E=>{if(E._tag==="Failure"){let R=E.cause.error;if(R&&typeof R=="object"&&R._tag==="None"){t.close({_tag:"Success",value:void 0});return}}t.close(E);};t.fork(e.acquire).join(E=>{if(E._tag==="Failure"){t.close(E),r({_tag:"Failure",cause:{_tag:"Fail",error:s$1(E.cause.error)}});return}let{stream:R,release:u$1}=E.value;t.addFinalizer(c=>u$1(c));let i=c=>m(j((d,A)=>{s(c)(d,l=>{if(l._tag==="Failure"){o(l),A(l);return}let[$,J]=l.value;A(u.succeed([$,i(J)]));});}));O().fork(s(i(R))).join(r);});})}}function X(e,a){throw new Error(a??`Unexpected value: ${String(e)}`)}function y(e,a){switch(e._tag){case "Empty":return P();case "Emit":return Y(y$1(e.value,a));case "FromPull":return m(y$1(e.pull,([r,n])=>[a(r),y(n,a)]));case "Concat":return w(y(e.left,a),y(e.right,a));case "Flatten":{let r=y(e.stream,n=>y(n,a));return N(r)}case "Merge":return Q(y(e.left,a),y(e.right,a),e.flip);case "Scoped":return D(y$1(e.acquire,r=>y(r,a)),e.release);case "Managed":return K(y$1(e.acquire,({stream:r,release:n})=>({stream:y(r,a),release:n})));default:return X(e)}}function le(e,a){let r$1=n=>m(n>a?g(r):f([n,r$1(n+1)]));return r$1(e)}function ee(e,a){let r=b(d(s(e),n=>C(n)),n=>g(n),([n,t])=>b(d(s(a),o=>C(o)),o=>g(o),([o,E])=>f([[n,o],ee(t,E)])));return m(r)}function ye(e,a){let r=n=>b(d(s(n),t=>C(t)),t=>t._tag==="None"?f(void 0):g(t),([t,o])=>l(d(a(t),E=>s$1(E)),()=>r(o)));return b(r(e),n=>n._tag==="None"?f(void 0):g(n.value),()=>f(void 0))}function pe(e){let a=P();for(let r=e.length-1;r>=0;r--){let n=Y(v(e[r]));a=w(n,a);}return a}function Se(e){let a=(r,n)=>b(s(r),t=>t._tag==="None"?v(n):w$1(t),([t,o])=>a(o,[...n,t]));return A(a(e,[]),r=>{if(r._tag==="Some")return r.value;throw new Error("unreachable: stream end handled as success")})}function ae(e,a){let r$1=j((n,t)=>{e.read().then(({done:o,value:E})=>{if(o){t({_tag:"Failure",cause:{_tag:"Fail",error:r}});return}t({_tag:"Success",value:[E,m(r$1)]});}).catch(o=>{t({_tag:"Failure",cause:{_tag:"Fail",error:s$1(a(o))}});});});return m(r$1)}function de(e,a){if(!e)return P();let r;return D(x(()=>(r=e.getReader(),ae(r,a))),()=>h(()=>{try{r?.cancel();}catch{}}))}export{C as a,m as b,D as c,K as d,Q as e,P as f,Y as g,w as h,N as i,Ae as j,s as k,X as l,y as m,le as n,ee as o,ye as p,pe as q,Se as r,de as s};
@@ -0,0 +1,2 @@
1
+ 'use strict';var module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var J={succeed:r=>({_tag:"Succeed",value:r}),fail:r=>({_tag:"Fail",error:r}),sync:r=>({_tag:"Sync",thunk:r}),async:r=>({_tag:"Async",register:r})};function F(r,e,n){return {_tag:"Fold",first:r,onFailure:e,onSuccess:n}}function Ye(r,e){return F(r,n=>e(n),n=>E(n))}function re(r,e){return F(r,n=>T(e(n)),n=>E(n))}var ie={_tag:"Succeed",value:void 0},Se={_tag:"Succeed",value:true},Ie={_tag:"Succeed",value:false},we={_tag:"Succeed",value:null},m=()=>ie,E=r=>r===void 0?ie:r===true?Se:r===false?Ie:r===null?we:{_tag:"Succeed",value:r},T=r=>({_tag:"Fail",error:r}),B=r=>({_tag:"Sync",thunk:r}),Xe=r=>B(()=>r()),h=r=>({_tag:"Async",register:r});function se(r,e){return y(r,n=>E(e(n)))}function y(r,e){return {_tag:"FlatMap",first:r,andThen:e}}function en(r,e,n){return y(r,t=>(n.addFinalizer(i=>e(t,i)),E(t)))}function nn(r){return h(r)}var tn=r=>e=>{let n=e;return n.toPromise||(n.toPromise=t=>r(e,t),n.unsafeRunPromise=()=>r(e,{})),n},rn=(r,e)=>y(r,n=>E(e(n))),sn=(r,e)=>y(r,n=>B(()=>e(n)));var oe={_tag:"None"},an=r=>({_tag:"Some",value:r});var c={fail:r=>({_tag:"Fail",error:r}),interrupt:()=>({_tag:"Interrupt"}),die:r=>({_tag:"Die",defect:r})},l={succeed:r=>({_tag:"Success",value:r}),failCause:r=>({_tag:"Failure",cause:r})},ln=r=>E(r),xe=r=>T(r),fn=r=>B(e=>r(e)),pn=(r,e)=>se(r,e),hn=(r,e)=>y(r,n=>e(n)),yn=(r,e)=>re(r,e),mn=(r,e)=>F(r,n=>e(n),n=>E(n));function gn(r,e){return F(r,n=>n._tag==="Some"?T(n):e(),n=>E(n))}var bn=()=>xe(oe);var _e=(t=>(t[t.Ok=0]="Ok",t[t.Grew=1]="Grew",t[t.Dropped=2]="Dropped",t))(_e||{}),I=class{buf;head=0;tail=0;size_=0;maxCap;constructor(e=1024,n=e){let t=Math.max(2,e);t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++;let i=Math.max(t,n);i--,i|=i>>>1,i|=i>>>2,i|=i>>>4,i|=i>>>8,i|=i>>>16,i++,this.buf=new Array(t),this.maxCap=i;}get length(){return this.size_}get capacity(){return this.buf.length}isEmpty(){return this.size_===0}push(e){return this.size_===this.buf.length?this.buf.length>=this.maxCap?2:(this.grow(),this.buf[this.tail]=e,this.tail=this.tail+1&this.buf.length-1,this.size_++,1):(this.buf[this.tail]=e,this.tail=this.tail+1&this.buf.length-1,this.size_++,0)}shift(){if(this.size_===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=this.head+1&this.buf.length-1,this.size_--,e}clear(){this.head=0,this.tail=0,this.size_=0;}grow(){let e=this.buf,n=Math.min(e.length*2,this.maxCap),t=new Array(n);for(let i=0;i<this.size_;i++)t[i]=e[this.head+i&e.length-1];this.buf=t,this.head=0,this.tail=this.size_;}};var $,ae=[];function R(r={}){if(!r.fresh&&r.modulePath==null&&$!==void 0)return $;let e=Be(),n=Te(r.modulePath),t=[];if(!e)return t.push("no CommonJS-compatible require/createRequire was available"),L(r,null,t);for(let i of n)try{return L(r,e(i),t)}catch(s){t.push(`${i}: ${De(s)}`);}return L(r,null,t)}function ue(){return ae.slice()}function Te(r){return r?[r]:["brass-runtime/wasm/pkg/brass_runtime_wasm_engine.js","../wasm/pkg/brass_runtime_wasm_engine.js","../../../wasm/pkg/brass_runtime_wasm_engine.js","../../../../../wasm/pkg/brass_runtime_wasm_engine.js",`${Me()}/wasm/pkg/brass_runtime_wasm_engine.js`]}function L(r,e,n){return !r.fresh&&r.modulePath==null&&($=e,ae=n),e}function Be(){return We()??Oe()??Ne()}function We(){try{return (0,eval)("typeof __non_webpack_require__ === 'function' ? __non_webpack_require__ : undefined")}catch{return}}function Oe(){try{return (0,eval)("typeof require === 'function' ? require : undefined")}catch{return}}function Ne(){try{return module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-K47BP5A2.cjs', document.baseURI).href)))}catch{return}}function Me(){try{return (0,eval)("typeof process !== 'undefined' ? process.cwd() : ''")}catch{return ""}}function De(r){return r instanceof Error?r.message:String(r)}var W;function de(){return W!==void 0||(W=R()?.BrassWasmRingBuffer??null),W}var O=class{engine="wasm";fallbackUsed=false;inner;pushes=0;shifts=0;clears=0;dropped=0;constructor(e,n){let t=de();if(!t)throw new Error("brass-runtime wasm ring buffer is not available. Run npm run build:wasm first.");this.inner=new t(e,n);}get length(){return this.inner.len()}get capacity(){return this.inner.capacity()}isEmpty(){return this.inner.is_empty()}push(e){this.pushes++;let n=this.inner.push(e);return (n&2)!==0&&this.dropped++,n}shift(){let e=this.inner.shift();return e!==void 0&&this.shifts++,e===void 0?void 0:e}clear(){this.clears++,this.inner.clear();}stats(){return {engine:"wasm",fallbackUsed:false,data:{len:this.length,capacity:this.capacity,pushes:this.pushes,shifts:this.shifts,clears:this.clears,dropped:this.dropped}}}},N=class{constructor(e,n){this.inner=e;this.fallbackUsed=n;}inner;fallbackUsed;engine="js";pushes=0;shifts=0;clears=0;dropped=0;get length(){return this.inner.length}get capacity(){return this.inner.capacity}isEmpty(){return this.inner.isEmpty()}push(e){this.pushes++;let n=this.inner.push(e);return (n&2)!==0&&this.dropped++,n}shift(){let e=this.inner.shift();return e!==void 0&&this.shifts++,e}clear(){this.clears++,this.inner.clear();}stats(){return {engine:"js",fallbackUsed:this.fallbackUsed,data:{len:this.length,capacity:this.capacity,pushes:this.pushes,shifts:this.shifts,clears:this.clears,dropped:this.dropped}}}};function Z(r,e=r,n={}){let t=n.engine??"auto";return t==="js"?new N(new I(r,e),false):t==="wasm"?new O(r,e):de()?new O(r,e):new N(new I(r,e),true)}var ce=2048,le=4096,He=8192,Ue=(()=>{if(typeof globalThis.setImmediate=="function")return r=>globalThis.setImmediate(r);if(typeof globalThis.MessageChannel=="function"){let r=new globalThis.MessageChannel,e=null;return r.port1.onmessage=()=>{let n=e;e=null,n?.();},n=>{e=n,r.port2.postMessage(0);}}return r=>setTimeout(r,0)})();function fe(){return R()?.BrassWasmSchedulerStateMachine??null}var Q=class{tasks;tags;flushing=false;scheduled=false;scheduledFlushes=0;completedFlushes=0;enqueuedTasks=0;executedTasks=0;droppedTasks=0;yieldedByBudget=0;constructor(e){let n=e.initialCapacity??1024,t=e.maxCapacity??n;this.tasks=Z(n,t,{engine:e.engine}),this.tags=Z(n,t,{engine:e.engine});}},M=class{machine;nextRef=1;tasks=new Map;tags=new Map;constructor(e){let n=fe();if(!n)throw new Error("brass-runtime wasm scheduler is not available. Run npm run build:wasm first.");this.machine=new n(e.initialCapacity??1024,e.maxCapacity??He,e.flushBudget??ce,e.microThreshold??le);}enqueue(e,n){let t=this.nextRef++;this.tasks.set(t,e),this.tags.set(t,n);let i=this.machine.enqueue(t);return i===3&&(this.tasks.delete(t),this.tags.delete(t)),i}beginFlush(){return this.machine.begin_flush()}shift(){let e=this.machine.shift();if(e===0)return;let n=this.tasks.get(e),t=this.tags.get(e)??"anonymous";return this.tasks.delete(e),this.tags.delete(e),n?{task:n,tag:t}:void 0}endFlush(e){return this.machine.end_flush(e)}get length(){return this.machine.len()}stats(){return {engine:"wasm",fallbackUsed:false,data:JSON.parse(this.machine.stats_json())}}},G=class{engine;js;wasm;flushBudget;microThreshold;fallbackUsed;boundFlush=()=>this.flush();constructor(e={}){this.flushBudget=e.flushBudget??ce,this.microThreshold=e.microThreshold??le;let n=e.engine??"js";if(n==="wasm"){this.wasm=new M(e),this.engine="wasm",this.fallbackUsed=false;return}if(n==="auto"&&fe()){this.wasm=new M(e),this.engine="wasm",this.fallbackUsed=false;return}this.js=new Q({...e,engine:"js"}),this.engine="js",this.fallbackUsed=n==="auto";}schedule(e,n="anonymous"){if(typeof e=="function"){if(this.wasm)return this.scheduleWasm(e,n);this.scheduleJs(e,n);}}stats(){if(this.wasm)return this.wasm.stats();let e=this.js;return {engine:"js",fallbackUsed:this.fallbackUsed,data:{len:e.tasks.length,capacity:e.tasks.capacity,phase:e.flushing?"flushing":e.scheduled?"scheduled":"idle",scheduledFlushes:e.scheduledFlushes,completedFlushes:e.completedFlushes,enqueuedTasks:e.enqueuedTasks,executedTasks:e.executedTasks,droppedTasks:e.droppedTasks,yieldedByBudget:e.yieldedByBudget}}}scheduleWasm(e,n){let t=this.wasm.enqueue(e,n);t===0?this.requestFlush("micro"):t===1&&this.requestFlush("macro");}scheduleJs(e,n){let t=this.js,i=t.tasks.push(e),s=t.tags.push(n);if(t.enqueuedTasks++,((i&2)!==0||(s&2)!==0)&&t.droppedTasks++,!t.flushing&&!t.scheduled){t.scheduled=true,t.scheduledFlushes++;let o=t.tasks.length>this.microThreshold?"macro":"micro";this.requestFlush(o);}}requestFlush(e){e==="micro"?queueMicrotask(this.boundFlush):Ue(this.boundFlush);}flush(){if(this.wasm)return this.flushWasm();this.flushJs();}flushWasm(){let e=this.wasm,n=e.beginFlush();if(n<=0)return;let t=0;try{for(;t<n;){let i=e.shift();if(!i)break;t++;try{i.task();}catch(s){console.error(`[Scheduler] task threw (tag=${i.tag})`,s);}}}finally{let i=e.endFlush(t);i===0?this.requestFlush("micro"):i===1&&this.requestFlush("macro");}}flushJs(){let e=this.js;if(e.flushing)return;e.flushing=true,e.scheduled=false;let n=0;try{for(;n<this.flushBudget;){let t=e.tasks.shift();if(!t)break;let i=e.tags.shift();n++,e.executedTasks++;try{t();}catch(s){console.error(`[Scheduler] task threw (tag=${i})`,s);}}}finally{if(e.flushing=false,e.completedFlushes++,e.tasks.length>0&&!e.scheduled){e.scheduled=true,e.scheduledFlushes++;let t=n>=this.flushBudget||e.tasks.length>this.microThreshold?"macro":"micro";n>=this.flushBudget&&e.yieldedByBudget++,this.requestFlush(t);}}}},w=new G;var pe={parent:null,patch:Object.create(null)};function ye(r,e){let n=je(r);return {initChild(t,i,s){let o=i?.fiberContext,a=Pe(n,o?.trace??null);t.fiberContext={log:o?.log??pe,trace:a},t.parentFiberId=i?.id,t.name=n.childName(i?.name),s!==void 0&&(t.scopeId=s),e.emit({type:"fiber.start",fiberId:t.id,parentFiberId:i?.id,scopeId:t.scopeId,name:t.name},{fiberId:i?.id,traceId:o?.trace?.traceId,spanId:o?.trace?.spanId});}}}function je(r){let e={newTraceId:()=>he("trace"),newSpanId:()=>he("span")},n=r?.brass,t=n?.tracer??e,i=n?.traceSeed,s=n?.childName??(o=>o?`${o}/child`:void 0);return {tracer:t,seed:i,childName:s}}function he(r){let e=globalThis.crypto;return typeof e?.randomUUID=="function"?e.randomUUID():`${r}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function Pe(r,e){return e?{traceId:e.traceId,spanId:r.tracer.newSpanId(),parentSpanId:e.spanId,sampled:e.sampled}:r.seed?{...r.seed}:{traceId:r.tracer.newTraceId(),spanId:r.tracer.newSpanId(),sampled:true}}var me={async execute(r){return {kind:"error",actionId:r.actionId,error:new Error(`No HostExecutor configured for HostAction kind=${r.kind} target=${r.target}`)}}};var x=class{constructor(e){this.runtime=e;}runtime;kind="js";startedFibers=0;fork(e,n){this.startedFibers+=1;let t=new D(this.runtime,e);return n!==void 0&&(t.scopeId=n),t}stats(){return {engine:this.kind,startedFibers:this.startedFibers,runningFibers:0,suspendedFibers:0,queuedFibers:0,completedFibers:0,failedFibers:0,interruptedFibers:0,pendingHostEffects:0}}};var K=class{nextRef=1;refs=new Map;register(e){let n=this.nextRef++;return this.refs.set(n,e),n}get(e){if(!this.refs.has(e))throw new Error(`Missing host registry ref ${e}`);return this.refs.get(e)}set(e,n){this.refs.set(e,n);}delete(e){this.refs.delete(e);}clear(){this.refs.clear();}size(){return this.refs.size}},H=class{nodes=[];registry=new K;compile(e){return {program:{version:1,root:this.visit(e),nodes:this.nodes},registry:this.registry}}append(e){let n=this.nodes.length;return {root:this.visit(e),nodes:this.nodes.slice(n)}}add(e){let n=this.nodes.length;return this.nodes.push(e),n}visit(e){let n=e;switch(n._tag){case "Succeed":return this.add({tag:"Succeed",valueRef:this.registry.register(n.value)});case "Fail":return this.add({tag:"Fail",errorRef:this.registry.register(n.error)});case "Sync":return this.add({tag:"Sync",fnRef:this.registry.register(n.thunk)});case "Async":return this.add({tag:"Async",registerRef:this.registry.register(n.register)});case "FlatMap":return this.add({tag:"FlatMap",first:this.visit(n.first),fnRef:this.registry.register(n.andThen)});case "Fold":return this.add({tag:"Fold",first:this.visit(n.first),onFailureRef:this.registry.register(n.onFailure),onSuccessRef:this.registry.register(n.onSuccess)});case "Fork":{let t={tag:"Fork",effectRef:this.registry.register(n.effect)};return this.add(n.scopeId===void 0?t:{...t,scopeId:n.scopeId})}case "HostAction":{let t={tag:"HostAction",actionRef:this.registry.register(n.action)};return this.add(n.decode===void 0?t:{...t,decodeRef:this.registry.register(n.decode)})}default:return this.add({tag:"Fail",errorRef:this.registry.register(new Error(`Unknown Async opcode: ${n?._tag}`))})}}};var U=class{constructor(e,n,t,i,s,o){this.onScheduledStep=t;this.onInterrupt=i;this.onJoiner=s;this.onQueued=o;this.id=e,this.runtime=n;}onScheduledStep;onInterrupt;onJoiner;onQueued;id;runtime;fiberContext;name;scopeId;parentFiberId;result=null;joiners=[];finalizers=[];finalizersDrained=false;internalStatus="running";queued=false;status(){return this.result==null?"Running":this.result._tag==="Failure"&&this.result.cause._tag==="Interrupt"?"Interrupted":"Done"}engineStatus(){return this.internalStatus}setEngineStatus(e){this.internalStatus=e;}join(e){this.result!=null?e(this.result):(this.onJoiner?.(this.id),this.joiners.push(e));}interrupt(){this.result==null&&this.onInterrupt(this.id,c.interrupt());}addFinalizer(e){this.finalizers.push(e);}schedule(e="step"){this.result!=null||this.queued||(this.queued=true,this.internalStatus="queued",this.onQueued?.(this.id),this.runtime.scheduler.schedule(()=>{this.queued=false,this.result==null&&this.onScheduledStep(this.id);},`wasm-fiber#${this.id}.${e}`));}emit(e){this.runtime.hooks.emit(e,{fiberId:this.id,scopeId:this.scopeId,traceId:this.fiberContext?.trace?.traceId,spanId:this.fiberContext?.trace?.spanId});}succeed(e){this.complete(l.succeed(e));}fail(e){this.complete(l.failCause(c.fail(e)));}die(e){this.complete(l.failCause(c.die(e)));}interrupted(){this.complete(l.failCause(c.interrupt()));}complete(e){if(this.result!=null)return;this.runFinalizersOnce(e),this.result=e,this.internalStatus=e._tag==="Success"?"done":e.cause._tag==="Interrupt"?"interrupted":"failed";let n=e._tag==="Success"?"success":e.cause._tag==="Interrupt"?"interrupted":"failure";this.emit({type:"fiber.end",fiberId:this.id,status:n,error:e._tag==="Failure"?e.cause:void 0});for(let t of this.joiners)t(e);this.joiners.length=0;}runFinalizersOnce(e){if(!this.finalizersDrained)for(this.finalizersDrained=true;this.finalizers.length>0;){let n=this.finalizers.pop();try{let t=n(e);t&&typeof t=="object"&&"_tag"in t&&this.runtime.fork(t);}catch{}}}};var j=class{kind="wasm-reference";nextFiberId=1;fibers=new Map;started=0;completed=0;failed=0;interrupted=0;createFiber(e){let n=this.nextFiberId++;return this.started+=1,this.fibers.set(n,{id:n,program:qe(e),current:e.root,stack:[],status:"running",lastEvent:void 0}),n}poll(e){let n=this.mustFiber(e);return n.status==="suspended"&&n.lastEvent?n.lastEvent:this.step(n)}provideValue(e,n){let t=this.mustFiber(e);return t.status="running",t.lastEvent=void 0,this.success(t,n)}provideError(e,n){let t=this.mustFiber(e);return t.status="running",t.lastEvent=void 0,this.failure(t,n)}provideEffect(e,n,t){let i=this.mustFiber(e);return i.status="running",i.lastEvent=void 0,i.program.nodes.push(...t.map(s=>({...s}))),i.current=n,this.step(i)}interrupt(e,n){let t=this.mustFiber(e);t.status="interrupted",t.current=void 0,t.stack=[],this.interrupted+=1;let i={kind:"Interrupted",fiberId:e,reasonRef:n};return t.lastEvent=i,i}dropFiber(e){this.fibers.delete(e);}stats(){let e=0,n=0;for(let t of this.fibers.values())t.status==="running"&&(e+=1),t.status==="suspended"&&(n+=1);return {started:this.started,live:this.fibers.size,running:e,suspended:n,completed:this.completed,failed:this.failed,interrupted:this.interrupted}}mustFiber(e){let n=this.fibers.get(e);if(!n)throw new Error(`Fiber ${e} not found`);return n}step(e){for(;;){if(e.status==="interrupted"){let t=e.lastEvent??{kind:"Interrupted",fiberId:e.id,reasonRef:0};return e.lastEvent=t,t}if(e.current===void 0)return this.markFailed(e,0);let n=e.program.nodes[e.current];if(!n)return this.markFailed(e,0);switch(n.tag){case "Succeed":return e.current=void 0,this.success(e,n.valueRef);case "Fail":return e.current=void 0,this.failure(e,n.errorRef);case "Sync":return this.suspend(e,{kind:"InvokeSync",fiberId:e.id,fnRef:n.fnRef});case "Async":return this.suspend(e,{kind:"InvokeAsync",fiberId:e.id,registerRef:n.registerRef});case "FlatMap":e.stack.push({tag:"SuccessCont",fnRef:n.fnRef}),e.current=n.first;continue;case "Fold":e.stack.push({tag:"FoldCont",onFailureRef:n.onFailureRef,onSuccessRef:n.onSuccessRef}),e.current=n.first;continue;case "Fork":{let t=n.scopeId===void 0?{kind:"InvokeFork",fiberId:e.id,effectRef:n.effectRef}:{kind:"InvokeFork",fiberId:e.id,effectRef:n.effectRef,scopeId:n.scopeId};return this.suspend(e,t)}case "HostAction":{let t=n.decodeRef===void 0?{kind:"InvokeHostAction",fiberId:e.id,actionRef:n.actionRef}:{kind:"InvokeHostAction",fiberId:e.id,actionRef:n.actionRef,decodeRef:n.decodeRef};return this.suspend(e,t)}}}}success(e,n){let t=e.stack.pop();return t?t.tag==="SuccessCont"?this.suspend(e,{kind:"InvokeFlatMap",fiberId:e.id,fnRef:t.fnRef,valueRef:n}):this.suspend(e,{kind:"InvokeFoldSuccess",fiberId:e.id,fnRef:t.onSuccessRef,valueRef:n}):this.markDone(e,n)}failure(e,n){for(;e.stack.length>0;){let t=e.stack.pop();if(t.tag==="FoldCont")return this.suspend(e,{kind:"InvokeFoldFailure",fiberId:e.id,fnRef:t.onFailureRef,errorRef:n})}return this.markFailed(e,n)}suspend(e,n){return e.status="suspended",e.lastEvent=n,n}markDone(e,n){e.status="done",e.current=void 0,this.completed+=1;let t={kind:"Done",fiberId:e.id,valueRef:n};return e.lastEvent=t,t}markFailed(e,n){e.status="failed",e.current=void 0,this.failed+=1;let t={kind:"Failed",fiberId:e.id,errorRef:n};return e.lastEvent=t,t}};function qe(r){return {version:r.version,root:r.root,nodes:r.nodes.map(e=>({...e}))}}var P=class{kind="wasm";vm;constructor(e){let n=ze(e);this.vm=new n.BrassWasmVm;}createFiber(e){return this.vm.create_fiber(JSON.stringify(e))}poll(e){return JSON.parse(this.vm.poll(e))}provideValue(e,n){return JSON.parse(this.vm.provide_value(e,n))}provideError(e,n){return JSON.parse(this.vm.provide_error(e,n))}provideEffect(e,n,t){return JSON.parse(this.vm.provide_effect(e,n,JSON.stringify(t)))}interrupt(e,n){return JSON.parse(this.vm.interrupt(e,n))}dropFiber(e){this.vm.drop_fiber(e);}stats(){return JSON.parse(this.vm.stats_json())}};function ze(r){let e=R({modulePath:r});if(e)return e;let n=ue();throw new Error(["engine='wasm' could not load wasm/pkg/brass_runtime_wasm_engine.js.","Run `npm run build:wasm` first and make sure wasm/pkg is present in the package.","For Node 18 + webpack, keep brass-runtime's wasm/pkg files available at runtime or externalize brass-runtime.",...n.map(t=>`- ${t}`)].join(`
2
+ `))}var ge=0,be=1,Re=2,Ee=3,ve=4,Ae=5,q=class{registry;constructor(){let n=R()?.BrassWasmFiberRegistry;if(!n)throw new Error("brass-runtime wasm fiber registry is not available. Run npm run build:wasm first.");this.registry=new n;}registerFiber(e,n,t){this.registry.register_fiber(e,n??0,t??0,Date.now());}markQueued(e){this.registry.mark_queued(e,Date.now());}markRunning(e){this.registry.mark_running(e,Date.now());}markSuspended(e){this.registry.mark_suspended(e,Date.now());}markDone(e,n){return this.registry.mark_done(e,Ve(n),Date.now())}dropFiber(e){this.registry.drop_fiber(e);}addJoiner(e){this.registry.add_joiner(e);}wake(e){return this.registry.wake(e)}drainWakeup(){let e=this.registry.drain_wakeup();return e===0?void 0:e}drainWakeups(){let e=[];for(;;){let n=this.drainWakeup();if(n===void 0)return e;e.push(n);}}wakeQueueLength(){return this.registry.wake_queue_len()}stateOf(e){let n=this.registry.state_of(e);return n===4294967295?"missing":Je(n)}stats(){return JSON.parse(this.registry.stats_json())}};function Ve(r){switch(r){case "queued":return ge;case "running":return be;case "suspended":return Re;case "done":return Ee;case "failed":return ve;case "interrupted":return Ae}}function Je(r){switch(r){case ge:return "queued";case be:return "running";case Re:return "suspended";case Ee:return "done";case ve:return "failed";case Ae:return "interrupted";default:return "missing"}}var Le=4096,k=class{constructor(e,n={}){this.runtime=e;this.bridge=n.bridge??(n.reference?new j:new P(n.modulePath)),this.kind=this.bridge.kind,this.fiberRegistry=this.kind==="wasm"?new q:void 0;}runtime;kind;bridge;startedFibers=0;runningFibers=0;suspendedFibers=0;completedFibers=0;failedFibers=0;interruptedFibers=0;pendingHostEffects=0;states=new Map;fiberRegistry;fork(e,n){let t=new H,i=t.compile(e),s=this.bridge.createFiber(i.program),o=new AbortController,a=new U(s,this.runtime,d=>this.scheduleWakeup(d),(d,p)=>this.interruptById(d,p),d=>this.fiberRegistry?.addJoiner(d),d=>this.fiberRegistry?.markQueued(d));n!==void 0&&(a.scopeId=n);let u={fiberId:s,handle:a,builder:t,registry:i.registry,controller:o,startedAt:Date.now(),completed:false,status:"running",pendingCleanups:new Set};return this.states.set(s,u),this.fiberRegistry?.registerFiber(s,void 0,n),this.startedFibers+=1,this.runningFibers+=1,a}stats(){let e=0;for(let n of this.states.values())e+=n.registry.size();return {engine:this.kind,startedFibers:this.startedFibers,runningFibers:this.runningFibers,suspendedFibers:this.suspendedFibers,queuedFibers:0,completedFibers:this.completedFibers,failedFibers:this.failedFibers,interruptedFibers:this.interruptedFibers,pendingHostEffects:this.pendingHostEffects,hostRegistryRefs:e,wasm:this.bridge.stats(),fiberRegistry:this.fiberRegistry?.stats()}}async shutdown(){for(let e of Array.from(this.states.values()))this.interruptState(e,c.interrupt());}scheduleWakeup(e){let n=this.states.get(e);if(!(!n||n.completed)){if(!this.fiberRegistry){this.driveById(e);return}this.fiberRegistry.wake(e)&&this.drainWakeups();}}drainWakeups(){if(this.fiberRegistry)for(let e of this.fiberRegistry.drainWakeups())this.driveById(e);}driveById(e){let n=this.states.get(e);!n||n.completed||(this.fiberRegistry?.markRunning(e),_(n.handle,()=>this.drive(n)));}drive(e,n){if(e.completed)return;let t=Le,i=n??this.bridge.poll(e.fiberId);for(e.status="running",e.handle.setEngineStatus("running");!e.completed&&t-- >0;)try{switch(i.kind){case "Continue":i=this.bridge.poll(e.fiberId);continue;case "Done":{let s=e.registry.get(i.valueRef);this.completeSuccess(e,s);return}case "Failed":{let s=i.errorRef===0?new Error("WASM fiber failed"):e.registry.get(i.errorRef);this.completeFailure(e,s);return}case "Interrupted":{this.completeInterrupted(e);return}case "InvokeSync":{let s=e.registry.get(i.fnRef);try{let o=e.registry.register(s(this.runtime.env));i=this.bridge.provideValue(e.fiberId,o);}catch(o){i=this.bridge.provideError(e.fiberId,e.registry.register(o));}continue}case "InvokeFlatMap":{let s=e.registry.get(i.fnRef),o=e.registry.get(i.valueRef);try{let a=s(o),u=e.builder.append(a);i=this.bridge.provideEffect(e.fiberId,u.root,u.nodes);}catch(a){i=this.bridge.provideError(e.fiberId,e.registry.register(a));}continue}case "InvokeFoldFailure":{let s=e.registry.get(i.fnRef),o=e.registry.get(i.errorRef);try{let a=s(o),u=e.builder.append(a);i=this.bridge.provideEffect(e.fiberId,u.root,u.nodes);}catch(a){i=this.bridge.provideError(e.fiberId,e.registry.register(a));}continue}case "InvokeFoldSuccess":{let s=e.registry.get(i.fnRef),o=e.registry.get(i.valueRef);try{let a=s(o),u=e.builder.append(a);i=this.bridge.provideEffect(e.fiberId,u.root,u.nodes);}catch(a){i=this.bridge.provideError(e.fiberId,e.registry.register(a));}continue}case "InvokeFork":{let s=e.registry.get(i.effectRef);try{let o=this.runtime.fork(s,i.scopeId);i=this.bridge.provideValue(e.fiberId,e.registry.register(o));}catch(o){i=this.bridge.provideError(e.fiberId,e.registry.register(o));}continue}case "InvokeAsync":{this.scheduleAsync(e,i.registerRef);return}case "InvokeHostAction":{this.scheduleHostAction(e,i.actionRef,i.decodeRef);return}}}catch(s){i=this.bridge.provideError(e.fiberId,e.registry.register(s));}e.completed||e.handle.schedule("budget-yield");}scheduleAsync(e,n){this.markSuspended(e,"async"),this.pendingHostEffects+=1;let t=e.registry.get(n),i=false,s=false,o=null,a=()=>{i=true,e.pendingCleanups.delete(a);};e.pendingCleanups.add(a);let u=d=>{if(i)return;let p=d;if(!s){o=p;return}a(),this.pendingHostEffects=Math.max(0,this.pendingHostEffects-1),this.markRunning(e,"async"),this.resumeWithExit(e,p);};try{let d=t(this.runtime.env,u);if(s=!0,o){a(),this.pendingHostEffects=Math.max(0,this.pendingHostEffects-1),this.markRunning(e,"async-sync"),this.resumeWithExit(e,o);return}if(typeof d=="function"){let p=()=>{if(!i){i=!0;try{d();}catch{}e.pendingCleanups.delete(p);}};e.pendingCleanups.add(p),e.handle.addFinalizer(()=>p());}}catch(d){a(),this.pendingHostEffects=Math.max(0,this.pendingHostEffects-1),this.markRunning(e,"async-register-error"),this.resumeWithError(e,d);}}scheduleHostAction(e,n,t){this.markSuspended(e,"host-action"),this.pendingHostEffects+=1;let i=e.registry.get(n),o=()=>{e.pendingCleanups.delete(o);};e.pendingCleanups.add(o),this.runtime.hostExecutor.execute(i,{fiberId:e.fiberId,env:this.runtime.env,signal:e.controller.signal,deadlineAt:i.timeoutMs===void 0?void 0:Date.now()+i.timeoutMs}).then(a=>{if(o(),!e.completed){this.pendingHostEffects=Math.max(0,this.pendingHostEffects-1),this.markRunning(e,"host-action");try{if(t!==void 0){let u=e.registry.get(t);this.resumeWithValue(e,u(a));return}if(a.kind==="error"){this.resumeWithError(e,a.error);return}this.resumeWithValue(e,a.value);}catch(u){this.resumeWithError(e,u);}}}).catch(a=>{o(),!e.completed&&(this.pendingHostEffects=Math.max(0,this.pendingHostEffects-1),this.markRunning(e,"host-action-error"),this.resumeWithError(e,a));});}resumeWithExit(e,n){if(e.completed)return;if(n._tag==="Success"){this.resumeWithValue(e,n.value);return}let t=n.cause;if(t._tag==="Interrupt"){this.interruptState(e,t);return}if(t._tag==="Fail"){this.resumeWithError(e,t.error);return}this.completeDie(e,t.defect);}resumeWithValue(e,n){let t=this.bridge.provideValue(e.fiberId,e.registry.register(n));this.runtime.scheduler.schedule(()=>_(e.handle,()=>this.drive(e,t)),`wasm-fiber#${e.fiberId}.resume`);}resumeWithError(e,n){let t=this.bridge.provideError(e.fiberId,e.registry.register(n));this.runtime.scheduler.schedule(()=>_(e.handle,()=>this.drive(e,t)),`wasm-fiber#${e.fiberId}.resume-error`);}interruptById(e,n){let t=this.states.get(e);t&&this.interruptState(t,n);}interruptState(e,n){if(e.completed)return;e.controller.signal.aborted||e.controller.abort(n);for(let i of Array.from(e.pendingCleanups))i();let t=this.bridge.interrupt(e.fiberId,e.registry.register(n));this.drive(e,t);}markSuspended(e,n){e.status!=="suspended"&&(this.suspendedFibers+=1,e.status="suspended",this.fiberRegistry?.markSuspended(e.fiberId),e.handle.setEngineStatus("suspended"),e.handle.emit({type:"fiber.suspend",fiberId:e.fiberId,reason:n}));}markRunning(e,n){e.status==="suspended"&&(this.suspendedFibers=Math.max(0,this.suspendedFibers-1),e.status="running",this.fiberRegistry?.markRunning(e.fiberId),e.handle.setEngineStatus("running"),e.handle.emit({type:"fiber.resume",fiberId:e.fiberId}));}completeSuccess(e,n){e.completed||(e.completed=true,e.status="done",this.fiberRegistry?.markDone(e.fiberId,"done"),this.completedFibers+=1,this.cleanupState(e),e.handle.succeed(n));}completeFailure(e,n){e.completed||(e.completed=true,e.status="failed",this.fiberRegistry?.markDone(e.fiberId,"failed"),this.failedFibers+=1,this.cleanupState(e),e.handle.fail(n));}completeDie(e,n){e.completed||(e.completed=true,e.status="failed",this.fiberRegistry?.markDone(e.fiberId,"failed"),this.failedFibers+=1,this.cleanupState(e),e.handle.die(n));}completeInterrupted(e){e.completed||(e.completed=true,e.status="interrupted",this.fiberRegistry?.markDone(e.fiberId,"interrupted"),this.interruptedFibers+=1,this.cleanupState(e),e.handle.interrupted());}cleanupState(e){this.runningFibers=Math.max(0,this.runningFibers-1),e.status==="suspended"&&(this.suspendedFibers=Math.max(0,this.suspendedFibers-1));for(let n of Array.from(e.pendingCleanups))n();e.pendingCleanups.clear(),this.bridge.dropFiber(e.fiberId),this.fiberRegistry?.dropFiber(e.fiberId),e.registry.clear(),this.states.delete(e.fiberId);}};function Y(){let r=R();return {wasmAvailable:!!r,wasmFiberEngine:typeof r?.BrassWasmVm=="function",wasmRingBuffer:typeof r?.BrassWasmRingBuffer=="function",wasmScheduler:typeof r?.BrassWasmSchedulerStateMachine=="function",wasmFiberRegistry:typeof r?.BrassWasmFiberRegistry=="function",wasmStreamChunks:typeof r?.BrassWasmChunkBuffer=="function"}}var X={emit(){}},C=class r{env;scheduler;hooks;hostExecutor;engineMode;wasmOptions;fiberEngine;fallbackUsed;forkPolicy;registry;constructor(e){this.env=e.env,this.scheduler=e.scheduler??w,this.hooks=e.hooks??X,this.hostExecutor=e.hostExecutor??me,this.engineMode=e.engine??"auto",this.wasmOptions=e.wasm,this.forkPolicy=ye(this.env,this.hooks);let n=this.makeFiberEngine(this.engineMode,e.wasm);this.fiberEngine=n.engine,this.fallbackUsed=n.fallbackUsed;}makeFiberEngine(e,n){if(e==="js")return {engine:new x(this),fallbackUsed:false};if(e==="wasm-reference")return {engine:new k(this,{...n,reference:true}),fallbackUsed:false};if(e==="wasm")return {engine:new k(this,n),fallbackUsed:false};try{if(Y().wasmFiberEngine)return {engine:new k(this,n),fallbackUsed:!1}}catch{}return {engine:new x(this),fallbackUsed:true}}hasActiveHooks(){return this.hooks!==X}provide(e){return new r({env:Object.assign({},this.env,e),scheduler:this.scheduler,hooks:this.hooks,engine:this.engineMode,hostExecutor:this.hostExecutor,wasm:this.wasmOptions})}emit(e){if(this.hooks===X)return;let n=S(),t={fiberId:n?.id,scopeId:n?.scopeId,traceId:n?.fiberContext?.trace?.traceId,spanId:n?.fiberContext?.trace?.spanId};this.hooks.emit(e,t);}fork(e,n){let t=S(),i=this.fiberEngine.fork(e,n);return n!==void 0&&(i.scopeId=n),this.forkPolicy.initChild(i,t,n),i.schedule?.("initial-step"),i}stats(){let e=this.fiberEngine.stats();return {engine:this.fiberEngine.kind==="js"?"js":"wasm",fallbackUsed:this.fallbackUsed,data:e}}capabilities(){return Y()}shutdown(){return this.fiberEngine.shutdown?.()}unsafeRunAsync(e,n){this.fork(e).join(n);}toPromise(e){return new Promise((n,t)=>{this.fork(e).join(s=>{if(s._tag==="Success")n(s.value);else {let o=s.cause;o?._tag==="Fail"?t(o.error):t(new Error("Interrupted"));}});})}unsafeRun(e){this.unsafeRunAsync(e,()=>{});}delay(e,n){return h((t,i)=>{let s=setTimeout(()=>{this.unsafeRunAsync(n,i);},e);return ()=>clearTimeout(s)})}static make(e,n=w){return new r({env:e,scheduler:n})}static makeWithEngine(e,n,t={}){return new r({...t,env:e,engine:n})}log(e,n,t){this.emit({type:"log",level:e,message:n,fields:t});}};function pt(r,e){return C.make(e??{}).fork(r)}function ee(r,e,n){C.make(e??{}).unsafeRunAsync(r,n);}function ht(r,e){return C.make(e??{}).toPromise(r)}function yt(r,e){return {_tag:"Async",register:(n,t)=>{let i=new AbortController,s=false;return r(i.signal,n).then(o=>{s||(s=true,t(l.succeed(o)));}).catch(o=>{s||(s=true,t(l.failCause(c.fail(e(o)))));}),()=>{s||(s=true,i.abort(),t(l.failCause(c.interrupt())));}}}}function mt(r,e,n,t){ee(r,e,i=>{i._tag==="Failure"?n(i.cause):t(i.value);});}var z=null,g={CONTINUE:"Continue",SUSPEND:"Suspend",DONE:"Done"},v={QUEUED:"Queued",RUNNING:"Running",SUSPENDED:"Suspended",DONE:"Done"},$e=1,Fe=4096,ne;function kt(r){ne=r;}function St(){return ne}function Ze(r){let e=r;for(;e._tag==="FlatMap"&&e.first?._tag==="FlatMap";){let n=e.first,t=e.andThen;e={_tag:"FlatMap",first:n.first,andThen:i=>({_tag:"FlatMap",first:n.andThen(i),andThen:t})};}return e}var D=class{id;runtime;closing=null;finishing=false;runState=v.RUNNING;interrupted=false;result=null;joiners=[];current;stack=[];fiberFinalizers=[];finalizersDrained=false;fiberContext;name;scopeId;boundStep;constructor(e,n){this.id=$e++,this.runtime=e,this.current=n,this.boundStep=()=>{_(this,()=>{if(this.runState===v.DONE)return;switch(this.runState=v.RUNNING,this.step()){case g.CONTINUE:this.schedule("continue");return;case g.SUSPEND:this.runState=v.SUSPENDED,this.emit({type:"fiber.suspend",fiberId:this.id});return;case g.DONE:this.runState=v.DONE;return}});};}get env(){return this.runtime.env}get scheduler(){return this.runtime.scheduler??w}emit(e){this.runtime.hooks.emit(e,{fiberId:this.id,scopeId:this.scopeId,traceId:this.fiberContext?.trace?.traceId,spanId:this.fiberContext?.trace?.spanId});}addFinalizer(e){this.fiberFinalizers.push(e);}status(){return this.result==null?"Running":this.result._tag==="Failure"&&this.result.cause._tag==="Interrupt"?"Interrupted":"Done"}join(e){this.result!=null?e(this.result):this.joiners.push(e);}interrupt(){this.result==null&&(this.interrupted||(this.interrupted=true,this.schedule("interrupt-step")));}schedule(e="step"){this.runState===v.DONE||this.runState===v.QUEUED||(this.runState===v.SUSPENDED&&this.emit({type:"fiber.resume",fiberId:this.id}),this.runState=v.QUEUED,this.scheduler.schedule(this.boundStep,`fiber#${this.id}.${e}`));}runFinalizersOnce(e){if(!this.finalizersDrained)for(this.finalizersDrained=true;this.fiberFinalizers.length>0;){let n=this.fiberFinalizers.pop();try{let t=n(e);t&&typeof t=="object"&&"_tag"in t&&ee(t,this.env,()=>{});}catch{}}}notify(e){if(this.result!=null||this.closing!=null)return;this.finishing=true,this.closing=e,this.runFinalizersOnce(e),this.result=e;let n=e._tag==="Success"?"success":e.cause._tag==="Interrupt"?"interrupted":"failure";this.emit({type:"fiber.end",fiberId:this.id,status:n,error:e._tag==="Failure"?e.cause:void 0});for(let t of this.joiners)t(e);this.joiners.length=0;}onSuccess(e){let n=this.stack.pop();if(!n){this.notify(l.succeed(e));return}if(n._tag==="SuccessCont"){try{this.current=n.k(e);}catch(t){this.notify(l.failCause(c.die(t)));}return}try{this.current=n.onSuccess(e);}catch(t){this.notify(l.failCause(c.die(t)));}}onFailure(e){for(;this.stack.length>0;){let n=this.stack.pop();if(n._tag==="FoldCont")try{this.current=n.onFailure(e);return}catch(t){e=t;continue}}this.notify(l.failCause(c.fail(e)));}budget=Fe;step(){if(this.result!=null)return g.DONE;if(this.interrupted)return this.notify(l.failCause(c.interrupt())),g.DONE;for(this.budget=ne??Fe;this.budget-- >0;){this.current=Ze(this.current);let e=this.current;switch(e._tag){case "Succeed":{this.onSuccess(e.value);break}case "Fail":{this.onFailure(e.error);break}case "FlatMap":{this.stack.push({_tag:"SuccessCont",k:e.andThen}),this.current=e.first;break}case "Fold":{this.stack.push({_tag:"FoldCont",onFailure:e.onFailure,onSuccess:e.onSuccess}),this.current=e.first;break}case "Async":{if(this.finishing)return this.result!=null?g.DONE:g.CONTINUE;let n=false,t=false,i=false,s=null,o=u=>{if(n||(n=true,this.result!=null||this.closing!=null))return;if(!t){i=true,s=u;return}if(u._tag==="Success"){this.current=J.succeed(u.value),this.schedule("async-resume");return}let d=u.cause;if(d._tag==="Interrupt"){this.notify(l.failCause(c.interrupt()));return}if(d._tag==="Fail"){this.current=J.fail(d.error),this.schedule("async-resume");return}this.notify(l.failCause(c.die(d.defect)));},a=e.register(this.env,o);if(t=true,i&&s){let u=s;if(u._tag==="Success")this.onSuccess(u.value);else {let d=u.cause;d._tag==="Interrupt"?this.notify(l.failCause(c.interrupt())):d._tag==="Fail"?this.onFailure(d.error):this.notify(l.failCause(c.die(d.defect)));}break}return typeof a=="function"&&this.addFinalizer(()=>{n=true;try{a();}catch{}}),g.SUSPEND}case "Fork":{let n=this.runtime.fork(e.effect,e.scopeId);this.onSuccess(n);break}case "Sync":{try{let n=e.thunk(this.env);this.onSuccess(n);}catch(n){this.onFailure(n);}break}default:return this.onFailure(new Error(`Unknown opcode: ${e._tag}`)),g.CONTINUE}if(this.result!=null)return g.DONE}return g.CONTINUE}};function S(){return z}function It(){let r=S();if(!r?.runtime)throw new Error("unsafeGetCurrentRuntime: no current fiber/runtime");return r.runtime}function _(r,e){let n=z;z=r;try{return e()}finally{z=n;}}var Qe=1;function Ge(r){return h((e,n)=>{let t=r.length;if(t===0){n({_tag:"Success",value:void 0});return}for(let i of r)i.join(()=>{t-=1,t===0&&n({_tag:"Success",value:void 0});});})}var te=class r{constructor(e,n){this.runtime=e;this.parentScopeId=n;this.id=Qe++;let t=this.parentScopeId??S()?.scopeId;this.runtime.hasActiveHooks()&&this.runtime.emit({type:"scope.open",scopeId:this.id,parentScopeId:t});}runtime;parentScopeId;id;closed=false;children=new Set;subScopes=new Set;finalizers=[];addFinalizer(e){if(this.closed)throw new Error("Trying to add finalizer to closed scope");this.finalizers.push(e);}subScope(){if(this.closed)throw new Error("Scope closed");let e=new r(this.runtime,this.id);return this.subScopes.add(e),e}fork(e){if(this.closed)throw new Error("Scope closed");let n=this.runtime.fork(e,this.id);return this.children.add(n),n.join(()=>this.children.delete(n)),n}close(e={_tag:"Success",value:void 0}){this.runtime.fork(this.closeAsync(e));}emitCloseEvent(e){if(this.runtime.hasActiveHooks()){let n=e._tag==="Success"?"success":e.cause._tag==="Interrupt"?"interrupted":"failure";this.runtime.emit({type:"scope.close",scopeId:this.id,status:n,error:e._tag==="Failure"&&e.cause._tag==="Fail"?e.cause.error:void 0});}}buildFinalizerEffect(e){let n=this.finalizers;if(n.length===0)return m();let t=m();for(let i=n.length-1;i>=0;i--){let s=n[i];t=y(t,()=>{let o;try{o=s(e);}catch{return m()}return o._tag==="Succeed"?m():F(o,()=>m(),()=>m())});}return t}closeAsync(e={_tag:"Success",value:void 0},n={awaitChildren:true}){return y(m(),()=>h((t,i)=>{if(this.closed){i({_tag:"Success",value:void 0});return}this.closed=true;let s=Array.from(this.children),o=Array.from(this.subScopes);for(let V of s)V.interrupt();let a=o.reduceRight((V,ke)=>y(V,()=>ke.closeAsync(e,n)),m()),u=this.buildFinalizerEffect(e),d=n.awaitChildren&&s.length>0,p=d?Ge(s):m(),b=o.length>0,f=this.finalizers.length===0;if(!b&&!d&&f){this.emitCloseEvent(e),i({_tag:"Success",value:void 0});return}let A=y(a,()=>y(p,()=>u));this.runtime.fork(A).join(()=>{this.emitCloseEvent(e),i({_tag:"Success",value:void 0});});}))}};function Ke(r,e){return h((n,t)=>{let i=new te(r),s=false,o=u=>{r.fork(i.closeAsync(u)).join(()=>{s||(s=true,t(u));});},a=r.fork(e(i));return a.join(o),()=>{s||(a.interrupt(),r.fork(i.closeAsync(l.failCause(c.interrupt()))));}})}function Wt(r,e){return Ke(r,n=>{let t=e(n);return t&&typeof t=="object"&&"_tag"in t?t:m()})}function Dt(r,e,n){return h((t,i)=>{let s=n.subScope(),o=false,a=p=>{o||(o=true,s.close(p),i(p));},u=s.fork(r),d=s.fork(e);u.join(a),d.join(a);})}function Ht(r,e,n){return h((t,i)=>{let s=n.subScope(),o=null,a=null,u=false,d=()=>{if(!o||!a||u)return;if(u=true,o._tag==="Success"&&a._tag==="Success"){s.close({_tag:"Success",value:void 0}),i({_tag:"Success",value:[o.value,a.value]});return}let f;if(o._tag==="Failure")f=o.cause;else if(a._tag==="Failure")f=a.cause;else throw new Error("zipPar: unreachable state (no Failure exit)");let A={_tag:"Failure",cause:f};s.close(A),i(A);},p=s.fork(r),b=s.fork(e);p.join(f=>{o=f,d();}),b.join(f=>{a=f,d();});})}function Ut(r,e){return h((n,t)=>{let i=e.subScope(),s=new Array(r.length),o=0,a=false;r.forEach((u,d)=>{i.fork(u).join(b=>{if(!a){if(b._tag==="Failure"){a=true;let f={_tag:"Failure",cause:b.cause};i.close(f),t(f);return}if(s[d]=b.value,o++,o===r.length){a=true;let f={_tag:"Success",value:s};i.close({_tag:"Success",value:void 0}),t(f);}}});});})}function jt(r,e,n,t,i){return h((s,o)=>{let a=n.subScope(),u=false,d=a.fork(r),p=a.fork(e),b=f=>{a.fork(f).join(A=>{a.close(A),o(A);});};d.join(f=>{u||(u=true,b(t(f,p,a)));}),p.join(f=>{u||(u=true,b(i(f,d,a)));});})}exports.$=C;exports.A=yn;exports.B=mn;exports.C=gn;exports.D=bn;exports.E=_e;exports.F=I;exports.G=R;exports.H=Z;exports.I=G;exports.J=w;exports.K=kt;exports.L=St;exports.M=D;exports.N=S;exports.O=It;exports.P=_;exports.Q=me;exports.R=x;exports.S=K;exports.T=H;exports.U=U;exports.V=j;exports.W=P;exports.X=q;exports.Y=k;exports.Z=Y;exports._=X;exports.a=J;exports.aa=pt;exports.b=F;exports.ba=ee;exports.c=Ye;exports.ca=ht;exports.d=re;exports.da=yt;exports.e=m;exports.ea=mt;exports.f=E;exports.fa=te;exports.g=T;exports.ga=Ke;exports.h=B;exports.ha=Wt;exports.i=Xe;exports.ia=Dt;exports.j=h;exports.ja=Ht;exports.k=se;exports.ka=Ut;exports.l=y;exports.la=jt;exports.m=en;exports.n=nn;exports.o=tn;exports.p=rn;exports.q=sn;exports.r=oe;exports.s=an;exports.t=c;exports.u=l;exports.v=ln;exports.w=xe;exports.x=fn;exports.y=pn;exports.z=hn;
@@ -0,0 +1,2 @@
1
+ import {createRequire}from'module';var J={succeed:r=>({_tag:"Succeed",value:r}),fail:r=>({_tag:"Fail",error:r}),sync:r=>({_tag:"Sync",thunk:r}),async:r=>({_tag:"Async",register:r})};function F(r,e,n){return {_tag:"Fold",first:r,onFailure:e,onSuccess:n}}function Ye(r,e){return F(r,n=>e(n),n=>E(n))}function re(r,e){return F(r,n=>T(e(n)),n=>E(n))}var ie={_tag:"Succeed",value:void 0},Se={_tag:"Succeed",value:true},Ie={_tag:"Succeed",value:false},we={_tag:"Succeed",value:null},m=()=>ie,E=r=>r===void 0?ie:r===true?Se:r===false?Ie:r===null?we:{_tag:"Succeed",value:r},T=r=>({_tag:"Fail",error:r}),B=r=>({_tag:"Sync",thunk:r}),Xe=r=>B(()=>r()),h=r=>({_tag:"Async",register:r});function se(r,e){return y(r,n=>E(e(n)))}function y(r,e){return {_tag:"FlatMap",first:r,andThen:e}}function en(r,e,n){return y(r,t=>(n.addFinalizer(i=>e(t,i)),E(t)))}function nn(r){return h(r)}var tn=r=>e=>{let n=e;return n.toPromise||(n.toPromise=t=>r(e,t),n.unsafeRunPromise=()=>r(e,{})),n},rn=(r,e)=>y(r,n=>E(e(n))),sn=(r,e)=>y(r,n=>B(()=>e(n)));var oe={_tag:"None"},an=r=>({_tag:"Some",value:r});var c={fail:r=>({_tag:"Fail",error:r}),interrupt:()=>({_tag:"Interrupt"}),die:r=>({_tag:"Die",defect:r})},l={succeed:r=>({_tag:"Success",value:r}),failCause:r=>({_tag:"Failure",cause:r})},ln=r=>E(r),xe=r=>T(r),fn=r=>B(e=>r(e)),pn=(r,e)=>se(r,e),hn=(r,e)=>y(r,n=>e(n)),yn=(r,e)=>re(r,e),mn=(r,e)=>F(r,n=>e(n),n=>E(n));function gn(r,e){return F(r,n=>n._tag==="Some"?T(n):e(),n=>E(n))}var bn=()=>xe(oe);var _e=(t=>(t[t.Ok=0]="Ok",t[t.Grew=1]="Grew",t[t.Dropped=2]="Dropped",t))(_e||{}),I=class{buf;head=0;tail=0;size_=0;maxCap;constructor(e=1024,n=e){let t=Math.max(2,e);t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++;let i=Math.max(t,n);i--,i|=i>>>1,i|=i>>>2,i|=i>>>4,i|=i>>>8,i|=i>>>16,i++,this.buf=new Array(t),this.maxCap=i;}get length(){return this.size_}get capacity(){return this.buf.length}isEmpty(){return this.size_===0}push(e){return this.size_===this.buf.length?this.buf.length>=this.maxCap?2:(this.grow(),this.buf[this.tail]=e,this.tail=this.tail+1&this.buf.length-1,this.size_++,1):(this.buf[this.tail]=e,this.tail=this.tail+1&this.buf.length-1,this.size_++,0)}shift(){if(this.size_===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=this.head+1&this.buf.length-1,this.size_--,e}clear(){this.head=0,this.tail=0,this.size_=0;}grow(){let e=this.buf,n=Math.min(e.length*2,this.maxCap),t=new Array(n);for(let i=0;i<this.size_;i++)t[i]=e[this.head+i&e.length-1];this.buf=t,this.head=0,this.tail=this.size_;}};var $,ae=[];function R(r={}){if(!r.fresh&&r.modulePath==null&&$!==void 0)return $;let e=Be(),n=Te(r.modulePath),t=[];if(!e)return t.push("no CommonJS-compatible require/createRequire was available"),L(r,null,t);for(let i of n)try{return L(r,e(i),t)}catch(s){t.push(`${i}: ${De(s)}`);}return L(r,null,t)}function ue(){return ae.slice()}function Te(r){return r?[r]:["brass-runtime/wasm/pkg/brass_runtime_wasm_engine.js","../wasm/pkg/brass_runtime_wasm_engine.js","../../../wasm/pkg/brass_runtime_wasm_engine.js","../../../../../wasm/pkg/brass_runtime_wasm_engine.js",`${Me()}/wasm/pkg/brass_runtime_wasm_engine.js`]}function L(r,e,n){return !r.fresh&&r.modulePath==null&&($=e,ae=n),e}function Be(){return We()??Oe()??Ne()}function We(){try{return (0,eval)("typeof __non_webpack_require__ === 'function' ? __non_webpack_require__ : undefined")}catch{return}}function Oe(){try{return (0,eval)("typeof require === 'function' ? require : undefined")}catch{return}}function Ne(){try{return createRequire(import.meta.url)}catch{return}}function Me(){try{return (0,eval)("typeof process !== 'undefined' ? process.cwd() : ''")}catch{return ""}}function De(r){return r instanceof Error?r.message:String(r)}var W;function de(){return W!==void 0||(W=R()?.BrassWasmRingBuffer??null),W}var O=class{engine="wasm";fallbackUsed=false;inner;pushes=0;shifts=0;clears=0;dropped=0;constructor(e,n){let t=de();if(!t)throw new Error("brass-runtime wasm ring buffer is not available. Run npm run build:wasm first.");this.inner=new t(e,n);}get length(){return this.inner.len()}get capacity(){return this.inner.capacity()}isEmpty(){return this.inner.is_empty()}push(e){this.pushes++;let n=this.inner.push(e);return (n&2)!==0&&this.dropped++,n}shift(){let e=this.inner.shift();return e!==void 0&&this.shifts++,e===void 0?void 0:e}clear(){this.clears++,this.inner.clear();}stats(){return {engine:"wasm",fallbackUsed:false,data:{len:this.length,capacity:this.capacity,pushes:this.pushes,shifts:this.shifts,clears:this.clears,dropped:this.dropped}}}},N=class{constructor(e,n){this.inner=e;this.fallbackUsed=n;}inner;fallbackUsed;engine="js";pushes=0;shifts=0;clears=0;dropped=0;get length(){return this.inner.length}get capacity(){return this.inner.capacity}isEmpty(){return this.inner.isEmpty()}push(e){this.pushes++;let n=this.inner.push(e);return (n&2)!==0&&this.dropped++,n}shift(){let e=this.inner.shift();return e!==void 0&&this.shifts++,e}clear(){this.clears++,this.inner.clear();}stats(){return {engine:"js",fallbackUsed:this.fallbackUsed,data:{len:this.length,capacity:this.capacity,pushes:this.pushes,shifts:this.shifts,clears:this.clears,dropped:this.dropped}}}};function Z(r,e=r,n={}){let t=n.engine??"auto";return t==="js"?new N(new I(r,e),false):t==="wasm"?new O(r,e):de()?new O(r,e):new N(new I(r,e),true)}var ce=2048,le=4096,He=8192,Ue=(()=>{if(typeof globalThis.setImmediate=="function")return r=>globalThis.setImmediate(r);if(typeof globalThis.MessageChannel=="function"){let r=new globalThis.MessageChannel,e=null;return r.port1.onmessage=()=>{let n=e;e=null,n?.();},n=>{e=n,r.port2.postMessage(0);}}return r=>setTimeout(r,0)})();function fe(){return R()?.BrassWasmSchedulerStateMachine??null}var Q=class{tasks;tags;flushing=false;scheduled=false;scheduledFlushes=0;completedFlushes=0;enqueuedTasks=0;executedTasks=0;droppedTasks=0;yieldedByBudget=0;constructor(e){let n=e.initialCapacity??1024,t=e.maxCapacity??n;this.tasks=Z(n,t,{engine:e.engine}),this.tags=Z(n,t,{engine:e.engine});}},M=class{machine;nextRef=1;tasks=new Map;tags=new Map;constructor(e){let n=fe();if(!n)throw new Error("brass-runtime wasm scheduler is not available. Run npm run build:wasm first.");this.machine=new n(e.initialCapacity??1024,e.maxCapacity??He,e.flushBudget??ce,e.microThreshold??le);}enqueue(e,n){let t=this.nextRef++;this.tasks.set(t,e),this.tags.set(t,n);let i=this.machine.enqueue(t);return i===3&&(this.tasks.delete(t),this.tags.delete(t)),i}beginFlush(){return this.machine.begin_flush()}shift(){let e=this.machine.shift();if(e===0)return;let n=this.tasks.get(e),t=this.tags.get(e)??"anonymous";return this.tasks.delete(e),this.tags.delete(e),n?{task:n,tag:t}:void 0}endFlush(e){return this.machine.end_flush(e)}get length(){return this.machine.len()}stats(){return {engine:"wasm",fallbackUsed:false,data:JSON.parse(this.machine.stats_json())}}},G=class{engine;js;wasm;flushBudget;microThreshold;fallbackUsed;boundFlush=()=>this.flush();constructor(e={}){this.flushBudget=e.flushBudget??ce,this.microThreshold=e.microThreshold??le;let n=e.engine??"js";if(n==="wasm"){this.wasm=new M(e),this.engine="wasm",this.fallbackUsed=false;return}if(n==="auto"&&fe()){this.wasm=new M(e),this.engine="wasm",this.fallbackUsed=false;return}this.js=new Q({...e,engine:"js"}),this.engine="js",this.fallbackUsed=n==="auto";}schedule(e,n="anonymous"){if(typeof e=="function"){if(this.wasm)return this.scheduleWasm(e,n);this.scheduleJs(e,n);}}stats(){if(this.wasm)return this.wasm.stats();let e=this.js;return {engine:"js",fallbackUsed:this.fallbackUsed,data:{len:e.tasks.length,capacity:e.tasks.capacity,phase:e.flushing?"flushing":e.scheduled?"scheduled":"idle",scheduledFlushes:e.scheduledFlushes,completedFlushes:e.completedFlushes,enqueuedTasks:e.enqueuedTasks,executedTasks:e.executedTasks,droppedTasks:e.droppedTasks,yieldedByBudget:e.yieldedByBudget}}}scheduleWasm(e,n){let t=this.wasm.enqueue(e,n);t===0?this.requestFlush("micro"):t===1&&this.requestFlush("macro");}scheduleJs(e,n){let t=this.js,i=t.tasks.push(e),s=t.tags.push(n);if(t.enqueuedTasks++,((i&2)!==0||(s&2)!==0)&&t.droppedTasks++,!t.flushing&&!t.scheduled){t.scheduled=true,t.scheduledFlushes++;let o=t.tasks.length>this.microThreshold?"macro":"micro";this.requestFlush(o);}}requestFlush(e){e==="micro"?queueMicrotask(this.boundFlush):Ue(this.boundFlush);}flush(){if(this.wasm)return this.flushWasm();this.flushJs();}flushWasm(){let e=this.wasm,n=e.beginFlush();if(n<=0)return;let t=0;try{for(;t<n;){let i=e.shift();if(!i)break;t++;try{i.task();}catch(s){console.error(`[Scheduler] task threw (tag=${i.tag})`,s);}}}finally{let i=e.endFlush(t);i===0?this.requestFlush("micro"):i===1&&this.requestFlush("macro");}}flushJs(){let e=this.js;if(e.flushing)return;e.flushing=true,e.scheduled=false;let n=0;try{for(;n<this.flushBudget;){let t=e.tasks.shift();if(!t)break;let i=e.tags.shift();n++,e.executedTasks++;try{t();}catch(s){console.error(`[Scheduler] task threw (tag=${i})`,s);}}}finally{if(e.flushing=false,e.completedFlushes++,e.tasks.length>0&&!e.scheduled){e.scheduled=true,e.scheduledFlushes++;let t=n>=this.flushBudget||e.tasks.length>this.microThreshold?"macro":"micro";n>=this.flushBudget&&e.yieldedByBudget++,this.requestFlush(t);}}}},w=new G;var pe={parent:null,patch:Object.create(null)};function ye(r,e){let n=je(r);return {initChild(t,i,s){let o=i?.fiberContext,a=Pe(n,o?.trace??null);t.fiberContext={log:o?.log??pe,trace:a},t.parentFiberId=i?.id,t.name=n.childName(i?.name),s!==void 0&&(t.scopeId=s),e.emit({type:"fiber.start",fiberId:t.id,parentFiberId:i?.id,scopeId:t.scopeId,name:t.name},{fiberId:i?.id,traceId:o?.trace?.traceId,spanId:o?.trace?.spanId});}}}function je(r){let e={newTraceId:()=>he("trace"),newSpanId:()=>he("span")},n=r?.brass,t=n?.tracer??e,i=n?.traceSeed,s=n?.childName??(o=>o?`${o}/child`:void 0);return {tracer:t,seed:i,childName:s}}function he(r){let e=globalThis.crypto;return typeof e?.randomUUID=="function"?e.randomUUID():`${r}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function Pe(r,e){return e?{traceId:e.traceId,spanId:r.tracer.newSpanId(),parentSpanId:e.spanId,sampled:e.sampled}:r.seed?{...r.seed}:{traceId:r.tracer.newTraceId(),spanId:r.tracer.newSpanId(),sampled:true}}var me={async execute(r){return {kind:"error",actionId:r.actionId,error:new Error(`No HostExecutor configured for HostAction kind=${r.kind} target=${r.target}`)}}};var x=class{constructor(e){this.runtime=e;}runtime;kind="js";startedFibers=0;fork(e,n){this.startedFibers+=1;let t=new D(this.runtime,e);return n!==void 0&&(t.scopeId=n),t}stats(){return {engine:this.kind,startedFibers:this.startedFibers,runningFibers:0,suspendedFibers:0,queuedFibers:0,completedFibers:0,failedFibers:0,interruptedFibers:0,pendingHostEffects:0}}};var K=class{nextRef=1;refs=new Map;register(e){let n=this.nextRef++;return this.refs.set(n,e),n}get(e){if(!this.refs.has(e))throw new Error(`Missing host registry ref ${e}`);return this.refs.get(e)}set(e,n){this.refs.set(e,n);}delete(e){this.refs.delete(e);}clear(){this.refs.clear();}size(){return this.refs.size}},H=class{nodes=[];registry=new K;compile(e){return {program:{version:1,root:this.visit(e),nodes:this.nodes},registry:this.registry}}append(e){let n=this.nodes.length;return {root:this.visit(e),nodes:this.nodes.slice(n)}}add(e){let n=this.nodes.length;return this.nodes.push(e),n}visit(e){let n=e;switch(n._tag){case "Succeed":return this.add({tag:"Succeed",valueRef:this.registry.register(n.value)});case "Fail":return this.add({tag:"Fail",errorRef:this.registry.register(n.error)});case "Sync":return this.add({tag:"Sync",fnRef:this.registry.register(n.thunk)});case "Async":return this.add({tag:"Async",registerRef:this.registry.register(n.register)});case "FlatMap":return this.add({tag:"FlatMap",first:this.visit(n.first),fnRef:this.registry.register(n.andThen)});case "Fold":return this.add({tag:"Fold",first:this.visit(n.first),onFailureRef:this.registry.register(n.onFailure),onSuccessRef:this.registry.register(n.onSuccess)});case "Fork":{let t={tag:"Fork",effectRef:this.registry.register(n.effect)};return this.add(n.scopeId===void 0?t:{...t,scopeId:n.scopeId})}case "HostAction":{let t={tag:"HostAction",actionRef:this.registry.register(n.action)};return this.add(n.decode===void 0?t:{...t,decodeRef:this.registry.register(n.decode)})}default:return this.add({tag:"Fail",errorRef:this.registry.register(new Error(`Unknown Async opcode: ${n?._tag}`))})}}};var U=class{constructor(e,n,t,i,s,o){this.onScheduledStep=t;this.onInterrupt=i;this.onJoiner=s;this.onQueued=o;this.id=e,this.runtime=n;}onScheduledStep;onInterrupt;onJoiner;onQueued;id;runtime;fiberContext;name;scopeId;parentFiberId;result=null;joiners=[];finalizers=[];finalizersDrained=false;internalStatus="running";queued=false;status(){return this.result==null?"Running":this.result._tag==="Failure"&&this.result.cause._tag==="Interrupt"?"Interrupted":"Done"}engineStatus(){return this.internalStatus}setEngineStatus(e){this.internalStatus=e;}join(e){this.result!=null?e(this.result):(this.onJoiner?.(this.id),this.joiners.push(e));}interrupt(){this.result==null&&this.onInterrupt(this.id,c.interrupt());}addFinalizer(e){this.finalizers.push(e);}schedule(e="step"){this.result!=null||this.queued||(this.queued=true,this.internalStatus="queued",this.onQueued?.(this.id),this.runtime.scheduler.schedule(()=>{this.queued=false,this.result==null&&this.onScheduledStep(this.id);},`wasm-fiber#${this.id}.${e}`));}emit(e){this.runtime.hooks.emit(e,{fiberId:this.id,scopeId:this.scopeId,traceId:this.fiberContext?.trace?.traceId,spanId:this.fiberContext?.trace?.spanId});}succeed(e){this.complete(l.succeed(e));}fail(e){this.complete(l.failCause(c.fail(e)));}die(e){this.complete(l.failCause(c.die(e)));}interrupted(){this.complete(l.failCause(c.interrupt()));}complete(e){if(this.result!=null)return;this.runFinalizersOnce(e),this.result=e,this.internalStatus=e._tag==="Success"?"done":e.cause._tag==="Interrupt"?"interrupted":"failed";let n=e._tag==="Success"?"success":e.cause._tag==="Interrupt"?"interrupted":"failure";this.emit({type:"fiber.end",fiberId:this.id,status:n,error:e._tag==="Failure"?e.cause:void 0});for(let t of this.joiners)t(e);this.joiners.length=0;}runFinalizersOnce(e){if(!this.finalizersDrained)for(this.finalizersDrained=true;this.finalizers.length>0;){let n=this.finalizers.pop();try{let t=n(e);t&&typeof t=="object"&&"_tag"in t&&this.runtime.fork(t);}catch{}}}};var j=class{kind="wasm-reference";nextFiberId=1;fibers=new Map;started=0;completed=0;failed=0;interrupted=0;createFiber(e){let n=this.nextFiberId++;return this.started+=1,this.fibers.set(n,{id:n,program:qe(e),current:e.root,stack:[],status:"running",lastEvent:void 0}),n}poll(e){let n=this.mustFiber(e);return n.status==="suspended"&&n.lastEvent?n.lastEvent:this.step(n)}provideValue(e,n){let t=this.mustFiber(e);return t.status="running",t.lastEvent=void 0,this.success(t,n)}provideError(e,n){let t=this.mustFiber(e);return t.status="running",t.lastEvent=void 0,this.failure(t,n)}provideEffect(e,n,t){let i=this.mustFiber(e);return i.status="running",i.lastEvent=void 0,i.program.nodes.push(...t.map(s=>({...s}))),i.current=n,this.step(i)}interrupt(e,n){let t=this.mustFiber(e);t.status="interrupted",t.current=void 0,t.stack=[],this.interrupted+=1;let i={kind:"Interrupted",fiberId:e,reasonRef:n};return t.lastEvent=i,i}dropFiber(e){this.fibers.delete(e);}stats(){let e=0,n=0;for(let t of this.fibers.values())t.status==="running"&&(e+=1),t.status==="suspended"&&(n+=1);return {started:this.started,live:this.fibers.size,running:e,suspended:n,completed:this.completed,failed:this.failed,interrupted:this.interrupted}}mustFiber(e){let n=this.fibers.get(e);if(!n)throw new Error(`Fiber ${e} not found`);return n}step(e){for(;;){if(e.status==="interrupted"){let t=e.lastEvent??{kind:"Interrupted",fiberId:e.id,reasonRef:0};return e.lastEvent=t,t}if(e.current===void 0)return this.markFailed(e,0);let n=e.program.nodes[e.current];if(!n)return this.markFailed(e,0);switch(n.tag){case "Succeed":return e.current=void 0,this.success(e,n.valueRef);case "Fail":return e.current=void 0,this.failure(e,n.errorRef);case "Sync":return this.suspend(e,{kind:"InvokeSync",fiberId:e.id,fnRef:n.fnRef});case "Async":return this.suspend(e,{kind:"InvokeAsync",fiberId:e.id,registerRef:n.registerRef});case "FlatMap":e.stack.push({tag:"SuccessCont",fnRef:n.fnRef}),e.current=n.first;continue;case "Fold":e.stack.push({tag:"FoldCont",onFailureRef:n.onFailureRef,onSuccessRef:n.onSuccessRef}),e.current=n.first;continue;case "Fork":{let t=n.scopeId===void 0?{kind:"InvokeFork",fiberId:e.id,effectRef:n.effectRef}:{kind:"InvokeFork",fiberId:e.id,effectRef:n.effectRef,scopeId:n.scopeId};return this.suspend(e,t)}case "HostAction":{let t=n.decodeRef===void 0?{kind:"InvokeHostAction",fiberId:e.id,actionRef:n.actionRef}:{kind:"InvokeHostAction",fiberId:e.id,actionRef:n.actionRef,decodeRef:n.decodeRef};return this.suspend(e,t)}}}}success(e,n){let t=e.stack.pop();return t?t.tag==="SuccessCont"?this.suspend(e,{kind:"InvokeFlatMap",fiberId:e.id,fnRef:t.fnRef,valueRef:n}):this.suspend(e,{kind:"InvokeFoldSuccess",fiberId:e.id,fnRef:t.onSuccessRef,valueRef:n}):this.markDone(e,n)}failure(e,n){for(;e.stack.length>0;){let t=e.stack.pop();if(t.tag==="FoldCont")return this.suspend(e,{kind:"InvokeFoldFailure",fiberId:e.id,fnRef:t.onFailureRef,errorRef:n})}return this.markFailed(e,n)}suspend(e,n){return e.status="suspended",e.lastEvent=n,n}markDone(e,n){e.status="done",e.current=void 0,this.completed+=1;let t={kind:"Done",fiberId:e.id,valueRef:n};return e.lastEvent=t,t}markFailed(e,n){e.status="failed",e.current=void 0,this.failed+=1;let t={kind:"Failed",fiberId:e.id,errorRef:n};return e.lastEvent=t,t}};function qe(r){return {version:r.version,root:r.root,nodes:r.nodes.map(e=>({...e}))}}var P=class{kind="wasm";vm;constructor(e){let n=ze(e);this.vm=new n.BrassWasmVm;}createFiber(e){return this.vm.create_fiber(JSON.stringify(e))}poll(e){return JSON.parse(this.vm.poll(e))}provideValue(e,n){return JSON.parse(this.vm.provide_value(e,n))}provideError(e,n){return JSON.parse(this.vm.provide_error(e,n))}provideEffect(e,n,t){return JSON.parse(this.vm.provide_effect(e,n,JSON.stringify(t)))}interrupt(e,n){return JSON.parse(this.vm.interrupt(e,n))}dropFiber(e){this.vm.drop_fiber(e);}stats(){return JSON.parse(this.vm.stats_json())}};function ze(r){let e=R({modulePath:r});if(e)return e;let n=ue();throw new Error(["engine='wasm' could not load wasm/pkg/brass_runtime_wasm_engine.js.","Run `npm run build:wasm` first and make sure wasm/pkg is present in the package.","For Node 18 + webpack, keep brass-runtime's wasm/pkg files available at runtime or externalize brass-runtime.",...n.map(t=>`- ${t}`)].join(`
2
+ `))}var ge=0,be=1,Re=2,Ee=3,ve=4,Ae=5,q=class{registry;constructor(){let n=R()?.BrassWasmFiberRegistry;if(!n)throw new Error("brass-runtime wasm fiber registry is not available. Run npm run build:wasm first.");this.registry=new n;}registerFiber(e,n,t){this.registry.register_fiber(e,n??0,t??0,Date.now());}markQueued(e){this.registry.mark_queued(e,Date.now());}markRunning(e){this.registry.mark_running(e,Date.now());}markSuspended(e){this.registry.mark_suspended(e,Date.now());}markDone(e,n){return this.registry.mark_done(e,Ve(n),Date.now())}dropFiber(e){this.registry.drop_fiber(e);}addJoiner(e){this.registry.add_joiner(e);}wake(e){return this.registry.wake(e)}drainWakeup(){let e=this.registry.drain_wakeup();return e===0?void 0:e}drainWakeups(){let e=[];for(;;){let n=this.drainWakeup();if(n===void 0)return e;e.push(n);}}wakeQueueLength(){return this.registry.wake_queue_len()}stateOf(e){let n=this.registry.state_of(e);return n===4294967295?"missing":Je(n)}stats(){return JSON.parse(this.registry.stats_json())}};function Ve(r){switch(r){case "queued":return ge;case "running":return be;case "suspended":return Re;case "done":return Ee;case "failed":return ve;case "interrupted":return Ae}}function Je(r){switch(r){case ge:return "queued";case be:return "running";case Re:return "suspended";case Ee:return "done";case ve:return "failed";case Ae:return "interrupted";default:return "missing"}}var Le=4096,k=class{constructor(e,n={}){this.runtime=e;this.bridge=n.bridge??(n.reference?new j:new P(n.modulePath)),this.kind=this.bridge.kind,this.fiberRegistry=this.kind==="wasm"?new q:void 0;}runtime;kind;bridge;startedFibers=0;runningFibers=0;suspendedFibers=0;completedFibers=0;failedFibers=0;interruptedFibers=0;pendingHostEffects=0;states=new Map;fiberRegistry;fork(e,n){let t=new H,i=t.compile(e),s=this.bridge.createFiber(i.program),o=new AbortController,a=new U(s,this.runtime,d=>this.scheduleWakeup(d),(d,p)=>this.interruptById(d,p),d=>this.fiberRegistry?.addJoiner(d),d=>this.fiberRegistry?.markQueued(d));n!==void 0&&(a.scopeId=n);let u={fiberId:s,handle:a,builder:t,registry:i.registry,controller:o,startedAt:Date.now(),completed:false,status:"running",pendingCleanups:new Set};return this.states.set(s,u),this.fiberRegistry?.registerFiber(s,void 0,n),this.startedFibers+=1,this.runningFibers+=1,a}stats(){let e=0;for(let n of this.states.values())e+=n.registry.size();return {engine:this.kind,startedFibers:this.startedFibers,runningFibers:this.runningFibers,suspendedFibers:this.suspendedFibers,queuedFibers:0,completedFibers:this.completedFibers,failedFibers:this.failedFibers,interruptedFibers:this.interruptedFibers,pendingHostEffects:this.pendingHostEffects,hostRegistryRefs:e,wasm:this.bridge.stats(),fiberRegistry:this.fiberRegistry?.stats()}}async shutdown(){for(let e of Array.from(this.states.values()))this.interruptState(e,c.interrupt());}scheduleWakeup(e){let n=this.states.get(e);if(!(!n||n.completed)){if(!this.fiberRegistry){this.driveById(e);return}this.fiberRegistry.wake(e)&&this.drainWakeups();}}drainWakeups(){if(this.fiberRegistry)for(let e of this.fiberRegistry.drainWakeups())this.driveById(e);}driveById(e){let n=this.states.get(e);!n||n.completed||(this.fiberRegistry?.markRunning(e),_(n.handle,()=>this.drive(n)));}drive(e,n){if(e.completed)return;let t=Le,i=n??this.bridge.poll(e.fiberId);for(e.status="running",e.handle.setEngineStatus("running");!e.completed&&t-- >0;)try{switch(i.kind){case "Continue":i=this.bridge.poll(e.fiberId);continue;case "Done":{let s=e.registry.get(i.valueRef);this.completeSuccess(e,s);return}case "Failed":{let s=i.errorRef===0?new Error("WASM fiber failed"):e.registry.get(i.errorRef);this.completeFailure(e,s);return}case "Interrupted":{this.completeInterrupted(e);return}case "InvokeSync":{let s=e.registry.get(i.fnRef);try{let o=e.registry.register(s(this.runtime.env));i=this.bridge.provideValue(e.fiberId,o);}catch(o){i=this.bridge.provideError(e.fiberId,e.registry.register(o));}continue}case "InvokeFlatMap":{let s=e.registry.get(i.fnRef),o=e.registry.get(i.valueRef);try{let a=s(o),u=e.builder.append(a);i=this.bridge.provideEffect(e.fiberId,u.root,u.nodes);}catch(a){i=this.bridge.provideError(e.fiberId,e.registry.register(a));}continue}case "InvokeFoldFailure":{let s=e.registry.get(i.fnRef),o=e.registry.get(i.errorRef);try{let a=s(o),u=e.builder.append(a);i=this.bridge.provideEffect(e.fiberId,u.root,u.nodes);}catch(a){i=this.bridge.provideError(e.fiberId,e.registry.register(a));}continue}case "InvokeFoldSuccess":{let s=e.registry.get(i.fnRef),o=e.registry.get(i.valueRef);try{let a=s(o),u=e.builder.append(a);i=this.bridge.provideEffect(e.fiberId,u.root,u.nodes);}catch(a){i=this.bridge.provideError(e.fiberId,e.registry.register(a));}continue}case "InvokeFork":{let s=e.registry.get(i.effectRef);try{let o=this.runtime.fork(s,i.scopeId);i=this.bridge.provideValue(e.fiberId,e.registry.register(o));}catch(o){i=this.bridge.provideError(e.fiberId,e.registry.register(o));}continue}case "InvokeAsync":{this.scheduleAsync(e,i.registerRef);return}case "InvokeHostAction":{this.scheduleHostAction(e,i.actionRef,i.decodeRef);return}}}catch(s){i=this.bridge.provideError(e.fiberId,e.registry.register(s));}e.completed||e.handle.schedule("budget-yield");}scheduleAsync(e,n){this.markSuspended(e,"async"),this.pendingHostEffects+=1;let t=e.registry.get(n),i=false,s=false,o=null,a=()=>{i=true,e.pendingCleanups.delete(a);};e.pendingCleanups.add(a);let u=d=>{if(i)return;let p=d;if(!s){o=p;return}a(),this.pendingHostEffects=Math.max(0,this.pendingHostEffects-1),this.markRunning(e,"async"),this.resumeWithExit(e,p);};try{let d=t(this.runtime.env,u);if(s=!0,o){a(),this.pendingHostEffects=Math.max(0,this.pendingHostEffects-1),this.markRunning(e,"async-sync"),this.resumeWithExit(e,o);return}if(typeof d=="function"){let p=()=>{if(!i){i=!0;try{d();}catch{}e.pendingCleanups.delete(p);}};e.pendingCleanups.add(p),e.handle.addFinalizer(()=>p());}}catch(d){a(),this.pendingHostEffects=Math.max(0,this.pendingHostEffects-1),this.markRunning(e,"async-register-error"),this.resumeWithError(e,d);}}scheduleHostAction(e,n,t){this.markSuspended(e,"host-action"),this.pendingHostEffects+=1;let i=e.registry.get(n),o=()=>{e.pendingCleanups.delete(o);};e.pendingCleanups.add(o),this.runtime.hostExecutor.execute(i,{fiberId:e.fiberId,env:this.runtime.env,signal:e.controller.signal,deadlineAt:i.timeoutMs===void 0?void 0:Date.now()+i.timeoutMs}).then(a=>{if(o(),!e.completed){this.pendingHostEffects=Math.max(0,this.pendingHostEffects-1),this.markRunning(e,"host-action");try{if(t!==void 0){let u=e.registry.get(t);this.resumeWithValue(e,u(a));return}if(a.kind==="error"){this.resumeWithError(e,a.error);return}this.resumeWithValue(e,a.value);}catch(u){this.resumeWithError(e,u);}}}).catch(a=>{o(),!e.completed&&(this.pendingHostEffects=Math.max(0,this.pendingHostEffects-1),this.markRunning(e,"host-action-error"),this.resumeWithError(e,a));});}resumeWithExit(e,n){if(e.completed)return;if(n._tag==="Success"){this.resumeWithValue(e,n.value);return}let t=n.cause;if(t._tag==="Interrupt"){this.interruptState(e,t);return}if(t._tag==="Fail"){this.resumeWithError(e,t.error);return}this.completeDie(e,t.defect);}resumeWithValue(e,n){let t=this.bridge.provideValue(e.fiberId,e.registry.register(n));this.runtime.scheduler.schedule(()=>_(e.handle,()=>this.drive(e,t)),`wasm-fiber#${e.fiberId}.resume`);}resumeWithError(e,n){let t=this.bridge.provideError(e.fiberId,e.registry.register(n));this.runtime.scheduler.schedule(()=>_(e.handle,()=>this.drive(e,t)),`wasm-fiber#${e.fiberId}.resume-error`);}interruptById(e,n){let t=this.states.get(e);t&&this.interruptState(t,n);}interruptState(e,n){if(e.completed)return;e.controller.signal.aborted||e.controller.abort(n);for(let i of Array.from(e.pendingCleanups))i();let t=this.bridge.interrupt(e.fiberId,e.registry.register(n));this.drive(e,t);}markSuspended(e,n){e.status!=="suspended"&&(this.suspendedFibers+=1,e.status="suspended",this.fiberRegistry?.markSuspended(e.fiberId),e.handle.setEngineStatus("suspended"),e.handle.emit({type:"fiber.suspend",fiberId:e.fiberId,reason:n}));}markRunning(e,n){e.status==="suspended"&&(this.suspendedFibers=Math.max(0,this.suspendedFibers-1),e.status="running",this.fiberRegistry?.markRunning(e.fiberId),e.handle.setEngineStatus("running"),e.handle.emit({type:"fiber.resume",fiberId:e.fiberId}));}completeSuccess(e,n){e.completed||(e.completed=true,e.status="done",this.fiberRegistry?.markDone(e.fiberId,"done"),this.completedFibers+=1,this.cleanupState(e),e.handle.succeed(n));}completeFailure(e,n){e.completed||(e.completed=true,e.status="failed",this.fiberRegistry?.markDone(e.fiberId,"failed"),this.failedFibers+=1,this.cleanupState(e),e.handle.fail(n));}completeDie(e,n){e.completed||(e.completed=true,e.status="failed",this.fiberRegistry?.markDone(e.fiberId,"failed"),this.failedFibers+=1,this.cleanupState(e),e.handle.die(n));}completeInterrupted(e){e.completed||(e.completed=true,e.status="interrupted",this.fiberRegistry?.markDone(e.fiberId,"interrupted"),this.interruptedFibers+=1,this.cleanupState(e),e.handle.interrupted());}cleanupState(e){this.runningFibers=Math.max(0,this.runningFibers-1),e.status==="suspended"&&(this.suspendedFibers=Math.max(0,this.suspendedFibers-1));for(let n of Array.from(e.pendingCleanups))n();e.pendingCleanups.clear(),this.bridge.dropFiber(e.fiberId),this.fiberRegistry?.dropFiber(e.fiberId),e.registry.clear(),this.states.delete(e.fiberId);}};function Y(){let r=R();return {wasmAvailable:!!r,wasmFiberEngine:typeof r?.BrassWasmVm=="function",wasmRingBuffer:typeof r?.BrassWasmRingBuffer=="function",wasmScheduler:typeof r?.BrassWasmSchedulerStateMachine=="function",wasmFiberRegistry:typeof r?.BrassWasmFiberRegistry=="function",wasmStreamChunks:typeof r?.BrassWasmChunkBuffer=="function"}}var X={emit(){}},C=class r{env;scheduler;hooks;hostExecutor;engineMode;wasmOptions;fiberEngine;fallbackUsed;forkPolicy;registry;constructor(e){this.env=e.env,this.scheduler=e.scheduler??w,this.hooks=e.hooks??X,this.hostExecutor=e.hostExecutor??me,this.engineMode=e.engine??"auto",this.wasmOptions=e.wasm,this.forkPolicy=ye(this.env,this.hooks);let n=this.makeFiberEngine(this.engineMode,e.wasm);this.fiberEngine=n.engine,this.fallbackUsed=n.fallbackUsed;}makeFiberEngine(e,n){if(e==="js")return {engine:new x(this),fallbackUsed:false};if(e==="wasm-reference")return {engine:new k(this,{...n,reference:true}),fallbackUsed:false};if(e==="wasm")return {engine:new k(this,n),fallbackUsed:false};try{if(Y().wasmFiberEngine)return {engine:new k(this,n),fallbackUsed:!1}}catch{}return {engine:new x(this),fallbackUsed:true}}hasActiveHooks(){return this.hooks!==X}provide(e){return new r({env:Object.assign({},this.env,e),scheduler:this.scheduler,hooks:this.hooks,engine:this.engineMode,hostExecutor:this.hostExecutor,wasm:this.wasmOptions})}emit(e){if(this.hooks===X)return;let n=S(),t={fiberId:n?.id,scopeId:n?.scopeId,traceId:n?.fiberContext?.trace?.traceId,spanId:n?.fiberContext?.trace?.spanId};this.hooks.emit(e,t);}fork(e,n){let t=S(),i=this.fiberEngine.fork(e,n);return n!==void 0&&(i.scopeId=n),this.forkPolicy.initChild(i,t,n),i.schedule?.("initial-step"),i}stats(){let e=this.fiberEngine.stats();return {engine:this.fiberEngine.kind==="js"?"js":"wasm",fallbackUsed:this.fallbackUsed,data:e}}capabilities(){return Y()}shutdown(){return this.fiberEngine.shutdown?.()}unsafeRunAsync(e,n){this.fork(e).join(n);}toPromise(e){return new Promise((n,t)=>{this.fork(e).join(s=>{if(s._tag==="Success")n(s.value);else {let o=s.cause;o?._tag==="Fail"?t(o.error):t(new Error("Interrupted"));}});})}unsafeRun(e){this.unsafeRunAsync(e,()=>{});}delay(e,n){return h((t,i)=>{let s=setTimeout(()=>{this.unsafeRunAsync(n,i);},e);return ()=>clearTimeout(s)})}static make(e,n=w){return new r({env:e,scheduler:n})}static makeWithEngine(e,n,t={}){return new r({...t,env:e,engine:n})}log(e,n,t){this.emit({type:"log",level:e,message:n,fields:t});}};function pt(r,e){return C.make(e??{}).fork(r)}function ee(r,e,n){C.make(e??{}).unsafeRunAsync(r,n);}function ht(r,e){return C.make(e??{}).toPromise(r)}function yt(r,e){return {_tag:"Async",register:(n,t)=>{let i=new AbortController,s=false;return r(i.signal,n).then(o=>{s||(s=true,t(l.succeed(o)));}).catch(o=>{s||(s=true,t(l.failCause(c.fail(e(o)))));}),()=>{s||(s=true,i.abort(),t(l.failCause(c.interrupt())));}}}}function mt(r,e,n,t){ee(r,e,i=>{i._tag==="Failure"?n(i.cause):t(i.value);});}var z=null,g={CONTINUE:"Continue",SUSPEND:"Suspend",DONE:"Done"},v={QUEUED:"Queued",RUNNING:"Running",SUSPENDED:"Suspended",DONE:"Done"},$e=1,Fe=4096,ne;function kt(r){ne=r;}function St(){return ne}function Ze(r){let e=r;for(;e._tag==="FlatMap"&&e.first?._tag==="FlatMap";){let n=e.first,t=e.andThen;e={_tag:"FlatMap",first:n.first,andThen:i=>({_tag:"FlatMap",first:n.andThen(i),andThen:t})};}return e}var D=class{id;runtime;closing=null;finishing=false;runState=v.RUNNING;interrupted=false;result=null;joiners=[];current;stack=[];fiberFinalizers=[];finalizersDrained=false;fiberContext;name;scopeId;boundStep;constructor(e,n){this.id=$e++,this.runtime=e,this.current=n,this.boundStep=()=>{_(this,()=>{if(this.runState===v.DONE)return;switch(this.runState=v.RUNNING,this.step()){case g.CONTINUE:this.schedule("continue");return;case g.SUSPEND:this.runState=v.SUSPENDED,this.emit({type:"fiber.suspend",fiberId:this.id});return;case g.DONE:this.runState=v.DONE;return}});};}get env(){return this.runtime.env}get scheduler(){return this.runtime.scheduler??w}emit(e){this.runtime.hooks.emit(e,{fiberId:this.id,scopeId:this.scopeId,traceId:this.fiberContext?.trace?.traceId,spanId:this.fiberContext?.trace?.spanId});}addFinalizer(e){this.fiberFinalizers.push(e);}status(){return this.result==null?"Running":this.result._tag==="Failure"&&this.result.cause._tag==="Interrupt"?"Interrupted":"Done"}join(e){this.result!=null?e(this.result):this.joiners.push(e);}interrupt(){this.result==null&&(this.interrupted||(this.interrupted=true,this.schedule("interrupt-step")));}schedule(e="step"){this.runState===v.DONE||this.runState===v.QUEUED||(this.runState===v.SUSPENDED&&this.emit({type:"fiber.resume",fiberId:this.id}),this.runState=v.QUEUED,this.scheduler.schedule(this.boundStep,`fiber#${this.id}.${e}`));}runFinalizersOnce(e){if(!this.finalizersDrained)for(this.finalizersDrained=true;this.fiberFinalizers.length>0;){let n=this.fiberFinalizers.pop();try{let t=n(e);t&&typeof t=="object"&&"_tag"in t&&ee(t,this.env,()=>{});}catch{}}}notify(e){if(this.result!=null||this.closing!=null)return;this.finishing=true,this.closing=e,this.runFinalizersOnce(e),this.result=e;let n=e._tag==="Success"?"success":e.cause._tag==="Interrupt"?"interrupted":"failure";this.emit({type:"fiber.end",fiberId:this.id,status:n,error:e._tag==="Failure"?e.cause:void 0});for(let t of this.joiners)t(e);this.joiners.length=0;}onSuccess(e){let n=this.stack.pop();if(!n){this.notify(l.succeed(e));return}if(n._tag==="SuccessCont"){try{this.current=n.k(e);}catch(t){this.notify(l.failCause(c.die(t)));}return}try{this.current=n.onSuccess(e);}catch(t){this.notify(l.failCause(c.die(t)));}}onFailure(e){for(;this.stack.length>0;){let n=this.stack.pop();if(n._tag==="FoldCont")try{this.current=n.onFailure(e);return}catch(t){e=t;continue}}this.notify(l.failCause(c.fail(e)));}budget=Fe;step(){if(this.result!=null)return g.DONE;if(this.interrupted)return this.notify(l.failCause(c.interrupt())),g.DONE;for(this.budget=ne??Fe;this.budget-- >0;){this.current=Ze(this.current);let e=this.current;switch(e._tag){case "Succeed":{this.onSuccess(e.value);break}case "Fail":{this.onFailure(e.error);break}case "FlatMap":{this.stack.push({_tag:"SuccessCont",k:e.andThen}),this.current=e.first;break}case "Fold":{this.stack.push({_tag:"FoldCont",onFailure:e.onFailure,onSuccess:e.onSuccess}),this.current=e.first;break}case "Async":{if(this.finishing)return this.result!=null?g.DONE:g.CONTINUE;let n=false,t=false,i=false,s=null,o=u=>{if(n||(n=true,this.result!=null||this.closing!=null))return;if(!t){i=true,s=u;return}if(u._tag==="Success"){this.current=J.succeed(u.value),this.schedule("async-resume");return}let d=u.cause;if(d._tag==="Interrupt"){this.notify(l.failCause(c.interrupt()));return}if(d._tag==="Fail"){this.current=J.fail(d.error),this.schedule("async-resume");return}this.notify(l.failCause(c.die(d.defect)));},a=e.register(this.env,o);if(t=true,i&&s){let u=s;if(u._tag==="Success")this.onSuccess(u.value);else {let d=u.cause;d._tag==="Interrupt"?this.notify(l.failCause(c.interrupt())):d._tag==="Fail"?this.onFailure(d.error):this.notify(l.failCause(c.die(d.defect)));}break}return typeof a=="function"&&this.addFinalizer(()=>{n=true;try{a();}catch{}}),g.SUSPEND}case "Fork":{let n=this.runtime.fork(e.effect,e.scopeId);this.onSuccess(n);break}case "Sync":{try{let n=e.thunk(this.env);this.onSuccess(n);}catch(n){this.onFailure(n);}break}default:return this.onFailure(new Error(`Unknown opcode: ${e._tag}`)),g.CONTINUE}if(this.result!=null)return g.DONE}return g.CONTINUE}};function S(){return z}function It(){let r=S();if(!r?.runtime)throw new Error("unsafeGetCurrentRuntime: no current fiber/runtime");return r.runtime}function _(r,e){let n=z;z=r;try{return e()}finally{z=n;}}var Qe=1;function Ge(r){return h((e,n)=>{let t=r.length;if(t===0){n({_tag:"Success",value:void 0});return}for(let i of r)i.join(()=>{t-=1,t===0&&n({_tag:"Success",value:void 0});});})}var te=class r{constructor(e,n){this.runtime=e;this.parentScopeId=n;this.id=Qe++;let t=this.parentScopeId??S()?.scopeId;this.runtime.hasActiveHooks()&&this.runtime.emit({type:"scope.open",scopeId:this.id,parentScopeId:t});}runtime;parentScopeId;id;closed=false;children=new Set;subScopes=new Set;finalizers=[];addFinalizer(e){if(this.closed)throw new Error("Trying to add finalizer to closed scope");this.finalizers.push(e);}subScope(){if(this.closed)throw new Error("Scope closed");let e=new r(this.runtime,this.id);return this.subScopes.add(e),e}fork(e){if(this.closed)throw new Error("Scope closed");let n=this.runtime.fork(e,this.id);return this.children.add(n),n.join(()=>this.children.delete(n)),n}close(e={_tag:"Success",value:void 0}){this.runtime.fork(this.closeAsync(e));}emitCloseEvent(e){if(this.runtime.hasActiveHooks()){let n=e._tag==="Success"?"success":e.cause._tag==="Interrupt"?"interrupted":"failure";this.runtime.emit({type:"scope.close",scopeId:this.id,status:n,error:e._tag==="Failure"&&e.cause._tag==="Fail"?e.cause.error:void 0});}}buildFinalizerEffect(e){let n=this.finalizers;if(n.length===0)return m();let t=m();for(let i=n.length-1;i>=0;i--){let s=n[i];t=y(t,()=>{let o;try{o=s(e);}catch{return m()}return o._tag==="Succeed"?m():F(o,()=>m(),()=>m())});}return t}closeAsync(e={_tag:"Success",value:void 0},n={awaitChildren:true}){return y(m(),()=>h((t,i)=>{if(this.closed){i({_tag:"Success",value:void 0});return}this.closed=true;let s=Array.from(this.children),o=Array.from(this.subScopes);for(let V of s)V.interrupt();let a=o.reduceRight((V,ke)=>y(V,()=>ke.closeAsync(e,n)),m()),u=this.buildFinalizerEffect(e),d=n.awaitChildren&&s.length>0,p=d?Ge(s):m(),b=o.length>0,f=this.finalizers.length===0;if(!b&&!d&&f){this.emitCloseEvent(e),i({_tag:"Success",value:void 0});return}let A=y(a,()=>y(p,()=>u));this.runtime.fork(A).join(()=>{this.emitCloseEvent(e),i({_tag:"Success",value:void 0});});}))}};function Ke(r,e){return h((n,t)=>{let i=new te(r),s=false,o=u=>{r.fork(i.closeAsync(u)).join(()=>{s||(s=true,t(u));});},a=r.fork(e(i));return a.join(o),()=>{s||(a.interrupt(),r.fork(i.closeAsync(l.failCause(c.interrupt()))));}})}function Wt(r,e){return Ke(r,n=>{let t=e(n);return t&&typeof t=="object"&&"_tag"in t?t:m()})}function Dt(r,e,n){return h((t,i)=>{let s=n.subScope(),o=false,a=p=>{o||(o=true,s.close(p),i(p));},u=s.fork(r),d=s.fork(e);u.join(a),d.join(a);})}function Ht(r,e,n){return h((t,i)=>{let s=n.subScope(),o=null,a=null,u=false,d=()=>{if(!o||!a||u)return;if(u=true,o._tag==="Success"&&a._tag==="Success"){s.close({_tag:"Success",value:void 0}),i({_tag:"Success",value:[o.value,a.value]});return}let f;if(o._tag==="Failure")f=o.cause;else if(a._tag==="Failure")f=a.cause;else throw new Error("zipPar: unreachable state (no Failure exit)");let A={_tag:"Failure",cause:f};s.close(A),i(A);},p=s.fork(r),b=s.fork(e);p.join(f=>{o=f,d();}),b.join(f=>{a=f,d();});})}function Ut(r,e){return h((n,t)=>{let i=e.subScope(),s=new Array(r.length),o=0,a=false;r.forEach((u,d)=>{i.fork(u).join(b=>{if(!a){if(b._tag==="Failure"){a=true;let f={_tag:"Failure",cause:b.cause};i.close(f),t(f);return}if(s[d]=b.value,o++,o===r.length){a=true;let f={_tag:"Success",value:s};i.close({_tag:"Success",value:void 0}),t(f);}}});});})}function jt(r,e,n,t,i){return h((s,o)=>{let a=n.subScope(),u=false,d=a.fork(r),p=a.fork(e),b=f=>{a.fork(f).join(A=>{a.close(A),o(A);});};d.join(f=>{u||(u=true,b(t(f,p,a)));}),p.join(f=>{u||(u=true,b(i(f,d,a)));});})}export{C as $,yn as A,mn as B,gn as C,bn as D,_e as E,I as F,R as G,Z as H,G as I,w as J,kt as K,St as L,D as M,S as N,It as O,_ as P,me as Q,x as R,K as S,H as T,U,j as V,P as W,q as X,k as Y,Y as Z,X as _,J as a,pt as aa,F as b,ee as ba,Ye as c,ht as ca,re as d,yt as da,m as e,mt as ea,E as f,te as fa,T as g,Ke as ga,B as h,Wt as ha,Xe as i,Dt as ia,h as j,Ht as ja,se as k,Ut as ka,y as l,jt as la,en as m,nn as n,tn as o,rn as p,sn as q,oe as r,an as s,c as t,l as u,ln as v,xe as w,fn as x,pn as y,hn as z};