brass-runtime 1.13.2 → 1.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brass-runtime",
3
- "version": "1.13.2",
3
+ "version": "1.13.3",
4
4
  "description": "Effect runtime utilities for TypeScript",
5
5
  "license": "MIT",
6
6
  "author": "Augusto Vivaldelli",
@@ -29,10 +29,7 @@
29
29
  },
30
30
  "files": [
31
31
  "dist",
32
- "wasm/pkg/brass_runtime_wasm_engine.js",
33
- "wasm/pkg/brass_runtime_wasm_engine_bg.wasm",
34
- "wasm/pkg/package.json",
35
- "wasm/pkg/*.d.ts",
32
+ "wasm/pkg",
36
33
  "README.md",
37
34
  "LICENSE",
38
35
  "package.json"
@@ -67,6 +64,7 @@
67
64
  "build:types": "tsc -p tsconfig.types.json",
68
65
  "build:esm": "tsc -p tsconfig.esm.json",
69
66
  "build:cjs": "tsc -p tsconfig.cjs.json",
67
+ "prepack": "npm run build:wasm && npm run build",
70
68
  "prepublishOnly": "npm run build:wasm && npm run build",
71
69
  "agent:dev": "tsx src/agent/cli/main.ts",
72
70
  "agent:doctor": "tsx src/agent/cli/main.ts --doctor",
@@ -1,16 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';var chunk6OUI6UGZ_cjs=require('../../chunk-6OUI6UGZ.cjs'),chunkK47BP5A2_cjs=require('../../chunk-K47BP5A2.cjs'),fs=require('fs'),promises=require('fs/promises'),path=require('path'),child_process=require('child_process');var Xe=new Function("specifier","return import(specifier)"),Ze=e=>["y","yes","approve","approved","si","s\xED","s"].includes(e),en=e=>["n","no","reject","rejected","deny","denied"].includes(e),nn=(e,n)=>{let t=e.trim().toLowerCase();return t?Ze(t)?{type:"approved"}:en(t)?{type:"rejected",reason:"Rejected by user."}:{type:"rejected",reason:`Unrecognized approval answer: ${e}`}:n.defaultAnswer==="approve"?{type:"approved"}:{type:"rejected",reason:"Rejected by default answer."}},Pe=(e={})=>({request:n=>chunkK47BP5A2_cjs.j((t,o)=>{let r=false,a;return Xe("node:readline/promises").then(({createInterface:l})=>{if(r)return;let s=e.input??process.stdin,c=e.output??process.stderr??process.stdout,h=n.defaultAnswer==="approve"?"Y/n":"y/N";return a=l({input:s,output:c}),c?.write?.(`
3
- Approval required (${n.risk})
4
- `),c?.write?.(`Action: ${chunk6OUI6UGZ_cjs.T(n.action)}
5
- `),c?.write?.(`Reason: ${n.reason}
6
- `),a.question(`Approve? [${h}] `)}).then(l=>{l===void 0||r||(r=true,a?.close?.(),o(chunkK47BP5A2_cjs.u.succeed(nn(l,n))));}).catch(l=>{r||(r=true,a?.close?.(),o(chunkK47BP5A2_cjs.u.failCause(chunkK47BP5A2_cjs.t.fail({_tag:"AgentLoopError",message:`Approval prompt failed: ${String(l)}`}))));}),()=>{r||(r=true,a?.close?.());}})});var _=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),N=e=>{try{return JSON.parse(fs.readFileSync(e,"utf8"))}catch{return}},Le=(e,n)=>{let t=path.resolve(e);for(;;){let o=path.join(t,"package.json"),r=N(o);if(_(r)&&r.name===n)return t;let a=path.resolve(t,"..");if(a===t)return;t=a;}},M=(e,n=["--version"],t)=>{let o=child_process.spawnSync(e,[...n],{cwd:t,encoding:"utf8",shell:false,timeout:1e4});if(!(o.error||(o.status??0)!==0))return `${o.stdout??""}${o.stderr??""}`.trim().split(/\r?\n/g)[0]},L=e=>!!(e&&process.env[e]),ln=()=>process.env.BRASS_AGENT_VSCODE_EXTENSION==="1",cn=e=>{let n=N(path.join(e,"package.json")),t=_(n)&&typeof n.packageManager=="string"?n.packageManager.split("@")[0]:void 0;return t?{manager:t,source:"package.json packageManager"}:fs.existsSync(path.join(e,"pnpm-lock.yaml"))?{manager:"pnpm",source:"pnpm-lock.yaml"}:fs.existsSync(path.join(e,"yarn.lock"))?{manager:"yarn",source:"yarn.lock"}:fs.existsSync(path.join(e,"bun.lockb"))||fs.existsSync(path.join(e,"bun.lock"))?{manager:"bun",source:"bun lockfile"}:fs.existsSync(path.join(e,"package-lock.json"))||fs.existsSync(path.join(e,"npm-shrinkwrap.json"))?{manager:"npm",source:"npm lockfile"}:{manager:"npm",source:"fallback"}},pn=e=>_(e)&&_(e.scripts)?Object.entries(e.scripts).filter(([,n])=>typeof n=="string").map(([n])=>n).sort():[],dn=(e,n)=>e.find(t=>n.some(o=>o.test(t))),un=(e,n)=>{let t=pn(n),o=["Cargo.toml","Cargo.lock","src-tauri/tauri.conf.json","apps/desktop/package.json","apps/desktop/src-tauri/tauri.conf.json","bridges/whatsmeow-bridge/Cargo.toml","apps","packages","bridges","turbo.json","nx.json","pnpm-workspace.yaml"].filter(s=>fs.existsSync(path.join(e,s))),r=[];_(n)&&r.push("node"),o.some(s=>s==="Cargo.toml"||s==="Cargo.lock"||s.endsWith("Cargo.toml"))&&r.push("rust"),(o.some(s=>s.includes("tauri"))||t.some(s=>s.includes("tauri")))&&r.push("tauri"),(o.some(s=>s.startsWith("apps"))||t.some(s=>s.includes("desktop")))&&r.push("desktop"),(o.some(s=>s.startsWith("bridges"))||t.some(s=>s.includes("bridge")))&&r.push("bridge"),o.some(s=>["apps","packages","bridges","turbo.json","nx.json","pnpm-workspace.yaml"].includes(s))&&r.push("monorepo");let a=dn(t,[/^repo:check$/,/^check$/,/(^|:)check($|:)/,/(^|:)doctor($|:)/,/(^|:)health($|:)/,/(^|:)verify($|:)/,/(^|:)validate($|:)/,/(^|:)ci($|:)/]),l=[`stacks: ${r.length>0?[...new Set(r)].join(", "):"none detected"}`,`markers: ${o.length>0?o.slice(0,8).join(", "):"none"}`,a?`likely validation: npm run ${a}`:"likely validation: none detected"];return {id:"workspace.projectProfile",label:"Workspace project profile",status:r.length>0?"ok":"skip",message:l.join(". ")}},gn=e=>{if(!e)return {id:"envFile",label:"Agent env file",status:"skip",message:"Env file loading did not run."};if(e.disabled)return {id:"envFile",label:"Agent env file",status:"skip",message:"Env file loading disabled by --no-env-file."};if(e.errors.length>0)return {id:"envFile",label:"Agent env file",status:"fail",message:e.errors.join("; ")};if(e.paths.length===0)return {id:"envFile",label:"Agent env file",status:"skip",message:"No .brass-agent.env, .env.local, or .env found in workspace; using exported shell environment only."};let n=[`Loaded ${e.paths.join(", ")}`];return e.loadedKeys.length>0&&n.push(`keys: ${e.loadedKeys.join(", ")}`),e.alreadySetKeys.length>0&&n.push(`already set by shell: ${e.alreadySetKeys.join(", ")}`),e.emptyKeys.length>0&&n.push(`empty keys skipped: ${e.emptyKeys.join(", ")}`),e.ignoredKeys.length>0&&n.push(`non-agent keys ignored: ${e.ignoredKeys.slice(0,8).join(", ")}${e.ignoredKeys.length>8?", ...":""}`),e.invalidLines.length>0&&n.push(`invalid lines: ${e.invalidLines.join(", ")}`),{id:"envFile",label:"Agent env file",status:e.loadedKeys.length>0||e.alreadySetKeys.length>0?"ok":"warn",message:n.join(". ")}},fn=e=>{let n=(process.env.BRASS_LLM_PROVIDER??e?.llm?.provider)?.trim().toLowerCase(),t=e?.llm?.apiKeyEnv;if(n==="fake")return {id:"llm",label:"LLM provider",status:"ok",message:"Fake LLM provider is selected."};if(n==="google"||n==="gemini"){let o=L(t)||L("BRASS_GOOGLE_API_KEY")||L("GOOGLE_API_KEY")||L("GEMINI_API_KEY");return {id:"llm",label:"LLM provider",status:o?"ok":"fail",message:o?`Google/Gemini provider is configured (${n}).`:"Google/Gemini provider is selected but no API key env var is set. Export GEMINI_API_KEY or put it in .env/.brass-agent.env."}}if(n==="openai"||n==="openai-compatible"){let o=!!(process.env.BRASS_LLM_ENDPOINT??e?.llm?.endpoint),r=L(t)||L("BRASS_LLM_API_KEY");return {id:"llm",label:"LLM provider",status:o&&r?"ok":"fail",message:o&&r?`OpenAI-compatible provider is configured (${n}).`:"OpenAI-compatible provider is selected but endpoint or API key env var is missing. Export BRASS_LLM_API_KEY or put it in .env/.brass-agent.env."}}return L("BRASS_GOOGLE_API_KEY")||L("GOOGLE_API_KEY")||L("GEMINI_API_KEY")?{id:"llm",label:"LLM provider",status:"ok",message:"Google/Gemini credentials are available and will be auto-detected."}:(process.env.BRASS_LLM_ENDPOINT??e?.llm?.endpoint)&&L("BRASS_LLM_API_KEY")?{id:"llm",label:"LLM provider",status:"ok",message:"OpenAI-compatible credentials are available and will be auto-detected."}:{id:"llm",label:"LLM provider",status:"warn",message:"No real LLM credentials found. The CLI will fall back to the fake provider unless config selects a real provider."}},mn=e=>{let n=N(path.join(e,".vscode","settings.json"));if(!_(n))return;let t=n["brassAgent.command"];return typeof t=="string"?t:void 0},yn=e=>{try{return fs.readdirSync(e).filter(n=>n.endsWith(".vsix")).sort().at(-1)}catch{return}},y=(e,n)=>{e.push(n);},_e=async e=>{let n=path.resolve(e.cwd),t=[],o=Le(n,"brass-runtime")??Le(process.cwd(),"brass-runtime"),r=Number(process.versions.node.split(".")[0]??"0");y(t,{id:"node",label:"Node.js",status:r>=18?"ok":"fail",message:`Node ${process.versions.node}${r>=18?"":" is too old; use Node 18 or newer."}`});let a=M("npm");y(t,{id:"npm",label:"npm",status:a?"ok":"fail",message:a?`npm ${a}`:"npm is not available on PATH."});let l=M("git");y(t,{id:"git",label:"git",status:l?"ok":"warn",message:l||"git is not available; patch apply/rollback uses git apply."});let s=M("rg");if(y(t,{id:"ripgrep",label:"ripgrep",status:s?"ok":"warn",message:s||"rg is not available; context discovery search will be limited."}),y(t,{id:"workspace",label:"Workspace",status:fs.existsSync(n)?"ok":"fail",message:fs.existsSync(n)?n:`Workspace does not exist: ${n}`}),e.workspaceDiscovery){let p=e.workspaceDiscovery;y(t,{id:"workspace.discovery",label:"Workspace discovery",status:p.disabled?"skip":p.marker?"ok":"warn",message:p.disabled?"Workspace discovery disabled by --no-discover-workspace.":p.marker?`${p.changed?`Resolved ${p.inputCwd} -> ${p.cwd}`:`Using ${p.cwd}`} via ${p.marker}.`:`No workspace marker found upward from ${p.inputCwd}; using input cwd.`});}let c=path.join(n,"package.json"),h=N(c);if(y(t,{id:"workspace.packageJson",label:"Workspace package.json",status:_(h)?"ok":"warn",message:_(h)?`Found ${c}`:"No package.json found in workspace; project command discovery may use fallbacks."}),_(h)){let p=_(h.scripts)?Object.keys(h.scripts):[];y(t,{id:"workspace.scripts",label:"Workspace scripts",status:p.length?"ok":"warn",message:p.length?`Scripts: ${p.slice(0,12).join(", ")}${p.length>12?", ...":""}`:"No package scripts found."});let g=cn(n),m=M(g.manager);y(t,{id:"workspace.packageManager",label:"Workspace package manager",status:m?"ok":"warn",message:m?`${g.manager} available (${g.source}): ${m}`:`${g.manager} inferred from ${g.source}, but command is not available on PATH.`});}if(y(t,un(n,h)),y(t,gn(e.envFileLoad)),y(t,fn(e.config)),y(t,{id:"config",label:"Agent config",status:e.configPath?"ok":"skip",message:e.configPath?`Loaded ${e.configPath}`:"No .brass-agent.json / brass-agent.config.json loaded; using built-in defaults and VS Code/CLI settings."}),e.includeVsCode!==false){let p=M(process.env.BRASS_CODE_CMD??"code");y(t,{id:"vscode.code",label:"VS Code CLI",status:p?"ok":"warn",message:p?`code ${p}`:"VS Code CLI `code` is not available on PATH; .vsix install needs it unless using the VS Code UI."});let g=mn(n),m=ln();y(t,{id:"vscode.settings",label:"VS Code extension setting",status:g?"ok":m?"skip":"warn",message:g?`brassAgent.command = ${g}`:m?`No workspace brassAgent.command needed; launched by the VS Code extension (${process.env.BRASS_AGENT_VSCODE_CLI_SOURCE??"auto"}).`:"No workspace .vscode/settings.json brassAgent.command found."});}if(o){let p=path.join(o,"src","agent","cli","main.ts"),g=path.join(o,"dist","agent","cli","main.cjs"),m=path.join(o,"extensions","vscode-brass-agent");y(t,{id:"repo.root",label:"brass-runtime repo",status:"ok",message:o}),y(t,{id:"repo.cliSource",label:"CLI source",status:fs.existsSync(p)?"ok":"fail",message:fs.existsSync(p)?`Found ${p}`:`Missing ${p}`}),y(t,{id:"repo.cliBuild",label:"CLI build",status:fs.existsSync(g)?"ok":"warn",message:fs.existsSync(g)?`Found ${g}`:"dist/agent/cli/main.cjs is missing; run npm run build."}),y(t,{id:"repo.extensionDir",label:"VS Code extension source",status:fs.existsSync(path.join(m,"package.json"))?"ok":"warn",message:fs.existsSync(path.join(m,"package.json"))?m:"extensions/vscode-brass-agent was not found."}),y(t,{id:"repo.extensionBuild",label:"VS Code extension build",status:fs.existsSync(path.join(m,"out","extension.js"))?"ok":"warn",message:fs.existsSync(path.join(m,"out","extension.js"))?"out/extension.js exists.":"Extension output missing; run npm run agent:vscode:package or compile the extension."});let S=yn(m);y(t,{id:"repo.extensionVsix",label:"VSIX package",status:S?"ok":"warn",message:S?`Found ${S}`:"No .vsix found in extensions/vscode-brass-agent."});let R=await promises.access(g,promises.constants.R_OK).then(()=>true).catch(()=>false);y(t,{id:"repo.cliReadable",label:"CLI artifact readable",status:R?"ok":"warn",message:R?"Built CLI artifact is readable.":"Built CLI artifact is not readable yet."});}else y(t,{id:"repo.root",label:"brass-runtime repo",status:"skip",message:"Not running inside a brass-runtime checkout; local source/build checks skipped."});let E=t.some(p=>p.status==="fail")?"fail":t.some(p=>p.status==="warn")?"warn":"ok";return {generatedAt:new Date().toISOString(),cwd:n,...e.configPath?{configPath:e.configPath}:{},...o?{repoRoot:o}:{},status:E,checks:t}},hn=e=>{switch(e){case "ok":return "\u2713";case "warn":return "!";case "fail":return "\u2717";case "skip":return "-"}},xe=e=>{console.log("brass-agent doctor"),console.log(`workspace: ${e.cwd}`),e.configPath&&console.log(`config: ${e.configPath}`),e.repoRoot&&console.log(`repo: ${e.repoRoot}`),console.log(`status: ${e.status}`),console.log("");for(let n of e.checks)console.log(`${hn(n.status)} ${n.label}: ${n.message}`);};var kn=[".brass-agent.env",".env.local",".env"],wn=new Set(["BRASS_LLM_PROVIDER","BRASS_FAKE_LLM_RESPONSE","BRASS_GOOGLE_API_KEY","GOOGLE_API_KEY","GEMINI_API_KEY","BRASS_GOOGLE_MODEL","BRASS_GOOGLE_API_VERSION","BRASS_GOOGLE_BASE_URL","BRASS_GOOGLE_ENDPOINT","BRASS_GOOGLE_SYSTEM_INSTRUCTION","BRASS_GOOGLE_TEMPERATURE","BRASS_GOOGLE_TOP_P","BRASS_GOOGLE_TOP_K","BRASS_GOOGLE_MAX_OUTPUT_TOKENS","BRASS_LLM_ENDPOINT","BRASS_LLM_API_KEY","BRASS_LLM_MODEL","BRASS_AGENT_APPROVAL","BRASS_AGENT_AUTO_APPROVE","BRASS_CODE_CMD"]),C=e=>Array.from(new Set(e)),Sn=e=>{if(e.length<2)return;let n=e[0];if(n!=='"'&&n!=="'"||e[e.length-1]!==n)return;let t=e.slice(1,-1);return n==="'"?t:t.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")},En=e=>{let n=e.trim();if(!n||n.startsWith("#"))return {type:"skip"};let t=n.startsWith("export ")?n.slice(7).trimStart():n,o=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(t);if(!o)return {type:"invalid"};let r=o[1]??"",l=(o[2]??"").trim(),c=Sn(l)??l.replace(/\s+#.*$/u,"").trim();return {type:"assignment",key:r,value:c}},Rn=(e,n)=>n?[path.isAbsolute(n)?n:path.resolve(e,n)]:kn.map(t=>path.join(e,t)),Ce=e=>{let n=path.resolve(e.cwd),t=e.allowedExtraKeys?.filter(Boolean)??[],o=new Set([...wn,...t]),r=e.noEnvFile?[]:Rn(n,e.envFile),a=[],l=[],s=[],c=[],h=[],E=[],p=[];if(e.noEnvFile)return {cwd:n,disabled:true,filesChecked:[],paths:[],loadedKeys:[],alreadySetKeys:[],emptyKeys:[],ignoredKeys:[],invalidLines:[],errors:[]};for(let g of r){if(!fs.existsSync(g)){e.envFile&&p.push(`Env file does not exist: ${g}`);continue}a.push(g);let m;try{m=fs.readFileSync(g,"utf8").replace(/^\uFEFF/u,"");}catch(S){p.push(`Could not read env file ${g}: ${S instanceof Error?S.message:String(S)}`);continue}for(let[S,R]of m.split(/\r?\n/gu).entries()){let b=En(R);if(b.type!=="skip"){if(b.type==="invalid"){E.push(`${g}:${S+1}`);continue}if(!o.has(b.key)){h.push(b.key);continue}if(!b.value){c.push(b.key);continue}if(process.env[b.key]!==void 0){s.push(b.key);continue}process.env[b.key]=b.value,l.push(b.key);}}}return {cwd:n,disabled:false,...e.envFile?{explicitPath:path.isAbsolute(e.envFile)?e.envFile:path.resolve(n,e.envFile)}:{},filesChecked:r,paths:a,loadedKeys:C(l),alreadySetKeys:C(s),emptyKeys:C(c),ignoredKeys:C(h),invalidLines:C(E),errors:C(p)}};var Fe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),On=e=>{try{return JSON.parse(fs.readFileSync(e,"utf8"))}catch{return}},Me=e=>{let n=On(path.join(e,"package.json"));return Fe(n)?n:void 0},$e=e=>{let n=e?.scripts;return Fe(n)?Object.entries(n).filter(([,t])=>typeof t=="string").map(([t])=>t).sort():[]},$=(e,n)=>n.some(t=>e.includes(t)),Cn=(e,n)=>{let t=typeof n?.packageManager=="string"?n.packageManager.split("@")[0]:void 0;return t==="npm"||t==="pnpm"||t==="yarn"||t==="bun"?t:fs.existsSync(path.join(e,"pnpm-lock.yaml"))?"pnpm":fs.existsSync(path.join(e,"yarn.lock"))?"yarn":fs.existsSync(path.join(e,"bun.lockb"))||fs.existsSync(path.join(e,"bun.lock"))?"bun":fs.existsSync(path.join(e,"package-lock.json"))||fs.existsSync(path.join(e,"npm-shrinkwrap.json"))?"npm":"auto"},In=e=>{switch(e){case "default":return;case "google":return {provider:"google",model:"gemini-2.5-flash",apiKeyEnv:"GEMINI_API_KEY",temperature:.2,maxOutputTokens:4096};case "openai-compatible":return {provider:"openai-compatible",endpoint:"https://api.openai.com/v1/chat/completions",model:"gpt-4.1",apiKeyEnv:"BRASS_LLM_API_KEY",temperature:.2};case "fake":return {provider:"fake",fakeResponse:"Fake plan from brass-agent init. Configure a real provider when ready."}}},Fn=(e,n)=>{let t=Me(e),o=$e(t),r=$(o,["typecheck","type-check","check-types","tsc","check"]),a=$(o,["lint","lint:ci"]),l=In(n);return {mode:"propose",approval:"auto",...l?{llm:l}:{},project:{packageManager:Cn(e,t),testScriptNames:["test","test:ci","test:unit"],includeTypecheck:r,includeLint:a,maxValidationCommands:2},context:{enabled:true,maxSearchQueries:3,maxFiles:4,maxSearchResults:40,globs:["*.ts","*.tsx","*.js","*.jsx","*.mjs","*.cjs","*.json","*.md","*.yml","*.yaml"],excludeGlobs:[".env*","**/.env*","**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/*.pem","**/*.key","**/secrets/**"]},patchQuality:{enabled:true,maxRepairAttempts:1},rollback:{enabled:true,onFinalValidationFailure:true,strategy:"all",maxRollbackDepth:8,runValidationAfterRollback:true,allowForSuppliedPatches:false},redaction:{enabled:true,additionalPatterns:[]},language:{response:"auto"},permissions:{shell:{inheritDefaults:true,ask:[{pattern:"npm run build",reason:"Build commands can be slow and may produce large outputs.",risk:"medium",defaultAnswer:"approve"},{pattern:"pnpm run build",reason:"Build commands can be slow and may produce large outputs.",risk:"medium",defaultAnswer:"approve"},{pattern:"yarn run build",reason:"Build commands can be slow and may produce large outputs.",risk:"medium",defaultAnswer:"approve"},{pattern:"bun run build",reason:"Build commands can be slow and may produce large outputs.",risk:"medium",defaultAnswer:"approve"}],deny:["rm *","git push *","git reset *","git clean *"]},patchApply:{decision:"ask",reason:"Apply the generated unified diff to the workspace.",risk:"high",defaultAnswer:"reject"}},tools:{"fs.readFile":{timeoutMs:1e4,retries:1},"fs.exists":{timeoutMs:5e3,retries:0},"fs.searchText":{timeoutMs:1e4,retries:1},"shell.exec":{timeoutMs:18e4,retries:0},"llm.complete":{timeoutMs:9e4,retries:2},"patch.apply":{timeoutMs:3e4,retries:0},"patch.rollback":{timeoutMs:3e4,retries:0}}}},Mn=e=>{let n=$e(Me(e)),t=[{preset:"inspect",mode:"read-only"}];return $(n,["typecheck","type-check","check-types","tsc","check"])&&t.push({preset:"typecheck",mode:"propose"}),$(n,["lint","lint:ci"])&&t.push({preset:"lint",mode:"propose"}),$(n,["test","test:ci","test:unit"])&&t.push({preset:"fix-tests",mode:"propose"}),t},$n=e=>`${JSON.stringify({stopOnFailure:false,goals:Mn(e)},null,2)}
8
- `,jn=e=>{let n=["# Brass Agent environment variables","# Copy this file to .env or .brass-agent.env, or export the variables in your shell.","# brass-agent auto-loads supported agent env keys from --cwd.","# Do not commit real API keys.",""];return e==="fake"&&n.push("BRASS_LLM_PROVIDER=fake","BRASS_FAKE_LLM_RESPONSE=Fake plan from .env.example",""),n.push("# Google / Gemini","# Used when .brass-agent.json selects provider google, or when auto-detected.","GEMINI_API_KEY=","BRASS_GOOGLE_MODEL=gemini-2.5-flash","","# OpenAI-compatible providers","# BRASS_LLM_PROVIDER=openai-compatible","BRASS_LLM_ENDPOINT=https://api.openai.com/v1/chat/completions","BRASS_LLM_API_KEY=","BRASS_LLM_MODEL=gpt-4.1","","# Approval behavior: auto | interactive | approve | deny","# BRASS_AGENT_APPROVAL=auto",""),e==="google"?n.splice(4,0,"BRASS_LLM_PROVIDER=google",""):e==="openai-compatible"&&n.splice(4,0,"BRASS_LLM_PROVIDER=openai-compatible",""),`${n.join(`
9
- `)}
10
- `},Bn=()=>["# Brass Agent","","This workspace was initialized with `brass-agent --init`.","","Generated files:","","- `.brass-agent.json` \u2014 local policy/config for Brass Agent.","- `brass-agent.batch.json` \u2014 sample multi-goal batch workflow.","- `.env.example` \u2014 example environment variables. Copy to `.env` or `.brass-agent.env`; keep real secrets out of git.","","Recommended first commands:","","```bash","brass-agent --doctor","brass-agent --preset inspect","brass-agent --batch-file brass-agent.batch.json","```","","Apply mode is intentionally approval-gated:","","```bash",'brass-agent --apply "fix the failing tests"',"```",""].join(`
11
- `),Dn=e=>{let n=["Review .brass-agent.json and adjust permissions/context budgets for this repo.","Run: brass-agent --doctor","Run: brass-agent --preset inspect","Run: brass-agent --batch-file brass-agent.batch.json"];return e==="google"?["Set GEMINI_API_KEY in your shell, `.env`, or `.brass-agent.env`.",...n]:e==="openai-compatible"?["Set BRASS_LLM_API_KEY and BRASS_LLM_ENDPOINT in your shell, `.env`, or `.brass-agent.env`.",...n]:e==="default"?["Set an LLM provider env var in your shell, `.env`, or `.brass-agent.env` when ready, or let the CLI fall back to fake mode.",...n]:n},T=async e=>{let n=path.resolve(e.cwd,e.relativePath),o=fs.existsSync(n)?e.force?"overwritten":"skipped":"created";return !e.dryRun&&o!=="skipped"&&(await promises.mkdir(path.dirname(n),{recursive:true}),await promises.writeFile(n,e.content,"utf8")),{path:n,relativePath:e.relativePath,status:o,bytes:Buffer.byteLength(e.content,"utf8")}},je=async e=>{let n=path.resolve(e.cwd),t=e.profile??"default",o=e.force??false,r=e.dryRun??false,a=Fn(n,t),l=await Promise.all([T({cwd:n,relativePath:".brass-agent.json",content:`${JSON.stringify(a,null,2)}
12
- `,force:o,dryRun:r}),T({cwd:n,relativePath:"brass-agent.batch.json",content:$n(n),force:o,dryRun:r}),T({cwd:n,relativePath:".env.example",content:jn(t),force:o,dryRun:r}),T({cwd:n,relativePath:"BRASS_AGENT.md",content:Bn(),force:o,dryRun:r})]);return {cwd:n,profile:t,dryRun:r,files:l,nextSteps:Dn(t)}},Gn=e=>{switch(e){case "created":return "\u2713";case "overwritten":return "!";case "skipped":return "-"}},Be=e=>{console.log(`brass-agent init${e.dryRun?" (dry run)":""}`),console.log(`workspace: ${e.cwd}`),console.log(`profile: ${e.profile}`),console.log("");for(let n of e.files)console.log(`${Gn(n.status)} ${n.status} ${n.relativePath}`);console.log(""),console.log("next steps:");for(let n of e.nextSteps)console.log(`- ${n}`);};var F=new Function("specifier","return import(specifier)"),Nn=async(e,n)=>{let t=await F("node:path");return (await F("node:fs/promises")).readFile(t.resolve(e,n),"utf8")},K=e=>{if(e===void 0||e.trim()==="")return;let n=Number(e);return Number.isFinite(n)?n:void 0},Ye=e=>e==="read-only"||e==="propose"||e==="write"||e==="autonomous",Je=e=>e==="auto"||e==="interactive"||e==="approve"||e==="deny",De=e=>e==="default"||e==="google"||e==="openai-compatible"||e==="fake",Tn=e=>["auto","match-user","en","es","pt","fr","de","it","custom"].includes(e),k=(e,n,t)=>{let o=e[n],r=o.startsWith(`${t}=`)?o.slice(t.length+1):void 0;if(r!==void 0&&r!=="")return [r,n];let a=e[n+1];if(!a)throw new Error(`${t} requires a value`);return [a,n+1]},Kn=e=>{let n=process.cwd(),t=true,o=false,r="propose",a=false,l=false,s="human",c="auto",h=false,E,p=false,g,m=false,S=false,R,b="apply",V,re=false,se=false,W,Y,D,ae=false,ie=false,le=false,G="default",ce=false,J,U=[];for(let u=0;u<e.length;u+=1){let i=e[u];if(i==="--"){U.push(...e.slice(u+1));break}if(i==="--help"||i==="-h"){l=true;continue}if(i==="--doctor"){ae=true;continue}if(i==="--where"||i==="--print-workspace"){o=true;continue}if(i==="--no-discover-workspace"){t=false;continue}if(i==="--init"){ie=true;continue}if(i==="--force"||i==="--init-force"){le=true;continue}if(i==="--init-dry-run"){ce=true;continue}if(i==="--init-profile"||i.startsWith("--init-profile=")){let[d,f]=k(e,u,"--init-profile");if(!De(d))throw new Error("--init-profile requires one of: default, google, openai-compatible, fake");G=d,u=f;continue}if(i==="--init-provider"||i.startsWith("--init-provider=")){let[d,f]=k(e,u,"--init-provider");if(d==="auto")G="default";else if(De(d))G=d;else throw new Error("--init-provider requires one of: auto, fake, google, openai-compatible");u=f;continue}if(i==="--language"||i.startsWith("--language=")){let[d,f]=k(e,u,"--language");if(!Tn(d))throw new Error("--language requires one of: auto, match-user, en, es, pt, fr, de, it, custom");J=d,u=f;continue}if(i==="--json"){s="json";continue}if(i==="--events-json"){s="events-json";continue}if(i==="--protocol-json"){s="protocol-json";continue}if(i==="--protocol-full-patches"){S=true;continue}if(i==="--preset"||i.startsWith("--preset=")){let[d,f]=k(e,u,"--preset");if(!chunk6OUI6UGZ_cjs.ga(d))throw new Error("--preset requires one of: fix-tests, inspect, typecheck, lint");W=d,u=f;continue}if(i==="--batch-file"||i.startsWith("--batch-file=")){let[d,f]=k(e,u,"--batch-file");Y=d,u=f;continue}if(i==="--batch-stop-on-failure"){D=true;continue}if(i==="--batch-continue-on-failure"){D=false;continue}if(i==="--ci"){re=true;continue}if(i==="--fail-on-patch-proposed"){se=true;continue}if(i==="--yes"||i==="-y"){c="approve",h=true;continue}if(i==="--no-input"){c="deny",h=true;continue}if(i==="--approval"||i.startsWith("--approval=")){let[d,f]=k(e,u,"--approval");if(!Je(d))throw new Error("--approval requires one of: auto, interactive, approve, deny");c=d,h=true,u=f;continue}if(i==="--apply"){r="write",a=true;continue}if(i==="--patch-file"||i.startsWith("--patch-file=")){let[d,f]=k(e,u,"--patch-file");R=d,u=f;continue}if(i==="--apply-patch-file"||i.startsWith("--apply-patch-file=")){let[d,f]=k(e,u,"--apply-patch-file");R=d,b="apply",r="write",a=true,u=f;continue}if(i==="--rollback-patch-file"||i.startsWith("--rollback-patch-file=")){let[d,f]=k(e,u,"--rollback-patch-file");R=d,b="rollback",r="write",a=true,u=f;continue}if(i==="--mode"||i.startsWith("--mode=")){let[d,f]=k(e,u,"--mode");if(!Ye(d))throw new Error("--mode requires one of: read-only, propose, write, autonomous");r=d,a=true,u=f;continue}if(i==="--cwd"||i.startsWith("--cwd=")){let[d,f]=k(e,u,"--cwd");n=d,u=f;continue}if(i==="--save-run"||i.startsWith("--save-run=")){let[d,f]=k(e,u,"--save-run");V=d,u=f;continue}if(i==="--config"||i.startsWith("--config=")){let[d,f]=k(e,u,"--config");E=d,p=false,u=f;continue}if(i==="--no-config"){E=void 0,p=true;continue}if(i==="--env-file"||i.startsWith("--env-file=")){let[d,f]=k(e,u,"--env-file");g=d,m=false,u=f;continue}if(i==="--no-env-file"){g=void 0,m=true;continue}if(i.startsWith("--"))throw new Error(`Unknown option: ${i}`);U.push(i);}return {cwd:n,discoverWorkspace:t,where:o,goalText:U.join(" ").trim(),mode:r,modeSpecified:a,showHelp:l,output:s,approval:c,approvalSpecified:h,...E?{configPath:E}:{},noConfig:p,...g?{envFile:g}:{},noEnvFile:m,protocolFullPatches:S,patchFileMode:b,ci:re,failOnPatchProposed:se,...W?{preset:W}:{},...Y?{batchFile:Y}:{},...D!==void 0?{batchStopOnFailure:D}:{},doctor:ae,init:ie,initForce:le,initProfile:G,initDryRun:ce,...J?{language:J}:{},...V?{saveRunDir:V}:{},...R?{patchFile:R}:{}}},Ue=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vn=(e,n)=>{if(typeof e=="string")return e;if(!Ue(e))throw new Error(`${n} must be a string or object.`);let t=e.goal,o=e.preset,r=e.mode,a=e.cwd,l=e.patchFile,s=e.patchFileMode,c=e.saveRunDir;if(t!==void 0&&typeof t!="string")throw new Error(`${n}.goal must be a string.`);if(a!==void 0&&typeof a!="string")throw new Error(`${n}.cwd must be a string.`);if(l!==void 0&&typeof l!="string")throw new Error(`${n}.patchFile must be a string.`);if(c!==void 0&&typeof c!="string")throw new Error(`${n}.saveRunDir must be a string.`);if(o!==void 0&&(typeof o!="string"||!chunk6OUI6UGZ_cjs.ga(o)))throw new Error(`${n}.preset must be one of: fix-tests, inspect, typecheck, lint.`);if(r!==void 0&&(typeof r!="string"||!Ye(r)))throw new Error(`${n}.mode must be one of: read-only, propose, write, autonomous.`);if(s!==void 0&&s!=="apply"&&s!=="rollback")throw new Error(`${n}.patchFileMode must be apply or rollback.`);if(t===void 0&&o===void 0&&l===void 0)throw new Error(`${n} must include goal, preset, or patchFile.`);return {...t?{goal:t}:{},...o?{preset:o}:{},...r?{mode:r}:{},...a?{cwd:a}:{},...l?{patchFile:l}:{},...s?{patchFileMode:s}:{},...c?{saveRunDir:c}:{}}},Wn=e=>{let n=Array.isArray(e)?e:Ue(e)&&Array.isArray(e.goals)?e.goals:void 0;if(!n)throw new Error("Batch file must be a JSON array or an object with a goals array.");return n.map((t,o)=>Vn(t,`goals[${o}]`))},Yn=async(e,n)=>{let t=await F("node:path"),o=await F("node:fs/promises"),r=t.isAbsolute(n)?n:t.resolve(e,n),a=String(await o.readFile(r,"utf8")).replace(/^\uFEFF/,"");try{return Wn(JSON.parse(a))}catch(l){if(!(l instanceof SyntaxError))throw l;let s=a.split(/\r?\n/g).map(c=>c.trim()).filter(c=>c&&!c.startsWith("#"));if(s.length===0)throw new Error(`Batch file has no goals: ${r}`);return s}},Jn=(e,n)=>typeof e=="string"?e:e.goal?e.goal:e.preset?chunk6OUI6UGZ_cjs.ha(e.preset):e.patchFile??n?"apply supplied patch":"",Un=(e,n,t)=>typeof e!="string"&&e.mode?e.mode:typeof e!="string"&&e.preset==="inspect"&&!n.modeSpecified?"read-only":n.modeSpecified?n.mode:t.mode??n.mode,qn=(e,n,t)=>e.map((o,r)=>{let a=Jn(o,n.patchFile),l=typeof o=="string"?n.cwd:o.cwd??n.cwd,s=typeof o=="string"?n.patchFile:o.patchFile??n.patchFile,c=typeof o=="string"?n.patchFileMode:o.patchFileMode??n.patchFileMode,h=typeof o=="string"?n.saveRunDir:o.saveRunDir??n.saveRunDir;if(!a)throw new Error(`Batch goal ${r+1} resolved to an empty goal.`);return {index:r,cwd:l,goalText:a,mode:Un(o,n,t),patchFileMode:c,...s?{patchFile:s}:{},...h?{saveRunDir:h}:{}}}),Hn=async e=>{let n=chunk6OUI6UGZ_cjs.ta(e.cwd,{enabled:e.discoverWorkspace}),t=n.cwd,o={...e,cwd:t},r=await chunk6OUI6UGZ_cjs.pa({cwd:t,configPath:e.configPath,noConfig:e.noConfig}),a=Ce({cwd:t,envFile:e.envFile,noEnvFile:e.noEnvFile,allowedExtraKeys:r.config.llm?.apiKeyEnv?[r.config.llm.apiKeyEnv]:[]}),l=!e.goalText&&!e.preset&&!e.patchFile,s=e.batchFile?await Yn(t,e.batchFile):l?r.config.batch?.goals??[]:[],c=qn(s,o,r.config);return {...o,goalText:e.goalText||(e.preset?chunk6OUI6UGZ_cjs.ha(e.preset):e.patchFile?"apply supplied patch":e.goalText),mode:e.modeSpecified?e.mode:e.preset==="inspect"?"read-only":r.config.mode??e.mode,approval:e.approvalSpecified?e.approval:r.config.approval??e.approval,config:r.config,workspaceDiscovery:n,batchRuns:c,batchStopOnFailureResolved:e.batchStopOnFailure??r.config.batch?.stopOnFailure??e.ci,envFileLoad:a,...r.path?{resolvedConfigPath:r.path}:{}}},Ge=()=>{console.log(['Usage: brass-agent [options] "goal"',"","Options:"," --mode read-only|propose|write|autonomous"," Agent permission mode. Default: propose, or config.mode if present."," --preset fix-tests|inspect|typecheck|lint"," Use a built-in goal preset when no explicit goal text is provided."," --apply"," Alias for --mode write."," --cwd PATH"," Starting directory for workspace discovery. Default: current directory."," --no-discover-workspace"," Use --cwd exactly instead of searching upward for package.json, .brass-agent.json, or .git."," --where, --print-workspace"," Print the resolved workspace root and exit."," --config PATH"," Load a specific .brass-agent.json policy/config file."," --save-run DIR"," Write final run JSON and Markdown artifacts to DIR."," --batch-file PATH"," Run multiple goals sequentially from a JSON or line-based file."," --batch-stop-on-failure"," Stop a batch after the first failed run."," --batch-continue-on-failure"," Continue a batch even when a run fails."," --doctor"," Check local CLI, workspace, VS Code, package manager, and LLM setup."," --init"," Initialize this workspace with .brass-agent.json, brass-agent.batch.json, .env.example, and BRASS_AGENT.md."," --force, --init-force"," Overwrite files generated by --init when they already exist."," --init-profile default|google|openai-compatible|fake"," Initialization profile. Default: default, which leaves provider auto-detection enabled."," --init-provider auto|fake|google|openai-compatible"," Alias for choosing an LLM-oriented init profile. auto maps to default."," --init-dry-run"," Preview generated files without writing them."," --no-config"," Do not discover or load an agent config file."," --language auto|match-user|en|es|pt|fr|de|it"," Response language for LLM summaries. Default: config.language or auto-match the user goal."," --env-file PATH"," Load Brass Agent environment variables from a specific env file."," --no-env-file"," Do not auto-load .brass-agent.env, .env.local, or .env from --cwd."," --json"," Print the full final AgentState JSON. Suppresses live event output."," --ci"," Preserve output mode but set process exit codes from the final run status."," --fail-on-patch-proposed"," In --ci mode, exit 2 when a patch was proposed but not applied."," --events-json"," Stream AgentEvent objects as JSON Lines. Does not print the final AgentState."," --protocol-json"," Stream Brass Agent protocol JSON Lines, including events and a final-state message."," --protocol-full-patches"," Keep patch payloads untruncated in protocol/event JSON output for trusted local integrations."," --patch-file PATH"," Supply a precomputed unified diff to the agent. Respects --mode."," --apply-patch-file PATH"," Supply and apply a precomputed unified diff. Alias for --patch-file PATH --mode write."," --rollback-patch-file PATH"," Reverse-apply a precomputed unified diff through PatchService. Requires write mode approvals."," --yes, -y"," Auto-approve approval prompts. Useful for CI and smoke tests."," --no-input"," Do not prompt; reject any action that requires approval."," --approval auto|interactive|approve|deny"," Approval strategy. Default: auto, or config.approval if present."," --help, -h"," Show this help message.","","Config files:"," brass-agent first resolves a workspace root by searching upward from --cwd."," It looks for .brass-agent.json, brass-agent.config.json, package.json, workspace markers, or .git."," brass-agent then searches upward from that workspace root for .brass-agent.json or brass-agent.config.json."," config.batch.goals can define a default batch when --batch-file is not provided.","","Examples:",' brass-agent "fix the failing tests"'," brass-agent --preset fix-tests"," brass-agent --preset inspect"," brass-agent --batch-file ./brass-agent.batch.json --ci"," brass-agent --where"," brass-agent --doctor"," brass-agent --doctor --json"," brass-agent --env-file .env --doctor"," brass-agent --init"," brass-agent --init --init-profile google"," brass-agent --init --init-profile fake --init-dry-run",' brass-agent --config ./agent.policy.json "fix the failing tests"',' brass-agent --no-config "fix the failing tests"',' brass-agent --json "fix the failing tests"',' brass-agent --events-json "fix the failing tests"',' brass-agent --protocol-json "fix the failing tests"',' brass-agent --protocol-json --protocol-full-patches "fix the failing tests"',' brass-agent --apply-patch-file ./approved.diff --yes "apply approved patch"',' brass-agent --apply "fix the failing tests"',' brass-agent --apply --yes "fix the failing tests"',' brass-agent --mode read-only --cwd ./repo "inspect the test failure"',"","LLM providers:"," BRASS_LLM_PROVIDER=fake"," BRASS_LLM_PROVIDER=google GEMINI_API_KEY=..."," BRASS_LLM_PROVIDER=openai-compatible BRASS_LLM_ENDPOINT=... BRASS_LLM_API_KEY=..."].join(`
13
- `));},qe=e=>e?process.env[e]:void 0,Ne=e=>{let n=qe(e?.apiKeyEnv)??process.env.BRASS_GOOGLE_API_KEY??process.env.GOOGLE_API_KEY??process.env.GEMINI_API_KEY;if(n)return chunk6OUI6UGZ_cjs.ra({apiKey:n,model:process.env.BRASS_GOOGLE_MODEL??process.env.BRASS_LLM_MODEL??e?.model??"gemini-2.5-flash",apiVersion:process.env.BRASS_GOOGLE_API_VERSION??e?.apiVersion??"v1beta",baseUrl:process.env.BRASS_GOOGLE_BASE_URL??e?.baseUrl,endpoint:process.env.BRASS_GOOGLE_ENDPOINT??e?.endpoint,systemInstruction:process.env.BRASS_GOOGLE_SYSTEM_INSTRUCTION??e?.systemInstruction,temperature:K(process.env.BRASS_GOOGLE_TEMPERATURE)??e?.temperature,topP:K(process.env.BRASS_GOOGLE_TOP_P)??e?.topP,topK:K(process.env.BRASS_GOOGLE_TOP_K)??e?.topK,maxOutputTokens:K(process.env.BRASS_GOOGLE_MAX_OUTPUT_TOKENS)??e?.maxOutputTokens})},Te=e=>{let n=process.env.BRASS_LLM_ENDPOINT??e?.endpoint,t=qe(e?.apiKeyEnv)??process.env.BRASS_LLM_API_KEY,o=process.env.BRASS_LLM_MODEL??e?.model??"gpt-4.1";if(!(!n||!t))return chunk6OUI6UGZ_cjs.qa({endpoint:n,apiKey:t,model:o})},zn=e=>{let n=(process.env.BRASS_LLM_PROVIDER??e?.provider)?.trim().toLowerCase(),t=process.env.BRASS_FAKE_LLM_RESPONSE??e?.fakeResponse;if(n==="fake")return chunk6OUI6UGZ_cjs.sa({content:t});if(n==="google"||n==="gemini"){let o=Ne(e);if(!o)throw new Error("Google LLM provider requires BRASS_GOOGLE_API_KEY, GOOGLE_API_KEY, GEMINI_API_KEY, or config.llm.apiKeyEnv.");return o}if(n==="openai"||n==="openai-compatible"){let o=Te(e);if(!o)throw new Error("OpenAI-compatible LLM provider requires BRASS_LLM_ENDPOINT/config.llm.endpoint and BRASS_LLM_API_KEY/config.llm.apiKeyEnv.");return o}if(n)throw new Error(`Unsupported LLM provider: ${n}`);return Ne(e)??Te(e)??chunk6OUI6UGZ_cjs.sa({content:t})},Qn=()=>{let e=process.env.BRASS_AGENT_APPROVAL?.trim().toLowerCase();if(e){if(Je(e))return e;throw new Error("BRASS_AGENT_APPROVAL must be one of: auto, interactive, approve, deny")}},Xn=e=>e==="1"||e?.toLowerCase()==="true"||e?.toLowerCase()==="yes",Zn=()=>!!(process.stdin?.isTTY&&(process.stderr?.isTTY??process.stdout?.isTTY)),et=e=>{if(e.approvalSpecified&&e.approval!=="auto")return e.approval;if(Xn(process.env.BRASS_AGENT_AUTO_APPROVE))return "approve";let n=Qn();return n&&n!=="auto"?n:e.approval!=="auto"?e.approval:e.output==="human"&&Zn()?"interactive":"deny"},nt=e=>{switch(et(e)){case "approve":return chunk6OUI6UGZ_cjs.ka;case "deny":return chunk6OUI6UGZ_cjs.la("Approval rejected because the CLI is running without interactive input. Use --yes to auto-approve.");case "interactive":return Pe()}},Ke=(e,n=2e3)=>e.length<=n?e:`${e.slice(0,n)}
14
- \u2026 truncated ${e.length-n} chars`,I=(e,n=1e3)=>e.length<=n?e:`${e.slice(0,n)}\u2026 truncated ${e.length-n} chars`,B=(e,n)=>n.fullPatches?e:I(e),He=(e,n)=>({...e,...e.initialPatch?{initialPatch:B(e.initialPatch,n)}:{}}),j=(e,n={})=>{switch(e.type){case "llm.complete":return {...e,prompt:I(e.prompt)};case "patch.apply":case "patch.rollback":case "patch.propose":return {...e,patch:B(e.patch,n)};default:return e}},ne=(e,n={})=>{switch(e.type){case "fs.fileRead":return {...e,content:I(e.content)};case "llm.response":return {...e,content:I(e.content)};case "shell.result":return {...e,stdout:I(e.stdout),stderr:I(e.stderr)};case "fs.searchResult":return {...e,matches:e.matches.slice(0,30),omittedMatches:Math.max(0,e.matches.length-30)};case "patch.proposed":return {...e,patch:B(e.patch,n)};case "patch.applied":case "patch.rolledBack":return e.patch?{...e,patch:B(e.patch,n)}:e;default:return e}},ze=(e,n={})=>{switch(e.type){case "agent.run.started":case "agent.run.completed":return {...e,goal:He(e.goal,n)};case "agent.action.started":return {...e,action:j(e.action,n)};case "agent.action.completed":return {...e,action:j(e.action,n),observation:ne(e.observation,n)};case "agent.action.failed":return {...e,action:j(e.action,n)};case "agent.observation.recorded":return {...e,observation:ne(e.observation,n)};case "agent.tool.timeout":case "agent.permission.denied":case "agent.approval.requested":case "agent.approval.resolved":return {...e,action:j(e.action,n)};default:return e}},te=(e,n={})=>({...e,goal:He(e.goal,n),observations:e.observations.map(t=>ne(t,n)),errors:e.errors.map(t=>{switch(t._tag){case "PermissionDenied":case "ApprovalRejected":return {...t,action:j(t.action,n)};case "PatchError":return {...t,cause:String(t.cause),...t.patch?{patch:B(t.patch,n)}:{}};case "FsError":case "ShellError":case "LLMError":return {...t,cause:String(t.cause)};default:return t}})}),oe=e=>({protocol:"brass-agent",version:1,...e}),tt=e=>{switch(e){case "ok":return "\u2713";case "warn":return "!";case "fail":return "\u2717"}},Ve=e=>`${Math.max(0,e)}ms`,w=(e,n)=>[...e.observations].reverse().find(t=>t.type===n),ot=e=>({emit(n){switch(n.type){case "agent.run.started":console.log(`brass-agent ${n.goal.mode}`),console.log(`workspace: ${n.goal.cwd}`),e&&console.log(`config: ${e}`),console.log(`goal: ${n.goal.text}`),console.log("");break;case "agent.action.started":console.log(`\u2192 ${chunk6OUI6UGZ_cjs.T(n.action)}`);break;case "agent.action.completed":{let t=chunk6OUI6UGZ_cjs.V(n.observation);console.log(`${tt(t)} ${chunk6OUI6UGZ_cjs.U(n.observation)} ${Ve(n.durationMs)}`);break}case "agent.action.failed":n.error._tag!=="ToolTimeout"&&n.error._tag!=="PermissionDenied"&&n.error._tag!=="ApprovalRejected"&&console.log(`\u2717 ${chunk6OUI6UGZ_cjs.T(n.action)} failed with ${n.error._tag} ${Ve(n.durationMs)}`);break;case "agent.tool.timeout":console.log(`! ${chunk6OUI6UGZ_cjs.T(n.action)} timed out after ${n.timeoutMs}ms`);break;case "agent.permission.denied":console.log(`\u2717 ${chunk6OUI6UGZ_cjs.T(n.action)} denied: ${n.reason}`);break;case "agent.approval.requested":console.log(`? approval required for ${chunk6OUI6UGZ_cjs.T(n.action)} (${n.risk})`);break;case "agent.approval.resolved":n.approved?console.log(`\u2713 approval granted for ${chunk6OUI6UGZ_cjs.T(n.action)}`):console.log(`\u2717 approval rejected for ${chunk6OUI6UGZ_cjs.T(n.action)}${n.reason?`: ${n.reason}`:""}`);break;case "agent.patch.applied":break;case "agent.patch.rolledBack":n.automatic&&console.log(`\u2713 automatic rollback completed (${n.changedFiles.join(", ")||"no files reported"})`);break;}}}),rt=(e={})=>({emit(n){console.log(JSON.stringify(ze(n,e)));}}),st=(e={})=>({emit(n){console.log(JSON.stringify(oe({type:"event",event:ze(n,e)})));}}),We=e=>e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"run",ee=e=>e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),at=async(e,n,t)=>{let o=await F("node:path"),r=await F("node:fs/promises"),a=o.isAbsolute(n)?n:o.resolve(e.goal.cwd,n);await r.mkdir(a,{recursive:true});let s=`${We(e.goal.id)}-${We(e.goal.text)}`,c=o.join(a,`${s}.json`),h=o.join(a,`${s}.md`),E=w(e,"agent.done"),p=w(e,"agent.error"),g=w(e,"patch.applied"),m=w(e,"patch.rolledBack");await r.writeFile(c,`${JSON.stringify(te(e,t),null,2)}
15
- `,"utf8"),await r.writeFile(h,[`# Brass Agent Run ${ee(e.goal.id)}`,"",`- Goal: ${ee(e.goal.text)}`,`- Workspace: ${ee(e.goal.cwd)}`,`- Mode: ${e.goal.mode}`,`- Phase: ${e.phase}`,`- Steps: ${e.steps}`,g?`- Changed files: ${g.changedFiles.join(", ")||"none reported"}`:void 0,m?`- Rolled back files: ${m.changedFiles.join(", ")||"none reported"}`:void 0,"","## Summary","",E?.summary?.trim()||(p?`Error: ${p.error._tag}`:"No summary recorded.")].filter(Boolean).join(`
16
- `),"utf8"),process.stderr?.isTTY&&console.error(`saved run artifacts: ${c} ${h}`);},it=e=>w(e,"shell.result"),lt=(e,n)=>{if(w(e,"agent.error"))return 1;let t=it(e);return t&&t.exitCode!==0?1:n.failOnPatchProposed&&w(e,"patch.proposed")&&!w(e,"patch.applied")?2:0},ct=e=>{let n=w(e,"agent.done"),t=w(e,"agent.error"),o=w(e,"patch.proposed"),r=w(e,"patch.applied"),a=w(e,"patch.rolledBack"),l=w(e,"llm.response");console.log(""),console.log(`phase: ${e.phase}`),console.log(`steps: ${e.steps}`),a?console.log(`rolled back files: ${a.changedFiles.join(", ")||"(none reported)"}`):r?console.log(`changed files: ${r.changedFiles.join(", ")||"(none reported)"}`):o&&console.log("patch: proposed only; rerun with --apply to apply it"),n?(console.log(""),console.log("summary:"),console.log(Ke(n.summary.trim()||"Agent completed."))):t?(console.log(""),console.log("error:"),console.log(JSON.stringify(t.error,null,2))):l&&(console.log(""),console.log("llm response:"),console.log(Ke(l.content.trim())));},pt=(e,n)=>e.output==="human"?ot(e.resolvedConfigPath):e.output==="events-json"?rt(n):e.output==="protocol-json"?st(n):void 0,dt=(e,n)=>{let t=chunk6OUI6UGZ_cjs.ma;return {shell:t,fs:chunk6OUI6UGZ_cjs.na(t),patch:chunk6OUI6UGZ_cjs.oa(t),llm:zn(e.config.llm),permissions:chunk6OUI6UGZ_cjs.ia(e.config.permissions),approvals:nt(e),...n?{events:n}:{},...e.config.tools?{toolPolicies:e.config.tools}:{}}},ut=e=>({index:0,cwd:e.cwd,goalText:e.goalText,mode:e.mode,patchFileMode:e.patchFileMode,...e.patchFile?{patchFile:e.patchFile}:{},...e.saveRunDir?{saveRunDir:e.saveRunDir}:{}}),gt=async(e,n,t,o)=>{let r=dt(e,o),a=new chunkK47BP5A2_cjs.$({env:r}),l=n.patchFile?await Nn(n.cwd,n.patchFile):void 0,s=await a.toPromise(chunk6OUI6UGZ_cjs.ba(a,{id:`agent-${Date.now()}-${n.index+1}`,cwd:n.cwd,text:n.goalText,mode:n.mode,...e.config.project?{project:e.config.project}:{},...e.config.context?{context:e.config.context}:{},...e.config.patchQuality?{patchQuality:e.config.patchQuality}:{},...e.config.rollback?{rollback:e.config.rollback}:{},...e.config.redaction?{redaction:e.config.redaction}:{},...e.language?{language:{response:e.language}}:e.config.language?{language:e.config.language}:{},...l?{initialPatch:l,initialPatchMode:n.patchFileMode}:{}}));return n.saveRunDir&&await at(s,n.saveRunDir,t),{run:n,state:s,exitCode:lt(s,{failOnPatchProposed:e.failOnPatchProposed})}},ft=e=>e.some(n=>n.exitCode===1)?1:e.some(n=>n.exitCode===2)?2:0,Qe=(e,n)=>({total:e.length,completed:n.length,failed:n.filter(t=>t.exitCode!==0).length,exitCode:ft(n),stoppedEarly:n.length<e.length}),mt=(e,n)=>{let t=Qe(e,n);console.log(""),console.log("batch summary:"),console.log(`completed: ${t.completed}/${t.total}`),console.log(`failed: ${t.failed}`),t.stoppedEarly&&console.log("stopped early: yes"),console.log(`exit code: ${t.exitCode}`);},yt=e=>{let n={cwd:e.cwd,inputCwd:e.workspaceDiscovery.inputCwd,changed:e.workspaceDiscovery.changed,disabled:!!e.workspaceDiscovery.disabled,marker:e.workspaceDiscovery.marker,markerPath:e.workspaceDiscovery.markerPath,configPath:e.resolvedConfigPath,envFiles:e.envFileLoad.paths};if(e.output==="json"||e.output==="protocol-json"){console.log(JSON.stringify(n,null,2));return}console.log("brass-agent workspace"),console.log(`input: ${n.inputCwd}`),console.log(`workspace: ${n.cwd}`),n.disabled?console.log("discovery: disabled"):n.marker?console.log(`marker: ${n.marker} (${n.markerPath})`):console.log("marker: none found; using input cwd"),n.configPath&&console.log(`config: ${n.configPath}`),n.envFiles.length>0&&console.log(`env: ${n.envFiles.join(", ")}`);},ht=async()=>{let e=await Hn(Kn(process.argv.slice(2))),n=e.batchRuns.length>0;if(e.showHelp&&(Ge(),process.exit(0)),e.where){yt(e);return}if(e.init){let s=await je({cwd:e.cwd,force:e.initForce,dryRun:e.initDryRun,profile:e.initProfile});e.output==="json"?console.log(JSON.stringify(s,null,2)):Be(s);return}if(e.doctor){let s=await _e({cwd:e.cwd,config:e.config,configPath:e.resolvedConfigPath,envFileLoad:e.envFileLoad,workspaceDiscovery:e.workspaceDiscovery});e.output==="json"?console.log(JSON.stringify(s,null,2)):xe(s),process.exitCode=s.status==="fail"?1:0;return}!e.goalText&&!n&&(Ge(),process.exit(1));let t={fullPatches:e.protocolFullPatches},o=pt(e,t),r=n?e.batchRuns:[ut(e)],a=[];for(let s of r){let c=await gt(e,s,t,o);if(a.push(c),e.output==="protocol-json"?console.log(JSON.stringify(oe({type:"final-state",state:te(c.state,t)}))):e.output==="human"&&ct(c.state),n&&e.batchStopOnFailureResolved&&c.exitCode!==0)break}if(n){let s=Qe(r,a);e.output==="json"?console.log(JSON.stringify({type:"batch",summary:s,results:a.map(c=>({index:c.run.index,goal:c.run.goalText,cwd:c.run.cwd,mode:c.run.mode,exitCode:c.exitCode,state:te(c.state,t)}))},null,2)):e.output==="protocol-json"?console.log(JSON.stringify(oe({type:"batch-summary",summary:s}))):e.output==="human"&&mt(r,a),e.ci&&(process.exitCode=s.exitCode);return}let l=a[0];if(!l)throw new Error("Agent run did not produce a result.");e.output==="json"&&console.log(JSON.stringify(l.state,null,2)),e.ci&&(process.exitCode=l.exitCode);};ht().catch(e=>{console.error(e),process.exit(1);});
@@ -1 +0,0 @@
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,25 +0,0 @@
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
- `,"\r","(","'",'"',"`","<","["]),Zt=new Set([" "," ",`
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
- `)).join(`
5
- `),Ge=e=>[e.goal.text,rn(e)].filter(Boolean).join(`
6
- `),qe=e=>{let t=H(e),n=Ge(e),r=new RegExp(`(?:file://)?(?:[A-Za-z]:)?[./\\\\]?(?:[A-Za-z0-9_@.-]+[/\\\\])*[A-Za-z0-9_@.-]+\\.(?:${le.join("|")})(?::\\d+){0,2}`,"g"),o=n.match(r)??[];return _(o.map(a=>Ne(e.goal.cwd,a)).filter(a=>!!a).filter(a=>!Ie(a,t.excludeGlobs)))},Be=e=>_(e.observations.filter(t=>t.type==="fs.searchResult").map(t=>t.query)),pe=e=>_(e.observations.filter(t=>t.type==="fs.fileRead").map(t=>t.path)),de=e=>e.observations.filter(t=>t.type==="fs.exists"),on=(e,t)=>pe(e).includes(t),an=(e,t)=>de(e).some(n=>n.path===t&&!n.exists),sn=(e,t)=>de(e).some(n=>n.path===t&&n.exists),cn=(e,t)=>de(e).some(n=>n.path===t),ln=(e,t)=>e.observations.filter(n=>n.type==="fs.searchResult").flatMap(n=>n.matches).slice(0,t),Ve=(e,t)=>{let n=H(e);return _(ln(e,t).map(r=>Ne(e.goal.cwd,r.path)).filter(r=>!!r).filter(r=>!Ie(r,n.excludeGlobs)))},Oe=e=>{let t=e.length;return /^[A-Z][A-Za-z0-9_]+$/.test(e)&&(t+=8),/[A-Z][a-z]+[A-Z]/.test(e)&&(t+=6),/^[a-z]+[A-Z]/.test(e)&&(t+=6),/Error$/.test(e)&&(t+=4),/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)&&(t+=2),t},pn=e=>{let t=[],n=/["'`]([^"'`\n]{4,80})["'`]/g,r;for(;r=n.exec(e);){let o=r[1]?.trim();o&&(/\s{3,}/.test(o)||/^[A-Za-z0-9_./:-]+$/.test(o)&&t.push(o));}return t},ze=e=>{let t=Ge(e),n=pn(t),r=t.match(/[A-Za-z_][A-Za-z0-9_]{3,}/g)??[];return [..._([...n,...r]).map(a=>a.trim()).filter(a=>a.length>=4&&a.length<=80).filter(a=>!a.includes("/")).filter(a=>!Wt.has(a.toLowerCase())).filter(a=>!/^\d+$/.test(a)).filter(a=>/^[A-Za-z0-9_]+$/.test(a))].sort((a,l)=>Oe(l)-Oe(a)).slice(0,8)},Ue=e=>pe(e).filter(t=>t!=="package.json").length,ue=e=>{let t=dn(e);if(!t.enabled)return "Context discovery: disabled.";let n=t.searchedQueries.join(", ")||"none",r=t.pendingQueries.slice(0,5).join(", ")||"none",o=t.discoveredPaths.slice(0,8).join(", ")||"none",a=t.readPaths.filter(l=>l!=="package.json").join(", ")||"none";return [`Context discovery: searched queries: ${n}.`,`Pending queries: ${r}.`,`Discovered paths: ${o}.`,`Read context files: ${a}.`,`Remaining file budget: ${t.remainingFileBudget}.`].join(" ")},dn=e=>{let t=H(e),n=Be(e),r=ze(e),o=qe(e),a=Ve(e,t.maxSearchResults),l=pe(e),s=Math.max(0,t.maxFiles-Ue(e));return {enabled:t.enabled,searchedQueries:n,pendingQueries:r.filter(p=>!n.includes(p)),discoveredPaths:_([...o,...a]),readPaths:l,remainingFileBudget:s}},We=e=>{let t=H(e);if(!t.enabled||e.goal.initialPatch?.trim())return;let n=Be(e),r=Math.max(0,t.maxFiles-Ue(e)),o=qe(e),a=Ve(e,t.maxSearchResults);if(r>0){let s=[...o,...a].find(p=>p!=="package.json"&&!on(e,p)&&!an(e,p));if(s){if(!cn(e,s))return {type:"fs.exists",path:s};if(sn(e,s))return {type:"fs.readFile",path:s}}}if(n.length>=t.maxSearchQueries)return;let l=ze(e).find(s=>!n.includes(s));if(l)return {type:"fs.searchText",query:l,globs:nn(t)}};var Qe=["Cargo.toml","Cargo.lock","src-tauri/tauri.conf.json","src-tauri/Cargo.toml","apps/desktop/package.json","apps/desktop/src-tauri/tauri.conf.json","apps/desktop/src-tauri/Cargo.toml","bridges/whatsmeow-bridge/Cargo.toml","bridges/whatsmeow-bridge/package.json","apps","packages","bridges","turbo.json","nx.json","pnpm-workspace.yaml"],me=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),un=e=>[...e.observations].reverse().find(t=>t.type==="fs.fileRead"&&t.path==="package.json"),gn=e=>{let t=un(e);if(t)try{let n=JSON.parse(t.content);return me(n)?n:void 0}catch{return}},mn=e=>{if(!e||!me(e.scripts))return {};let t={};for(let[n,r]of Object.entries(e.scripts))typeof r=="string"&&(t[n]=r);return t},u=(e,t)=>e.observations.some(n=>n.type==="fs.exists"&&n.path===t&&n.exists),fn=(e,t)=>[e?.dependencies,e?.devDependencies,e?.optionalDependencies].some(r=>me(r)&&typeof r[t]=="string"),yn=(e,t)=>t.some(n=>fn(e,n)),ge=e=>[...new Set(e)],hn=(e,t)=>{let n=[];for(let r of Object.keys(e))t.some(o=>o.test(r))&&n.push(r);return n},Ke=e=>Qe.find(t=>!e.observations.some(n=>n.type==="fs.exists"&&n.path===t)),fe=(e,t)=>{let n=gn(e),r=mn(n),o=Object.keys(r),a=Qe.filter(A=>u(e,A)),l=[],s=[];n&&l.push("node");let p=u(e,"Cargo.toml")||u(e,"Cargo.lock")||u(e,"src-tauri/Cargo.toml")||u(e,"apps/desktop/src-tauri/Cargo.toml")||u(e,"bridges/whatsmeow-bridge/Cargo.toml");p&&l.push("rust");let d=u(e,"src-tauri/tauri.conf.json")||u(e,"apps/desktop/src-tauri/tauri.conf.json")||yn(n,["@tauri-apps/api","@tauri-apps/cli"])||o.some(A=>A.includes("tauri"));d&&l.push("tauri"),(u(e,"apps/desktop/package.json")||o.some(A=>A.includes("desktop")))&&l.push("desktop");let f=u(e,"bridges")||u(e,"bridges/whatsmeow-bridge/Cargo.toml")||u(e,"bridges/whatsmeow-bridge/package.json")||o.some(A=>A.includes("bridge"));f&&l.push("bridge");let k=u(e,"pnpm-workspace.yaml")||u(e,"turbo.json")||u(e,"nx.json")||u(e,"apps")||u(e,"packages")||u(e,"bridges")||Array.isArray(n?.workspaces);k&&l.push("monorepo");let j=ge([...hn(r,[/^repo:check$/,/^check$/,/(^|:)check($|:)/,/(^|:)doctor($|:)/,/(^|:)health($|:)/,/(^|:)verify($|:)/,/(^|:)validate($|:)/,/(^|:)ci($|:)/])]),m=j.map(A=>t==="npm"&&A==="test"?"npm test":t==="pnpm"&&A==="test"?"pnpm test":t==="yarn"&&A==="test"?"yarn test":t==="bun"?`bun run ${A}`:`${t} run ${A}`);p&&u(e,"Cargo.toml")&&m.push("cargo check"),j.length>0&&s.push(`Likely health/check scripts: ${j.slice(0,5).join(", ")}.`),d&&s.push("Tauri markers detected; desktop validation may involve npm scripts plus Cargo checks."),f&&s.push("Bridge markers detected; bridge-specific doctor/check scripts may be relevant."),k&&s.push("Workspace/monorepo markers detected; prefer repo-level check scripts when available.");let se=d&&p&&n?"tauri":n&&p?"mixed":p?"rust":n?"node":"unknown",Vt=k&&n&&p?"mixed":k?"monorepo":n?"single-package":"unknown";return {kind:se,packageManager:t,stacks:ge(l),workspaceStyle:Vt,markers:a,scripts:o,candidateValidationScripts:j,candidateValidationCommands:ge(m),notes:s}},ye=e=>{let t=e.stacks.length>0?e.stacks.join(", "):"none detected",n=e.markers.length>0?e.markers.slice(0,8).join(", "):"none",r=e.candidateValidationCommands.length>0?e.candidateValidationCommands.slice(0,6).join("; "):"none",o=e.notes.length>0?` Notes: ${e.notes.join(" ")}`:"";return `Project profile: ${e.kind}; workspace: ${e.workspaceStyle}; stacks: ${t}; markers: ${n}; likely validation: ${r}.${o}`};var An=["pnpm-lock.yaml","yarn.lock","bun.lockb","bun.lock","package-lock.json","npm-shrinkwrap.json"],bn=["test","test:ci","test:unit"],kn=["typecheck","type-check","check-types","tsc","check"],xn=["lint","lint:ci"],Sn=[/^repo:check$/,/^check$/,/(^|:)check($|:)/,/(^|:)doctor($|:)/,/(^|:)health($|:)/,/(^|:)verify($|:)/,/(^|:)validate($|:)/,/(^|:)ci($|:)/],Je=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vn=e=>[...e.observations].reverse().find(t=>t.type==="fs.fileRead"&&t.path==="package.json"),Xe=e=>{let t=vn(e);if(t)try{let n=JSON.parse(t.content);return Je(n)?n:void 0}catch{return}},En=e=>{if(!e||!Je(e.scripts))return {};let t={};for(let[n,r]of Object.entries(e.scripts))typeof r=="string"&&(t[n]=r);return t},wn=(e,t)=>e.observations.some(n=>n.type==="fs.exists"&&n.path===t),Ye=e=>{let t=e.goal.project;if(!t?.validationCommands&&(!t?.packageManager||t.packageManager==="auto")){for(let r of An)if(!wn(e,r))return {type:"fs.exists",path:r}}let n=Ke(e);return n?{type:"fs.exists",path:n}:void 0},Pn=e=>{let t=typeof e?.packageManager=="string"?e.packageManager:void 0;if(!t)return;let n=t.split("@")[0]?.trim();if(n==="npm"||n==="pnpm"||n==="yarn"||n==="bun")return n},T=(e,t)=>e.observations.some(n=>n.type==="fs.exists"&&n.path===t&&n.exists),Rn=e=>{if(T(e,"pnpm-lock.yaml"))return "pnpm";if(T(e,"yarn.lock"))return "yarn";if(T(e,"bun.lockb")||T(e,"bun.lock"))return "bun";if(T(e,"package-lock.json")||T(e,"npm-shrinkwrap.json"))return "npm"},Ze=e=>{let t=e.goal.project?.packageManager;return t&&t!=="auto"?t:Pn(Xe(e))??Rn(e)??"npm"},Cn=e=>/no test specified/i.test(e)&&/exit\s+1/.test(e),he=(e,t,n={})=>{for(let r of t){let o=e[r];if(o!==void 0&&!(n.skipPlaceholderTest&&r==="test"&&Cn(o)))return r}},jn=(e,t)=>{for(let n of Object.keys(e))if(t.some(r=>r.test(n)))return n},He=(e,t)=>{let n=e.toLowerCase();return t.some(r=>n.includes(r))},$n=e=>{let t=[],n="",r,o=false;for(let a of e.trim()){if(o){n+=a,o=false;continue}if(a==="\\"){o=true;continue}if(r){a===r?r=void 0:n+=a;continue}if(a==="'"||a==='"'){r=a;continue}if(/\s/.test(a)){n&&(t.push(n),n="");continue}n+=a;}return n&&t.push(n),t},et=e=>e.join(" "),Fn=e=>{let t=new Set,n=[];for(let r of e){let o=et(r);t.has(o)||(t.add(o),n.push(r));}return n},J=(e,t)=>{switch(e){case "npm":return t==="test"?["npm","test"]:["npm","run",t];case "pnpm":return t==="test"?["pnpm","test"]:["pnpm","run",t];case "yarn":return t==="test"?["yarn","test"]:["yarn","run",t];case "bun":return ["bun","run",t]}},Mn=e=>{if(e?.validationCommands)return e.validationCommands.map(t=>$n(t)).filter(t=>t.length>0)},P=e=>{let t=e.goal.project,n=Mn(t);if(n){let m=Ze(e),se=fe(e,m);return {packageManager:m,validationCommands:n,source:"config",notes:n.length>0?["Using validation commands from project config."]:["Project config explicitly disables validation commands."],profileSummary:ye(se)}}let r=Xe(e),o=En(r),a=Ze(e),l=fe(e,a),s=[],p=[],d=he(o,t?.testScriptNames??bn,{skipPlaceholderTest:true});if(d)s.push(J(a,d)),p.push(`Selected test script: ${d}.`);else {p.push("No usable test script found in package.json.");let m=jn(o,Sn);m&&(s.push(J(a,m)),p.push(`Selected project health script: ${m}.`));}if(t?.includeTypecheck===true||He(e.goal.text,["typecheck","type-check","type check","types","tsc"])||s.length===0){let m=he(o,kn);m&&(s.push(J(a,m)),p.push(`Selected typecheck script: ${m}.`));}if(t?.includeLint===true||He(e.goal.text,["lint","eslint"])||s.length===0){let m=he(o,xn);m&&(s.push(J(a,m)),p.push(`Selected lint script: ${m}.`));}s.length===0&&l.stacks.includes("rust")&&l.markers.includes("Cargo.toml")&&(s.push(["cargo","check"]),p.push("Selected Cargo check because a root Cargo.toml was detected."));let k=t?.maxValidationCommands??2,j=Fn(s).slice(0,Math.max(0,k));return {packageManager:a,validationCommands:j,source:j.length>0?"package-json":"fallback",notes:p,profileSummary:ye(l)}},Ln=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),_n=(e,t)=>e.type==="shell.result"&&Ln(e.command,t),X=(e,t)=>e.find(n=>!t.some(r=>_n(r,n))),Ae=e=>{let t=e.validationCommands.map(et).join("; ")||"none",n=e.notes.length>0?` Notes: ${e.notes.join(" ")}`:"",r=e.profileSummary?` ${e.profileSummary}`:"";return `Package manager: ${e.packageManager}. Validation commands: ${t}.${n}${r}`};var Tn=(e,t)=>e===void 0||!Number.isFinite(e)?t:Math.max(0,Math.floor(e)),On=e=>e.observations.filter(t=>t.type==="llm.response"&&t.purpose==="patch").length,Y=e=>{let t=e.goal.patchQuality?.enabled??true,n=Tn(e.goal.patchQuality?.maxRepairAttempts,1),r=On(e);return {enabled:t,maxRepairAttempts:n,repairAttemptsUsed:r,repairsRemaining:Math.max(0,n-r),exactSuppliedPatch:!!e.goal.initialPatch?.trim()}},ee=e=>{let t=Y(e);return t.enabled&&!t.exactSuppliedPatch&&t.repairsRemaining>0},Dn=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),Nn=(e,t)=>e.flatMap(n=>t.filter(r=>r.type==="shell.result"&&Dn(r.command,n)).slice(-1)),tt=(e,t)=>{if(e.length===0)return {type:"not-run"};let n=Nn(e,t);return n.length<e.length?{type:"pending",completed:n.length,total:e.length}:n.some(r=>r.exitCode!==0)?{type:"failed",results:n}:{type:"passed",results:n}},be=e=>{let t=Y(e);return t.enabled?t.exactSuppliedPatch?"Patch quality loop: disabled for supplied exact patches.":[`Patch quality loop: ${t.repairAttemptsUsed}/${t.maxRepairAttempts} repair attempts used.`,`Repairs remaining: ${t.repairsRemaining}.`].join(" "):"Patch quality loop: disabled."};var In=(e,t)=>e===void 0||!Number.isFinite(e)?t:Math.max(0,Math.floor(e)),Gn=e=>e==="last"?"last":"all",O=e=>{let t=e.goal.rollback,n=t?.enabled??true,r=In(t?.maxRollbackDepth,8),o=e.observations.filter(l=>l.type==="patch.rolledBack").length,a=nt(e).length;return {enabled:n,onFinalValidationFailure:t?.onFinalValidationFailure??true,strategy:Gn(t?.strategy),maxRollbackDepth:r,runValidationAfterRollback:t?.runValidationAfterRollback??true,allowForSuppliedPatches:t?.allowForSuppliedPatches??false,rollbackCount:o,appliedStackDepth:a,exactSuppliedPatch:!!e.goal.initialPatch?.trim()}},nt=e=>{let t=[];for(let[n,r]of e.observations.entries()){if(r.type==="patch.applied"&&r.patch?.trim()){t.push({index:n,patch:r.patch,changedFiles:r.changedFiles});continue}if(r.type==="patch.rolledBack"&&r.patch?.trim()){let o=[...t].reverse().findIndex(a=>a.patch.trim()===r.patch?.trim());o>=0&&t.splice(t.length-1-o,1);}}return t},rt=e=>nt(e).at(-1),ke=e=>{let t=O(e);return !t.enabled||t.rollbackCount>=t.maxRollbackDepth||t.exactSuppliedPatch&&!t.allowForSuppliedPatches?false:t.appliedStackDepth>0},ot=e=>{let t=O(e);return e.observations.at(-1)?.type==="patch.rolledBack"&&t.strategy==="all"&&ke(e)},qn=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),Bn=(e,t)=>e.flatMap(n=>t.filter(r=>r.type==="shell.result"&&qn(r.command,n)).slice(-1)),at=(e,t)=>{if(e.length===0)return {type:"not-run"};let n=Bn(e,t);return n.length<e.length?{type:"pending",completed:n.length,total:e.length}:n.some(r=>r.exitCode!==0)?{type:"failed",results:n}:{type:"passed",results:n}},xe=e=>{let t=O(e);return t.enabled?t.exactSuppliedPatch&&!t.allowForSuppliedPatches?"Rollback safety: disabled for supplied exact patches.":[`Rollback safety: ${t.onFinalValidationFailure?"enabled":"not configured for final validation failure"}.`,`Strategy: ${t.strategy}.`,`Rollbacks used: ${t.rollbackCount}/${t.maxRollbackDepth}.`,`Applied patch stack depth: ${t.appliedStackDepth}.`].join(" "):"Rollback safety: disabled."};var Vn=/```(?:diff|patch)?\s*\n([\s\S]*?)```/g,zn=e=>e.replace(/^[ab]\//,""),B=e=>e.replace(/\r\n/g,`
7
- `).trim(),st=e=>{let t=B(e);return t.includes("+++ ")&&t.includes("--- ")},Un=e=>{let t=B(e),n=t.indexOf("diff --git "),r=t.indexOf("--- "),o=[n,r].filter(l=>l>=0).sort((l,s)=>l-s)[0];if(o===void 0)return;let a=t.slice(o).trim();return st(a)?a:void 0},M=e=>{let t=B(e);if(!t)return;let n=t.matchAll(Vn);for(let r of n){let o=B(r[1]??"");if(st(o))return o}return Un(t)},Wn=e=>{let t=e.trim().split(/\s+/)[0];if(!(!t||t==="/dev/null"))return zn(t)},it=e=>{let t=B(e);if(!t)return [];let n=new Set,r=[];for(let o of t.split(`
8
- `))if(o.startsWith("+++ ")||o.startsWith("--- ")){let a=Wn(o.slice(4));if(!a||n.has(a))continue;n.add(a),r.push(a);}return r};var Qn=[/\b(?:sk|pk|rk|ghp|gho|ghu|ghs|github_pat)_[A-Za-z0-9_\-]{16,}\b/g,/\bAIza[0-9A-Za-z_\-]{20,}\b/g,/\b(?:xoxb|xoxp|xoxa|xoxr)-[A-Za-z0-9\-]{20,}\b/g,/\b[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/g,/((?:api[_-]?key|token|secret|password|passwd|authorization)\s*[:=]\s*)(["']?)[^\s"']{8,}\2/gi,/(Bearer\s+)[A-Za-z0-9._\-+/=]{12,}/gi],Kn=e=>{try{return new RegExp(e,"gi")}catch{return}},Zn=e=>(e?.additionalPatterns??[]).map(Kn).filter(t=>!!t),Hn=e=>e?.enabled??true,ct=(e,t)=>!Hn(t)||!e?e:[...Qn,...Zn(t)].reduce((n,r)=>n.replace(r,(o,a)=>typeof a=="string"&&a.length>0&&o.startsWith(a)?`${a}[REDACTED]`:"[REDACTED]"),e);var Jn={en:"English",es:"Spanish",pt:"Portuguese",fr:"French",de:"German",it:"Italian"},Xn=/[¿¡ñáéíóúü]|\b(aca|acá|ahora|arregl|ayuda|como|cómo|consulta|cual|cuál|cuando|cuándo|dale|decime|deberia|debería|donde|dónde|errores|explica|explicame|hacer|hagamos|mejorar|porque|porqué|por que|por qué|proyecto|quiero|seria|sería|tengo|usar|vayamos)\b/i,Yn=/[ãõç]|\b(como|corrigir|erro|falha|quero|projeto|porque|você|voce)\b/i,er=/[àâçéèêëîïôûùüÿœ]|\b(comment|pourquoi|corriger|erreur|projet|fichier)\b/i,tr=/[äöüß]|\b(warum|fehler|projekt|datei|bitte)\b/i,nr=/\b(come|perché|perche|errore|progetto|file|voglio)\b/i,lt=e=>{if(Xn.test(e))return "Spanish";if(Yn.test(e))return "Portuguese";if(er.test(e))return "French";if(tr.test(e))return "German";if(nr.test(e))return "Italian"},pt=e=>{let t=e?.response??"auto";if(t==="custom")return e?.custom?.trim()||void 0;if(!(t==="auto"||t==="match-user"))return Jn[t]},rr=e=>pt(e.language)??lt(e.text),Se=e=>{let t=pt(e.language),n=lt(e.text);return t?[`Language policy: respond in ${t}.`,"Keep code, identifiers, file paths, shell commands, logs, and unified diffs unchanged."].join(" "):n?[`Language policy: the user goal appears to be in ${n}; respond in ${n}.`,"Keep code, identifiers, file paths, shell commands, logs, and unified diffs unchanged."].join(" "):["Language policy: respond in the same natural language as the user's latest goal or follow-up.","If the user's goal is in Spanish, respond in Spanish.","Keep code, identifiers, file paths, shell commands, logs, and unified diffs unchanged."].join(" ")},te=e=>rr(e)==="Spanish";var ne=(e,t)=>e.observations.some(n=>n.type===t),D=(e,t)=>[...e.observations].reverse().find(n=>n.type===t),or=(e,t)=>e.observations.find(n=>n.type===t),ve=(e,t)=>[...e.observations].map(n=>n.type).lastIndexOf(t),ar=e=>{let t=e.observations.findIndex(n=>n.type==="llm.response"&&n.purpose==="plan");return t<0?e.observations:e.observations.slice(0,t)},Ee=e=>{let t=ve(e,"patch.applied");return t<0?[]:e.observations.slice(t+1)},ft=e=>Math.max(ve(e,"patch.applied"),ve(e,"patch.rolledBack")),we=e=>{let t=ft(e);return t<0?[]:e.observations.slice(t+1)},V=e=>{let t=ft(e),n=t<0?void 0:e.observations[t];return n?.type==="patch.applied"||n?.type==="patch.rolledBack"?n:void 0},sr=e=>{switch(e.type){case "fs.fileRead":{let t=e.path.toLowerCase(),r=t.endsWith("package-lock.json")||t.endsWith("npm-shrinkwrap.json")||t.endsWith("pnpm-lock.yaml")||t.endsWith("yarn.lock")||t.endsWith("cargo.lock")?1500:8e3;return {type:e.type,path:e.path,content:e.content.slice(0,r),omittedChars:Math.max(0,e.content.length-r)}}case "fs.exists":return {type:e.type,path:e.path,exists:e.exists};case "shell.result":return {type:e.type,command:e.command,exitCode:e.exitCode,stdout:e.stdout.slice(-8e3),stderr:e.stderr.slice(-8e3)};case "fs.searchResult":return {type:e.type,query:e.query,matches:e.matches.slice(0,20),omittedMatches:Math.max(0,e.matches.length-20)};case "patch.proposed":return {type:e.type,patch:e.patch.slice(0,8e3)};case "patch.applied":return {type:e.type,changedFiles:e.changedFiles};case "patch.rolledBack":return {type:e.type,changedFiles:e.changedFiles,...e.automatic!==void 0?{automatic:e.automatic}:{},...e.reason?{reason:e.reason}:{}};case "agent.done":case "agent.error":return e;case "llm.response":return {type:e.type,purpose:e.purpose,content:e.content.slice(-8e3)}}},z=(e,t)=>ct(t,e.goal.redaction),ir=e=>e.type==="fs.exists"&&!e.exists,yt=e=>z(e,e.observations.filter(t=>!ir(t)).map(t=>JSON.stringify(sr(t),null,2)).join(`
9
-
10
- `)),cr=e=>{if(e instanceof Error)return e.message||String(e);if(typeof e=="string")return e;if(e&&typeof e=="object")try{let t=JSON.stringify(e);if(t&&t!=="{}")return t}catch{}return String(e)},R=(e,t)=>z(e,cr(t)).slice(0,2e3),lr=e=>{let t=P(e);return z(e,["You are a coding agent running on brass-runtime.","Return a concise diagnosis and proposed plan.","If you can infer a patch, include it as a unified diff inside a ```diff fenced block.","Do not claim that you edited files unless the runtime reports patch.applied.","Prefer a single focused patch over speculative broad changes.","Only propose a patch when the observations are strong enough.","Use the project command discovery summary as context, but do not invent commands that were not run.",Se(e.goal),"",`Goal: ${e.goal.text}`,`Workspace: ${e.goal.cwd}`,`Project commands: ${Ae(t)}`,ue(e),be(e),xe(e),"","Observations:",yt(e)||"No observations yet."].join(`
11
- `))},dt=e=>Ee(e).filter(t=>t.type==="shell.result"&&t.exitCode!==0).map(t=>[`Command: ${t.command.join(" ")}`,`Exit code: ${t.exitCode}`,t.stdout?`stdout:
12
- ${t.stdout.slice(-8e3)}`:void 0,t.stderr?`stderr:
13
- ${t.stderr.slice(-8e3)}`:void 0].filter(Boolean).join(`
14
- `)),pr=(e,t)=>{let n=P(e),r=Y(e),o=D(e,"agent.error")?.error,a=hr(e);return z(e,["You are repairing a generated patch for a coding agent running on brass-runtime.","The previous generated patch either failed to apply or failed validation.","Return a concise diagnosis and, if you can fix it, include a replacement incremental unified diff inside a ```diff fenced block.","The new diff should apply on top of the current workspace state, after any previous patch.applied observations.","Do not repeat the old patch unless it is still correct for the current workspace state.","Do not claim files were edited unless the runtime later reports patch.applied.",Se(e.goal),"",`Goal: ${e.goal.text}`,`Workspace: ${e.goal.cwd}`,`Repair reason: ${t}`,`Repair attempts used: ${r.repairAttemptsUsed}/${r.maxRepairAttempts}`,`Project commands: ${Ae(n)}`,ue(e),be(e),xe(e),"",a?`Latest materialized patch:
15
- ${a.slice(-8e3)}`:"Latest materialized patch: none.","",dt(e).length>0?`Failed validation after latest patch:
16
- ${dt(e).join(`
17
-
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
- `))},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
- `)},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)?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;
@@ -1 +0,0 @@
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};
@@ -1,2 +0,0 @@
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;