broods 0.54.1 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{L,U,F,y,b,z,k,B,H,S,f,O,m,C,x,Z,g,T,N,G,E,ne,v,h}from"../chunk-aqcx0cwa.js";import{p,_}from"../chunk-xv88e799.js";import{chmod as Vs,lstat as Ys,mkdir as Fn,readFile as co,readdir as zs,stat as Js,writeFile as Se}from"node:fs/promises";import{createHash as lo}from"node:crypto";import qs from"node:module";import{basename as Xs,join as Be,relative as Zs,resolve as M,sep as Qs}from"node:path";import{watch as ei}from"node:fs";import{spawn as uo}from"node:child_process";import{tmpdir as ni}from"node:os";import{performance as oo}from"node:perf_hooks";import{stripVTControlCharacters as Un}from"node:util";import{fileURLToPath as Do,pathToFileURL as ht}from"node:url";import{createHash as No}from"node:crypto";import{existsSync as Uo,readFileSync as Lo}from"node:fs";import{mkdtemp as Mo,readdir as bt,readFile as Bo,rm as Go,writeFile as Wo}from"node:fs/promises";import st from"node:module";import{tmpdir as Fo}from"node:os";import{basename as Ko,extname as Ho,isAbsolute as Vo,join as He,relative as Re,resolve as Ve}from"node:path";import{build as Yo,transformSync as wt}from"esbuild";var qn=/\$\{([A-Z][A-Z0-9_]*)\}/;var Xn=["alibaba","anthropic","azure","baseten","bedrock","cerebras","chatgpt","cloudflare","cohere","custom","deepinfra","deepseek","fireworks","google","groq","huggingface","llmgateway","minimax","mistral","moonshotai","ollama","openai","openrouter","perplexity","togetherai","v0","vercel","vertex","xai","zai"],xo={alibaba:{label:"Alibaba Qwen",modelPlaceholder:"qwen3-max"},anthropic:{label:"Anthropic",modelPlaceholder:"claude-sonnet-4-5-20250929"},azure:{label:"Azure OpenAI",modelPlaceholder:"gpt-4.1-mini"},baseten:{label:"Baseten",modelPlaceholder:"deepseek-ai/DeepSeek-V3"},bedrock:{label:"Amazon Bedrock",modelPlaceholder:"anthropic.claude-sonnet-4-5-20250929-v1:0"},cerebras:{label:"Cerebras",modelPlaceholder:"llama3.1-8b"},chatgpt:{label:"ChatGPT plan",modelPlaceholder:"gpt-5.5"},cloudflare:{label:"Cloudflare",modelPlaceholder:"@cf/meta/llama-3.3-70b-instruct-fp8-fast"},cohere:{label:"Cohere",modelPlaceholder:"command-a-03-2025"},custom:{label:"Custom OpenAI-compatible",modelPlaceholder:"gpt-oss-120b"},deepinfra:{label:"DeepInfra",modelPlaceholder:"deepseek-ai/DeepSeek-V3"},deepseek:{label:"DeepSeek",modelPlaceholder:"deepseek-chat"},fireworks:{label:"Fireworks",modelPlaceholder:"accounts/fireworks/models/deepseek-v3"},google:{label:"Google",modelPlaceholder:"gemini-2.5-flash"},groq:{label:"Groq",modelPlaceholder:"llama-3.3-70b-versatile"},huggingface:{label:"Hugging Face",modelPlaceholder:"meta-llama/Llama-3.3-70B-Instruct"},llmgateway:{label:"LLM Gateway",modelPlaceholder:"openai/gpt-4.1-mini"},minimax:{label:"MiniMax",modelPlaceholder:"MiniMax-M2.7"},mistral:{label:"Mistral",modelPlaceholder:"mistral-large-latest"},moonshotai:{label:"Moonshot AI Kimi",modelPlaceholder:"kimi-k2.6"},ollama:{label:"Ollama",modelPlaceholder:"gpt-oss:120b"},openai:{label:"OpenAI",modelPlaceholder:"gpt-4.1-mini"},openrouter:{label:"OpenRouter",modelPlaceholder:"anthropic/claude-sonnet-4.5"},perplexity:{label:"Perplexity",modelPlaceholder:"low"},togetherai:{label:"Together.ai",modelPlaceholder:"deepseek-ai/DeepSeek-V3"},v0:{label:"Vercel v0",modelPlaceholder:"v0-1.0-md"},vercel:{label:"Vercel AI Gateway",modelPlaceholder:"openai/gpt-4.1-mini"},vertex:{label:"Google Vertex AI",modelPlaceholder:"gemini-2.5-flash"},xai:{label:"xAI Grok",modelPlaceholder:"grok-4"},zai:{label:"Z.ai GLM",modelPlaceholder:"glm-4.7"}};function Zn(e){return Object.hasOwn(xo,e)}var Po=/(?:^|[\n;])\s*import\s+(?:[^;"'`]*?\s+from\s*)?["'](?!\.{1,2}\/|\/|node:)[^"']+["']|import\s*\(\s*["'](?!\.{1,2}\/|\/|node:)[^"']+["']\s*\)/,To=/(?:import\s+(?:[^;"'`]*?\s+from\s*)?["']node:|import\s*\(\s*["']node:)/,_o=/(?<![.\w$])(?:process|Buffer)\s*(?:\?\.|\.|\[)/,Io=[/\b(?:__)?require\s*\(/,/(?<![.\w$])setImmediate\s*\(/,To,_o,/\b__dirname\b/,Po],jo=/(?<![.\w$])eval\s*\(|\bnew\s+Function\s*\(/;function Qn(e){return![...Io,jo].some((n)=>n.test(e))}var et=new Set(["lambda","sandbox","vercel"]),nt=new Set(["daytona"]);var tt=`${[...et].join("/")}, or ${[...nt].join(" or ")} with options.mountAwsS3Buckets: true`;function ot(e,n){if(et.has(e))return!0;return nt.has(e)&&n?.mountAwsS3Buckets===!0}var un=32;var gn=["conversation","agent"];function rt(e){return gn.some((n)=>n===e)}var Pe="*",zo=new RegExp(qn.source,"g"),Jo=`const passthrough = (input) => input;
2
+ import{L,U,B,y,b,z,k,F,H,S,f,O,m,C,x,Z,g,T,N,K,E,ne,v,h}from"../chunk-2vxrctp1.js";import{p,_}from"../chunk-xv88e799.js";import{chmod as zs,lstat as Js,mkdir as Fn,readFile as uo,readdir as qs,stat as Xs,writeFile as Ee}from"node:fs/promises";import{createHash as go}from"node:crypto";import Zs from"node:module";import{basename as Qs,join as Fe,relative as ei,resolve as M,sep as ni}from"node:path";import{watch as ti}from"node:fs";import{spawn as po}from"node:child_process";import{tmpdir as oi}from"node:os";import{performance as oo}from"node:perf_hooks";import{stripVTControlCharacters as Un}from"node:util";import{fileURLToPath as Uo,pathToFileURL as ht}from"node:url";import{createHash as Lo}from"node:crypto";import{existsSync as Mo,readFileSync as Bo}from"node:fs";import{mkdtemp as Go,readdir as bt,readFile as Wo,rm as Fo,writeFile as Ho}from"node:fs/promises";import st from"node:module";import{tmpdir as Ko}from"node:os";import{basename as Vo,extname as Yo,isAbsolute as zo,join as ze,relative as Oe,resolve as Je}from"node:path";import{build as Jo,transformSync as wt}from"esbuild";var qn=/\$\{([A-Z][A-Z0-9_]*)\}/;var Xn=["alibaba","anthropic","azure","baseten","bedrock","cerebras","chatgpt","cloudflare","cohere","custom","deepinfra","deepseek","fireworks","google","groq","huggingface","llmgateway","minimax","mistral","moonshotai","ollama","openai","openrouter","perplexity","togetherai","v0","vercel","vertex","xai","zai"],To={alibaba:{label:"Alibaba Qwen",modelPlaceholder:"qwen3-max"},anthropic:{label:"Anthropic",modelPlaceholder:"claude-sonnet-4-5-20250929"},azure:{label:"Azure OpenAI",modelPlaceholder:"gpt-4.1-mini"},baseten:{label:"Baseten",modelPlaceholder:"deepseek-ai/DeepSeek-V3"},bedrock:{label:"Amazon Bedrock",modelPlaceholder:"anthropic.claude-sonnet-4-5-20250929-v1:0"},cerebras:{label:"Cerebras",modelPlaceholder:"llama3.1-8b"},chatgpt:{label:"ChatGPT plan",modelPlaceholder:"gpt-5.5"},cloudflare:{label:"Cloudflare",modelPlaceholder:"@cf/meta/llama-3.3-70b-instruct-fp8-fast"},cohere:{label:"Cohere",modelPlaceholder:"command-a-03-2025"},custom:{label:"Custom OpenAI-compatible",modelPlaceholder:"gpt-oss-120b"},deepinfra:{label:"DeepInfra",modelPlaceholder:"deepseek-ai/DeepSeek-V3"},deepseek:{label:"DeepSeek",modelPlaceholder:"deepseek-chat"},fireworks:{label:"Fireworks",modelPlaceholder:"accounts/fireworks/models/deepseek-v3"},google:{label:"Google",modelPlaceholder:"gemini-2.5-flash"},groq:{label:"Groq",modelPlaceholder:"llama-3.3-70b-versatile"},huggingface:{label:"Hugging Face",modelPlaceholder:"meta-llama/Llama-3.3-70B-Instruct"},llmgateway:{label:"LLM Gateway",modelPlaceholder:"openai/gpt-4.1-mini"},minimax:{label:"MiniMax",modelPlaceholder:"MiniMax-M2.7"},mistral:{label:"Mistral",modelPlaceholder:"mistral-large-latest"},moonshotai:{label:"Moonshot AI Kimi",modelPlaceholder:"kimi-k2.6"},ollama:{label:"Ollama",modelPlaceholder:"gpt-oss:120b"},openai:{label:"OpenAI",modelPlaceholder:"gpt-4.1-mini"},openrouter:{label:"OpenRouter",modelPlaceholder:"anthropic/claude-sonnet-4.5"},perplexity:{label:"Perplexity",modelPlaceholder:"low"},togetherai:{label:"Together.ai",modelPlaceholder:"deepseek-ai/DeepSeek-V3"},v0:{label:"Vercel v0",modelPlaceholder:"v0-1.0-md"},vercel:{label:"Vercel AI Gateway",modelPlaceholder:"openai/gpt-4.1-mini"},vertex:{label:"Google Vertex AI",modelPlaceholder:"gemini-2.5-flash"},xai:{label:"xAI Grok",modelPlaceholder:"grok-4"},zai:{label:"Z.ai GLM",modelPlaceholder:"glm-4.7"}};function Zn(e){return Object.hasOwn(To,e)}var Io=/(?:^|[\n;])\s*import\s+(?:[^;"'`]*?\s+from\s*)?["'](?!\.{1,2}\/|\/|node:)[^"']+["']|import\s*\(\s*["'](?!\.{1,2}\/|\/|node:)[^"']+["']\s*\)/,_o=/(?:import\s+(?:[^;"'`]*?\s+from\s*)?["']node:|import\s*\(\s*["']node:)/,jo=/(?<![.\w$])(?:process|Buffer)\s*(?:\?\.|\.|\[)/,Do=[/\b(?:__)?require\s*\(/,/(?<![.\w$])setImmediate\s*\(/,_o,jo,/\b__dirname\b/,Io],No=/(?<![.\w$])eval\s*\(|\bnew\s+Function\s*\(/;function Qn(e){return![...Do,No].some((n)=>n.test(e))}var et=new Set(["lambda","sandbox","vercel"]),nt=new Set(["daytona"]);var tt=`${[...et].join("/")}, or ${[...nt].join(" or ")} with options.mountAwsS3Buckets: true`;function ot(e,n){if(et.has(e))return!0;return nt.has(e)&&n?.mountAwsS3Buckets===!0}var gn=32;var pn=["conversation","agent"];function rt(e){return pn.some((n)=>n===e)}var Te="*",qo=new RegExp(qn.source,"g"),Xo=`const passthrough = (input) => input;
3
3
  export const defineAgent = passthrough;
4
4
  export const defineBroods = passthrough;
5
5
  export const defineCron = passthrough;
@@ -14,8 +14,6 @@ export const defineInstagramChannel = passthrough;
14
14
  export const defineInstagramConnection = passthrough;
15
15
  export const defineLinearChannel = passthrough;
16
16
  export const defineLinearConnection = passthrough;
17
- export const defineMatrixChannel = passthrough;
18
- export const defineMatrixConnection = passthrough;
19
17
  export const defineMcp = passthrough;
20
18
  export const defineMessengerChannel = passthrough;
21
19
  export const defineMessengerConnection = passthrough;
@@ -39,15 +37,15 @@ export const defineZaloChannel = passthrough;
39
37
  export const defineZaloConnection = passthrough;
40
38
  export const env = (name) => ({ __beeblastEnv: true, name });
41
39
  export default {};
42
- `,Ye=1e7,it=50000000,hn=1e7,at=20000000,ct=200,qo=new Set(["node_modules",".git"]),Xo=[/^\.env(?:\.|$)/i,/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/i,/\.(?:pem|key|p12|pfx)$/i],pn={onStart:"agent.started",onStepFinish:"agent.step.finished",onToolCall:"tool.call.started",onToolResult:"tool.result",onFinish:"agent.finished",onApproval:"agent.approval.required",onError:"agent.failed",onSubagentFinish:"subagent.task.finished",onMessageReceived:"channel.message.received",onMessageSending:"channel.message.sending"};async function pe(e={}){let n=e.cwd??process.cwd();m(n);let t=Ve(n,y);if(!Uo(t))throw Error(`No ${y}/ folder in ${n}. Run \`broods dev\` to scaffold one.`);let o=await Qo(t),r=await er(o),s=await tr(r,n,e.project),i=r.filter((I)=>h(I.value)).map((I)=>({exportName:I.exportName,file:I.file,resource:I.value})),a=i.map((I)=>I.resource);gt(a),gr(a);let c=fr(i,r),l=hr(a);for(let I of a)rr(I);for(let I of a)sr(I);for(let I of a)ir(I);ar(a),lr(a),mr(i,l);let d=pr(i),w=Zo(s,e.stage??(e.useRuntimeStage===!1?void 0:S()),e.command??"dev"),u=(await Promise.all(i.map((I)=>br(I,t,l)))).flat().sort((I,K)=>`${I.kind}:${I.name}`.localeCompare(`${K.kind}:${K.name}`)),P=new Map(u.filter((I)=>I.kind==="mcp").map((I)=>[I.name,I.config])),j=u.map((I)=>Ur(I,P));return gt(j),{config:s,resources:a,resourceAliases:d,channels:c,manifest:{version:1,project:s.project,stage:w,resources:j}}}function yt(e){let n=new Set;for(let t of e.resources){Te(t.config,n,t.kind==="workspace");let o=t.config;if(t.kind==="agent")Te(o.mcp,n,!0);if(t.kind==="mcp")Te(o.headers,n,!0)}return[...n].sort()}function Te(e,n,t){if(t&&typeof e==="string"){for(let o of e.matchAll(zo))n.add(o[1]);return}if(Array.isArray(e)){for(let o of e)Te(o,n,t);return}if(e&&typeof e==="object"){let o=e;if(o.__beeblastEnv===!0&&typeof o.name==="string"){n.add(o.name);return}for(let r of Object.values(o))Te(r,n,t)}}function Zo(e,n,t){if(n)return n;let o=e.stages?.[t];if(o)return o;return t==="deploy"?"production":"development"}async function Qo(e){let n=[];async function t(o){let r=await bt(o,{withFileTypes:!0});for(let s of r){let i=He(o,s.name);if(s.isDirectory()){if(s.name===b||s.name==="generated")continue;await t(i)}else if(s.isFile()&&s.name.endsWith(".ts"))n.push(i)}}return await t(e),n.sort((o,r)=>Re(e,o).localeCompare(Re(e,r)))}async function er(e){nr();let n=[];for(let t of e){let r=await import(`${ht(t).href}?t=${Date.now()}`);n.push(...Object.entries(r).map(([s,i])=>({exportName:s,file:t,value:i})))}return n}var lt=!1;function nr(){if(lt)return;if(lt=!0,typeof st.registerHooks!=="function")return;st.registerHooks({resolve:(e,n,t)=>{try{return t(e,n)}catch(o){if(!/^\.{1,2}\//.test(e))throw o;let r=Ho(e)===".js"?[`${e.slice(0,-3)}.ts`]:[`${e}.ts`,`${e}/index.ts`];for(let s of r)try{return t(s,n)}catch{}throw o}},load:(e,n,t)=>{let[o]=e.split("?");if(o===void 0||!o.startsWith("file:")||!o.endsWith(".ts"))return t(e,n);let r=Do(o);return{format:"module",shortCircuit:!0,source:wt(Lo(r,"utf8"),{loader:"ts",format:"esm",sourcefile:r,sourcemap:"inline"}).code}}})}async function tr(e,n,t){let r=e.find((i)=>ne(i.value))?.value?.config??{},s=t??process.env.BROODS_PROJECT??r.project??Hr(Ko(Ve(n)));if(!s.trim())throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT.");return{...r,project:s}}var dt=new Set(["agent","harness","model","provider","session","hooks","connections","tools","mcp","denyTools","sandboxes","workspaces","subagent","skills","scheduler","browser","policies","publicAccess","allowRunOverrides"]),or={workspace:"workspaces",skill:"skills",policy:"policies",tool:"tools",mcpServers:"mcp",channel:"connections",channels:"connections",hook:"hooks",subagents:"subagent",systemPrompt:"agent",system:"agent"};function rr(e){if(e.kind!=="agent")return;let n=e.config;for(let t of Object.keys(n)){if(dt.has(t))continue;if(t==="sandbox")throw Error(`Agent "${e.name}" config.sandbox was removed; use sandboxes, the first is the default`);let o=or[t],r=o?` Did you mean "${o}"?`:` Allowed keys: ${[...dt].sort().join(", ")}.`;throw Error(`Agent "${e.name}" has an unknown config key "${t}".${r}`)}}function sr(e){if(e.kind!=="workspace")return;let t=e.config.storage;if(t===void 0)return;if(!t||typeof t!=="object"||Array.isArray(t))throw Error(`Workspace "${e.name}" config.storage must be an object`);let o=t.provider;if(o===void 0||o==="s3")return;if(o==="vercel")throw Error(`Workspace "${e.name}" uses storage.provider "vercel", but Vercel Drive workspace storage is not supported yet. Use storage.provider "s3" or omit storage until Vercel Drive is wired.`);throw Error(`Workspace "${e.name}" config.storage.provider must be one of: s3`)}function ir(e){if(e.kind!=="workspace")return;let n=e.config;if(n.partitioned!==void 0&&!rt(n.partitioned))throw Error(`Workspace "${e.name}" config.partitioned must be one of: ${gn.join(", ")}`);if(n.isolation!==void 0)throw Error(`Workspace "${e.name}" config.isolation is no longer supported; use partitioned.`)}function ar(e){let n=new Map(e.filter((t)=>t.kind==="workspace").map((t)=>[t.name,t]));for(let t of e){if(t.kind!=="agent")continue;let o=t.config,r=o.connections;if(r!==void 0&&!Array.isArray(r))throw Error(`Agent "${t.name}" config.connections must be an array of connection definitions`);let s=Array.isArray(r)?r.filter(v):[],i=new Set;for(let d of s){let w=d.config,u=typeof w.id==="string"?w.id:void 0;if(u){if(i.has(u))throw Error(`Duplicate channel id: ${u}`);i.add(u)}if(d.partition)vt(d.partition,`Agent "${t.name}" connection "${d.type}"`);if(d.config&&typeof d.config==="object"&&(("workspaceIsolationScope"in d.config)||("workspaceScope"in d.config)))throw Error(`Agent "${t.name}" connection "${d.type}" uses workspaceScope, which is no longer supported; use partition.`)}let c=(Array.isArray(o.workspaces)?o.workspaces.map((d)=>cr(d,n)).filter((d)=>Boolean(d)):[]).filter((d)=>d.config.partitioned==="conversation"),l=s.filter((d)=>d.partition);if(l.length>0&&c.length===0){let d=l[0];throw Error(`Agent "${t.name}" connection "${d.type}" defines partition, but no attached workspace has partitioned: "conversation".`)}if(c.length>0){for(let d of s)if(!d.partition)throw Error(`Agent "${t.name}" attaches partitioned workspace "${c[0].name}", but connection "${d.type}" does not define partition.`)}}}function vt(e,n){if(!e)return;if(e.by==="shared"){if("alias"in e&&e.alias!==void 0)throw Error(`${n} partition.alias is only supported when partition.by is conversation`);return}if(e.by!=="conversation")throw Error(`${n} partition.by must be one of: shared, conversation`);if(typeof e.alias!=="string"||e.alias.length===0)throw Error(`${n} partition.alias is required when partition.by is conversation`);if(!/^[A-Za-z0-9._-]+$/.test(e.alias))throw Error(`${n} partition.alias must use only letters, numbers, dots, underscores, or hyphens`);if(e.alias==="."||e.alias==="..")throw Error(`${n} partition.alias must not be "." or ".."`)}function cr(e,n){if(h(e)&&e.kind==="workspace")return e;if(typeof e==="string")return n.get(e);if(e&&typeof e==="object"&&"workspace"in e){let t=e.workspace;if(h(t)&&t.kind==="workspace")return t;if(typeof t==="string")return n.get(t)}return}function lr(e){let n=new Map(e.filter((t)=>t.kind==="sandbox").map((t)=>[t.name,t]));for(let t of e){if(t.kind!=="agent")continue;let o=t.config,r=St(Array.isArray(o.sandboxes)?o.sandboxes[0]:void 0,n),s=o.workspaces;if(!Array.isArray(s))continue;for(let i of s){let a=ur(i),c=dr(i,r,n);if(!c||ot(ut(c),c.config.options))continue;throw Error(`Agent "${t.name}" workspace "${a}" uses sandbox "${c.name}" (${ut(c)}) which does not support S3 workspace mounts. Use ${tt}, or set this workspace ref to sandbox: null for read-only S3 access.`)}}}function St(e,n){if(h(e)&&e.kind==="sandbox")return e;if(typeof e==="string")return n.get(e);return}function dr(e,n,t){if(e&&typeof e==="object"&&"sandbox"in e){let o=e.sandbox;if(o===null)return;return St(o,t)}return n}function ur(e){if(h(e)&&e.kind==="workspace")return e.name;if(e&&typeof e==="object"&&"workspace"in e){let n=e.workspace;if(h(n))return n.name;if(typeof n==="string")return n}return"<unknown>"}function ut(e){return typeof e.config.provider==="string"?e.config.provider:"lambda"}function gr(e){let n=new Set(e.filter((t)=>t.kind==="sandbox").map((t)=>t.name));for(let t of e){if(t.kind!=="agent")continue;let o=t.config.sandboxes;if(o===void 0)continue;if(!Array.isArray(o))throw Error(`Agent "${t.name}" sandboxes must be an array of sandbox resources or names`);let r=o;for(let[s,i]of r.entries()){let a=typeof i==="string"&&i.trim().length>0,c=h(i)&&i.kind==="sandbox";if(!a&&!c)throw Error(`Agent "${t.name}" sandboxes[${s}] must be a sandbox resource or a non-empty name`);if(c&&!n.has(i.name))throw Error(`Agent "${t.name}" sandboxes references sandbox "${i.name}", but that sandbox is not exported from broods/`)}}}function gt(e){let n=new Set;for(let t of e){let o=`${t.kind}:${t.name}`;if(n.has(o))throw Error(`Duplicate resource: ${o}`);n.add(o)}}function pr(e){let n={},t=new Set;for(let{exportName:o,resource:r}of e){if(o==="default"||!fn(o))continue;let s=`${r.kind}:${o}`;if(t.has(s))throw Error(`Duplicate export alias for ${r.kind}: ${o}`);t.add(s),n[r.kind]??={},n[r.kind][r.name]=o}return n}function fr(e,n){let t=new Map;for(let i of n){if(!v(i.value)||i.exportName==="default"||!fn(i.exportName))continue;let a=t.get(i.value);if(a&&a!==i.exportName)throw Error(`Channel is exported more than once: ${a}, ${i.exportName}`);t.set(i.value,i.exportName)}let o=new Map,r=new Set,s=[];for(let{exportName:i,resource:a}of e){if(a.kind!=="agent")continue;let c=a.config.connections;if(c===void 0)continue;if(!Array.isArray(c))throw Error(`Agent "${a.name}" config.connections must be an array of connection definitions`);let l=new Set;for(let d of c){if(!v(d))throw Error(`Agent "${a.name}" config.connections must contain connection definitions`);let w=o.get(d);if(w&&w!==a.name)throw Error(`Channel ${d.type} is already attached to agent "${w}" and cannot also attach to "${a.name}"`);if(l.has(d.type))throw Error(`Agent "${a.name}" cannot configure more than one ${d.type} channel`);o.set(d,a.name),l.add(d.type);let u=i!=="default"&&fn(i)?i:a.name,P=t.get(d)??`${u}${kt(d.type)}Channel`;if(r.has(P))throw Error(`Duplicate channel export alias: ${P}`);r.add(P),s.push({alias:P,type:d.type,id:P,agentName:a.name})}}for(let[i,a]of t)if(!o.has(i))throw Error(`Channel "${a}" must be attached to exactly one agent`);return s.sort((i,a)=>i.alias.localeCompare(a.alias))}function mr(e,n){for(let{resource:t}of e){if(t.kind!=="agent")continue;let o=t.config.connections;if(!Array.isArray(o))continue;for(let r of o){if(!v(r))continue;if(Et(r,n).length>0)continue;throw Error(`Agent "${t.name}" connection "${r.type}" reaches no rooms: declare a ${r.type} channel for it, or set allowedChannelIds: ["*"] to answer everywhere`)}}}function Et(e,n){let t=e.config.allowedChannelIds??[];if(t.includes(Pe))return[Pe];return[...new Set([...n.get(e)??[],...t])]}function hr(e){let n=new Map;for(let t of e){if(t.kind!=="channelRecord")continue;let o=t.config;if(!v(o.connection))continue;let r=$t(t.name,o.externalId);if(r.length===0)continue;let s=n.get(o.connection)??new Set;for(let i of r)s.add(i);n.set(o.connection,s)}return n}function kt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function fn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}async function br(e,n,t){let o=e.resource;if(o.kind==="agent"){let r=Cr(o,n,t);return[...r.hookResource?[r.hookResource]:[],{kind:o.kind,name:o.name,...o.description?{description:o.description}:{},config:r.config}]}if(o.kind==="channelRecord"){let r=o.config,s=$t(o.name,r.externalId);return s.map((i)=>({kind:o.kind,name:s.length===1?o.name:`${o.name}-${i}`,...o.description?{description:o.description}:{},config:Br(o.name,{...r,externalId:i})}))}return[{kind:o.kind,name:o.name,...o.description?{description:o.description}:{},config:await wr(e,n)}]}function $t(e,n){if(n===void 0)return[];if(typeof n==="string")return pt(e,n),[n];if(!Array.isArray(n))throw Error(`Channel "${e}" externalId must be a string or an array`);if(n.length===0)throw Error(`Channel "${e}" externalId must not be an empty array`);let t=new Set;for(let o of n){if(typeof o!=="string"||o.length===0)throw Error(`Channel "${e}" externalId must be an array of non-empty strings`);if(t.has(o))throw Error(`Channel "${e}" externalId lists ${o} twice`);pt(e,o),t.add(o)}return n}function pt(e,n){if(n!==Pe)return;throw Error(`Channel "${e}" cannot use "${Pe}" as its id: a record matches one exact room. To answer everywhere, set allowedChannelIds: ["${Pe}"] on the connection; undeclared rooms already fall back to its agent.`)}async function wr(e,n){let t=e.resource;if(t.kind==="skill")return await Ir(t.config,n);if(t.kind==="workspace"){let o={...t.config},r=o.partitioned;if(delete o.partitioned,r!==void 0)o.isolation=r;return ce(o)}if(t.kind==="mcp")return await jr(e,t.config,n);if(t.kind==="policy"){let o={...t.config};return o.version=o.version??1,ce(o)}if(t.kind==="cron"){let o={...t.config},r=o.agent;if(o.agentId=h(r)?r.name:r,o.name=o.name??t.name,o.status===void 0)o.status="active";if(delete o.agent,typeof o.input==="string")o.events=[{role:"user",content:[{type:"text",text:o.input}]}],delete o.input;return ce(o)}return ce(t.config)}var yr=new Set(["apiKey","base_url","baseURL","gatewayId"]),vr=new Set(["activeTools","debug","inactiveTools","permissionMode","startupTimeoutMs","type","webSearch"]),Sr=new Set(["enabled","level","subsystems"]);function Er(e){if(yr.has(e))return"";let n=e.replace(/[^a-z0-9]/gi,"").toLowerCase();if(n==="baseurl")return'"base_url" or "baseURL"';if(n==="apikey")return'"apiKey"';if(n==="gatewayid")return'"gatewayId"';return""}function kr(e,n){if(n===void 0||n===null)return;if(typeof n!=="object"||Array.isArray(n))throw Error(`Agent "${e}" config.provider must be an object`);for(let[t,o]of Object.entries(n)){if(!Zn(t))throw Error(`Agent "${e}" config.provider.${t} is not a supported provider (expected one of: ${Xn.join(", ")})`);if(typeof o!=="object"||o===null||Array.isArray(o))throw Error(`Agent "${e}" config.provider.${t} must be an object`);let r=o;for(let s of Object.keys(r)){let i=Er(s);if(i)throw Error(`Agent "${e}" config.provider.${t} has unknown option "${s}". Did you mean ${i}?`)}if(t==="custom"&&r.base_url===void 0&&r.baseURL===void 0)throw Error(`Agent "${e}" config.provider.custom.base_url is required (use "base_url" or "baseURL")`)}}function $r(e,n){if(n===void 0||n===null)return;if(typeof n!=="object"||Array.isArray(n))throw Error(`Agent "${e}" config.harness must be an object`);let t=n;if("sandbox"in t)throw Error(`Agent "${e}" harness sandbox was removed; list it first in the agent's sandboxes`);for(let o of Object.keys(t))if(!vr.has(o))throw Error(`Agent "${e}" config.harness has unknown option "${o}"`);if(t.type!=="claude-code"&&t.type!=="codex"&&t.type!=="deepagents"&&t.type!=="opencode"&&t.type!=="pi")throw Error(`Agent "${e}" config.harness.type must be claude-code, codex, deepagents, opencode, or pi`);if(t.permissionMode!==void 0&&t.permissionMode!=="allow-reads"&&t.permissionMode!=="allow-edits"&&t.permissionMode!=="allow-all")throw Error(`Agent "${e}" config.harness.permissionMode must be allow-reads, allow-edits, or allow-all`);if(t.type==="codex"&&t.permissionMode!==void 0&&t.permissionMode!=="allow-all")throw Error(`Agent "${e}" config.harness.permissionMode must be allow-all for codex`);if(t.startupTimeoutMs!==void 0&&(typeof t.startupTimeoutMs!=="number"||!Number.isSafeInteger(t.startupTimeoutMs)||t.startupTimeoutMs<1||t.startupTimeoutMs>600000))throw Error(`Agent "${e}" config.harness.startupTimeoutMs must be an integer from 1 to 600000`);if(t.webSearch!==void 0&&typeof t.webSearch!=="boolean")throw Error(`Agent "${e}" config.harness.webSearch must be a boolean`);if(t.type!=="codex"&&t.webSearch!==void 0)throw Error(`Agent "${e}" config.harness.webSearch is only supported by codex`);if(t.type==="pi"&&t.startupTimeoutMs!==void 0)throw Error(`Agent "${e}" config.harness.startupTimeoutMs is not supported by pi`);if(mn(e,t.activeTools,"activeTools"),mn(e,t.inactiveTools,"inactiveTools"),t.activeTools!==void 0&&t.inactiveTools!==void 0)throw Error(`Agent "${e}" config.harness must use either activeTools or inactiveTools, not both`);Rr(e,t.debug)}function Rr(e,n){if(n===void 0)return;if(typeof n!=="object"||n===null||Array.isArray(n))throw Error(`Agent "${e}" config.harness.debug must be an object`);let t=n;for(let o of Object.keys(t))if(!Sr.has(o))throw Error(`Agent "${e}" config.harness.debug has unknown option "${o}"`);if(t.enabled!==void 0&&typeof t.enabled!=="boolean")throw Error(`Agent "${e}" config.harness.debug.enabled must be a boolean`);if(t.level!==void 0&&t.level!=="error"&&t.level!=="warn"&&t.level!=="info"&&t.level!=="debug"&&t.level!=="trace")throw Error(`Agent "${e}" config.harness.debug.level must be error, warn, info, debug, or trace`);mn(e,t.subsystems,"debug.subsystems")}function mn(e,n,t){if(n!==void 0&&(!Array.isArray(n)||!n.every((o)=>typeof o==="string"&&o.trim().length>0)))throw Error(`Agent "${e}" config.harness.${t} must be an array of non-empty strings`)}function Or(e){if(new Set(e.config.skills?.allowed?.map((t)=>h(t)?t.name:t)).size<=un)return;throw Error(`Agent "${e.name}" config.skills.allowed must list at most ${un} skills`)}function Cr(e,n,t){let o={...e.config};kr(e.name,o.provider),$r(e.name,o.harness);let r=Array.isArray(o.sandboxes)?o.sandboxes.map((i)=>h(i)?i.name:i):void 0;if(r)o.sandboxes=r;r?.forEach((i,a)=>{if(r.indexOf(i)===a)return;throw Error(`Agent "${e.name}" sandboxes[${a}] "${String(i)}" is listed more than once`)}),Or(e);let s=Ar(e.name,o.hooks);if(s)o.hooks=s.agentHooksConfig;else if(o.hooks!==void 0)o.hooks=Rt(o.hooks,e.name);if(o.connections!==void 0){if(!Array.isArray(o.connections))throw Error(`Agent "${e.name}" config.connections must be an array of connection definitions`);o.channels=Object.fromEntries(o.connections.map((i)=>{if(!v(i))throw Error(`Agent "${e.name}" config.connections must contain connection definitions`);let a=`${e.name}${kt(i.type)}Channel`,c=Et(i,t);return[i.type,{id:a,...i.config,...i.partition?{partition:i.partition}:{},allowedChannelIds:c}]})),delete o.connections}if(Array.isArray(o.workspaces)){let i=o.workspaces.map((a)=>Lr(a,e.name));for(let a of i){let c=r?.indexOf(a.sandbox)??-1;if(c>=1)throw Error(`Agent "${e.name}" sandboxes[${c}] "${String(a.sandbox)}" also backs workspace "${String(a.name)}"; only the first sandbox can back a workspace`)}o.workspaces=i}if(o.harness&&!r?.length)throw Error(`Agent "${e.name}" runs a harness, so it needs sandboxes; the first runs the harness`);if(o.policies!==void 0){let i=Tr(o.policies,e.name);if(i)o.policies=i;else delete o.policies}return{config:ce(o),...s?.hookResource?{hookResource:s.hookResource}:{}}}function Ar(e,n){if(n===void 0)return;if(!n||typeof n!=="object"||Array.isArray(n))throw Error(`Agent "${e}" config.hooks must be an object`);let t=n,o=Object.keys(pn).flatMap((l)=>{let d=t[l];if(d===void 0)return[];if(typeof d!=="function")throw Error(`Agent "${e}" config.hooks.${l} must be a function`);return[{name:l,event:pn[l],source:xr(d.toString())}]});if(o.length===0)return;let r=`${e}-hooks`,s=Pr(e,o),i=Buffer.byteLength(s);if(i>Ye)throw Error(`Agent "${e}" hook bundle is too large (${i} bytes, max ${Ye})`);let a=o.map((l)=>l.event),c=Rt(t,e);return c.code=[{hookId:r}],{agentHooksConfig:c,hookResource:{kind:"hook",name:r,description:`Inline hooks for agent ${e}`,config:{events:a,bundle:s,sha256:_e(s)}}}}function Rt(e,n){if(!e||typeof e!=="object"||Array.isArray(e))throw Error(`Agent "${n}" config.hooks must be an object`);let t=Object.entries(e);for(let[r]of t){if(r==="webhooks"||r in pn)continue;throw Error(`Agent "${n}" config.hooks.${r} is not supported. Use inline hook callbacks or hooks.webhooks.`)}return Object.fromEntries(t.filter(([r])=>r==="webhooks"))}function xr(e){let n=e.trim();if(/^(async\s+)?function\b/.test(n)||/^(async\s*)?\(/.test(n)||/^(async\s+)?[A-Za-z_$][\w$]*\s*=>/.test(n))return n;if(/^(async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(n))return n.replace(/^(async\s+)?/,"$1function ");return n}function Pr(e,n){let t=`export default {
40
+ `,qe=1e7,it=50000000,bn=1e7,at=20000000,ct=200,Zo=new Set(["node_modules",".git"]),Qo=[/^\.env(?:\.|$)/i,/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/i,/\.(?:pem|key|p12|pfx)$/i],fn={onStart:"agent.started",onStepFinish:"agent.step.finished",onToolCall:"tool.call.started",onToolResult:"tool.result",onFinish:"agent.finished",onApproval:"agent.approval.required",onError:"agent.failed",onSubagentFinish:"subagent.task.finished",onMessageReceived:"channel.message.received",onMessageSending:"channel.message.sending"};async function pe(e={}){let n=e.cwd??process.cwd();m(n);let t=Je(n,y);if(!Mo(t))throw Error(`No ${y}/ folder in ${n}. Run \`broods dev\` to scaffold one.`);let o=await nr(t),r=await tr(o),s=await rr(r,n,e.project),i=r.filter((I)=>h(I.value)).map((I)=>({exportName:I.exportName,file:I.file,resource:I.value})),a=i.map((I)=>I.resource);gt(a),fr(a);let c=hr(i,r),d=wr(a);for(let I of a)ir(I);for(let I of a)ar(I);for(let I of a)cr(I);lr(a),ur(a),br(i,d);let l=mr(i),w=er(s,e.stage??(e.useRuntimeStage===!1?void 0:S()),e.command??"dev"),u=(await Promise.all(i.map((I)=>yr(I,t,d)))).flat().sort((I,W)=>`${I.kind}:${I.name}`.localeCompare(`${W.kind}:${W.name}`)),P=new Map(u.filter((I)=>I.kind==="mcp").map((I)=>[I.name,I.config])),j=u.map((I)=>Mr(I,P));return gt(j),{config:s,resources:a,resourceAliases:l,channels:c,manifest:{version:1,project:s.project,stage:w,resources:j}}}function yt(e){let n=new Set;for(let t of e.resources){Ie(t.config,n,t.kind==="workspace");let o=t.config;if(t.kind==="agent")Ie(o.mcp,n,!0);if(t.kind==="mcp")Ie(o.headers,n,!0)}return[...n].sort()}function Ie(e,n,t){if(t&&typeof e==="string"){for(let o of e.matchAll(qo))n.add(o[1]);return}if(Array.isArray(e)){for(let o of e)Ie(o,n,t);return}if(e&&typeof e==="object"){let o=e;if(o.__beeblastEnv===!0&&typeof o.name==="string"){n.add(o.name);return}for(let r of Object.values(o))Ie(r,n,t)}}function er(e,n,t){if(n)return n;let o=e.stages?.[t];if(o)return o;return t==="deploy"?"production":"development"}async function nr(e){let n=[];async function t(o){let r=await bt(o,{withFileTypes:!0});for(let s of r){let i=ze(o,s.name);if(s.isDirectory()){if(s.name===b||s.name==="generated")continue;await t(i)}else if(s.isFile()&&s.name.endsWith(".ts"))n.push(i)}}return await t(e),n.sort((o,r)=>Oe(e,o).localeCompare(Oe(e,r)))}async function tr(e){or();let n=[];for(let t of e){let r=await import(`${ht(t).href}?t=${Date.now()}`);n.push(...Object.entries(r).map(([s,i])=>({exportName:s,file:t,value:i})))}return n}var lt=!1;function or(){if(lt)return;if(lt=!0,typeof st.registerHooks!=="function")return;st.registerHooks({resolve:(e,n,t)=>{try{return t(e,n)}catch(o){if(!/^\.{1,2}\//.test(e))throw o;let r=Yo(e)===".js"?[`${e.slice(0,-3)}.ts`]:[`${e}.ts`,`${e}/index.ts`];for(let s of r)try{return t(s,n)}catch{}throw o}},load:(e,n,t)=>{let[o]=e.split("?");if(o===void 0||!o.startsWith("file:")||!o.endsWith(".ts"))return t(e,n);let r=Uo(o);return{format:"module",shortCircuit:!0,source:wt(Bo(r,"utf8"),{loader:"ts",format:"esm",sourcefile:r,sourcemap:"inline"}).code}}})}async function rr(e,n,t){let r=e.find((i)=>ne(i.value))?.value?.config??{},s=t??process.env.BROODS_PROJECT??r.project??Yr(Vo(Je(n)));if(!s.trim())throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT.");return{...r,project:s}}var dt=new Set(["agent","harness","model","provider","session","hooks","connections","tools","mcp","denyTools","sandboxes","workspaces","subagent","skills","scheduler","browser","policies","publicAccess","allowRunOverrides"]),sr={workspace:"workspaces",skill:"skills",policy:"policies",tool:"tools",mcpServers:"mcp",channel:"connections",channels:"connections",hook:"hooks",subagents:"subagent",systemPrompt:"agent",system:"agent"};function ir(e){if(e.kind!=="agent")return;let n=e.config;for(let t of Object.keys(n)){if(dt.has(t))continue;if(t==="sandbox")throw Error(`Agent "${e.name}" config.sandbox was removed; use sandboxes, the first is the default`);let o=sr[t],r=o?` Did you mean "${o}"?`:` Allowed keys: ${[...dt].sort().join(", ")}.`;throw Error(`Agent "${e.name}" has an unknown config key "${t}".${r}`)}}function ar(e){if(e.kind!=="workspace")return;let t=e.config.storage;if(t===void 0)return;if(!t||typeof t!=="object"||Array.isArray(t))throw Error(`Workspace "${e.name}" config.storage must be an object`);let o=t.provider;if(o===void 0||o==="s3")return;if(o==="vercel")throw Error(`Workspace "${e.name}" uses storage.provider "vercel", but Vercel Drive workspace storage is not supported yet. Use storage.provider "s3" or omit storage until Vercel Drive is wired.`);throw Error(`Workspace "${e.name}" config.storage.provider must be one of: s3`)}function cr(e){if(e.kind!=="workspace")return;let n=e.config;if(n.partitioned!==void 0&&!rt(n.partitioned))throw Error(`Workspace "${e.name}" config.partitioned must be one of: ${pn.join(", ")}`);if(n.isolation!==void 0)throw Error(`Workspace "${e.name}" config.isolation is no longer supported; use partitioned.`)}function lr(e){let n=new Map(e.filter((t)=>t.kind==="workspace").map((t)=>[t.name,t]));for(let t of e){if(t.kind!=="agent")continue;let o=t.config,r=o.connections;if(r!==void 0&&!Array.isArray(r))throw Error(`Agent "${t.name}" config.connections must be an array of connection definitions`);let s=Array.isArray(r)?r.filter(v):[],i=new Set;for(let l of s){let w=l.config,u=typeof w.id==="string"?w.id:void 0;if(u){if(i.has(u))throw Error(`Duplicate channel id: ${u}`);i.add(u)}if(l.partition)vt(l.partition,`Agent "${t.name}" connection "${l.type}"`);if(l.config&&typeof l.config==="object"&&(("workspaceIsolationScope"in l.config)||("workspaceScope"in l.config)))throw Error(`Agent "${t.name}" connection "${l.type}" uses workspaceScope, which is no longer supported; use partition.`)}let c=(Array.isArray(o.workspaces)?o.workspaces.map((l)=>dr(l,n)).filter((l)=>Boolean(l)):[]).filter((l)=>l.config.partitioned==="conversation"),d=s.filter((l)=>l.partition);if(d.length>0&&c.length===0){let l=d[0];throw Error(`Agent "${t.name}" connection "${l.type}" defines partition, but no attached workspace has partitioned: "conversation".`)}if(c.length>0){for(let l of s)if(!l.partition)throw Error(`Agent "${t.name}" attaches partitioned workspace "${c[0].name}", but connection "${l.type}" does not define partition.`)}}}function vt(e,n){if(!e)return;if(e.by==="shared"){if("alias"in e&&e.alias!==void 0)throw Error(`${n} partition.alias is only supported when partition.by is conversation`);return}if(e.by!=="conversation")throw Error(`${n} partition.by must be one of: shared, conversation`);if(typeof e.alias!=="string"||e.alias.length===0)throw Error(`${n} partition.alias is required when partition.by is conversation`);if(!/^[A-Za-z0-9._-]+$/.test(e.alias))throw Error(`${n} partition.alias must use only letters, numbers, dots, underscores, or hyphens`);if(e.alias==="."||e.alias==="..")throw Error(`${n} partition.alias must not be "." or ".."`)}function dr(e,n){if(h(e)&&e.kind==="workspace")return e;if(typeof e==="string")return n.get(e);if(e&&typeof e==="object"&&"workspace"in e){let t=e.workspace;if(h(t)&&t.kind==="workspace")return t;if(typeof t==="string")return n.get(t)}return}function ur(e){let n=new Map(e.filter((t)=>t.kind==="sandbox").map((t)=>[t.name,t]));for(let t of e){if(t.kind!=="agent")continue;let o=t.config,r=St(Array.isArray(o.sandboxes)?o.sandboxes[0]:void 0,n),s=o.workspaces;if(!Array.isArray(s))continue;for(let i of s){let a=pr(i),c=gr(i,r,n);if(!c||ot(ut(c),c.config.options))continue;throw Error(`Agent "${t.name}" workspace "${a}" uses sandbox "${c.name}" (${ut(c)}) which does not support S3 workspace mounts. Use ${tt}, or set this workspace ref to sandbox: null for read-only S3 access.`)}}}function St(e,n){if(h(e)&&e.kind==="sandbox")return e;if(typeof e==="string")return n.get(e);return}function gr(e,n,t){if(e&&typeof e==="object"&&"sandbox"in e){let o=e.sandbox;if(o===null)return;return St(o,t)}return n}function pr(e){if(h(e)&&e.kind==="workspace")return e.name;if(e&&typeof e==="object"&&"workspace"in e){let n=e.workspace;if(h(n))return n.name;if(typeof n==="string")return n}return"<unknown>"}function ut(e){return typeof e.config.provider==="string"?e.config.provider:"lambda"}function fr(e){let n=new Set(e.filter((t)=>t.kind==="sandbox").map((t)=>t.name));for(let t of e){if(t.kind!=="agent")continue;let o=t.config.sandboxes;if(o===void 0)continue;if(!Array.isArray(o))throw Error(`Agent "${t.name}" sandboxes must be an array of sandbox resources or names`);let r=o;for(let[s,i]of r.entries()){let a=typeof i==="string"&&i.trim().length>0,c=h(i)&&i.kind==="sandbox";if(!a&&!c)throw Error(`Agent "${t.name}" sandboxes[${s}] must be a sandbox resource or a non-empty name`);if(c&&!n.has(i.name))throw Error(`Agent "${t.name}" sandboxes references sandbox "${i.name}", but that sandbox is not exported from broods/`)}}}function gt(e){let n=new Set;for(let t of e){let o=`${t.kind}:${t.name}`;if(n.has(o))throw Error(`Duplicate resource: ${o}`);n.add(o)}}function mr(e){let n={},t=new Set;for(let{exportName:o,resource:r}of e){if(o==="default"||!mn(o))continue;let s=`${r.kind}:${o}`;if(t.has(s))throw Error(`Duplicate export alias for ${r.kind}: ${o}`);t.add(s),n[r.kind]??={},n[r.kind][r.name]=o}return n}function hr(e,n){let t=new Map;for(let i of n){if(!v(i.value)||i.exportName==="default"||!mn(i.exportName))continue;let a=t.get(i.value);if(a&&a!==i.exportName)throw Error(`Channel is exported more than once: ${a}, ${i.exportName}`);t.set(i.value,i.exportName)}let o=new Map,r=new Set,s=[];for(let{exportName:i,resource:a}of e){if(a.kind!=="agent")continue;let c=a.config.connections;if(c===void 0)continue;if(!Array.isArray(c))throw Error(`Agent "${a.name}" config.connections must be an array of connection definitions`);let d=new Set;for(let l of c){if(!v(l))throw Error(`Agent "${a.name}" config.connections must contain connection definitions`);let w=o.get(l);if(w&&w!==a.name)throw Error(`Channel ${l.type} is already attached to agent "${w}" and cannot also attach to "${a.name}"`);if(d.has(l.type))throw Error(`Agent "${a.name}" cannot configure more than one ${l.type} channel`);o.set(l,a.name),d.add(l.type);let u=i!=="default"&&mn(i)?i:a.name,P=t.get(l)??`${u}${Et(l.type)}Channel`;if(r.has(P))throw Error(`Duplicate channel export alias: ${P}`);r.add(P),s.push({alias:P,type:l.type,id:P,agentName:a.name})}}for(let[i,a]of t)if(!o.has(i))throw Error(`Channel "${a}" must be attached to exactly one agent`);return s.sort((i,a)=>i.alias.localeCompare(a.alias))}function br(e,n){for(let{resource:t}of e){if(t.kind!=="agent")continue;let o=t.config.connections;if(!Array.isArray(o))continue;for(let r of o){if(!v(r))continue;if(kt(r,n).length>0)continue;throw Error(`Agent "${t.name}" connection "${r.type}" reaches no rooms: declare a ${r.type} channel for it, or set allowedChannelIds: ["*"] to answer everywhere`)}}}function kt(e,n){let t=e.config.allowedChannelIds??[];if(t.includes(Te))return[Te];return[...new Set([...n.get(e)??[],...t])]}function wr(e){let n=new Map;for(let t of e){if(t.kind!=="channelRecord")continue;let o=t.config;if(!v(o.connection))continue;let r=$t(t.name,o.externalId);if(r.length===0)continue;let s=n.get(o.connection)??new Set;for(let i of r)s.add(i);n.set(o.connection,s)}return n}function Et(e){return e.charAt(0).toUpperCase()+e.slice(1)}function mn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}async function yr(e,n,t){let o=e.resource;if(o.kind==="agent"){let r=xr(o,n,t);return[...r.hookResource?[r.hookResource]:[],{kind:o.kind,name:o.name,...o.description?{description:o.description}:{},config:r.config}]}if(o.kind==="channelRecord"){let r=o.config,s=$t(o.name,r.externalId);return s.map((i)=>({kind:o.kind,name:s.length===1?o.name:`${o.name}-${i}`,...o.description?{description:o.description}:{},config:Wr(o.name,{...r,externalId:i})}))}return[{kind:o.kind,name:o.name,...o.description?{description:o.description}:{},config:await vr(e,n)}]}function $t(e,n){if(n===void 0)return[];if(typeof n==="string")return pt(e,n),[n];if(!Array.isArray(n))throw Error(`Channel "${e}" externalId must be a string or an array`);if(n.length===0)throw Error(`Channel "${e}" externalId must not be an empty array`);let t=new Set;for(let o of n){if(typeof o!=="string"||o.length===0)throw Error(`Channel "${e}" externalId must be an array of non-empty strings`);if(t.has(o))throw Error(`Channel "${e}" externalId lists ${o} twice`);pt(e,o),t.add(o)}return n}function pt(e,n){if(n!==Te)return;throw Error(`Channel "${e}" cannot use "${Te}" as its id: a record matches one exact room. To answer everywhere, set allowedChannelIds: ["${Te}"] on the connection; undeclared rooms already fall back to its agent.`)}async function vr(e,n){let t=e.resource;if(t.kind==="skill")return await Dr(t.config,n);if(t.kind==="workspace"){let o={...t.config},r=o.partitioned;if(delete o.partitioned,r!==void 0)o.isolation=r;return le(o)}if(t.kind==="mcp")return await Nr(e,t.config,n);if(t.kind==="policy"){let o={...t.config};return o.version=o.version??1,le(o)}if(t.kind==="cron"){let o={...t.config},r=o.agent;if(o.agentId=h(r)?r.name:r,o.name=o.name??t.name,o.status===void 0)o.status="active";if(delete o.agent,typeof o.input==="string")o.events=[{role:"user",content:[{type:"text",text:o.input}]}],delete o.input;return le(o)}return le(t.config)}var Sr=new Set(["apiKey","base_url","baseURL","gatewayId"]),kr=new Set(["activeTools","debug","inactiveTools","permissionMode","startupTimeoutMs","type","webSearch"]),Er=new Set(["enabled","level","subsystems"]);function $r(e){if(Sr.has(e))return"";let n=e.replace(/[^a-z0-9]/gi,"").toLowerCase();if(n==="baseurl")return'"base_url" or "baseURL"';if(n==="apikey")return'"apiKey"';if(n==="gatewayid")return'"gatewayId"';return""}function Rr(e,n){if(n===void 0||n===null)return;if(typeof n!=="object"||Array.isArray(n))throw Error(`Agent "${e}" config.provider must be an object`);for(let[t,o]of Object.entries(n)){if(!Zn(t))throw Error(`Agent "${e}" config.provider.${t} is not a supported provider (expected one of: ${Xn.join(", ")})`);if(typeof o!=="object"||o===null||Array.isArray(o))throw Error(`Agent "${e}" config.provider.${t} must be an object`);let r=o;for(let s of Object.keys(r)){let i=$r(s);if(i)throw Error(`Agent "${e}" config.provider.${t} has unknown option "${s}". Did you mean ${i}?`)}if(t==="custom"&&r.base_url===void 0&&r.baseURL===void 0)throw Error(`Agent "${e}" config.provider.custom.base_url is required (use "base_url" or "baseURL")`)}}function Or(e,n){if(n===void 0||n===null)return;if(typeof n!=="object"||Array.isArray(n))throw Error(`Agent "${e}" config.harness must be an object`);let t=n;if("sandbox"in t)throw Error(`Agent "${e}" harness sandbox was removed; list it first in the agent's sandboxes`);for(let o of Object.keys(t))if(!kr.has(o))throw Error(`Agent "${e}" config.harness has unknown option "${o}"`);if(t.type!=="claude-code"&&t.type!=="codex"&&t.type!=="deepagents"&&t.type!=="opencode"&&t.type!=="pi")throw Error(`Agent "${e}" config.harness.type must be claude-code, codex, deepagents, opencode, or pi`);if(t.permissionMode!==void 0&&t.permissionMode!=="allow-reads"&&t.permissionMode!=="allow-edits"&&t.permissionMode!=="allow-all")throw Error(`Agent "${e}" config.harness.permissionMode must be allow-reads, allow-edits, or allow-all`);if(t.type==="codex"&&t.permissionMode!==void 0&&t.permissionMode!=="allow-all")throw Error(`Agent "${e}" config.harness.permissionMode must be allow-all for codex`);if(t.startupTimeoutMs!==void 0&&(typeof t.startupTimeoutMs!=="number"||!Number.isSafeInteger(t.startupTimeoutMs)||t.startupTimeoutMs<1||t.startupTimeoutMs>600000))throw Error(`Agent "${e}" config.harness.startupTimeoutMs must be an integer from 1 to 600000`);if(t.webSearch!==void 0&&typeof t.webSearch!=="boolean")throw Error(`Agent "${e}" config.harness.webSearch must be a boolean`);if(t.type!=="codex"&&t.webSearch!==void 0)throw Error(`Agent "${e}" config.harness.webSearch is only supported by codex`);if(t.type==="pi"&&t.startupTimeoutMs!==void 0)throw Error(`Agent "${e}" config.harness.startupTimeoutMs is not supported by pi`);if(hn(e,t.activeTools,"activeTools"),hn(e,t.inactiveTools,"inactiveTools"),t.activeTools!==void 0&&t.inactiveTools!==void 0)throw Error(`Agent "${e}" config.harness must use either activeTools or inactiveTools, not both`);Cr(e,t.debug)}function Cr(e,n){if(n===void 0)return;if(typeof n!=="object"||n===null||Array.isArray(n))throw Error(`Agent "${e}" config.harness.debug must be an object`);let t=n;for(let o of Object.keys(t))if(!Er.has(o))throw Error(`Agent "${e}" config.harness.debug has unknown option "${o}"`);if(t.enabled!==void 0&&typeof t.enabled!=="boolean")throw Error(`Agent "${e}" config.harness.debug.enabled must be a boolean`);if(t.level!==void 0&&t.level!=="error"&&t.level!=="warn"&&t.level!=="info"&&t.level!=="debug"&&t.level!=="trace")throw Error(`Agent "${e}" config.harness.debug.level must be error, warn, info, debug, or trace`);hn(e,t.subsystems,"debug.subsystems")}function hn(e,n,t){if(n!==void 0&&(!Array.isArray(n)||!n.every((o)=>typeof o==="string"&&o.trim().length>0)))throw Error(`Agent "${e}" config.harness.${t} must be an array of non-empty strings`)}function Ar(e){if(new Set(e.config.skills?.allowed?.map((t)=>h(t)?t.name:t)).size<=gn)return;throw Error(`Agent "${e.name}" config.skills.allowed must list at most ${gn} skills`)}function xr(e,n,t){let o={...e.config};Rr(e.name,o.provider),Or(e.name,o.harness);let r=Array.isArray(o.sandboxes)?o.sandboxes.map((i)=>h(i)?i.name:i):void 0;if(r)o.sandboxes=r;r?.forEach((i,a)=>{if(r.indexOf(i)===a)return;throw Error(`Agent "${e.name}" sandboxes[${a}] "${String(i)}" is listed more than once`)}),Ar(e);let s=Pr(e.name,o.hooks);if(s)o.hooks=s.agentHooksConfig;else if(o.hooks!==void 0)o.hooks=Rt(o.hooks,e.name);if(o.connections!==void 0){if(!Array.isArray(o.connections))throw Error(`Agent "${e.name}" config.connections must be an array of connection definitions`);o.channels=Object.fromEntries(o.connections.map((i)=>{if(!v(i))throw Error(`Agent "${e.name}" config.connections must contain connection definitions`);let a=`${e.name}${Et(i.type)}Channel`,c=kt(i,t);return[i.type,{id:a,...i.config,...i.partition?{partition:i.partition}:{},allowedChannelIds:c}]})),delete o.connections}if(Array.isArray(o.workspaces)){let i=o.workspaces.map((a)=>Br(a,e.name));for(let a of i){let c=r?.indexOf(a.sandbox)??-1;if(c>=1)throw Error(`Agent "${e.name}" sandboxes[${c}] "${String(a.sandbox)}" also backs workspace "${String(a.name)}"; only the first sandbox can back a workspace`)}o.workspaces=i}if(o.harness&&!r?.length)throw Error(`Agent "${e.name}" runs a harness, so it needs sandboxes; the first runs the harness`);if(o.policies!==void 0){let i=_r(o.policies,e.name);if(i)o.policies=i;else delete o.policies}return{config:le(o),...s?.hookResource?{hookResource:s.hookResource}:{}}}function Pr(e,n){if(n===void 0)return;if(!n||typeof n!=="object"||Array.isArray(n))throw Error(`Agent "${e}" config.hooks must be an object`);let t=n,o=Object.keys(fn).flatMap((d)=>{let l=t[d];if(l===void 0)return[];if(typeof l!=="function")throw Error(`Agent "${e}" config.hooks.${d} must be a function`);return[{name:d,event:fn[d],source:Tr(l.toString())}]});if(o.length===0)return;let r=`${e}-hooks`,s=Ir(e,o),i=Buffer.byteLength(s);if(i>qe)throw Error(`Agent "${e}" hook bundle is too large (${i} bytes, max ${qe})`);let a=o.map((d)=>d.event),c=Rt(t,e);return c.code=[{hookId:r}],{agentHooksConfig:c,hookResource:{kind:"hook",name:r,description:`Inline hooks for agent ${e}`,config:{events:a,bundle:s,sha256:_e(s)}}}}function Rt(e,n){if(!e||typeof e!=="object"||Array.isArray(e))throw Error(`Agent "${n}" config.hooks must be an object`);let t=Object.entries(e);for(let[r]of t){if(r==="webhooks"||r in fn)continue;throw Error(`Agent "${n}" config.hooks.${r} is not supported. Use inline hook callbacks or hooks.webhooks.`)}return Object.fromEntries(t.filter(([r])=>r==="webhooks"))}function Tr(e){let n=e.trim();if(/^(async\s+)?function\b/.test(n)||/^(async\s*)?\(/.test(n)||/^(async\s+)?[A-Za-z_$][\w$]*\s*=>/.test(n))return n;if(/^(async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(n))return n.replace(/^(async\s+)?/,"$1function ");return n}function Ir(e,n){let t=`export default {
43
41
  ${n.map((o)=>` ${JSON.stringify(o.event)}: ${o.source},`).join(`
44
42
  `)}
45
43
  };
46
- `;try{return wt(t,{loader:"ts"}).code}catch(o){let r=o instanceof Error?o.message:String(o);throw Error(`Agent "${e}" inline hooks failed to transpile: ${r}`)}}function Tr(e,n){if(!Array.isArray(e))throw Error(`Agent "${n}" config.policies must be an array`);let t=e.map((o)=>{if(h(o)&&o.kind==="policy")return o.name;if(typeof o==="string")return o;throw Error(`Agent "${n}" config.policies must contain definePolicy(...) resources or strings`)});return t.length>0?t:void 0}async function ft(e,n){let t=await Mo(He(Fo(),"broods-mcp-"));try{let o=He(t,"server.mjs");await Wo(o,n,"utf8");let r;try{r=await import(ht(o).href)}catch(a){throw Error(`MCP server bundle ${e} failed to import: ${a instanceof Error?a.message:String(a)}`)}let s=r.default;if(!(typeof s==="function"||typeof s==="object"&&s!==null&&typeof s.fetch==="function"))throw Error(`MCP server bundle ${e} default export must be a fetch handler (createMcpHandler)`)}finally{await Go(t,{recursive:!0,force:!0})}}async function _r(e){let n=await Yo({stdin:e.stdin,absWorkingDir:e.stdin.resolveDir,bundle:!0,...e.workers?{platform:"browser",conditions:["workerd","worker","browser"]}:{platform:"node"},format:"esm",minify:!1,write:!1,logLevel:"silent",plugins:e.plugins??[]}).catch((t)=>{let o=Fr(t)?t.errors.map((r)=>r.text).filter(Boolean).join("; "):t instanceof Error?t.message:String(t);throw Error(`${e.label} ${e.manifestPath} failed to build${o?`: ${o}`:""}`)});if(n.outputFiles.length!==1)throw Error(`${e.label} ${e.manifestPath} failed to build: expected one output file`);return n.outputFiles[0].text}async function Ir(e,n){let t=Mr(n,e.path,"Skill"),o=Re(n,t).split("\\").join("/"),r=await Gr(t);if(!r.some((s)=>s.path==="SKILL.md"))throw Error(`Skill folder ${e.path} must contain SKILL.md`);return{source:"files",path:o,files:r}}async function jr(e,n,t){let{handler:o,...r}=n,s=[o,n.url,n.sandbox].filter((w)=>w!==void 0).length;if(s>1)throw Error(`MCP server "${e.resource.name}" declares more than one of url, handler and sandbox; pick one`);if(o===void 0){if(s===0)throw Error(`MCP server "${e.resource.name}" needs url (external), handler (hosted) or sandbox (on a machine)`);return ce(r)}let i=Re(t,e.file).split("\\").join("/");Wr(i,"MCP server");let a=(w)=>_r({stdin:{contents:Dr(e),resolveDir:t,sourcefile:"mcp-handler.mjs",loader:"js"},label:"MCP server bundle",manifestPath:i,plugins:[Nr()],workers:w}),c=n.runtime==="lambda"?void 0:await a(!0).catch(()=>{return}),l=c!==void 0&&Buffer.byteLength(c)<=hn&&Qn(c)&&await ft(i,c).then(()=>!0,()=>!1)?c:await a(!1),d=Buffer.byteLength(l);if(d>it)throw Error(`MCP server bundle ${i} is too large (${d} bytes, max ${it})`);return await ft(i,l),{...ce(r),bundle:l,sha256:_e(l)}}function Dr(e){return`import * as __exports from ${JSON.stringify(e.file)};
44
+ `;try{return wt(t,{loader:"ts"}).code}catch(o){let r=o instanceof Error?o.message:String(o);throw Error(`Agent "${e}" inline hooks failed to transpile: ${r}`)}}function _r(e,n){if(!Array.isArray(e))throw Error(`Agent "${n}" config.policies must be an array`);let t=e.map((o)=>{if(h(o)&&o.kind==="policy")return o.name;if(typeof o==="string")return o;throw Error(`Agent "${n}" config.policies must contain definePolicy(...) resources or strings`)});return t.length>0?t:void 0}async function ft(e,n){let t=await Go(ze(Ko(),"broods-mcp-"));try{let o=ze(t,"server.mjs");await Ho(o,n,"utf8");let r;try{r=await import(ht(o).href)}catch(a){throw Error(`MCP server bundle ${e} failed to import: ${a instanceof Error?a.message:String(a)}`)}let s=r.default;if(!(typeof s==="function"||typeof s==="object"&&s!==null&&typeof s.fetch==="function"))throw Error(`MCP server bundle ${e} default export must be a fetch handler (createMcpHandler)`)}finally{await Fo(t,{recursive:!0,force:!0})}}async function jr(e){let n=await Jo({stdin:e.stdin,absWorkingDir:e.stdin.resolveDir,bundle:!0,...e.workers?{platform:"browser",conditions:["workerd","worker","browser"]}:{platform:"node"},format:"esm",minify:!1,write:!1,logLevel:"silent",plugins:e.plugins??[]}).catch((t)=>{let o=Kr(t)?t.errors.map((r)=>r.text).filter(Boolean).join("; "):t instanceof Error?t.message:String(t);throw Error(`${e.label} ${e.manifestPath} failed to build${o?`: ${o}`:""}`)});if(n.outputFiles.length!==1)throw Error(`${e.label} ${e.manifestPath} failed to build: expected one output file`);return n.outputFiles[0].text}async function Dr(e,n){let t=Gr(n,e.path,"Skill"),o=Oe(n,t).split("\\").join("/"),r=await Fr(t);if(!r.some((s)=>s.path==="SKILL.md"))throw Error(`Skill folder ${e.path} must contain SKILL.md`);return{source:"files",path:o,files:r}}async function Nr(e,n,t){let{handler:o,...r}=n,s=[o,n.url,n.sandbox].filter((w)=>w!==void 0).length;if(s>1)throw Error(`MCP server "${e.resource.name}" declares more than one of url, handler and sandbox; pick one`);if(o===void 0){if(s===0)throw Error(`MCP server "${e.resource.name}" needs url (external), handler (hosted) or sandbox (on a machine)`);return le(r)}let i=Oe(t,e.file).split("\\").join("/");Hr(i,"MCP server");let a=(w)=>jr({stdin:{contents:Ur(e),resolveDir:t,sourcefile:"mcp-handler.mjs",loader:"js"},label:"MCP server bundle",manifestPath:i,plugins:[Lr()],workers:w}),c=n.runtime==="lambda"?void 0:await a(!0).catch(()=>{return}),d=c!==void 0&&Buffer.byteLength(c)<=bn&&Qn(c)&&await ft(i,c).then(()=>!0,()=>!1)?c:await a(!1),l=Buffer.byteLength(d);if(l>it)throw Error(`MCP server bundle ${i} is too large (${l} bytes, max ${it})`);return await ft(i,d),{...le(r),bundle:d,sha256:_e(d)}}function Ur(e){return`import * as __exports from ${JSON.stringify(e.file)};
47
45
  const __mcp = __exports[${JSON.stringify(e.exportName)}];
48
46
  export default __mcp?.config?.handler ?? __mcp?.handler;
49
- `}function Nr(){return{name:"broods-sdk-stub",setup:function(e){e.onResolve({filter:/^broods(\/.*)?$/},()=>({path:"broods",namespace:"broods-stub"})),e.onLoad({filter:/.*/,namespace:"broods-stub"},()=>({contents:Jo,loader:"js"}))}}}function Ur(e,n){if(e.kind!=="agent")return e;let t=e.config.mcp;if(!t)return e;let o=Object.entries(t).map(([r,s])=>{let i=n.get(r),a=new Set(Object.keys(s.headers??{}).map((w)=>w.toLowerCase())),c=Object.entries(i?.headers??{}).filter(([w])=>!a.has(w.toLowerCase())),{tokenUrl:l,...d}=i?.oauth??{};return[r,{...s,...c.length>0?{headers:{...Object.fromEntries(c),...s.headers}}:{},...i?.oauth?{oauth:{...d,...s.oauth}}:{}}]});return{...e,config:{...e.config,mcp:Object.fromEntries(o)}}}function Lr(e,n){if(h(e))return{name:e.name,workspaceId:e.name};if(e&&typeof e==="object"&&"workspace"in e){let t=e.workspace,o=h(t)?t.name:t;if(typeof o!=="string")throw Error(`Agent ${n} workspace ref must be a defineWorkspace(...) resource or its name`);let r={name:o,workspaceId:o};if("sandbox"in e){let s=e.sandbox;r.sandbox=s===null?null:h(s)?s.name:s}return r}throw Error(`Agent ${n} workspaces must be defineWorkspace(...) resources or { workspace, sandbox } refs`)}function Mr(e,n,t){if(n.trim().length===0)throw Error(`${t} path is required`);if(n.includes("\x00"))throw Error(`${t} path must not contain null bytes`);let o=Ve(e),r=Ve(o,n),s=Re(o,r);if(s===""||!s.startsWith("..")&&!Vo(s))return r;throw Error(`${t} path ${n} must stay inside ${y}/`)}function Br(e,n){let t={...n},o=t.connection;if(!v(o))throw Error(`Channel "${e}" config.connection must be a connection definition`);return delete t.connection,t.platform=o.type,vt(t.partition,`Channel "${e}"`),ce(t)}function ce(e){if(Array.isArray(e))return e.map((n)=>ce(n));if(h(e))return e.name;if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).map(([n,t])=>[n,ce(t)]));return e}async function Gr(e){let n=[],t=0;async function o(r){let s=await bt(r,{withFileTypes:!0});for(let i of s){let a=He(r,i.name),c=Re(e,a).split("\\").join("/");if(i.isDirectory()){if(mt(i.name))continue;await o(a)}else if(i.isFile()){if(mt(i.name)||Ot(c))continue;let l=await Bo(a);if(l.byteLength>Ye)throw Error(`Skill bundle file ${c} is too large (${l.byteLength} bytes, max ${Ye})`);if(t+=l.byteLength,t>at)throw Error(`Skill bundle at ${e} is too large (${t} bytes, max ${at})`);if(n.length>=ct)throw Error(`Skill bundle at ${e} has too many files (max ${ct})`);n.push({path:c,size:l.byteLength,sha256:_e(l),contentBase64:l.toString("base64"),contentType:Kr(c)})}}}return await o(e),n.sort((r,s)=>String(r.path).localeCompare(String(s.path)))}function mt(e){return e.startsWith(".")||qo.has(e)}function Wr(e,n){if(Ot(e))throw Error(`${n} bundle path ${e} looks like a hidden file or secret and will not be bundled`)}function Fr(e){return e instanceof Error&&Array.isArray(e.errors)}function Ot(e){return e.split("/").some((t)=>t.startsWith(".")||Xo.some((o)=>o.test(t)))}function _e(e){return No("sha256").update(e).digest("hex")}function Kr(e){if(e.endsWith(".md"))return"text/markdown; charset=utf-8";if(e.endsWith(".json"))return"application/json";if(e.endsWith(".js")||e.endsWith(".mjs"))return"application/javascript";if(e.endsWith(".ts"))return"text/typescript; charset=utf-8";if(e.endsWith(".txt"))return"text/plain; charset=utf-8";return"application/octet-stream"}function Hr(e){return e.replace(/^@/,"").replace(/\//g,"-").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}import{mkdir as Vr,writeFile as ze}from"node:fs/promises";import{resolve as Ie}from"node:path";async function Je(e,n,t=process.cwd(),o={},r=null,s=[]){let i=Ie(t,y,b),a=Yr(n,e);await Vr(i,{recursive:!0}),await ze(Ie(i,"ids.ts"),qr(a),"utf8"),await ze(Ie(i,"api.ts"),zr(e,a,o,r,s),"utf8"),await ze(Ie(i,"resources.ts"),Xr(e),"utf8"),await ze(Ie(i,"dataModel.ts"),Jr(),"utf8")}function Yr(e,n){let t={agents:fe(n,"agent"),workspaces:fe(n,"workspace"),sandboxes:fe(n,"sandbox"),crons:fe(n,"cron"),skills:fe(n,"skill"),mcp:fe(n,"mcp"),policies:fe(n,"policy"),channelRecords:fe(n,"channelRecord")};return{agents:me(e.agents,t.agents),workspaces:me(e.workspaces,t.workspaces),sandboxes:me(e.sandboxes,t.sandboxes),crons:me(e.crons,t.crons),skills:me(e.skills,t.skills),hooks:{},mcp:me(e.mcp,t.mcp),policies:me(e.policies,t.policies),channelRecords:me(e.channelRecords,t.channelRecords)}}function fe(e,n){return new Set(e.resources.filter((t)=>t.kind===n).map((t)=>t.name))}function me(e,n){return Object.fromEntries(Object.entries(e??{}).filter(([t])=>n.has(t)))}function zr(e,n,t,o,r){let s=Object.keys(n.agents),i=o?`, endpointId: ${JSON.stringify(o.endpointId)}, projectSlug: ${JSON.stringify(o.projectSlug)}, stageSlug: ${JSON.stringify(o.stageSlug)}`:"",a=s.map((l)=>` ${bn(t.agent?.[l]??l)}: { kind: "agent", name: ${JSON.stringify(l)}, id: ids.agents[${JSON.stringify(l)}], project: ${JSON.stringify(e.project)}, stage: ${JSON.stringify(e.stage)}${i} },`).join(`
50
- `),c=o?r.map((l)=>{let d=encodeURIComponent(o.accountId),w=o.stageKind===void 0||o.stageKind==="production"?`/v1/webhooks/${d}/${encodeURIComponent(l.type)}`:`/v1/webhooks/${d}/dev/${encodeURIComponent(o.endpointId)}/${encodeURIComponent(l.type)}`;return` ${bn(l.alias)}: { kind: "channel", type: ${JSON.stringify(l.type)}, agentName: ${JSON.stringify(l.agentName)}, agentId: ids.agents[${JSON.stringify(l.agentName)}], accountId: ${JSON.stringify(o.accountId)}, webhookPath: ${JSON.stringify(w)} },`}).join(`
47
+ `}function Lr(){return{name:"broods-sdk-stub",setup:function(e){e.onResolve({filter:/^broods(\/.*)?$/},()=>({path:"broods",namespace:"broods-stub"})),e.onLoad({filter:/.*/,namespace:"broods-stub"},()=>({contents:Xo,loader:"js"}))}}}function Mr(e,n){if(e.kind!=="agent")return e;let t=e.config.mcp;if(!t)return e;let o=Object.entries(t).map(([r,s])=>{let i=n.get(r),a=new Set(Object.keys(s.headers??{}).map((w)=>w.toLowerCase())),c=Object.entries(i?.headers??{}).filter(([w])=>!a.has(w.toLowerCase())),{tokenUrl:d,...l}=i?.oauth??{};return[r,{...s,...c.length>0?{headers:{...Object.fromEntries(c),...s.headers}}:{},...i?.oauth?{oauth:{...l,...s.oauth}}:{}}]});return{...e,config:{...e.config,mcp:Object.fromEntries(o)}}}function Br(e,n){if(h(e))return{name:e.name,workspaceId:e.name};if(e&&typeof e==="object"&&"workspace"in e){let t=e.workspace,o=h(t)?t.name:t;if(typeof o!=="string")throw Error(`Agent ${n} workspace ref must be a defineWorkspace(...) resource or its name`);let r={name:o,workspaceId:o};if("sandbox"in e){let s=e.sandbox;r.sandbox=s===null?null:h(s)?s.name:s}return r}throw Error(`Agent ${n} workspaces must be defineWorkspace(...) resources or { workspace, sandbox } refs`)}function Gr(e,n,t){if(n.trim().length===0)throw Error(`${t} path is required`);if(n.includes("\x00"))throw Error(`${t} path must not contain null bytes`);let o=Je(e),r=Je(o,n),s=Oe(o,r);if(s===""||!s.startsWith("..")&&!zo(s))return r;throw Error(`${t} path ${n} must stay inside ${y}/`)}function Wr(e,n){let t={...n},o=t.connection;if(!v(o))throw Error(`Channel "${e}" config.connection must be a connection definition`);return delete t.connection,t.platform=o.type,vt(t.partition,`Channel "${e}"`),le(t)}function le(e){if(Array.isArray(e))return e.map((n)=>le(n));if(h(e))return e.name;if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).map(([n,t])=>[n,le(t)]));return e}async function Fr(e){let n=[],t=0;async function o(r){let s=await bt(r,{withFileTypes:!0});for(let i of s){let a=ze(r,i.name),c=Oe(e,a).split("\\").join("/");if(i.isDirectory()){if(mt(i.name))continue;await o(a)}else if(i.isFile()){if(mt(i.name)||Ot(c))continue;let d=await Wo(a);if(d.byteLength>qe)throw Error(`Skill bundle file ${c} is too large (${d.byteLength} bytes, max ${qe})`);if(t+=d.byteLength,t>at)throw Error(`Skill bundle at ${e} is too large (${t} bytes, max ${at})`);if(n.length>=ct)throw Error(`Skill bundle at ${e} has too many files (max ${ct})`);n.push({path:c,size:d.byteLength,sha256:_e(d),contentBase64:d.toString("base64"),contentType:Vr(c)})}}}return await o(e),n.sort((r,s)=>String(r.path).localeCompare(String(s.path)))}function mt(e){return e.startsWith(".")||Zo.has(e)}function Hr(e,n){if(Ot(e))throw Error(`${n} bundle path ${e} looks like a hidden file or secret and will not be bundled`)}function Kr(e){return e instanceof Error&&Array.isArray(e.errors)}function Ot(e){return e.split("/").some((t)=>t.startsWith(".")||Qo.some((o)=>o.test(t)))}function _e(e){return Lo("sha256").update(e).digest("hex")}function Vr(e){if(e.endsWith(".md"))return"text/markdown; charset=utf-8";if(e.endsWith(".json"))return"application/json";if(e.endsWith(".js")||e.endsWith(".mjs"))return"application/javascript";if(e.endsWith(".ts"))return"text/typescript; charset=utf-8";if(e.endsWith(".txt"))return"text/plain; charset=utf-8";return"application/octet-stream"}function Yr(e){return e.replace(/^@/,"").replace(/\//g,"-").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}import{mkdir as zr,writeFile as Xe}from"node:fs/promises";import{resolve as je}from"node:path";async function Ze(e,n,t=process.cwd(),o={},r=null,s=[]){let i=je(t,y,b),a=Jr(n,e);await zr(i,{recursive:!0}),await Xe(je(i,"ids.ts"),Zr(a),"utf8"),await Xe(je(i,"api.ts"),qr(e,a,o,r,s),"utf8"),await Xe(je(i,"resources.ts"),Qr(e),"utf8"),await Xe(je(i,"dataModel.ts"),Xr(),"utf8")}function Jr(e,n){let t={agents:fe(n,"agent"),workspaces:fe(n,"workspace"),sandboxes:fe(n,"sandbox"),crons:fe(n,"cron"),skills:fe(n,"skill"),mcp:fe(n,"mcp"),policies:fe(n,"policy"),channelRecords:fe(n,"channelRecord")};return{agents:me(e.agents,t.agents),workspaces:me(e.workspaces,t.workspaces),sandboxes:me(e.sandboxes,t.sandboxes),crons:me(e.crons,t.crons),skills:me(e.skills,t.skills),hooks:{},mcp:me(e.mcp,t.mcp),policies:me(e.policies,t.policies),channelRecords:me(e.channelRecords,t.channelRecords)}}function fe(e,n){return new Set(e.resources.filter((t)=>t.kind===n).map((t)=>t.name))}function me(e,n){return Object.fromEntries(Object.entries(e??{}).filter(([t])=>n.has(t)))}function qr(e,n,t,o,r){let s=Object.keys(n.agents),i=o?`, endpointId: ${JSON.stringify(o.endpointId)}, projectSlug: ${JSON.stringify(o.projectSlug)}, stageSlug: ${JSON.stringify(o.stageSlug)}`:"",a=s.map((d)=>` ${wn(t.agent?.[d]??d)}: { kind: "agent", name: ${JSON.stringify(d)}, id: ids.agents[${JSON.stringify(d)}], project: ${JSON.stringify(e.project)}, stage: ${JSON.stringify(e.stage)}${i} },`).join(`
48
+ `),c=o?r.map((d)=>{let l=encodeURIComponent(o.accountId),w=o.stageKind===void 0||o.stageKind==="production"?`/v1/webhooks/${l}/${encodeURIComponent(d.type)}`:`/v1/webhooks/${l}/dev/${encodeURIComponent(o.endpointId)}/${encodeURIComponent(d.type)}`;return` ${wn(d.alias)}: { kind: "channel", type: ${JSON.stringify(d.type)}, agentName: ${JSON.stringify(d.agentName)}, agentId: ids.agents[${JSON.stringify(d.agentName)}], accountId: ${JSON.stringify(o.accountId)}, webhookPath: ${JSON.stringify(w)} },`}).join(`
51
49
  `):"";return`// Generated by broods. Do not edit by hand.
52
50
  import type { ResourceApi } from "broods";
53
51
  import { ids } from "./ids";
@@ -60,11 +58,11 @@ ${a}
60
58
  channels: {
61
59
  ${c}
62
60
  },
63
- workspaces: ${je("workspaces",n.workspaces,t.workspace)},
64
- sandboxes: ${je("sandboxes",n.sandboxes,t.sandbox)},
65
- crons: ${je("crons",n.crons,t.cron)},
66
- skills: ${je("skills",n.skills,t.skill)},
67
- policies: ${je("policies",n.policies,t.policy)},
61
+ workspaces: ${De("workspaces",n.workspaces,t.workspace)},
62
+ sandboxes: ${De("sandboxes",n.sandboxes,t.sandbox)},
63
+ crons: ${De("crons",n.crons,t.cron)},
64
+ skills: ${De("skills",n.skills,t.skill)},
65
+ policies: ${De("policies",n.policies,t.policy)},
68
66
  } as const);
69
67
 
70
68
  /** Fails the build when generated output drifts from the SDK's contract,
@@ -72,9 +70,9 @@ ${c}
72
70
  function resourceApi<T extends ResourceApi>(resources: T): T {
73
71
  return resources;
74
72
  }
75
- `}function Jr(){return`// Generated by broods. Do not edit by hand.
73
+ `}function Xr(){return`// Generated by broods. Do not edit by hand.
76
74
  export type { AgentReference, ChannelReference, AgentRunInput, AgentRunResult, ResourceApi } from "broods";
77
- `}function qr(e){return`// Generated by broods. Do not edit by hand.
75
+ `}function Zr(e){return`// Generated by broods. Do not edit by hand.
78
76
  export const ids = ${JSON.stringify(e,null,2)} as const;
79
77
  export const agents = ids.agents;
80
78
  export const workspaces = ids.workspaces;
@@ -82,19 +80,19 @@ export const sandboxes = ids.sandboxes;
82
80
  export const crons = ids.crons;
83
81
  export const skills = ids.skills;
84
82
  export const policies = ids.policies;
85
- `}function Xr(e){return`// Generated by broods. Do not edit by hand.
83
+ `}function Qr(e){return`// Generated by broods. Do not edit by hand.
86
84
  export const manifest = ${JSON.stringify(e,null,2)} as const;
87
- `}function je(e,n,t){let o=Object.keys(n);if(o.length===0)return"{}";return`{
88
- ${o.map((s)=>` ${bn(t?.[s]??s)}: ids.${e}[${JSON.stringify(s)}],`).join(`
85
+ `}function De(e,n,t){let o=Object.keys(n);if(o.length===0)return"{}";return`{
86
+ ${o.map((s)=>` ${wn(t?.[s]??s)}: ids.${e}[${JSON.stringify(s)}],`).join(`
89
87
  `)}
90
- }`}function bn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function Ct(e,n){return`${e}…${n.slice(-4)}`}var wn=["ap-southeast-1","eu-west-1","us-east-1"],At=["eu-west-1"];var Pt=1,Tt=0,xt=60000,qe=15000;function ee(e,n){return new Promise((t)=>{if(n?.aborted)return t();let o=setTimeout(t,e);n?.addEventListener("abort",()=>{clearTimeout(o),t()},{once:!0})})}function ie(){let e=globalThis.WebSocket;if(!e)throw Error("WebSocket is not available in this environment.");return e}class A extends Error{}async function*Xe(e,n={}){let t=new Set,o=500,r=0,s=Date.now();while(!n.signal?.aborted){let i=!1,a="the log stream closed";try{for await(let c of Zr(e,n,()=>{i=!0})){let l=`${c.ts}|${c.eventType}|${c.message}`;if(t.has(l))continue;if(t.add(l),t.size>5000)t.delete(t.values().next().value);yield c}}catch(c){if(n.signal?.aborted)return;if(a=c instanceof Error?c.message:String(c),c instanceof A||/unauthorized|invalid websocket token|scope does not match/i.test(a))throw c}if(n.signal?.aborted)return;if(i)o=500,r=0,s=Date.now();if(!n.keepReconnecting&&Date.now()-s>=xt)throw Error(`Gave up reconnecting to the live logs after ${xt/1000} s. Last error: ${a}`);r+=1,n.onReconnect?.(r,a),await ee(o,n.signal),o=Math.min(o*2,5000)}}async function*Zr(e,n,t){let{backfill:o=0,minLevel:r,sandboxId:s,signal:i}=n,a=n.liveOnly??o<=0;if(i?.aborted)return;let c=[],l=null,d=!1,w=null,u=()=>{w?.(),w=null},{socket:P,url:j}=It(e,await e.credential()),I=setTimeout(()=>{l=Error(`The observability gateway did not answer within ${qe/1000} s.`),d=!0,u()},qe),K=()=>{if(clearTimeout(I),P.readyState===Pt||P.readyState===Tt)P.close(1000,"client closed");i?.removeEventListener("abort",te)},te=()=>{d=!0,u(),K()};i?.addEventListener("abort",te,{once:!0}),P.onopen=()=>{if(i?.aborted){K();return}let Q={type:"subscribe",stream:"logs",...o>0?{backfill:o}:{},...a?{liveOnly:!0}:{},...r!==void 0?{minLevel:r}:{},...s!==void 0?{sandboxId:s}:{}};P.send(JSON.stringify(Q))},P.onmessage=(Q)=>{let be=Dt(Q.data);if(!be)return;if(clearTimeout(I),be.type!=="error")t();switch(be.type){case"backfill":if(be.stream==="logs"){for(let Ao of be.entries)c.push(Ao);u()}break;case"log":c.push(be.entry),u();break;case"error":l=Error(`Observability gateway error: ${be.error}`),d=!0,u();break;case"ready":break;default:break}},P.onerror=()=>{l=Error(`Cannot connect to the observability gateway at ${j}.`),d=!0,u()},P.onclose=(Q)=>{if(!d){if(Q.code!==1000)l=jt(Q);d=!0,u()}};try{while(!0){if(c.length>0){yield c.shift();continue}if(l)throw l;if(d)return;await new Promise((Q)=>{w=Q})}}finally{K()}}async function _t(e,n){let{socket:t,url:o}=It(e,await e.credential());return new Promise((r,s)=>{let i=!1,a=(d)=>{if(i)return;if(i=!0,clearTimeout(l),t.readyState===Pt||t.readyState===Tt)t.close(1000,"client closed");d()},c=(d)=>a(()=>s(d)),l=setTimeout(()=>{c(Error(`The observability gateway did not answer within ${qe/1000} s.`))},qe);t.onopen=()=>{let d={type:"fetchTrace",traceId:n};t.send(JSON.stringify(d))},t.onmessage=(d)=>{let w=Dt(d.data);if(w?.type==="error")c(Error(`Observability gateway error: ${w.error}`));else if(w?.type==="backfill"&&w.stream==="traces"){let u=w.entries;if(w.error)c(Error(w.error));else a(()=>r(u))}},t.onerror=()=>{c(Error(`Cannot connect to the observability gateway at ${o}.`))},t.onclose=(d)=>c(jt(d))})}function It(e,n){let t=Qr(e.baseUrl,e.project,e.stage);return{socket:new(ie())(t,E(n)),url:t}}function jt(e){return Error(e.reason?`Observability WebSocket closed: ${e.reason}`:`Observability WebSocket closed with code ${e.code}.`)}function Qr(e,n,t){return`${G(e)}/v1/projects/${encodeURIComponent(n)}/stages/${encodeURIComponent(t)}/observability/ws`}function Dt(e){if(typeof e!=="string")return null;try{let n=JSON.parse(e);return typeof n==="object"&&n!==null&&typeof n.type==="string"?n:null}catch{return null}}var es=new Set(["bundle","bundleStorageId","contentBase64"]),ns=new Set(["hook","mcp","skill"]),ts=30000;class Qe extends Error{}class en extends Error{}class q{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=f(e.baseUrl),this.token=e.token,this.fetchImpl=e.fetch??fetch}async getManifest(e,n){let t=await this.request(e,n,"/manifest",{method:"GET"});if(t.status===404)return null;return await Y(t,"Fetch manifest failed"),await t.json()}async putManifest(e,n,t=!1,o){let r=await this.externalizeLargeMcpBundles(e),s=await this.request(e.project,e.stage,"/manifest",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({manifest:r,prune:n,rotateRuntimeKey:t,...o!==void 0?{revision:o}:{}})},null);return await Y(s,"Sync manifest failed"),await s.json()}async externalizeLargeMcpBundles(e){if(e.resources.every((t)=>Lt(t)===null))return e;let n=await Promise.all(e.resources.map(async(t)=>{let o=Lt(t);if(o===null)return t;let{bundle:r,...s}=t.config,i=await this.uploadMcpBundle(e.project,e.stage,o);return{...t,config:{...s,bundleStorageId:i,sha256:_e(o)}}}));return{...e,resources:n}}async uploadMcpBundle(e,n,t){let o=await this.request(e,n,"/mcp-bundle-uploads",{method:"POST"});await Y(o,"Mint bundle upload URL failed");let{uploadUrl:r}=await o.json();if(!r)throw Error("Mint bundle upload URL failed: response omitted uploadUrl");let s=await this.send(r,{method:"POST",headers:{"Content-Type":"application/javascript"},body:t},null);await Y(s,"Bundle upload failed");let{storageId:i}=await s.json();if(!i)throw Error("Bundle upload failed: response omitted storageId");return i}async getRuntimeKey(e,n){let t=await this.request(e,n,"/runtime-key",{method:"GET"});if(t.status===404)return null;await Y(t,"Fetch runtime key failed");let o=await t.json();if(!o.apiKey)throw Error("Fetch runtime key failed: response omitted apiKey");return{apiKey:o.apiKey,keyHint:o.keyHint??"",...o.endpointId?{endpointId:o.endpointId}:{},...o.projectSlug?{projectSlug:o.projectSlug}:{},...o.stageSlug?{stageSlug:o.stageSlug}:{}}}async rotateUserTokenSecret(e,n){let t=await this.request(e,n,"/user-token-secret",{method:"POST"});if(t.status===404)return null;await Y(t,"Rotate user token signing secret failed");let o=await t.json();if(!o.secret||!o.hint)throw Error("Rotate user token signing secret failed: response omitted the secret");return{secret:o.secret,hint:o.hint}}async setEnv(e,n,t,o){let r=await this.request(e,n,`/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:o})});await Y(r,"Set environment variable failed")}async listEnv(e,n){let t=await this.request(e,n,"/env",{method:"GET"});return await Y(t,"List environment variables failed"),(await t.json()).variables??[]}async getEnv(e,n,t){let o=await this.request(e,n,`/env/${encodeURIComponent(t)}`,{method:"GET"});if(o.status===404)return null;return await Y(o,"Read environment variable failed"),(await o.json()).value??null}async removeEnv(e,n,t){let o=await this.request(e,n,`/env/${encodeURIComponent(t)}`,{method:"DELETE"});await Y(o,"Remove environment variable failed")}async getOnboarding(){let e=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Oe(e,"/v1/account/onboarding","broods org"),await Y(e,"Fetch CLI onboarding context failed"),await e.json()}async selectOnboardingOrg(e){let n=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({orgId:e})});return await Y(n,"Select CLI org failed"),await n.json()}async listStages(e){let n=await this.send(`${this.baseUrl}/v1/account/stages?project=${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Oe(n,"/v1/account/stages","broods stage"),await Y(n,"List stages failed"),(await n.json()).stages??[]}async createStage(e,n,t){let o=await this.send(`${this.baseUrl}/v1/account/stages`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({project:e,name:n,...t?{from:t}:{}})});return Oe(o,"/v1/account/stages","broods stage"),await Y(o,"Create stage failed"),await o.json()}async mintStageSession(e,n){let t=await this.send(`${this.baseUrl}/v1/account/stage-session`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({project:e,stage:n})});Oe(t,"/v1/account/stage-session","broods logs");try{await Y(t,"Open stage session failed")}catch(o){if(t.status===401||t.status===404)throw new A(o instanceof Error?o.message:String(o));throw o}return await t.json()}async listProjects(){let e=await this.send(`${this.baseUrl}/v1/account/projects`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Oe(e,"/v1/account/projects","broods project"),await Y(e,"List projects failed"),(await e.json()).projects??[]}async deleteProject(e){let n=await this.send(`${this.baseUrl}/v1/account/projects?projectId=${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`}});if(Oe(n,"/v1/account/projects","broods project"),n.status===404)return null;return await Y(n,"Delete project failed"),(await n.json()).deleted??null}async createOnboardingOrg(e){let n=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({createOrgName:e})});return await Y(n,"Create CLI org failed"),await n.json()}async request(e,n,t,o,r){let s=`${this.baseUrl}/v1/account/projects/${encodeURIComponent(e)}/stages/${encodeURIComponent(n)}${t}`;return await this.send(s,{...o,headers:{Authorization:`Bearer ${this.token}`,...o.headers}},r)}async send(e,n,t){return await nn(e,n,{fetch:this.fetchImpl,timeoutMs:t})}}async function nn(e,n,t={}){let o=t.fetch??fetch,r=t.timeoutMs===void 0?ts:t.timeoutMs;try{return await o(e,r===null?n:{...n,signal:AbortSignal.timeout(r)})}catch(s){throw Error(`Cannot reach ${new URL(e).origin}: ${ss(s,r)}`,{cause:s})}}function kn(e,n){let t=new Map((n?.resources??[]).map((l)=>[`${l.kind}:${l.name}`,l])),o=new Map(e.resources.map((l)=>[`${l.kind}:${l.name}`,l])),r=[],s=[],i=[];for(let[l,d]of o){let w=t.get(l);if(!w)s.push({key:l,resource:d});else if(Ze(vn(w))!==Ze(vn(d)))r.push({operation:"update",kind:d.kind,name:d.name})}for(let[l,d]of t)if(!o.has(l))i.push({key:l,resource:d});let a=new Set,c=new Set;for(let l of s){let d=i.find((w)=>!a.has(w.key)&&os(l.resource.kind)&&l.resource.kind===w.resource.kind&&Ze(Ut(l.resource))===Ze(Ut(w.resource)));if(!d)continue;c.add(l.key),a.add(d.key),r.push({operation:"rename",kind:l.resource.kind,name:l.resource.name,previousName:d.resource.name})}for(let{key:l,resource:d}of s)if(!c.has(l))r.push({operation:"create",kind:d.kind,name:d.name});for(let{key:l,resource:d}of i)if(!a.has(l))r.push({operation:"delete",kind:d.kind,name:d.name});return r.sort((l,d)=>Nt(l).localeCompare(Nt(d)))}function Nt(e){return`${{create:0,rename:1,update:2,delete:3}[e.operation]}:${e.kind}:${e.previousName??""}:${e.name}`}function os(e){return e==="agent"||e==="workspace"||e==="sandbox"||e==="policy"}function yn(e){if(Array.isArray(e))return e.map(yn);if(e&&typeof e==="object"){let n=e;if(n.__beeblastEnv===!0&&typeof n.name==="string")return`\${${n.name}}`;return Object.fromEntries(Object.entries(n).map(([t,o])=>[t,yn(o)]))}return e}function Ut(e){let n=vn(e),{name:t,...o}=n;return o}function vn(e){let n=yn(e);if(!ns.has(e.kind))return n;return{...n,config:En(n.config)}}function Sn(e){if(Array.isArray(e))return e.map(Sn);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>[n,Sn(t)]));return e}function Ze(e){return JSON.stringify(Sn(e))}function En(e){if(Array.isArray(e))return e.map(En);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).flatMap(([n,t])=>{if(es.has(n))return[];return[[n,En(t)]]}));return e}async function Y(e,n){if(e.ok)return;let t=await e.text(),{message:o=t,code:r}=rs(t);if(r==="manifest_conflict")throw new Qe(o);let s=e.status===401?"\nRun `broods login` to sign in again.":"";throw Error(`${n}: ${e.status} ${o}${s}`)}function rs(e){let n;try{n=JSON.parse(e)}catch{return{}}let t=typeof n==="object"&&n!==null&&"error"in n?n.error:void 0;if(typeof t!=="object"||t===null)return{};return{..."message"in t&&typeof t.message==="string"?{message:t.message}:{},..."code"in t&&typeof t.code==="string"?{code:t.code}:{}}}function Oe(e,n,t){if(e.status!==404)return;if((e.headers.get("Content-Type")??"").includes("application/json"))return;throw new en(`This broods server is older than your CLI and does not support \`${t}\` yet (no ${n} route).`)}function ss(e,n){if(!(e instanceof Error))return String(e);if(e.name==="TimeoutError"&&n!==null)return`no answer within ${n/1000} s`;let t=e.cause;if(!(t instanceof Error))return e.message;if(t.message)return t.message;return"code"in t&&typeof t.code==="string"?t.code:e.message}function Lt(e){if(e.kind!=="mcp")return null;let n=e.config?.bundle;if(typeof n!=="string")return null;return Buffer.byteLength(n)>hn?n:null}var tn=["chatgpt"];var we={chatgpt:{label:"ChatGPT plan",description:"Run agents on model.provider chatgpt with your ChatGPT plan",authorizeUrl:"https://auth.openai.com/api/accounts/authorize",tokenUrl:"https://auth.openai.com/api/accounts/oauth/token",revokeUrl:"https://auth.openai.com/api/accounts/oauth/revoke",jwksUrl:"https://auth.openai.com/.well-known/jwks.json",issuer:"https://auth.openai.com",scopes:["openid","profile","email","offline_access","resource.invoke","chatgpt.tokens.use.direct"],resource:"https://api.openai.com/v1",requiredScope:"chatgpt.tokens.use.direct",selfHostedOnly:"ChatGPT plan usage is only available on self-hosted Broods for now. Use an OpenAI API key with the `openai` provider instead.",managedOptIn:"CHATGPT_PLAN_ENABLED",modelsUrl:"https://api.openai.com/v1/models",usageUrl:"https://chatgpt.com/settings/usage"}};function $n(e){return tn.some((n)=>n===e)}import{createHash as Rs,randomBytes as Os,randomUUID as Jt}from"node:crypto";import{createServer as ps}from"node:http";import{createHash as fs,randomBytes as ms,randomUUID as hs}from"node:crypto";import{spawn as bs}from"node:child_process";import{createInterface as Ne}from"node:readline/promises";import{stdin as de,stdout as le}from"node:process";import{Writable as ws}from"node:stream";function Ce(e,n,t={}){let o=`${n?"*":" "} ${e}`;return n?W(o,"\x1B[1m\x1B[36m",re(t)):o}function Mt(e,n={}){let t=re(n),o=(i)=>W(i.padEnd(9),"\x1B[2m",t),r=!e.loggedIn?W("not logged in","\x1B[33m",t):e.org??W("unknown, run broods whoami","\x1B[2m",t),s=e.project??`none ${W(`(${e.projectGuess} from folder name)`,"\x1B[2m",t)}`;return[` ${o("org")}${r}`,` ${o("project")}${s}`,` ${o("stage")}${Kt(e.stage,t)}`,` ${o("server")}${e.server}`]}function is(e,n={}){let t=re(n),o=Ht(e.stage),r=o==="Development",s=W("▌",r?"\x1B[32m":"\x1B[33m",t),i=t?`${r?"\x1B[42m\x1B[30m\x1B[1m":"\x1B[43m\x1B[30m\x1B[1m"} ${o} \x1B[0m`:`[${o}]`,a=t?W("dashboard","\x1B[4m",t):"dashboard",c=`${e.dashboardUrl}?project=${encodeURIComponent(e.project)}&stage=${encodeURIComponent(e.stage)}`,l=W(c,"\x1B[2m\x1B[4m",t);return[`${s} Syncing ${o}: ${W(e.project,"",t)}`,`${s} ${i} ${e.stage} (${a})`,`${s} ${W("└─","\x1B[2m",t)} ${l}`].join(`
91
- `)}function as(e,n={}){let t=re(n);return e.map((o)=>{let r=gs(o.operation,t);if(o.operation==="rename"&&o.previousName)return` ${r} ${o.kind}:${o.previousName} -> ${o.name}`;return` ${r} ${o.kind}:${o.name}`})}function cs(e,n={}){let t=re(n),o=W("▌","\x1B[32m",t),r=W("↑","\x1B[32m",t);return`${o} ${r} Synced ${e.length} env var(s) from .env.local: ${e.join(", ")}`}function ls(e,n={}){return`${W("✖","\x1B[31m",re(n))} ${e}`}function Bt(e,n={}){let t=re(n),o=Math.max(...e.map(([r])=>r.length))+2;return e.map(([r,s])=>` ${r.padEnd(o)}${W(s,"\x1B[2m",t)}`)}function ds(e,n={}){let t=(n.now??new Date).toTimeString().slice(0,8);return`${W("✔","\x1B[32m",re(n))} ${t} Resources ready! (${Cn(e)})`}function us(e,n={}){return`${W("✔","\x1B[32m",re(n))} ${e}`}function Rn(e,n,t={}){let o=re(t),r=t.note?` ${W(`(${t.note})`,"\x1B[2m",o)}`:"";return` ${W("now","\x1B[2m",o)} ${e} → ${Kt(n,o)}${r}`}function De(e,n={}){return W(`! ${e}`,"\x1B[33m",re(n))}function Gt(e){console.error(is(e))}function on(e){for(let n of as(e))console.log(n)}function On(e){console.error(cs(e))}function Wt(e){console.error(ls(e,{stream:"stderr"}))}function Ft(e){console.error(ds(e))}function X(e){console.log(us(e,{stream:"stdout"}))}function D(e){console.log(De(e,{stream:"stdout"}))}function gs(e,n){if(e==="create")return`[${W("+","\x1B[32m",n)}]`;if(e==="rename")return`[${W("~","\x1B[33m",n)}]`;if(e==="update")return`[${W("*","\x1B[36m",n)}]`;return`[${W("-","\x1B[31m",n)}]`}function Cn(e){if(e>=1000)return`${(e/1000).toFixed(2)}s`;return`${Math.max(e,0).toFixed(1)}ms`}function W(e,n,t){return t?`${n}${e}\x1B[0m`:e}function Kt(e,n){let t=Ht(e)==="Development";return W(e,t?"\x1B[32m":"\x1B[33m",n)}function re(e){if(e.color!==void 0)return e.color;if(Object.hasOwn(process.env,"NO_COLOR"))return!1;if(process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0")return!0;return(e.stream==="stdout"?process.stdout:process.stderr).isTTY&&process.env.TERM!=="dumb"}function Ht(e){let n=e.trim().toLowerCase();if(n==="development")return"Development";if(n==="production")return"Production";return e.trim()}var ys=180000,vs=`Timed out waiting for browser login to complete.
88
+ }`}function wn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function Ct(e,n){return`${e}…${n.slice(-4)}`}var yn=["ap-southeast-1","eu-west-1","us-east-1"],At=["eu-west-1"];var Pt=1,Tt=0,xt=60000,Qe=15000;function ee(e,n){return new Promise((t)=>{if(n?.aborted)return t();let o=setTimeout(t,e);n?.addEventListener("abort",()=>{clearTimeout(o),t()},{once:!0})})}function ie(){let e=globalThis.WebSocket;if(!e)throw Error("WebSocket is not available in this environment.");return e}class A extends Error{}async function*en(e,n={}){let t=new Set,o=500,r=0,s=Date.now();while(!n.signal?.aborted){let i=!1,a="the log stream closed";try{for await(let c of es(e,n,()=>{i=!0})){let d=`${c.ts}|${c.eventType}|${c.message}`;if(t.has(d))continue;if(t.add(d),t.size>5000)t.delete(t.values().next().value);yield c}}catch(c){if(n.signal?.aborted)return;if(a=c instanceof Error?c.message:String(c),c instanceof A||/unauthorized|invalid websocket token|scope does not match/i.test(a))throw c}if(n.signal?.aborted)return;if(i)o=500,r=0,s=Date.now();if(!n.keepReconnecting&&Date.now()-s>=xt)throw Error(`Gave up reconnecting to the live logs after ${xt/1000} s. Last error: ${a}`);r+=1,n.onReconnect?.(r,a),await ee(o,n.signal),o=Math.min(o*2,5000)}}async function*es(e,n,t){let{backfill:o=0,minLevel:r,sandboxId:s,signal:i}=n,a=n.liveOnly??o<=0;if(i?.aborted)return;let c=[],d=null,l=!1,w=null,u=()=>{w?.(),w=null},{socket:P,url:j}=_t(e,await e.credential()),I=setTimeout(()=>{d=Error(`The observability gateway did not answer within ${Qe/1000} s.`),l=!0,u()},Qe),W=()=>{if(clearTimeout(I),P.readyState===Pt||P.readyState===Tt)P.close(1000,"client closed");i?.removeEventListener("abort",te)},te=()=>{l=!0,u(),W()};i?.addEventListener("abort",te,{once:!0}),P.onopen=()=>{if(i?.aborted){W();return}let Q={type:"subscribe",stream:"logs",...o>0?{backfill:o}:{},...a?{liveOnly:!0}:{},...r!==void 0?{minLevel:r}:{},...s!==void 0?{sandboxId:s}:{}};P.send(JSON.stringify(Q))},P.onmessage=(Q)=>{let we=Dt(Q.data);if(!we)return;if(clearTimeout(I),we.type!=="error")t();switch(we.type){case"backfill":if(we.stream==="logs"){for(let Po of we.entries)c.push(Po);u()}break;case"log":c.push(we.entry),u();break;case"error":d=Error(`Observability gateway error: ${we.error}`),l=!0,u();break;case"ready":break;default:break}},P.onerror=()=>{d=Error(`Cannot connect to the observability gateway at ${j}.`),l=!0,u()},P.onclose=(Q)=>{if(!l){if(Q.code!==1000)d=jt(Q);l=!0,u()}};try{while(!0){if(c.length>0){yield c.shift();continue}if(d)throw d;if(l)return;await new Promise((Q)=>{w=Q})}}finally{W()}}async function It(e,n){let{socket:t,url:o}=_t(e,await e.credential());return new Promise((r,s)=>{let i=!1,a=(l)=>{if(i)return;if(i=!0,clearTimeout(d),t.readyState===Pt||t.readyState===Tt)t.close(1000,"client closed");l()},c=(l)=>a(()=>s(l)),d=setTimeout(()=>{c(Error(`The observability gateway did not answer within ${Qe/1000} s.`))},Qe);t.onopen=()=>{let l={type:"fetchTrace",traceId:n};t.send(JSON.stringify(l))},t.onmessage=(l)=>{let w=Dt(l.data);if(w?.type==="error")c(Error(`Observability gateway error: ${w.error}`));else if(w?.type==="backfill"&&w.stream==="traces"){let u=w.entries;if(w.error)c(Error(w.error));else a(()=>r(u))}},t.onerror=()=>{c(Error(`Cannot connect to the observability gateway at ${o}.`))},t.onclose=(l)=>c(jt(l))})}function _t(e,n){let t=ns(e.baseUrl,e.project,e.stage);return{socket:new(ie())(t,E(n)),url:t}}function jt(e){return Error(e.reason?`Observability WebSocket closed: ${e.reason}`:`Observability WebSocket closed with code ${e.code}.`)}function ns(e,n,t){return`${K(e)}/v1/projects/${encodeURIComponent(n)}/stages/${encodeURIComponent(t)}/observability/ws`}function Dt(e){if(typeof e!=="string")return null;try{let n=JSON.parse(e);return typeof n==="object"&&n!==null&&typeof n.type==="string"?n:null}catch{return null}}var ts=new Set(["bundle","bundleStorageId","contentBase64"]),os=new Set(["hook","mcp","skill"]),rs=30000;class tn extends Error{}class on extends Error{}class X{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=f(e.baseUrl),this.token=e.token,this.fetchImpl=e.fetch??fetch}async getManifest(e,n){let t=await this.request(e,n,"/manifest",{method:"GET"});if(t.status===404)return null;return await Y(t,"Fetch manifest failed"),await t.json()}async putManifest(e,n,t=!1,o){let r=await this.externalizeLargeMcpBundles(e),s=await this.request(e.project,e.stage,"/manifest",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({manifest:r,prune:n,rotateRuntimeKey:t,...o!==void 0?{revision:o}:{}})},null);return await Y(s,"Sync manifest failed"),await s.json()}async externalizeLargeMcpBundles(e){if(e.resources.every((t)=>Lt(t)===null))return e;let n=await Promise.all(e.resources.map(async(t)=>{let o=Lt(t);if(o===null)return t;let{bundle:r,...s}=t.config,i=await this.uploadMcpBundle(e.project,e.stage,o);return{...t,config:{...s,bundleStorageId:i,sha256:_e(o)}}}));return{...e,resources:n}}async uploadMcpBundle(e,n,t){let o=await this.request(e,n,"/mcp-bundle-uploads",{method:"POST"});await Y(o,"Mint bundle upload URL failed");let{uploadUrl:r}=await o.json();if(!r)throw Error("Mint bundle upload URL failed: response omitted uploadUrl");let s=await this.send(r,{method:"POST",headers:{"Content-Type":"application/javascript"},body:t},null);await Y(s,"Bundle upload failed");let{storageId:i}=await s.json();if(!i)throw Error("Bundle upload failed: response omitted storageId");return i}async getRuntimeKey(e,n){let t=await this.request(e,n,"/runtime-key",{method:"GET"});if(t.status===404)return null;await Y(t,"Fetch runtime key failed");let o=await t.json();if(!o.apiKey)throw Error("Fetch runtime key failed: response omitted apiKey");return{apiKey:o.apiKey,keyHint:o.keyHint??"",...o.endpointId?{endpointId:o.endpointId}:{},...o.projectSlug?{projectSlug:o.projectSlug}:{},...o.stageSlug?{stageSlug:o.stageSlug}:{}}}async rotateUserTokenSecret(e,n){let t=await this.request(e,n,"/user-token-secret",{method:"POST"});if(t.status===404)return null;await Y(t,"Rotate user token signing secret failed");let o=await t.json();if(!o.secret||!o.hint)throw Error("Rotate user token signing secret failed: response omitted the secret");return{secret:o.secret,hint:o.hint}}async setEnv(e,n,t,o){let r=await this.request(e,n,`/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:o})});await Y(r,"Set environment variable failed")}async listEnv(e,n){let t=await this.request(e,n,"/env",{method:"GET"});return await Y(t,"List environment variables failed"),(await t.json()).variables??[]}async getEnv(e,n,t){let o=await this.request(e,n,`/env/${encodeURIComponent(t)}`,{method:"GET"});if(o.status===404)return null;return await Y(o,"Read environment variable failed"),(await o.json()).value??null}async removeEnv(e,n,t){let o=await this.request(e,n,`/env/${encodeURIComponent(t)}`,{method:"DELETE"});await Y(o,"Remove environment variable failed")}async getOnboarding(){let e=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return ye(e,"/v1/account/onboarding","broods org"),await Y(e,"Fetch CLI onboarding context failed"),await e.json()}async selectOnboardingOrg(e){let n=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({orgId:e})});return await Y(n,"Select CLI org failed"),await n.json()}async listStages(e){let n=await this.send(`${this.baseUrl}/v1/account/stages?project=${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return ye(n,"/v1/account/stages","broods stage"),await Y(n,"List stages failed"),(await n.json()).stages??[]}async createStage(e,n,t){let o=await this.send(`${this.baseUrl}/v1/account/stages`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({project:e,name:n,...t?{from:t}:{}})});return ye(o,"/v1/account/stages","broods stage"),await Y(o,"Create stage failed"),await o.json()}async mintStageSession(e,n){let t=await this.send(`${this.baseUrl}/v1/account/stage-session`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({project:e,stage:n})});ye(t,"/v1/account/stage-session","broods logs");try{await Y(t,"Open stage session failed")}catch(o){if(t.status===401||t.status===404)throw new A(o instanceof Error?o.message:String(o));throw o}return await t.json()}async listProjects(){let e=await this.send(`${this.baseUrl}/v1/account/projects`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return ye(e,"/v1/account/projects","broods project"),await Y(e,"List projects failed"),(await e.json()).projects??[]}async deleteProject(e){let n=await this.send(`${this.baseUrl}/v1/account/projects?projectId=${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`}});if(ye(n,"/v1/account/projects","broods project"),n.status===404)return null;return await Y(n,"Delete project failed"),(await n.json()).deleted??null}async githubStatus(e){return await this.github("GET","",e)}async githubRepos(e){return(await this.github("GET","/repos",e)).repos}async githubLink(e,n){return(await this.github("POST","/link",e,n)).repo}async githubUnlink(e){await this.github("DELETE","/link",e)}async githubConnect(){return await this.github("POST","/connect")}async createOnboardingOrg(e){let n=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({createOrgName:e})});return await Y(n,"Create CLI org failed"),await n.json()}async github(e,n,t,o){let r=t?`?project=${encodeURIComponent(t)}`:"",s=await this.send(`${this.baseUrl}/v1/account/github${n}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,...o===void 0?{}:{"Content-Type":"application/json"}},body:o===void 0?void 0:JSON.stringify(o)},e==="POST"?120000:void 0);return ye(s,"/v1/account/github","broods github"),await Y(s,`GitHub ${e} ${n||"status"} failed`),await s.json()}async request(e,n,t,o,r){let s=`${this.baseUrl}/v1/account/projects/${encodeURIComponent(e)}/stages/${encodeURIComponent(n)}${t}`;return await this.send(s,{...o,headers:{Authorization:`Bearer ${this.token}`,...o.headers}},r)}async send(e,n,t){return await rn(e,n,{fetch:this.fetchImpl,timeoutMs:t})}}async function rn(e,n,t={}){let o=t.fetch??fetch,r=t.timeoutMs===void 0?rs:t.timeoutMs;try{return await o(e,r===null?n:{...n,signal:AbortSignal.timeout(r)})}catch(s){throw Error(`Cannot reach ${new URL(e).origin}: ${as(s,r)}`,{cause:s})}}function $n(e,n){let t=new Map((n?.resources??[]).map((d)=>[`${d.kind}:${d.name}`,d])),o=new Map(e.resources.map((d)=>[`${d.kind}:${d.name}`,d])),r=[],s=[],i=[];for(let[d,l]of o){let w=t.get(d);if(!w)s.push({key:d,resource:l});else if(nn(Sn(w))!==nn(Sn(l)))r.push({operation:"update",kind:l.kind,name:l.name})}for(let[d,l]of t)if(!o.has(d))i.push({key:d,resource:l});let a=new Set,c=new Set;for(let d of s){let l=i.find((w)=>!a.has(w.key)&&ss(d.resource.kind)&&d.resource.kind===w.resource.kind&&nn(Ut(d.resource))===nn(Ut(w.resource)));if(!l)continue;c.add(d.key),a.add(l.key),r.push({operation:"rename",kind:d.resource.kind,name:d.resource.name,previousName:l.resource.name})}for(let{key:d,resource:l}of s)if(!c.has(d))r.push({operation:"create",kind:l.kind,name:l.name});for(let{key:d,resource:l}of i)if(!a.has(d))r.push({operation:"delete",kind:l.kind,name:l.name});return r.sort((d,l)=>Nt(d).localeCompare(Nt(l)))}function Nt(e){return`${{create:0,rename:1,update:2,delete:3}[e.operation]}:${e.kind}:${e.previousName??""}:${e.name}`}function ss(e){return e==="agent"||e==="workspace"||e==="sandbox"||e==="policy"}function vn(e){if(Array.isArray(e))return e.map(vn);if(e&&typeof e==="object"){let n=e;if(n.__beeblastEnv===!0&&typeof n.name==="string")return`\${${n.name}}`;return Object.fromEntries(Object.entries(n).map(([t,o])=>[t,vn(o)]))}return e}function Ut(e){let n=Sn(e),{name:t,...o}=n;return o}function Sn(e){let n=vn(e);if(!os.has(e.kind))return n;return{...n,config:En(n.config)}}function kn(e){if(Array.isArray(e))return e.map(kn);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>[n,kn(t)]));return e}function nn(e){return JSON.stringify(kn(e))}function En(e){if(Array.isArray(e))return e.map(En);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).flatMap(([n,t])=>{if(ts.has(n))return[];return[[n,En(t)]]}));return e}async function Y(e,n){if(e.ok)return;let t=await e.text(),{message:o=t,code:r}=is(t);if(r==="manifest_conflict")throw new tn(o);let s=e.status===401?"\nRun `broods login` to sign in again.":"";throw Error(`${n}: ${e.status} ${o}${s}`)}function is(e){let n;try{n=JSON.parse(e)}catch{return{}}let t=typeof n==="object"&&n!==null&&"error"in n?n.error:void 0;if(typeof t!=="object"||t===null)return{};return{..."message"in t&&typeof t.message==="string"?{message:t.message}:{},..."code"in t&&typeof t.code==="string"?{code:t.code}:{}}}function ye(e,n,t){if(e.status!==404)return;if((e.headers.get("Content-Type")??"").includes("application/json"))return;throw new on(`This broods server is older than your CLI and does not support \`${t}\` yet (no ${n} route).`)}function as(e,n){if(!(e instanceof Error))return String(e);if(e.name==="TimeoutError"&&n!==null)return`no answer within ${n/1000} s`;let t=e.cause;if(!(t instanceof Error))return e.message;if(t.message)return t.message;return"code"in t&&typeof t.code==="string"?t.code:e.message}function Lt(e){if(e.kind!=="mcp")return null;let n=e.config?.bundle;if(typeof n!=="string")return null;return Buffer.byteLength(n)>bn?n:null}var sn=["chatgpt"];var ve={chatgpt:{label:"ChatGPT plan",description:"Run agents on model.provider chatgpt with your ChatGPT plan",authorizeUrl:"https://auth.openai.com/api/accounts/authorize",tokenUrl:"https://auth.openai.com/api/accounts/oauth/token",revokeUrl:"https://auth.openai.com/api/accounts/oauth/revoke",jwksUrl:"https://auth.openai.com/.well-known/jwks.json",issuer:"https://auth.openai.com",scopes:["openid","profile","email","offline_access","resource.invoke","chatgpt.tokens.use.direct"],resource:"https://api.openai.com/v1",requiredScope:"chatgpt.tokens.use.direct",selfHostedOnly:"ChatGPT plan usage is only available on self-hosted Broods for now. Use an OpenAI API key with the `openai` provider instead.",managedOptIn:"CHATGPT_PLAN_ENABLED",modelsUrl:"https://api.openai.com/v1/models",usageUrl:"https://chatgpt.com/settings/usage"}};function Rn(e){return sn.some((n)=>n===e)}import{createHash as Cs,randomBytes as As,randomUUID as Jt}from"node:crypto";import{createServer as ms}from"node:http";import{createHash as hs,randomBytes as bs,randomUUID as ws}from"node:crypto";import{spawn as ys}from"node:child_process";import{createInterface as Ue}from"node:readline/promises";import{stdin as ue,stdout as de}from"node:process";import{Writable as vs}from"node:stream";function Ce(e,n,t={}){let o=`${n?"*":" "} ${e}`;return n?G(o,"\x1B[1m\x1B[36m",se(t)):o}function Mt(e,n={}){let t=se(n),o=(i)=>G(i.padEnd(9),"\x1B[2m",t),r=!e.loggedIn?G("not logged in","\x1B[33m",t):e.org??G("unknown, run broods whoami","\x1B[2m",t),s=e.project??`none ${G(`(${e.projectGuess} from folder name)`,"\x1B[2m",t)}`;return[` ${o("org")}${r}`,` ${o("project")}${s}`,` ${o("stage")}${Ht(e.stage,t)}`,` ${o("server")}${e.server}`]}function cs(e,n={}){let t=se(n),o=Kt(e.stage),r=o==="Development",s=G("▌",r?"\x1B[32m":"\x1B[33m",t),i=t?`${r?"\x1B[42m\x1B[30m\x1B[1m":"\x1B[43m\x1B[30m\x1B[1m"} ${o} \x1B[0m`:`[${o}]`,a=t?G("dashboard","\x1B[4m",t):"dashboard",c=`${e.dashboardUrl}?project=${encodeURIComponent(e.project)}&stage=${encodeURIComponent(e.stage)}`,d=G(c,"\x1B[2m\x1B[4m",t);return[`${s} Syncing ${o}: ${G(e.project,"",t)}`,`${s} ${i} ${e.stage} (${a})`,`${s} ${G("└─","\x1B[2m",t)} ${d}`].join(`
89
+ `)}function ls(e,n={}){let t=se(n);return e.map((o)=>{let r=fs(o.operation,t);if(o.operation==="rename"&&o.previousName)return` ${r} ${o.kind}:${o.previousName} -> ${o.name}`;return` ${r} ${o.kind}:${o.name}`})}function ds(e,n={}){let t=se(n),o=G("▌","\x1B[32m",t),r=G("↑","\x1B[32m",t);return`${o} ${r} Synced ${e.length} env var(s) from .env.local: ${e.join(", ")}`}function us(e,n={}){return`${G("✖","\x1B[31m",se(n))} ${e}`}function Bt(e,n={}){let t=se(n),o=Math.max(...e.map(([r])=>r.length))+2;return e.map(([r,s])=>` ${r.padEnd(o)}${G(s,"\x1B[2m",t)}`)}function gs(e,n={}){let t=(n.now??new Date).toTimeString().slice(0,8);return`${G("✔","\x1B[32m",se(n))} ${t} Resources ready! (${An(e)})`}function ps(e,n={}){return`${G("✔","\x1B[32m",se(n))} ${e}`}function On(e,n,t={}){let o=se(t),r=t.note?` ${G(`(${t.note})`,"\x1B[2m",o)}`:"";return` ${G("now","\x1B[2m",o)} ${e} → ${Ht(n,o)}${r}`}function Ne(e,n={}){return G(`! ${e}`,"\x1B[33m",se(n))}function Gt(e){console.error(cs(e))}function an(e){for(let n of ls(e))console.log(n)}function Cn(e){console.error(ds(e))}function Wt(e){console.error(us(e,{stream:"stderr"}))}function Ft(e){console.error(gs(e))}function q(e){console.log(ps(e,{stream:"stdout"}))}function D(e){console.log(Ne(e,{stream:"stdout"}))}function fs(e,n){if(e==="create")return`[${G("+","\x1B[32m",n)}]`;if(e==="rename")return`[${G("~","\x1B[33m",n)}]`;if(e==="update")return`[${G("*","\x1B[36m",n)}]`;return`[${G("-","\x1B[31m",n)}]`}function An(e){if(e>=1000)return`${(e/1000).toFixed(2)}s`;return`${Math.max(e,0).toFixed(1)}ms`}function G(e,n,t){return t?`${n}${e}\x1B[0m`:e}function Ht(e,n){let t=Kt(e)==="Development";return G(e,t?"\x1B[32m":"\x1B[33m",n)}function se(e){if(e.color!==void 0)return e.color;if(Object.hasOwn(process.env,"NO_COLOR"))return!1;if(process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0")return!0;return(e.stream==="stdout"?process.stdout:process.stderr).isTTY&&process.env.TERM!=="dumb"}function Kt(e){let n=e.trim().toLowerCase();if(n==="development")return"Development";if(n==="production")return"Production";return e.trim()}var Ss=180000,ks=`Timed out waiting for browser login to complete.
92
90
  Check the browser tab and the dashboard logs for an error. If the browser shows
93
91
  404 on /cli-auth/start, deploy the dashboard build that includes CLI auth or pass
94
92
  --dashboard-url for the environment you deployed. Other common causes are missing
95
- cliAuth Convex functions or no active API account (Organization settings -> API access).`,Vt=new Set(["--base-url","--cwd","--dashboard-url","--stage","--from","--level","--limit","--mcp","--project","--region","--sandbox","-n"]);function Ss(e,n=process.platform){if(n==="darwin")return{command:"open",args:[e]};if(n==="win32")return{command:"rundll32",args:["url.dll,FileProtocolHandler",e]};return{command:"xdg-open",args:[e]}}function V(e,n){let t=Vt.has(n)?`${n}=`:null;return e.some((o)=>o===n||t!==null&&o.startsWith(t))}function ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function R(e,n){for(let t=0;t<e.length;t+=1){let o=e[t];if(o===n)return e[t+1];if(o?.startsWith(`${n}=`))return o.slice(n.length+1)||void 0}return}function se(e){let n=[];for(let t=0;t<e.length;t+=1){let o=e[t];if(o===void 0)continue;if(Vt.has(o)){t+=1;continue}if(o.startsWith("-"))continue;n.push(o)}return n}async function An(e){let n=hs(),t=ms(32).toString("base64url"),o=fs("sha256").update(t).digest("base64url"),{code:r,close:s}=await Pn(n,{port:ks(),fixedPort:Boolean(process.env.BROODS_LOGIN_PORT),path:"/callback",read:$s,done:"broods CLI login complete. You can close this tab."});try{let i=r.callbackUrl,a=`${f(e)}/cli-auth/start?`+new URLSearchParams({callback:i,state:n,code_challenge:o});await Es(a),console.log(`Opening ${a}`),xn(a);let c=await Tn(r.promise),l=await nn(`${c.baseUrl}/v1/account/auth/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:c.code,code_verifier:t})});if(!l.ok)throw Error(`Login exchange failed: ${l.status} ${await l.text()}`);let d=await l.json(),w={baseUrl:c.baseUrl,dashboardUrl:f(e),token:d.token,createdAt:new Date().toISOString(),...d.user?{user:d.user}:{},...d.org?{org:d.org}:{},...d.account?{account:d.account}:{}};return await B(w),w}finally{s()}}async function ae(e){m();let n=k(e);if(!n){let t=process.env.BROODS_DASHBOARD_URL,o=e??process.env.BROODS_BASE_URL??(t?O(t):void 0);throw Error(o?`Not logged in to ${f(o)}. Run \`broods login\`.`:"Run `broods login` first, or set BROODS_TOKEN and BROODS_BASE_URL.")}return n}async function rn(e){if(!de.isTTY)return!1;let n=Ne({input:de,output:le});try{let t=(await n.question(`${e} [y/N] `)).trim().toLowerCase();return t==="y"||t==="yes"}finally{n.close()}}async function Yt(e){le.write(`${e}: `);let n=new ws({write:(r,s,i)=>i()}),t=de.isTTY===!0,o=Ne({input:de,output:n,terminal:t,crlfDelay:1/0});try{let r=[];for await(let i of o)if(r.push(i),t)break;let s=r.join(`
96
- `);if(!s)throw Error(`${e} is required`);return s}finally{o.close(),le.write(`
97
- `)}}async function Ue(e,n,t,o){if(n.length===0)throw Error(`${e}: no options available`);if(n.length===1)return n[0];let r=o!==void 0&&o>=0&&o<n.length?o:void 0;console.log(e),n.forEach((a,c)=>{console.log(Ce(`${c+1}. ${t(a)}`,c===r))});let s=r===void 0?`Choose 1-${n.length}: `:`Choose 1-${n.length} [${r+1}]: `,i=Ne({input:de,output:le});try{for(;;){let a=(await i.question(s)).trim();if(a===""&&r!==void 0)return n[r];let c=Number(a);if(Number.isInteger(c)&&c>=1&&c<=n.length)return n[c-1];console.log(`Enter a number from 1 to ${n.length}.`)}}finally{i.close()}}async function zt(e,n,t,o){console.log(e),n.forEach((i,a)=>{console.log(` ${a+1}. ${t(i)}`)});let r=n.length>0?`Choose 1-${n.length}, or `:"",s=Ne({input:de,output:le});try{let i=(await s.question(`${r}${o.hint} [${o.defaultValue}]: `)).trim();if(i==="")return o.defaultValue;let a=Number(i);if(Number.isInteger(a)&&a>=1&&a<=n.length)return n[a-1];return i}finally{s.close()}}async function ve(e,n){if(!de.isTTY)return n??"";let t=Ne({input:de,output:le});try{let o=t.question(`${e}: `);if(n){if(de.isTTY&&le.isTTY)le.write("\x1B[90m");if(t.write(n),de.isTTY&&le.isTTY)le.write("\x1B[0m")}return(await o).trim()||n||""}finally{t.close()}}function xn(e){let{command:n,args:t}=Ss(e),o=bs(n,t,{stdio:"ignore",detached:!0});o.on("error",(r)=>{console.error(De(`Could not open a browser (${r.message}). Open the URL above to continue.`,{stream:"stderr"}))}),o.unref()}function Pn(e,n){return new Promise((t,o)=>{let r=ps((c,l)=>{let d=new URL(c.url??"/","http://127.0.0.1");if(d.pathname!==n.path||d.searchParams.get("state")!==e){l.writeHead(400).end("Invalid callback.");return}try{let w=n.read(d.searchParams);l.writeHead(200,{"Content-Type":"text/plain"}).end(n.done),s(w)}catch(w){l.writeHead(400,{"Content-Type":"text/plain"}).end(w instanceof Error?w.message:String(w)),i(w)}}),s,i,a=new Promise((c,l)=>{s=c,i=l});r.on("error",(c)=>{if(!n.fixedPort&&n.port!==0&&c.code==="EADDRINUSE"){r.listen(0,"127.0.0.1");return}o(c)}),r.listen(n.port,"127.0.0.1",()=>{let c=r.address();if(!c||typeof c==="string"){o(Error("Failed to allocate callback port"));return}t({code:{callbackUrl:`http://127.0.0.1:${c.port}${n.path}`,promise:a},close:()=>r.close()})})})}async function Tn(e,n=vs){let t,o=new Promise((r,s)=>{t=setTimeout(()=>s(Error(n)),ys)});try{return await Promise.race([e,o])}finally{if(t)clearTimeout(t)}}async function Es(e){let n=await nn(e,{method:"GET",redirect:"manual"});if(n.status===404){let t=new URL(e);throw Error(`${t.origin} has no broods login page. Check that --dashboard-url points at your broods dashboard.`)}if(n.status>=500)throw Error(`The broods login page failed: ${n.status} ${await n.text()}`)}function ks(){let e=process.env.BROODS_LOGIN_PORT;if(e){let n=Number(e);if(Number.isInteger(n)&&n>0&&n<65536)return n;throw Error("BROODS_LOGIN_PORT must be a TCP port number")}return 18987}function $s(e){let n=e.get("error");if(n)throw Error(`Login failed: ${n}`);let t=e.get("code");if(!t)throw Error("Login callback carried no code.");let o=e.get("base_url");if(!o)throw Error("Login callback did not advertise the API base URL (base_url). Deploy a dashboard build that includes the Convex-direct CLI auth flow.");return{code:t,baseUrl:f(o)}}var Cs=1455,As="/auth/callback";async function qt(e,n,t=xn){let o=we[n].label,r=Jt(),s=Jt(),i=Os(32).toString("base64url"),{code:a,close:c}=await Pn(r,{port:Cs,fixedPort:!1,path:As,read:xs,done:`${o} is connected to broods. You can close this tab.`});try{let l=a.callbackUrl,d=await e.startConnection(n,{redirectUri:l,codeChallenge:Rs("sha256").update(i).digest("base64url"),state:r,nonce:s});t(d.authorizeUrl),console.log(`Opening ${d.authorizeUrl}`);let w=await Tn(a.promise,`Timed out waiting for the ${o} sign-in to finish in the browser.`);return await e.connect(n,{code:w.code,codeVerifier:i,redirectUri:l,nonce:s,clientId:w.clientId??d.clientId,hostId:d.hostId})}finally{c()}}function xs(e){let n=e.get("error");if(n)throw Error(`Sign-in failed: ${e.get("error_description")??n}`);let t=e.get("code");if(!t)throw Error("Sign-in callback carried no code.");return{code:t,clientId:e.get("client_id")??void 0}}import{existsSync as Zt}from"node:fs";import{mkdir as Ts,readFile as _s,writeFile as Is}from"node:fs/promises";import{dirname as Qt,join as jn,resolve as js,sep as he}from"node:path";import{fileURLToPath as Ds}from"node:url";var Le={name:"broods",version:"0.54.1",description:"CLI + TypeScript SDK for the broods agent platform.",keywords:["agents","ai","broods","cli","sdk"],homepage:"https://github.com/beeblastco/broods#readme",bugs:{url:"https://github.com/beeblastco/broods/issues"},license:"MIT",repository:{type:"git",url:"git+https://github.com/beeblastco/broods.git",directory:"packages/broods"},bin:{broods:"dist/cli/index.js"},files:["dist","README.md","LICENSE.md"],type:"module",main:"./dist/index.js",types:"./dist/index.d.ts",typesVersions:{"*":{account:["./dist/account.d.ts"]}},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./account":{types:"./dist/account.d.ts",import:"./dist/account.js"}},scripts:{build:"bun scripts/build.ts && rollup -c rollup.dts.config.mjs && rm -rf .dts-temp",check:"tsc --noEmit && tsc --noEmit -p tsconfig.scripts.json","pack:check":"bun run build && publint && attw --pack .",prepublishOnly:"bun run build",test:"bun test","test:desktop":"BROODS_TEST_DESKTOP=1 bun test tests/cli-desktop.test.ts"},dependencies:{"@modelcontextprotocol/client":"^2.3.1",esbuild:"^0.28.2"},devDependencies:{"@ai-sdk/tui":"1.0.155","@arethetypeswrong/cli":"^0.18.5","@chat-adapter/discord":"^4.43.0","@chat-adapter/github":"^4.43.0","@chat-adapter/slack":"^4.43.0","@chat-adapter/telegram":"^4.43.0","@modelcontextprotocol/server":"2.4.0","@types/bun":"^1.4.4","@typescript/typescript6":"6.0.2",ai:"^7.0.154",publint:"^0.3.25",rollup:"^4.65.0","rollup-plugin-dts":"^6.5.1",typescript:"^7.0.2",zod:"^4.6.7"},peerDependencies:{ai:"^7.0.154"},engines:{node:">=22.15"}};var _n=jn(Qt(z),"update-check.json"),Ns=86400000,Us="https://registry.npmjs.org/broods/latest",Ls=2000,Ms=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"]];function Dn(e,n){let t=In(e),o=In(n);for(let r=0;r<3;r+=1){let s=t[r]??0,i=o[r]??0;if(s!==i)return s>i}return!Xt(e)&&Xt(n)}async function Nn(e={}){let n=await Gs(),t=e.maxAgeMs??Ns;if(n&&Date.now()-n.checkedAt<t)return n.latest;let o=await Bs();if(o===null)return n?.latest??null;return await Fs({checkedAt:Date.now(),latest:o}),o}function Me(e){return In(e)[0]??0}function eo(e=js(process.cwd()),n=Ds(import.meta.url),t=Le.version){let o=`${he}node_modules${he}`,r=n.indexOf(o),s=r===-1?null:n.slice(0,r),i=s===null?n.startsWith(`${e}${he}`):e===s||e.startsWith(`${s}${he}`),a=n.includes(`${he}.bun${he}install${he}global${he}`),c=s??e,l=i?Ws(c):a?"bun":"npm",d=l==="npm"?"install":"add",w=l==="pnpm"&&Zt(jn(c,"pnpm-workspace.yaml"))?["-w"]:[],u=`broods@${Me(t)}`;return{manager:l,global:!i,command:l,cwd:i?c:e,args:i?[d,...w,u]:[d,"-g",u]}}async function Bs(){try{let e=await fetch(Us,{signal:AbortSignal.timeout(Ls),headers:{accept:"application/json"}});if(!e.ok)return null;let n=await e.json();return typeof n.version==="string"?n.version:null}catch{return null}}function Xt(e){return e.includes("-")}async function Gs(){try{let e=JSON.parse(await _s(_n,"utf8"));if(typeof e.latest!=="string")return null;if(typeof e.checkedAt!=="number")return null;return{checkedAt:e.checkedAt,latest:e.latest}}catch{return null}}function Ws(e){return Ms.find(([t])=>Zt(jn(e,t)))?.[1]??"npm"}function In(e){let[n]=e.trim().replace(/^v/,"").split("-");return(n??"").split(".").slice(0,3).map((t)=>Number.parseInt(t,10)||0)}async function Fs(e){try{await Ts(Qt(_n),{recursive:!0}),await Is(_n,`${JSON.stringify(e)}
93
+ cliAuth Convex functions or no active API account (Organization settings -> API access).`,Vt=new Set(["--base-url","--cwd","--dashboard-url","--development-branch","--folder","--production-branch","--stage","--from","--level","--limit","--mcp","--project","--region","--sandbox","-n"]);function Es(e,n=process.platform){if(n==="darwin")return{command:"open",args:[e]};if(n==="win32")return{command:"rundll32",args:["url.dll,FileProtocolHandler",e]};return{command:"xdg-open",args:[e]}}function V(e,n){let t=Vt.has(n)?`${n}=`:null;return e.some((o)=>o===n||t!==null&&o.startsWith(t))}function Se(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function R(e,n){for(let t=0;t<e.length;t+=1){let o=e[t];if(o===n)return e[t+1];if(o?.startsWith(`${n}=`))return o.slice(n.length+1)||void 0}return}function re(e){let n=[];for(let t=0;t<e.length;t+=1){let o=e[t];if(o===void 0)continue;if(Vt.has(o)){t+=1;continue}if(o.startsWith("-"))continue;n.push(o)}return n}async function xn(e){let n=ws(),t=bs(32).toString("base64url"),o=hs("sha256").update(t).digest("base64url"),{code:r,close:s}=await Pn(n,{port:Rs(),fixedPort:Boolean(process.env.BROODS_LOGIN_PORT),path:"/callback",read:Os,done:"broods CLI login complete. You can close this tab."});try{let i=r.callbackUrl,a=`${f(e)}/cli-auth/start?`+new URLSearchParams({callback:i,state:n,code_challenge:o});await $s(a),console.log(`Opening ${a}`),Be(a);let c=await Tn(r.promise),d=await rn(`${c.baseUrl}/v1/account/auth/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:c.code,code_verifier:t})});if(!d.ok)throw Error(`Login exchange failed: ${d.status} ${await d.text()}`);let l=await d.json(),w={baseUrl:c.baseUrl,dashboardUrl:f(e),token:l.token,createdAt:new Date().toISOString(),...l.user?{user:l.user}:{},...l.org?{org:l.org}:{},...l.account?{account:l.account}:{}};return await F(w),w}finally{s()}}async function ae(e){m();let n=k(e);if(!n){let t=process.env.BROODS_DASHBOARD_URL,o=e??process.env.BROODS_BASE_URL??(t?O(t):void 0);throw Error(o?`Not logged in to ${f(o)}. Run \`broods login\`.`:"Run `broods login` first, or set BROODS_TOKEN and BROODS_BASE_URL.")}return n}async function Le(e){if(!ue.isTTY)return!1;let n=Ue({input:ue,output:de});try{let t=(await n.question(`${e} [y/N] `)).trim().toLowerCase();return t==="y"||t==="yes"}finally{n.close()}}async function Yt(e){de.write(`${e}: `);let n=new vs({write:(r,s,i)=>i()}),t=ue.isTTY===!0,o=Ue({input:ue,output:n,terminal:t,crlfDelay:1/0});try{let r=[];for await(let i of o)if(r.push(i),t)break;let s=r.join(`
94
+ `);if(!s)throw Error(`${e} is required`);return s}finally{o.close(),de.write(`
95
+ `)}}async function Me(e,n,t,o){if(n.length===0)throw Error(`${e}: no options available`);if(n.length===1)return n[0];let r=o!==void 0&&o>=0&&o<n.length?o:void 0;console.log(e),n.forEach((a,c)=>{console.log(Ce(`${c+1}. ${t(a)}`,c===r))});let s=r===void 0?`Choose 1-${n.length}: `:`Choose 1-${n.length} [${r+1}]: `,i=Ue({input:ue,output:de});try{for(;;){let a=(await i.question(s)).trim();if(a===""&&r!==void 0)return n[r];let c=Number(a);if(Number.isInteger(c)&&c>=1&&c<=n.length)return n[c-1];console.log(`Enter a number from 1 to ${n.length}.`)}}finally{i.close()}}async function zt(e,n,t,o){console.log(e),n.forEach((i,a)=>{console.log(` ${a+1}. ${t(i)}`)});let r=n.length>0?`Choose 1-${n.length}, or `:"",s=Ue({input:ue,output:de});try{let i=(await s.question(`${r}${o.hint} [${o.defaultValue}]: `)).trim();if(i==="")return o.defaultValue;let a=Number(i);if(Number.isInteger(a)&&a>=1&&a<=n.length)return n[a-1];return i}finally{s.close()}}async function ke(e,n){if(!ue.isTTY)return n??"";let t=Ue({input:ue,output:de});try{let o=t.question(`${e}: `);if(n){if(ue.isTTY&&de.isTTY)de.write("\x1B[90m");if(t.write(n),ue.isTTY&&de.isTTY)de.write("\x1B[0m")}return(await o).trim()||n||""}finally{t.close()}}function Be(e){let{command:n,args:t}=Es(e),o=ys(n,t,{stdio:"ignore",detached:!0});o.on("error",(r)=>{console.error(Ne(`Could not open a browser (${r.message}). Open the URL above to continue.`,{stream:"stderr"}))}),o.unref()}function Pn(e,n){return new Promise((t,o)=>{let r=ms((c,d)=>{let l=new URL(c.url??"/","http://127.0.0.1");if(l.pathname!==n.path||l.searchParams.get("state")!==e){d.writeHead(400).end("Invalid callback.");return}try{let w=n.read(l.searchParams);d.writeHead(200,{"Content-Type":"text/plain"}).end(n.done),s(w)}catch(w){d.writeHead(400,{"Content-Type":"text/plain"}).end(w instanceof Error?w.message:String(w)),i(w)}}),s,i,a=new Promise((c,d)=>{s=c,i=d});r.on("error",(c)=>{if(!n.fixedPort&&n.port!==0&&c.code==="EADDRINUSE"){r.listen(0,"127.0.0.1");return}o(c)}),r.listen(n.port,"127.0.0.1",()=>{let c=r.address();if(!c||typeof c==="string"){o(Error("Failed to allocate callback port"));return}t({code:{callbackUrl:`http://127.0.0.1:${c.port}${n.path}`,promise:a},close:()=>r.close()})})})}async function Tn(e,n=ks){let t,o=new Promise((r,s)=>{t=setTimeout(()=>s(Error(n)),Ss)});try{return await Promise.race([e,o])}finally{if(t)clearTimeout(t)}}async function $s(e){let n=await rn(e,{method:"GET",redirect:"manual"});if(n.status===404){let t=new URL(e);throw Error(`${t.origin} has no broods login page. Check that --dashboard-url points at your broods dashboard.`)}if(n.status>=500)throw Error(`The broods login page failed: ${n.status} ${await n.text()}`)}function Rs(){let e=process.env.BROODS_LOGIN_PORT;if(e){let n=Number(e);if(Number.isInteger(n)&&n>0&&n<65536)return n;throw Error("BROODS_LOGIN_PORT must be a TCP port number")}return 18987}function Os(e){let n=e.get("error");if(n)throw Error(`Login failed: ${n}`);let t=e.get("code");if(!t)throw Error("Login callback carried no code.");let o=e.get("base_url");if(!o)throw Error("Login callback did not advertise the API base URL (base_url). Deploy a dashboard build that includes the Convex-direct CLI auth flow.");return{code:t,baseUrl:f(o)}}var xs=1455,Ps="/auth/callback";async function qt(e,n,t=Be){let o=ve[n].label,r=Jt(),s=Jt(),i=As(32).toString("base64url"),{code:a,close:c}=await Pn(r,{port:xs,fixedPort:!1,path:Ps,read:Ts,done:`${o} is connected to broods. You can close this tab.`});try{let d=a.callbackUrl,l=await e.startConnection(n,{redirectUri:d,codeChallenge:Cs("sha256").update(i).digest("base64url"),state:r,nonce:s});t(l.authorizeUrl),console.log(`Opening ${l.authorizeUrl}`);let w=await Tn(a.promise,`Timed out waiting for the ${o} sign-in to finish in the browser.`);return await e.connect(n,{code:w.code,codeVerifier:i,redirectUri:d,nonce:s,clientId:w.clientId??l.clientId,hostId:l.hostId})}finally{c()}}function Ts(e){let n=e.get("error");if(n)throw Error(`Sign-in failed: ${e.get("error_description")??n}`);let t=e.get("code");if(!t)throw Error("Sign-in callback carried no code.");return{code:t,clientId:e.get("client_id")??void 0}}import{existsSync as Zt}from"node:fs";import{mkdir as _s,readFile as js,writeFile as Ds}from"node:fs/promises";import{dirname as Qt,join as jn,resolve as Ns,sep as he}from"node:path";import{fileURLToPath as Us}from"node:url";var Ge={name:"broods",version:"0.55.0",description:"CLI + TypeScript SDK for the broods agent platform.",keywords:["agents","ai","broods","cli","sdk"],homepage:"https://github.com/beeblastco/broods#readme",bugs:{url:"https://github.com/beeblastco/broods/issues"},license:"MIT",repository:{type:"git",url:"git+https://github.com/beeblastco/broods.git",directory:"packages/broods"},bin:{broods:"dist/cli/index.js"},files:["dist","README.md","LICENSE.md"],type:"module",main:"./dist/index.js",types:"./dist/index.d.ts",typesVersions:{"*":{account:["./dist/account.d.ts"]}},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./account":{types:"./dist/account.d.ts",import:"./dist/account.js"}},scripts:{build:"bun scripts/build.ts && rollup -c rollup.dts.config.mjs && rm -rf .dts-temp",check:"tsc --noEmit && tsc --noEmit -p tsconfig.scripts.json","pack:check":"bun run build && publint && attw --pack .",prepublishOnly:"bun run build",test:"bun test","test:desktop":"BROODS_TEST_DESKTOP=1 bun test tests/cli-desktop.test.ts"},dependencies:{"@modelcontextprotocol/client":"^2.3.1",esbuild:"^0.28.2"},devDependencies:{"@ai-sdk/tui":"1.0.155","@arethetypeswrong/cli":"^0.18.5","@chat-adapter/discord":"^4.43.0","@chat-adapter/github":"^4.43.0","@chat-adapter/slack":"^4.43.0","@chat-adapter/telegram":"^4.43.0","@modelcontextprotocol/server":"2.4.0","@types/bun":"^1.4.4","@typescript/typescript6":"6.0.2",ai:"^7.0.154",publint:"^0.3.25",rollup:"^4.66.0","rollup-plugin-dts":"^6.5.1",typescript:"^7.0.2",zod:"^4.6.7"},peerDependencies:{ai:"^7.0.154"},engines:{node:">=22.15"}};var In=jn(Qt(z),"update-check.json"),Ls=86400000,Ms="https://registry.npmjs.org/broods/latest",Bs=2000,Gs=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"]];function Dn(e,n){let t=_n(e),o=_n(n);for(let r=0;r<3;r+=1){let s=t[r]??0,i=o[r]??0;if(s!==i)return s>i}return!Xt(e)&&Xt(n)}async function Nn(e={}){let n=await Fs(),t=e.maxAgeMs??Ls;if(n&&Date.now()-n.checkedAt<t)return n.latest;let o=await Ws();if(o===null)return n?.latest??null;return await Ks({checkedAt:Date.now(),latest:o}),o}function We(e){return _n(e)[0]??0}function eo(e=Ns(process.cwd()),n=Us(import.meta.url),t=Ge.version){let o=`${he}node_modules${he}`,r=n.indexOf(o),s=r===-1?null:n.slice(0,r),i=s===null?n.startsWith(`${e}${he}`):e===s||e.startsWith(`${s}${he}`),a=n.includes(`${he}.bun${he}install${he}global${he}`),c=s??e,d=i?Hs(c):a?"bun":"npm",l=d==="npm"?"install":"add",w=d==="pnpm"&&Zt(jn(c,"pnpm-workspace.yaml"))?["-w"]:[],u=`broods@${We(t)}`;return{manager:d,global:!i,command:d,cwd:i?c:e,args:i?[l,...w,u]:[l,"-g",u]}}async function Ws(){try{let e=await fetch(Ms,{signal:AbortSignal.timeout(Bs),headers:{accept:"application/json"}});if(!e.ok)return null;let n=await e.json();return typeof n.version==="string"?n.version:null}catch{return null}}function Xt(e){return e.includes("-")}async function Fs(){try{let e=JSON.parse(await js(In,"utf8"));if(typeof e.latest!=="string")return null;if(typeof e.checkedAt!=="number")return null;return{checkedAt:e.checkedAt,latest:e.latest}}catch{return null}}function Hs(e){return Gs.find(([t])=>Zt(jn(e,t)))?.[1]??"npm"}function _n(e){let[n]=e.trim().replace(/^v/,"").split("-");return(n??"").split(".").slice(0,3).map((t)=>Number.parseInt(t,10)||0)}async function Ks(e){try{await _s(Qt(In),{recursive:!0}),await Ds(In,`${JSON.stringify(e)}
98
96
  `,"utf8")}catch{}}var no=`---
99
97
  name: broods
100
98
  description: Work on a broods account alongside a developer from Claude Code or a development agent. Covers onboarding and sign-in, creating a broods project, defining and deploying agents and their resources with the CLI, and integrating a deployed agent into existing code with the SDK. Use when asked to set up broods, create or work on a broods project, create or manage agents or any account resource, or call a deployed agent from application code.
@@ -114,7 +112,7 @@ The \`broods\` CLI does the interaction: sign-in, project sync, env, logs, runni
114
112
 
115
113
  \`broods dev\` on first run does everything: scaffolds \`broods/\` with a starter agent, runs the browser login if needed, pushes model keys from \`.env.local\` to the cloud env store, syncs to the \`development\` stage, then watches for changes and tails logs. \`broods init\` and \`broods login\` exist standalone when you want the steps separate.
116
114
 
117
- A project is the \`broods/\` directory. \`broods/index.ts\` exports resources built with the \`define*\` functions: \`defineAgent\`, \`defineSandbox\`, \`defineWorkspace\`, \`defineSkill\`, \`defineCron\`, \`defineMcp\`, \`definePolicy\`, and the channel helpers. An optional \`export default defineBroods({...})\` sets project defaults like project name and stage mapping. The full reference is https://docs.broods.app/reference/configuration; the starter agent in \`broods/index.ts\` shows the minimum shape.
115
+ A project is the \`broods/\` directory. \`broods/index.ts\` exports resources built with the \`define*\` functions: \`defineAgent\`, \`defineSandbox\`, \`defineWorkspace\`, \`defineSkill\`, \`defineCron\`, \`defineMcp\`, \`definePolicy\`, \`defineHarness\`, the channel helpers, and the \`define<Provider>Connection\` helpers such as \`defineSlackConnection\`. An optional \`export default defineBroods({...})\` sets project defaults like project name and stage mapping. The full reference is https://docs.broods.app/reference/configuration; the starter agent in \`broods/index.ts\` shows the minimum shape.
118
116
 
119
117
  To create an agent, add a \`defineAgent\` to the project and sync. Talk to it with \`broods run <agent> "prompt"\`. Day to day: \`broods dev\` watches, \`broods diff\` previews, \`broods deploy\` syncs the production stage. Always \`diff\` before the first \`deploy\` on a stage you did not create.
120
118
 
@@ -138,13 +136,13 @@ When the user hands you a trace id, or a prompt copied from the dashboard's Trac
138
136
 
139
137
  ## When the CLI has no command
140
138
 
141
- Crons, skills, sandboxes, policies, roles, channels, and hooks have no CLI verb. Prefer changing them in the project definition and syncing. For one-off reads and operations a manifest cannot say, use the MCP server. \`claude mcp add broods -- broods mcp\` adds it, and its tool names mirror the SDK: \`list-agents\`, \`create-cron\`, \`update-agent\`, and so on. For scoped automation credentials, read the roles section of https://docs.broods.app/guides/security.
139
+ Crons, skills, sandboxes, policies, roles, channels, and hooks have no CLI verb. Prefer changing them in the project definition and syncing. Hooks have no MCP tool either, so they go through the project definition only. For one-off reads and operations a manifest cannot say, use the MCP server. \`claude mcp add broods -- broods mcp\` adds it, and its tool names mirror the SDK: \`list-agents\`, \`create-cron\`, \`update-agent\`, and so on. For scoped automation credentials, read the roles section of https://docs.broods.app/guides/security.
142
140
 
143
141
  ## Rules that keep you out of trouble
144
142
 
145
143
  - Say which stage you are touching before you touch it. Production is opt-in. Never write to a prod stage unless the request names it.
146
144
  - Skills are account-scoped, so two projects on one account share a skill namespace and a same-named skill overwrites the other. A skill's stored name comes from its \`SKILL.md\` frontmatter, not the folder name.
147
- - Env values are write-only. Reference them from configs as \`\${NAME}\`. If the user pastes a secret at you, put it in the env store and use the ref.
145
+ - The API never returns env values, but \`broods env get <name>\` reveals one and is audited. Do not read a value unless the user asks. Reference them from configs as \`\${NAME}\`. If the user pastes a secret at you, put it in the env store and use the ref.
148
146
  - Deletes are confirmed, named, and singular. Never loop a delete over a list.
149
147
  - Editing a manifest-declared resource outside the project drifts from the definition, and the next deploy silently reverts it.
150
148
  `;var to=`#!/usr/bin/env bash
@@ -173,7 +171,9 @@ STATUS=$?
173
171
  set -e
174
172
  echo "$WHOAMI"
175
173
 
176
- if printf '%s' "$WHOAMI" | grep -q "Not logged in"; then
174
+ # Signed out prints "Not logged in to <url>", or "Run \`broods login\` first"
175
+ # when no server is configured. whoami exits 0 on both.
176
+ if printf '%s' "$WHOAMI" | grep -qE 'Not logged in|Run \`broods login\` first'; then
177
177
  echo
178
178
  echo "Opening the browser to sign in. Finish the login there."
179
179
  broods login
@@ -182,17 +182,17 @@ elif [ "$STATUS" -ne 0 ]; then
182
182
  # Not the expected signed-out state: surface the real failure.
183
183
  exit "$STATUS"
184
184
  fi
185
- `;var ge=Le.version,sn=Be(".agents","skills","broods"),ue="https://dashboard.broods.app",ti=3,Ae="eu-west-1",oi=[{region:"eu-west-1",label:"eu-west-1 (Ireland)"},{region:"us-east-1",label:"us-east-1 (US East)"},{region:"ap-southeast-1",label:"ap-southeast-1 (Singapore)"}],J=`Global options:
185
+ `;var ge=Ge.version,cn=Fe(".agents","skills","broods"),ce="https://dashboard.broods.app",ri=3,Ae="eu-west-1",si=[{region:"eu-west-1",label:"eu-west-1 (Ireland)"},{region:"us-east-1",label:"us-east-1 (US East)"},{region:"ap-southeast-1",label:"ap-southeast-1 (Singapore)"}],J=`Global options:
186
186
  --project <name> Project name override (default: package name or folder)
187
187
  --stage <name> Target stage override (BROODS_STAGE otherwise)
188
188
  --base-url <url> broods API base URL for sync/env calls (default: discovered at login)
189
- --dashboard-url <url> Dashboard base URL for login and deep links (default: ${ue})
190
- -h, --help Show this help`,ri=`Commands
189
+ --dashboard-url <url> Dashboard base URL for login and deep links (default: ${ce})
190
+ -h, --help Show this help`,ii=`Commands
191
191
  Develop dev diff run logs stream
192
- Ship deploy env stage
192
+ Ship deploy env stage github
193
193
  Inspect agent trace whoami
194
194
  Account login connect disconnect org project
195
- Tools init machine mcp update`,Ln={stream:"stdout"},go={color:!1},si=new Set(["agent","deploy","dev","diff","env","logs","machine","run","stage","stream","trace"]),po={agent:`Usage: broods agent <list|get> [name]
195
+ Tools init machine mcp update`,Ln={stream:"stdout"},fo={color:!1},ai=new Set(["agent","deploy","dev","diff","env","logs","machine","run","stage","stream","trace"]),mo={agent:`Usage: broods agent <list|get> [name]
196
196
 
197
197
  Subcommands:
198
198
  list List the agents in the current project/stage scope
@@ -206,14 +206,15 @@ connections. Uses the account key in BROODS_ACCOUNT_SECRET when set, otherwise
206
206
  your broods login.
207
207
 
208
208
  Types:
209
- ${tn.map((e)=>` ${e.padEnd(11)} ${we[e].description}`).join(`
209
+ ${sn.map((e)=>` ${e.padEnd(11)} ${ve[e].description}`).join(`
210
210
  `)}
211
211
 
212
212
  ${J}`,deploy:`Usage: broods deploy [options]
213
213
 
214
214
  Syncs Production once and writes BROODS_API_KEY to .env.local, plus
215
- BROODS_USER_TOKEN_SECRET when the stage has no signing secret yet. Ignores
216
- BROODS_STAGE by design. Pass --stage to deploy anywhere else.
215
+ BROODS_USER_TOKEN_SECRET when the stage has no signing secret yet. With CI
216
+ set it writes neither. Ignores BROODS_STAGE by design. Pass --stage to deploy
217
+ anywhere else.
217
218
 
218
219
  Options:
219
220
  --prune Allow deploy to delete undeclared remote resources
@@ -326,6 +327,31 @@ Chats with an agent in a terminal UI (reasoning, tool cards, y/n approvals).
326
327
  A prompt is sent as the first turn; redirected output streams plain text and
327
328
  therefore requires a prompt.
328
329
 
330
+ ${J}`,github:`Usage: broods github <status|repos|link|unlink|connect> [owner/repo]
331
+
332
+ Links the project to a GitHub repo, so a push deploys its stage from your own
333
+ GitHub Actions: Broods seals a project key per stage into the repo and commits
334
+ .github/workflows/broods.yml.
335
+
336
+ Subcommands:
337
+ status The project's link, latest deploy per branch, and accounts
338
+ repos Repos the org's connected GitHub accounts let you link
339
+ link <owner/repo> Link a repo; by default the default branch deploys
340
+ Development, or Production when the project has that
341
+ stage, with dev (created when missing) for Development
342
+ unlink Unlink and revoke the keys; the repo keeps its workflow
343
+ connect Open the page that installs the Broods GitHub App on an
344
+ account (org admins)
345
+
346
+ Options:
347
+ --folder <path> The folder holding broods/, when there are several
348
+ --production-branch <name|none> Branch Production deploys from; none for no
349
+ Production deploys
350
+ --development-branch <name|none> Branch Development deploys from; none for
351
+ no Development deploys
352
+ --json Print the result as JSON
353
+ --yes Skip the unlink confirmation
354
+
329
355
  ${J}`,project:`Usage: broods project <list|delete> [name]
330
356
 
331
357
  Subcommands:
@@ -398,59 +424,61 @@ project the dependency is upgraded instead. A new major is only announced.`,whoa
398
424
 
399
425
  Shows the login, server, org, plan, project and stage the next command uses.
400
426
 
401
- ${J}`};async function ii(){aa();let[,,e,...n]=process.argv;switch(e){case void 0:case"--help":case"-h":console.log(Mn(n,Ln));return;case"--version":case"-v":console.log(ge);return}if(ca(e,n),po[e]&&(V(n,"--help")||V(n,"-h"))){console.log(ke(e,n));return}switch(e){case"init":await ci(n);return;case"login":await li(n);return;case"connect":await ui(n);return;case"disconnect":await gi(n);return;case"whoami":await mi(n);return;case"org":await bi(n);return;case"project":await wi(n);return;case"stage":await yi(n);return;case"diff":await vi(n);return;case"deploy":await Si(n);return;case"dev":await ki(n);return;case"env":await Vi(n);return;case"stream":await Ji(n);return;case"logs":await Zi(n);return;case"trace":await Qi(n);return;case"machine":await qi(n);return;case"agent":await na(n);return;case"run":await ra(n);return;case"mcp":await la();return;case"update":await Ei();return;default:throw Error(`Unknown command: ${e}
427
+ ${J}`};async function ci(){da();let[,,e,...n]=process.argv;switch(e){case void 0:case"--help":case"-h":console.log(Mn(n,Ln));return;case"--version":case"-v":console.log(ge);return}if(ua(e,n),mo[e]&&(V(n,"--help")||V(n,"-h"))){console.log(be(e,n));return}switch(e){case"init":await di(n);return;case"login":await ui(n);return;case"connect":await pi(n);return;case"disconnect":await fi(n);return;case"whoami":await bi(n);return;case"org":await yi(n);return;case"project":await vi(n);return;case"github":await Si(n);return;case"stage":await ki(n);return;case"diff":await Ei(n);return;case"deploy":await $i(n);return;case"dev":await Oi(n);return;case"env":await Ji(n);return;case"stream":await Zi(n);return;case"logs":await na(n);return;case"trace":await ta(n);return;case"machine":await Qi(n);return;case"agent":await ra(n);return;case"run":await aa(n);return;case"mcp":await ga();return;case"update":await Ri();return;default:throw Error(`Unknown command: ${e}
402
428
 
403
- ${Mn(n,go)}`)}}function oe(e){return po[e]??Mn([],go)}function fo(e){let n=m(),t=R(e,"--base-url")??n.baseUrl,o=k(t),r=f(t??o?.baseUrl??T);return{loggedIn:o!==null,org:o?.org?.name,project:R(e,"--project")??n.project,projectGuess:xe(process.cwd()),server:r.replace(/^https?:\/\//,""),stage:R(e,"--stage")??n.stage??"development"}}function ai(e){if(!e.loggedIn)return[["broods login","sign in through the dashboard"]];if(!e.project)return[["broods dev","create a project and sync on save"]];return[["broods dev","sync on save, tail logs"],["broods run <agent>","chat with an agent"]]}function ke(e,n){let t=oe(e);if(!si.has(e))return t;let o=fo(n),r=o.project??o.projectGuess;if(e!=="deploy"||R(n,"--stage")!==void 0)return`${Rn(r,o.stage,Ln)}
429
+ ${Mn(n,fo)}`)}}function oe(e){return mo[e]??Mn([],fo)}function ho(e){let n=m(),t=R(e,"--base-url")??n.baseUrl,o=k(t),r=f(t??o?.baseUrl??T);return{loggedIn:o!==null,org:o?.org?.name,project:R(e,"--project")??n.project,projectGuess:Pe(process.cwd()),server:r.replace(/^https?:\/\//,""),stage:R(e,"--stage")??n.stage??"development"}}function li(e){if(!e.loggedIn)return[["broods login","sign in through the dashboard"]];if(!e.project)return[["broods dev","create a project and sync on save"]];return[["broods dev","sync on save, tail logs"],["broods run <agent>","chat with an agent"]]}function be(e,n){let t=oe(e);if(!ai.has(e))return t;let o=ho(n),r=o.project??o.projectGuess;if(e!=="deploy"||R(n,"--stage")!==void 0)return`${On(r,o.stage,Ln)}
404
430
 
405
- ${t}`;let s=S(),i=s&&s!=="production"?`ignores stage ${s}`:void 0;return`${Rn(r,"production",{...Ln,note:i})}
431
+ ${t}`;let s=S(),i=s&&s!=="production"?`ignores stage ${s}`:void 0;return`${On(r,"production",{...Ln,note:i})}
406
432
 
407
- ${t}`}function Mn(e,n){let t=fo(e);return[`broods v${ge}`,"",...Mt(t,n),"","Next",...Bt(ai(t),n),"",ri,"","Usage: broods <command> [options] -h, --help -v, --version","Run `broods <command> --help` for a command's flags."].join(`
408
- `)}async function ci(e){let n=V(e,"--force"),t=M(process.cwd(),y);await Fn(M(t,b),{recursive:!0}),await cn(M(t,"index.ts"),Co(),n),await cn(M(t,".gitignore"),`_generated
433
+ ${t}`}function Mn(e,n){let t=ho(e);return[`broods v${ge}`,"",...Mt(t,n),"","Next",...Bt(li(t),n),"",ii,"","Usage: broods <command> [options] -h, --help -v, --version","Run `broods <command> --help` for a command's flags."].join(`
434
+ `)}async function di(e){let n=V(e,"--force"),t=M(process.cwd(),y);await Fn(M(t,b),{recursive:!0}),await dn(M(t,"index.ts"),xo(),n),await dn(M(t,".gitignore"),`_generated
409
435
  .cache
410
- `,n),await wo(n);let o=R(e,"--dashboard-url")??ue;await zn({dashboardUrl:o,baseUrl:O(o),project:R(e,"--project")??xe(process.cwd()),stage:R(e,"--stage")??"development",region:R(e,"--region")??Ae,force:n}),X(`Created ${y}/`)}async function li(e){let n=m(),t=R(e,"--dashboard-url")??n.dashboardUrl??ue,o=await An(t);await zn({dashboardUrl:o.dashboardUrl??t,baseUrl:o.baseUrl,project:R(e,"--project"),stage:R(e,"--stage"),region:R(e,"--region"),force:!1});let r=o.user?.email||o.user?.name||o.user?.authId,s=o.org?`${o.org.name} (${o.org.slug})`:void 0,i=o.account?.username;if(X(`Logged in to ${o.dashboardUrl}`),r)console.log(`User: ${r}`);if(s)console.log(`Org: ${s}`);if(i)console.log(`Account: ${i}`);let a=R(e,"--project")??process.env.BROODS_PROJECT;if(!a)return;let c=R(e,"--stage")??S()??"development";await fi(o.baseUrl,o.token,a,c)}function di(e){if(!(e instanceof p))return e instanceof Error?e.message:String(e);try{return JSON.parse(e.body).error?.message??e.message}catch{return e.message}}async function ui(e){let[n]=se(e),t=await mo(e);if(n===void 0){await pi(t);return}if(!$n(n))throw Error(`Unknown connection type ${n}.
436
+ `,n),await vo(n);let o=R(e,"--dashboard-url")??ce;await zn({dashboardUrl:o,baseUrl:O(o),project:R(e,"--project")??Pe(process.cwd()),stage:R(e,"--stage")??"development",region:R(e,"--region")??Ae,force:n}),q(`Created ${y}/`)}async function ui(e){let n=m(),t=R(e,"--dashboard-url")??n.dashboardUrl??ce,o=await xn(t);await zn({dashboardUrl:o.dashboardUrl??t,baseUrl:o.baseUrl,project:R(e,"--project"),stage:R(e,"--stage"),region:R(e,"--region"),force:!1});let r=o.user?.email||o.user?.name||o.user?.authId,s=o.org?`${o.org.name} (${o.org.slug})`:void 0,i=o.account?.username;if(q(`Logged in to ${o.dashboardUrl}`),r)console.log(`User: ${r}`);if(s)console.log(`Org: ${s}`);if(i)console.log(`Account: ${i}`);let a=R(e,"--project")??process.env.BROODS_PROJECT;if(!a)return;let c=R(e,"--stage")??S()??"development";await hi(o.baseUrl,o.token,a,c)}function gi(e){if(!(e instanceof p))return e instanceof Error?e.message:String(e);try{return JSON.parse(e.body).error?.message??e.message}catch{return e.message}}async function pi(e){let[n]=re(e),t=await bo(e);if(n===void 0){await mi(t);return}if(!Rn(n))throw Error(`Unknown connection type ${n}.
437
+
438
+ ${oe("connect")}`);let o=ve[n],r=await qt(t,n).catch((s)=>{throw Error(gi(s))});if(q(`Connected ${o.label}${r.email?` as ${r.email}`:""}.`),console.log(`Agents on model.provider "${n}" now run on it.`),o.usageUrl)console.log(`Manage usage: ${o.usageUrl}`);if(!r.models?.length)return;console.log("Models (use the id as model.modelId):");for(let s of r.models)console.log(` ${s}`)}async function bo(e){m();let n=R(e,"--base-url"),t=process.env.BROODS_ACCOUNT_SECRET;if(t)return new _({accountSecret:t,...n?{baseUrl:n}:{}});let o=await ae(n);return new _({accountSecret:o.token,baseUrl:n??o.baseUrl})}async function fi(e){let[n]=re(e);if(!n||!Rn(n))throw Error(oe("disconnect"));if(await(await bo(e)).disconnect(n)){q(`Disconnected ${ve[n].label}`);return}console.log(`No ${n} connection.`)}async function mi(e){let n=await e.listConnections();if(n.length===0)console.log("No connections yet.");else console.log(`${"TYPE".padEnd(16)} ACCOUNT`);for(let t of n)console.log(`${ve[t.type].label.padEnd(16)} ${t.email??t.clientId}`);console.log(`
439
+ Connect one: broods connect <${sn.join("|")}>`)}async function hi(e,n,t,o){try{let s=await new X({baseUrl:e,token:n}).getRuntimeKey(t,o);if(s?.apiKey)await $e("BROODS_API_KEY",s.apiKey),q(`Wrote BROODS_API_KEY (${s.keyHint}) to .env.local`)}catch{}}async function bi(e){let n=m(),t=Ve(e),o=R(e,"--dashboard-url")??n.dashboardUrl??ce,r=Boolean(R(e,"--project")??n.project);console.log(`broods v${ge}`),console.log(`Dashboard: ${o}`),console.log(`Project: ${r?t.project:`none (${t.project} from folder name)`}`),console.log(`Stage: ${t.stage}`);let s;try{s=await ae(R(e,"--base-url"))}catch(l){D(l instanceof Error?l.message:String(l));return}console.log(`Server: ${s.baseUrl}`);let i=new X({baseUrl:s.baseUrl,token:s.token}),a=await i.getOnboarding(),c=a.orgs.find((l)=>l.id===a.currentOrgId);if(a.user)console.log(`User: ${a.user.email}`);if(console.log(`Org: ${c?Ke(c):a.currentOrgId}`),a.account)console.log(`Account: ${a.account.username} (${a.account.status})`);if(!r){D("No project set. `broods dev` picks one.");return}await wi(i,t,c?.name);let d=a.projects.map((l)=>l.name);if(!d.includes(t.project))D(`This org has no project named ${t.project}. It has: ${d.length>0?d.join(", "):"none"}.`)}async function wi(e,n,t){let o=process.env.BROODS_API_KEY,r=C("BROODS_API_KEY")?"your shell":".env.local",s=null,i=null;try{s=await e.getRuntimeKey(n.project,n.stage)}catch(a){i=a instanceof Error?a.message:String(a)}if(i)console.log("Runtime key: unavailable"),D(`Could not read the runtime key: ${i}`);else if(!s?.apiKey)console.log("Runtime key: none for this scope"),D(`${n.project}/${n.stage} does not exist in ${t??"this org"} yet. \`broods dev\` will create it.`);else if(!o)console.log(`Runtime key: ${s.keyHint} (not in .env.local)`),D("BROODS_API_KEY is not set locally. Run `broods dev`.");else if(o===s.apiKey)console.log(`Runtime key: ${s.keyHint} (matches this org and stage)`);else console.log(`Runtime key: ${s.keyHint} expected`),D(`BROODS_API_KEY from ${r} belongs to a different org or stage. Run \`broods stage use ${n.stage}\` to repoint it.`)}async function yi(e){let[n,t]=re(e);if(!n){console.log(be("org",e));return}let o=n==="list"||n==="ls",r=n==="use"||n==="select";if(!o&&!r&&!(n==="create"||n==="new"))throw Error(`Unknown org subcommand: ${n}
411
440
 
412
- ${oe("connect")}`);let o=we[n],r=await qt(t,n).catch((s)=>{throw Error(di(s))});if(X(`Connected ${o.label}${r.email?` as ${r.email}`:""}.`),console.log(`Agents on model.provider "${n}" now run on it.`),o.usageUrl)console.log(`Manage usage: ${o.usageUrl}`);if(!r.models?.length)return;console.log("Models (use the id as model.modelId):");for(let s of r.models)console.log(` ${s}`)}async function mo(e){m();let n=R(e,"--base-url"),t=process.env.BROODS_ACCOUNT_SECRET;if(t)return new _({accountSecret:t,...n?{baseUrl:n}:{}});let o=await ae(n);return new _({accountSecret:o.token,baseUrl:n??o.baseUrl})}async function gi(e){let[n]=se(e);if(!n||!$n(n))throw Error(oe("disconnect"));if(await(await mo(e)).disconnect(n)){X(`Disconnected ${we[n].label}`);return}console.log(`No ${n} connection.`)}async function pi(e){let n=await e.listConnections();if(n.length===0)console.log("No connections yet.");else console.log(`${"TYPE".padEnd(16)} ACCOUNT`);for(let t of n)console.log(`${we[t.type].label.padEnd(16)} ${t.email??t.clientId}`);console.log(`
413
- Connect one: broods connect <${tn.join("|")}>`)}async function fi(e,n,t,o){try{let s=await new q({baseUrl:e,token:n}).getRuntimeKey(t,o);if(s?.apiKey)await Ee("BROODS_API_KEY",s.apiKey),X(`Wrote BROODS_API_KEY (${s.keyHint}) to .env.local`)}catch{}}async function mi(e){let n=m(),t=dn(e),o=R(e,"--dashboard-url")??n.dashboardUrl??ue,r=Boolean(R(e,"--project")??n.project);console.log(`broods v${ge}`),console.log(`Dashboard: ${o}`),console.log(`Project: ${r?t.project:`none (${t.project} from folder name)`}`),console.log(`Stage: ${t.stage}`);let s;try{s=await ae(R(e,"--base-url"))}catch(d){D(d instanceof Error?d.message:String(d));return}console.log(`Server: ${s.baseUrl}`);let i=new q({baseUrl:s.baseUrl,token:s.token}),a=await i.getOnboarding(),c=a.orgs.find((d)=>d.id===a.currentOrgId);if(a.user)console.log(`User: ${a.user.email}`);if(console.log(`Org: ${c?We(c):a.currentOrgId}`),a.account)console.log(`Account: ${a.account.username} (${a.account.status})`);if(!r){D("No project set. `broods dev` picks one.");return}await hi(i,t,c?.name);let l=a.projects.map((d)=>d.name);if(!l.includes(t.project))D(`This org has no project named ${t.project}. It has: ${l.length>0?l.join(", "):"none"}.`)}async function hi(e,n,t){let o=process.env.BROODS_API_KEY,r=C("BROODS_API_KEY")?"your shell":".env.local",s=null,i=null;try{s=await e.getRuntimeKey(n.project,n.stage)}catch(a){i=a instanceof Error?a.message:String(a)}if(i)console.log("Runtime key: unavailable"),D(`Could not read the runtime key: ${i}`);else if(!s?.apiKey)console.log("Runtime key: none for this scope"),D(`${n.project}/${n.stage} does not exist in ${t??"this org"} yet. \`broods dev\` will create it.`);else if(!o)console.log(`Runtime key: ${s.keyHint} (not in .env.local)`),D("BROODS_API_KEY is not set locally. Run `broods dev`.");else if(o===s.apiKey)console.log(`Runtime key: ${s.keyHint} (matches this org and stage)`);else console.log(`Runtime key: ${s.keyHint} expected`),D(`BROODS_API_KEY from ${r} belongs to a different org or stage. Run \`broods stage use ${n.stage}\` to repoint it.`)}async function bi(e){let[n,t]=se(e);if(!n){console.log(ke("org",e));return}let o=n==="list"||n==="ls",r=n==="use"||n==="select";if(!o&&!r&&!(n==="create"||n==="new"))throw Error(`Unknown org subcommand: ${n}
441
+ ${oe("org")}`);let i=m(),a=R(e,"--dashboard-url")??i.dashboardUrl??ce,c=await xe(a,R(e,"--base-url")),d=new X({baseUrl:c.baseUrl,token:c.token}),l=await d.getOnboarding();if(o){for(let u of l.orgs){let P=u.accountStatus==="active"?"":` [${u.accountStatus} account]`;console.log(Ce(`${Ke(u)}${P}`,u.id===l.currentOrgId))}console.log(`
442
+ Only orgs where you are owner or admin can be selected from the CLI.`);return}if(r){let u=l.orgs.filter((j)=>j.accountStatus==="active"),P=t?u.find((j)=>j.slug===t||j.name===t||j.id===t):await Me("Select organization",u,Ke,u.findIndex((j)=>j.id===l.currentOrgId));if(!P)throw Error(`No selectable organization matches "${t}". Run \`broods org list\`.`);await io(d,c,await d.selectOnboardingOrg(P.id),e);return}let w=t??await ke("Organization name",Pe(process.cwd()));if(!w.trim())throw Error("Organization name is required.");await io(d,c,await d.createOnboardingOrg(w),e)}async function vi(e){let[n,t]=re(e);if(!n){console.log(be("project",e));return}let o=n==="list"||n==="ls";if(!o&&!(n==="delete"||n==="rm"))throw Error(`Unknown project subcommand: ${n}
414
443
 
415
- ${oe("org")}`);let i=m(),a=R(e,"--dashboard-url")??i.dashboardUrl??ue,c=await Fe(a,R(e,"--base-url")),l=new q({baseUrl:c.baseUrl,token:c.token}),d=await l.getOnboarding();if(o){for(let u of d.orgs){let P=u.accountStatus==="active"?"":` [${u.accountStatus} account]`;console.log(Ce(`${We(u)}${P}`,u.id===d.currentOrgId))}console.log(`
416
- Only orgs where you are owner or admin can be selected from the CLI.`);return}if(r){let u=d.orgs.filter((j)=>j.accountStatus==="active"),P=t?u.find((j)=>j.slug===t||j.name===t||j.id===t):await Ue("Select organization",u,We,u.findIndex((j)=>j.id===d.currentOrgId));if(!P)throw Error(`No selectable organization matches "${t}". Run \`broods org list\`.`);await io(l,c,await l.selectOnboardingOrg(P.id),e);return}let w=t??await ve("Organization name",xe(process.cwd()));if(!w.trim())throw Error("Organization name is required.");await io(l,c,await l.createOnboardingOrg(w),e)}async function wi(e){let[n,t]=se(e);if(!n){console.log(ke("project",e));return}let o=n==="list"||n==="ls";if(!o&&!(n==="delete"||n==="rm"))throw Error(`Unknown project subcommand: ${n}
444
+ ${oe("project")}`);let s=m(),i=R(e,"--dashboard-url")??s.dashboardUrl??ce,a=Ve(e),c=await xe(i,R(e,"--base-url")),d=new X({baseUrl:c.baseUrl,token:c.token});if(o){let j=await d.listProjects();if(j.length===0){console.log("This org has no projects yet. `broods dev` creates one.");return}console.log("Projects:");for(let W of j)console.log(ji(W,a.project));let I=j.filter((W)=>W.empty);if(I.length>0)console.log(`
445
+ ${I.length} empty project(s). Delete one with \`broods project delete <name>\`.`);return}let l=t??await ke("Project to delete","");if(!l.trim())throw Error("Project name is required.");let w=await d.listProjects(),u=w.find((j)=>j.name===l||j.slug===l);if(!u)throw Error(`No project named "${l}". Existing: ${w.map((j)=>j.name).join(", ")}.`);if(!V(e,"--yes")){if(console.log(`Deleting ${u.name} removes ${Gn(u)}.`),!await Le(`Permanently delete project ${u.name}?`)){console.log("Left it alone. Pass --yes to skip this prompt.");return}}let P=await d.deleteProject(u.id);if(!P)throw Error(`Project ${u.name} was not found.`);if(q(`Deleted project ${P.name} (${Gn(P)})`),P.name===a.project||P.slug===a.project)console.log("That was the project this directory points at. Update BROODS_PROJECT in .env.local.")}async function Si(e){let[n,t]=re(e),o=["status","repos","link","unlink","connect"];if(!n){console.log(be("github",e));return}if(!o.includes(n))throw Error(`Unknown github subcommand: ${n}
417
446
 
418
- ${oe("project")}`);let s=m(),i=R(e,"--dashboard-url")??s.dashboardUrl??ue,a=dn(e),c=await Fe(i,R(e,"--base-url")),l=new q({baseUrl:c.baseUrl,token:c.token});if(o){let j=await l.listProjects();if(j.length===0){console.log("This org has no projects yet. `broods dev` creates one.");return}console.log("Projects:");for(let K of j)console.log(Ti(K,a.project));let I=j.filter((K)=>K.empty);if(I.length>0)console.log(`
419
- ${I.length} empty project(s). Delete one with \`broods project delete <name>\`.`);return}let d=t??await ve("Project to delete","");if(!d.trim())throw Error("Project name is required.");let w=await l.listProjects(),u=w.find((j)=>j.name===d||j.slug===d);if(!u)throw Error(`No project named "${d}". Existing: ${w.map((j)=>j.name).join(", ")}.`);if(!V(e,"--yes")){if(console.log(`Deleting ${u.name} removes ${Gn(u)}.`),!await rn(`Permanently delete project ${u.name}?`)){console.log("Left it alone. Pass --yes to skip this prompt.");return}}let P=await l.deleteProject(u.id);if(!P)throw Error(`Project ${u.name} was not found.`);if(X(`Deleted project ${P.name} (${Gn(P)})`),P.name===a.project||P.slug===a.project)console.log("That was the project this directory points at. Update BROODS_PROJECT in .env.local.")}async function yi(e){let[n,t]=se(e);if(!n){console.log(ke("stage",e));return}let o=n==="list"||n==="ls",r=n==="use"||n==="select";if(!o&&!r&&!(n==="create"||n==="new"))throw Error(`Unknown stage subcommand: ${n}
447
+ ${oe("github")}`);let r=m(),s=await xe(R(e,"--dashboard-url")??r.dashboardUrl??ce,R(e,"--base-url")),i=new X({baseUrl:s.baseUrl,token:s.token}),{project:a}=Ve(e),c=V(e,"--json"),d=(w,u)=>{if(c)console.log(JSON.stringify(w,null,2));else u()};if(n==="connect"){let{url:w}=await i.githubConnect();d({url:w},()=>{console.log(`Install the Broods GitHub App: ${w}`),Be(w)});return}if(n==="repos"){let[w,u]=await Promise.all([i.githubRepos(a),i.githubStatus(a)]);d(w,()=>{if(w.length===0)console.log("No repos yet. `broods github connect` adds an account.");for(let j of w)console.log(`${j.fullName} ${j.defaultBranch}${j.private?" private":""}`);let P=u.webUrl??"https://github.com";for(let j of u.installations)console.log(`Repo missing? Choose ${j.login}'s repos: ${j.accountType==="Organization"?`${P}/organizations/${j.login}/settings/installations/${j.installationId}`:`${P}/settings/installations/${j.installationId}`}`)});return}if(n==="link"){if(!t)throw Error("Usage: broods github link <owner/repo>");let w=await i.githubLink(a,{repo:t,folder:R(e,"--folder"),baseUrl:s.baseUrl,productionBranch:ao(e,"--production-branch"),developmentBranch:ao(e,"--development-branch")});d(w,()=>{q(`Linked ${w.fullName} to ${a}`),co(w)});return}if(n==="unlink"){if(!V(e,"--yes")&&!await Le(`Unlink ${a}'s repo and revoke its keys?`))return;await i.githubUnlink(a),d({unlinked:!0},()=>q(`Unlinked ${a}; the repo keeps its workflow file.`));return}let l=await i.githubStatus(a);d(l,()=>{if(!l.configured){console.log(`GitHub is not set up on ${s.baseUrl}.`);return}if(!l.repo)console.log(`${a} is not linked. \`broods github link <owner/repo>\` links one.`);else console.log(`${a} deploys from ${l.repo.fullName}`),co(l.repo,l.deploys);let w=l.installations.map((u)=>u.login);console.log(`Connected accounts: ${w.length>0?w.join(", "):"none (`broods github connect`)"}`)})}async function ki(e){let[n,t]=re(e);if(!n){console.log(be("stage",e));return}let o=n==="list"||n==="ls",r=n==="use"||n==="select";if(!o&&!r&&!(n==="create"||n==="new"))throw Error(`Unknown stage subcommand: ${n}
420
448
 
421
- ${oe("stage")}`);let i=m(),a=R(e,"--dashboard-url")??i.dashboardUrl??ue,c=dn(e),l=await Fe(a,R(e,"--base-url")),d=new q({baseUrl:l.baseUrl,token:l.token});if(o){let I=await d.listStages(c.project);if(I.length===0){console.log(`${c.project} has no stages yet. \`broods dev\` creates Development.`);return}console.log(`Stages for ${c.project}:`);for(let K of I)console.log(_i(K,c.stage));return}if(r){let I=await d.listStages(c.project),K=t?I.find((Q)=>Wn(Q.name,t)):await Ue("Select stage",I,yo,I.findIndex((Q)=>Wn(Q.name,c.stage)));if(!K)throw Error(`${c.project} has no stage "${t}". Existing: ${I.map((Q)=>Q.name).join(", ")}. Create it with \`broods stage create ${t} --from ${c.stage}\`.`);let te=C("BROODS_STAGE");await Ee("BROODS_STAGE",K.name),console.log(`Stage: ${K.name} (wrote BROODS_STAGE)`),Ge("BROODS_STAGE",te),await Bn(d,{project:c.project,stage:K.name});return}let w=t??await ve("Stage name","staging");if(!w.trim())throw Error("Stage name is required.");let u=R(e,"--from"),P=await d.createStage(c.project,w,u);if(X(`Created stage ${P.stage.name} in ${c.project}${P.clonedFrom?` from ${P.clonedFrom}`:""}`),P.clonedFrom)console.log(` ${P.stage.agentCount} agent(s), ${P.stage.variableCount} env var(s) copied`);if(!V(e,"--use")){console.log(`Switch to it with \`broods stage use ${P.stage.name}\`.`);return}let j=C("BROODS_STAGE");await Ee("BROODS_STAGE",P.stage.name),console.log(`Stage: ${P.stage.name} (wrote BROODS_STAGE)`),Ge("BROODS_STAGE",j),await Bn(d,{project:c.project,stage:P.stage.name})}async function vi(e){let{manifest:n,config:t}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),o=await ae(R(e,"--base-url")??t.baseUrl),r=new q({baseUrl:o.baseUrl,token:o.token}),s=await r.getManifest(n.project,n.stage);on(kn(n,s?.manifest??null)),Bi(await Kn(r,n),`${n.project}/${n.stage}`)}async function Si(e){let{manifest:n,config:t,resourceAliases:o,channels:r}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"deploy",useRuntimeStage:!1}),s=await ae(R(e,"--base-url")??t.baseUrl),i=new q({baseUrl:s.baseUrl,token:s.token}),a=R(e,"--region"),c=wn.find((d)=>d===a);if(V(e,"--region")&&!c)throw Error(`Unknown region ${a??"(empty)"}. Use one of: ${wn.join(", ")}`);let l=await i.putManifest(c?{...n,region:c}:n,V(e,"--prune"),V(e,"--rotate-key"));await Je(n,l.ids,process.cwd(),o,l.deployment,r),await Oo(),X(`Synced ${l.manifest.resources.length} resources to ${n.project}/${n.stage}`),await ho(i,n,l.deployment),vo(r,l),bo(l)}async function ho(e,n,t){if(!t)return;if(t.apiKey)await Ee("BROODS_API_KEY",t.apiKey),X(`Wrote BROODS_API_KEY (${t.keyHint}) to .env.local`);let o=t.userTokenSecretHint,r=(c)=>c!==void 0&&Ct(Z,c)===o,s=x(await $e(M(process.cwd(),".env.local")))[g];if(o&&(r(process.env[g])||r(s))){Ge(g,!r(process.env[g])&&C(g));return}if(o){D(`${n.project}/${n.stage} already has a user token signing secret (${o}), and ${g} here is unset or another one. Use the secret your backend signs with, or rotate it on the dashboard's Runtime key tab.`);return}let i=await e.rotateUserTokenSecret(n.project,n.stage).catch((c)=>(D(`${c instanceof Error?c.message:String(c)}. Set ${g} from the dashboard's Runtime key tab to sign user tokens.`),null));if(!i)return;let a=C(g);await Ee(g,i.secret),X(`Wrote a new user token signing secret to ${g} in .env.local`),Ge(g,a)}function bo(e){let n=e.warnings?.missingPolicies??[];if(n.length>0)D(`${n.length} policy ref(s) in agent config match no policy resource in this deploy. One that is not an existing policy id refuses every action at runtime: ${n.join(", ")}`);let t=e.warnings?.reservedResources??[];if(t.length>0)D(`Kept on prune, a reserved sandbox instance is still live: ${t.join(", ")}. Terminate it from the dashboard, then deploy again.`)}async function Ei(){let e=await Nn({maxAgeMs:0});if(e===null)throw Error("Could not reach the npm registry to check for a newer broods.");if(!Dn(e,ge)){console.log(`broods v${ge} is already the newest release.`);return}let n=eo(),t=Me(ge),o=Me(e)===t,r=o?e:`the newest ${t}.x`;if(console.log(`Updating broods ${ge} → ${r} ${n.global?"globally":"in this project"}`),console.log(`$ ${[n.command,...n.args].join(" ")}`),await new Promise((s,i)=>{let a=uo(n.command,n.args,{cwd:n.cwd,stdio:"inherit",shell:process.platform==="win32"});a.on("error",i),a.on("exit",(c)=>{if(c===0){s();return}i(Error(`${n.command} exited with code ${c??"unknown"}`))})}),console.log(`broods ${o?e:`${t}.x`} installed.`),!o)D(`broods ${e} is a new major version. Install broods@${Me(e)} yourself to move to it.`)}async function ro(){let e=await Nn();if(e===null||!Dn(e,ge))return;D(`broods ${e} is out, you are on ${ge}. Run \`broods update\`.`)}async function ki(e){if(await Ri(e),V(e,"--once")){if(!process.env.BROODS_SUPPRESS_DEV_TARGET)await ao(e),await ro();let u=oo.now();await Li(e),Ft(oo.now()-u);return}let n=Be(ni(),`broods-declined-${process.pid}.txt`),t={...process.env,BROODS_DECLINED_FILE:n,BROODS_SUPPRESS_DEV_TARGET:"1",BROODS_RELOAD_ENV:"1"};await ao(e),await ro();let o,r=!1,s=!1,i,a=async()=>{let u=await sa();if(u===i)return;await Ui(e,t),i=u},c=(u)=>console.error(u instanceof Error?u.message:String(u));await a().catch(c);let l=()=>{if(r){s=!0;return}r=!0,a().catch(c).finally(()=>{if(r=!1,s)s=!1,l()})},d=ei(M(process.cwd(),y),{recursive:!0},(u,P)=>{if(!P||ia(P))return;clearTimeout(o),o=setTimeout(l,150)}),w=new AbortController;$i(e,w.signal),process.on("SIGINT",()=>{w.abort(),d.close(),process.exit(0)})}async function $i(e,n){let t;try{t=await Ke(e)}catch(r){console.log(`· live logs off. ${r instanceof Error?r.message:String(r)}`);return}let o=Hn(e);try{for await(let r of Xe(t,{backfill:0,keepReconnecting:!0,minLevel:o,signal:n,onReconnect:Vn}))console.log(Yn(r))}catch(r){if(!n.aborted)console.error(`live logs: ${r instanceof Error?r.message:String(r)}`)}}async function Ri(e){await Ci(),await wo(!1),await Ai(e)}async function wo(e){let n=process.cwd();if(!(await Promise.all([".agent",".agents",".claude","AGENTS.md","CLAUDE.md"].map((c)=>so(M(n,c))))).includes(!0))return;let r=M(n,sn);if(!e&&await so(M(r,"SKILL.md")))return;let s=Be(sn,"SKILL.md"),i=Be(sn,"scripts","onboard.sh");for(let c of[s,i])if(await Oi(n,c)){D(`Skipped the agent skill: ${c} crosses a symlink.`);return}await Fn(M(r,"scripts"),{recursive:!0}),await Se(M(r,"SKILL.md"),no);let a=M(r,"scripts","onboard.sh");await Se(a,to),await Vs(a,493),X(`Installed the broods agent skill at ${sn}/`)}async function Oi(e,n){let t=e;for(let o of n.split(Qs)){t=M(t,o);try{if((await Ys(t)).isSymbolicLink())return!0}catch{return!1}}return!1}async function so(e){try{return await Js(e),!0}catch{return!1}}async function Ci(){let e=M(process.cwd(),y);await Fn(M(e,b),{recursive:!0});let n=[];if(await Jn(e,n),n.length>0)return;await cn(M(e,"index.ts"),Co(),!1),await cn(M(e,".gitignore"),`_generated
449
+ ${oe("stage")}`);let i=m(),a=R(e,"--dashboard-url")??i.dashboardUrl??ce,c=Ve(e),d=await xe(a,R(e,"--base-url")),l=new X({baseUrl:d.baseUrl,token:d.token});if(o){let I=await l.listStages(c.project);if(I.length===0){console.log(`${c.project} has no stages yet. \`broods dev\` creates Development.`);return}console.log(`Stages for ${c.project}:`);for(let W of I)console.log(Di(W,c.stage));return}if(r){let I=await l.listStages(c.project),W=t?I.find((Q)=>Wn(Q.name,t)):await Me("Select stage",I,So,I.findIndex((Q)=>Wn(Q.name,c.stage)));if(!W)throw Error(`${c.project} has no stage "${t}". Existing: ${I.map((Q)=>Q.name).join(", ")}. Create it with \`broods stage create ${t} --from ${c.stage}\`.`);let te=C("BROODS_STAGE");await $e("BROODS_STAGE",W.name),console.log(`Stage: ${W.name} (wrote BROODS_STAGE)`),He("BROODS_STAGE",te),await Bn(l,{project:c.project,stage:W.name});return}let w=t??await ke("Stage name","staging");if(!w.trim())throw Error("Stage name is required.");let u=R(e,"--from"),P=await l.createStage(c.project,w,u);if(q(`Created stage ${P.stage.name} in ${c.project}${P.clonedFrom?` from ${P.clonedFrom}`:""}`),P.clonedFrom)console.log(` ${P.stage.agentCount} agent(s), ${P.stage.variableCount} env var(s) copied`);if(!V(e,"--use")){console.log(`Switch to it with \`broods stage use ${P.stage.name}\`.`);return}let j=C("BROODS_STAGE");await $e("BROODS_STAGE",P.stage.name),console.log(`Stage: ${P.stage.name} (wrote BROODS_STAGE)`),He("BROODS_STAGE",j),await Bn(l,{project:c.project,stage:P.stage.name})}async function Ei(e){let{manifest:n,config:t}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),o=await ae(R(e,"--base-url")??t.baseUrl),r=new X({baseUrl:o.baseUrl,token:o.token}),s=await r.getManifest(n.project,n.stage);an($n(n,s?.manifest??null)),Fi(await Hn(r,n),`${n.project}/${n.stage}`)}async function $i(e){let{manifest:n,config:t,resourceAliases:o,channels:r}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"deploy",useRuntimeStage:!1}),s=await ae(R(e,"--base-url")??t.baseUrl),i=new X({baseUrl:s.baseUrl,token:s.token}),a=R(e,"--region"),c=yn.find((l)=>l===a);if(V(e,"--region")&&!c)throw Error(`Unknown region ${a??"(empty)"}. Use one of: ${yn.join(", ")}`);let d=await i.putManifest(c?{...n,region:c}:n,V(e,"--prune"),V(e,"--rotate-key"));await Ze(n,d.ids,process.cwd(),o,d.deployment,r),await Ao(),q(`Synced ${d.manifest.resources.length} resources to ${n.project}/${n.stage}`),await wo(i,n,d.deployment),ko(r,d),yo(d)}async function wo(e,n,t){if(!t||process.env.CI)return;if(t.apiKey)await $e("BROODS_API_KEY",t.apiKey),q(`Wrote BROODS_API_KEY (${t.keyHint}) to .env.local`);let o=t.userTokenSecretHint,r=(c)=>c!==void 0&&Ct(Z,c)===o,s=x(await Re(M(process.cwd(),".env.local")))[g];if(o&&(r(process.env[g])||r(s))){He(g,!r(process.env[g])&&C(g));return}if(o){D(`${n.project}/${n.stage} already has a user token signing secret (${o}), and ${g} here is unset or another one. Use the secret your backend signs with, or rotate it on the dashboard's Runtime key tab.`);return}let i=await e.rotateUserTokenSecret(n.project,n.stage).catch((c)=>(D(`${c instanceof Error?c.message:String(c)}. Set ${g} from the dashboard's Runtime key tab to sign user tokens.`),null));if(!i)return;let a=C(g);await $e(g,i.secret),q(`Wrote a new user token signing secret to ${g} in .env.local`),He(g,a)}function yo(e){let n=e.warnings?.missingPolicies??[];if(n.length>0)D(`${n.length} policy ref(s) in agent config match no policy resource in this deploy. One that is not an existing policy id refuses every action at runtime: ${n.join(", ")}`);let t=e.warnings?.reservedResources??[];if(t.length>0)D(`Kept on prune, a reserved sandbox instance is still live: ${t.join(", ")}. Terminate it from the dashboard, then deploy again.`)}async function Ri(){let e=await Nn({maxAgeMs:0});if(e===null)throw Error("Could not reach the npm registry to check for a newer broods.");if(!Dn(e,ge)){console.log(`broods v${ge} is already the newest release.`);return}let n=eo(),t=We(ge),o=We(e)===t,r=o?e:`the newest ${t}.x`;if(console.log(`Updating broods ${ge} → ${r} ${n.global?"globally":"in this project"}`),console.log(`$ ${[n.command,...n.args].join(" ")}`),await new Promise((s,i)=>{let a=po(n.command,n.args,{cwd:n.cwd,stdio:"inherit",shell:process.platform==="win32"});a.on("error",i),a.on("exit",(c)=>{if(c===0){s();return}i(Error(`${n.command} exited with code ${c??"unknown"}`))})}),console.log(`broods ${o?e:`${t}.x`} installed.`),!o)D(`broods ${e} is a new major version. Install broods@${We(e)} yourself to move to it.`)}async function ro(){let e=await Nn();if(e===null||!Dn(e,ge))return;D(`broods ${e} is out, you are on ${ge}. Run \`broods update\`.`)}async function Oi(e){if(await Ai(e),V(e,"--once")){if(!process.env.BROODS_SUPPRESS_DEV_TARGET)await lo(e),await ro();let u=oo.now();await Gi(e),Ft(oo.now()-u);return}let n=Fe(oi(),`broods-declined-${process.pid}.txt`),t={...process.env,BROODS_DECLINED_FILE:n,BROODS_SUPPRESS_DEV_TARGET:"1",BROODS_RELOAD_ENV:"1"};await lo(e),await ro();let o,r=!1,s=!1,i,a=async()=>{let u=await ca();if(u===i)return;await Bi(e,t),i=u},c=(u)=>console.error(u instanceof Error?u.message:String(u));await a().catch(c);let d=()=>{if(r){s=!0;return}r=!0,a().catch(c).finally(()=>{if(r=!1,s)s=!1,d()})},l=ti(M(process.cwd(),y),{recursive:!0},(u,P)=>{if(!P||la(P))return;clearTimeout(o),o=setTimeout(d,150)}),w=new AbortController;Ci(e,w.signal),process.on("SIGINT",()=>{w.abort(),l.close(),process.exit(0)})}async function Ci(e,n){let t;try{t=await Ye(e)}catch(r){console.log(`· live logs off. ${r instanceof Error?r.message:String(r)}`);return}let o=Kn(e);try{for await(let r of en(t,{backfill:0,keepReconnecting:!0,minLevel:o,signal:n,onReconnect:Vn}))console.log(Yn(r))}catch(r){if(!n.aborted)console.error(`live logs: ${r instanceof Error?r.message:String(r)}`)}}async function Ai(e){await Pi(),await vo(!1),await Ti(e)}async function vo(e){let n=process.cwd();if(!(await Promise.all([".agent",".agents",".claude","AGENTS.md","CLAUDE.md"].map((c)=>so(M(n,c))))).includes(!0))return;let r=M(n,cn);if(!e&&await so(M(r,"SKILL.md")))return;let s=Fe(cn,"SKILL.md"),i=Fe(cn,"scripts","onboard.sh");for(let c of[s,i])if(await xi(n,c)){D(`Skipped the agent skill: ${c} crosses a symlink.`);return}await Fn(M(r,"scripts"),{recursive:!0}),await Ee(M(r,"SKILL.md"),no);let a=M(r,"scripts","onboard.sh");await Ee(a,to),await zs(a,493),q(`Installed the broods agent skill at ${cn}/`)}async function xi(e,n){let t=e;for(let o of n.split(ni)){t=M(t,o);try{if((await Js(t)).isSymbolicLink())return!0}catch{return!1}}return!1}async function so(e){try{return await Xs(e),!0}catch{return!1}}async function Pi(){let e=M(process.cwd(),y);await Fn(M(e,b),{recursive:!0});let n=[];if(await Jn(e,n),n.length>0)return;await dn(M(e,"index.ts"),xo(),!1),await dn(M(e,".gitignore"),`_generated
422
450
  .cache
423
- `,!1),X(`Created starter ${y}/`)}async function Ai(e){let n=M(process.cwd(),".env.local"),t=await $e(n),o=x(t),r=o.BROODS_STAGE;if(["BROODS_DASHBOARD_URL","BROODS_BASE_URL","BROODS_PROJECT","BROODS_REGION"].filter((j)=>o[j]===void 0).length===0&&r!==void 0)return;let i=o.BROODS_PROJECT===void 0,a=r===void 0,c=o.BROODS_REGION===void 0,l=m(),d=R(e,"--dashboard-url")??l.dashboardUrl??ue,w=R(e,"--project")??process.env.BROODS_PROJECT??xe(process.cwd()),u=R(e,"--stage")??S()??"development",P=R(e,"--region")??process.env.BROODS_REGION??Ae;if(process.stdin.isTTY&&i){let j=await Fe(d,R(e,"--base-url")),I=new q({baseUrl:j.baseUrl,token:j.token}),K=await xi(I,j),te=await Ii(I,K);if(w=await Ni(te,w),!w.trim())throw Error("Project name is required.")}if(process.stdin.isTTY&&a){if(u=await ve("Stage",u),!u.trim())throw Error("Stage is required.")}if(process.stdin.isTTY&&c){let j=oi.filter((I)=>At.includes(I.region));P=await Ue("Select service region",j,(I)=>I.label,j.findIndex((I)=>I.region===P)).then((I)=>I.region)}await zn({dashboardUrl:d,baseUrl:l.baseUrl??O(d),project:w,stage:u,region:P,force:!1})}async function Fe(e,n){try{return await ae(n)}catch(t){if(!process.stdin.isTTY)throw t;return D(`${t instanceof Error?t.message:String(t)} Starting browser login.`),await An(e)}}async function xi(e,n){try{return await e.getOnboarding()}catch(t){if(!(t instanceof en)||!n.org)throw t;return D("This broods server cannot list your orgs yet; using the org from your login."),{currentOrgId:n.org.id,orgs:[{id:n.org.id,name:n.org.name,slug:n.org.slug,role:"admin",accountStatus:"active"}],projects:[]}}}async function io(e,n,t,o){let r=t.orgs.find((s)=>s.id===t.currentOrgId);if(!r)throw Error("Selected organization is not visible to this login");if(process.env.BROODS_TOKEN)D("BROODS_TOKEN is set, so the switch applies to this token only and was not stored.");else await B({...n,org:{id:r.id,name:r.name,slug:r.slug},...t.account?{account:{id:t.account.id,username:t.account.username}}:{}});console.log(`Org: ${We(r)}`),console.log(`Projects: ${t.projects.length>0?t.projects.map((s)=>s.name).join(", "):"none yet"}`),await Bn(e,dn(o))}async function Bn(e,n){let t;try{t=await e.getRuntimeKey(n.project,n.stage)}catch(r){D(`Could not read the runtime key for ${n.project}/${n.stage} (${r instanceof Error?r.message:String(r)}). BROODS_API_KEY still points at the previous scope. Run \`broods whoami\` to check it.`);return}if(!t?.apiKey){D(`${n.project}/${n.stage} is not synced here yet, so BROODS_API_KEY still points at the previous scope. Run \`broods dev\`.`);return}let o=C("BROODS_API_KEY");if(!o&&process.env.BROODS_API_KEY===t.apiKey)return;await Ee("BROODS_API_KEY",t.apiKey),X(`Wrote BROODS_API_KEY (${t.keyHint}) to .env.local`),Ge("BROODS_API_KEY",o)}function Ge(e,n){if(!n)return;D(`${e} is exported in your shell, which wins over .env.local. Run \`unset ${e}\` or the next broods command keeps the old value.`)}function We(e){let n=e.role==="owner"||e.role==="admin"?e.role:"member",t=e.plan?`, ${e.plan} plan`:"";return`${e.name} (${e.slug}, ${n}${t})`}function Pi(e){return e.slug===e.name?e.name:`${e.name} (${e.slug})`}function Gn(e){return e.empty?"nothing (it is already empty)":`${e.stageCount} stage(s), ${e.agentCount} agent(s), ${e.variableCount} env var(s), ${e.deploymentCount} deployment(s), ${e.fileCount} workspace file(s)`}function Ti(e,n){let t=e.empty?"empty":Gn(e);return Ce(`${e.name}: ${t}`,e.name===n||e.slug===n)}function _i(e,n){return Ce(yo(e),Wn(e.name,n))}function yo(e){let n=e.deploymentRegion?`, ${e.deploymentRegion}`:"";return`${e.name} (${e.kind}${n}): ${e.agentCount} agent(s), ${e.variableCount} env var(s)`}function Wn(e,n){return e.trim().toLowerCase()===n.trim().toLowerCase()}function dn(e){return m(),{project:R(e,"--project")??process.env.BROODS_PROJECT??xe(process.cwd()),stage:R(e,"--stage")??S()??"development"}}async function Ii(e,n){let t=n.orgs.filter((s)=>s.accountStatus==="active"),o={kind:"create",name:"New organization"},r=await Ue("Select organization",[...t,o],(s)=>("kind"in s)?"Create new organization":We(s),t.findIndex((s)=>s.id===n.currentOrgId));if("kind"in r){let s=await ve("Organization name",xe(process.cwd()));if(!s.trim())throw Error("Organization name is required.");return await e.createOnboardingOrg(s)}return r.id===n.currentOrgId?n:await e.selectOnboardingOrg(r.id)}function ji(e,n){return e.projects.find((o)=>o.name===n||o.slug===n)?.name??n}function Di(e,n){return e.projects.find((t)=>t.name===n||t.slug===n)}async function Ni(e,n){let t=ji(e,n);if(e.projects.length===0)return ve("Project name",t);for(;;){let o=await zt("Select project",e.projects,Pi,{hint:"type a new project name",defaultValue:t}),r=typeof o==="string"?o:o.name,s=Di(e,r);if(!s)return r;if(await rn(`Continue with the existing project ${s.name}?`))return s.name}}function Ui(e,n){return new Promise((t,o)=>{let r=process.argv[1]??"",s=uo(process.execPath,[r,"dev","--once",...e],{stdio:"inherit",env:n});s.on("error",o),s.on("exit",(i,a)=>{if(i===0){t();return}o(Error(a?`Sync child exited from signal ${a}`:`Sync child exited with code ${i??"unknown"}`))})})}async function Li(e){let n=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),t=await ae(R(e,"--base-url")??n.config.baseUrl),o=new q({baseUrl:t.baseUrl,token:t.token}),r=await So(o,n.manifest,await Kn(o,n.manifest));if(r.length>0)On(r);for(let s=1;;s+=1)try{return await Mi(o,n)}catch(i){if(!(i instanceof Qe)||s===ti)throw i;D("Stage changed in another session. Re-reading...")}}async function Mi(e,n){let{manifest:t,resourceAliases:o,channels:r}=n,s=await e.getManifest(t.project,t.stage),i=kn(t,s?.manifest??null);on(i.filter((u)=>u.operation!=="delete"));let a=await e.putManifest(t,!1,!1,s===null?0:s.revision);await Je(t,a.ids,process.cwd(),o,a.deployment,r),await Oo();let c=await Fi(),l=i.filter((u)=>u.operation==="delete"),d=l.filter((u)=>!c.has(`${u.kind}:${u.name}`)),w=!1;if(d.length>0)if(D("These remote resources are no longer declared locally:"),on(d),await rn(`Delete ${d.length} resource(s) from ${t.project}/${t.stage}?`))a=await e.putManifest(t,!0,!1,a.revision),await Je(t,a.ids,process.cwd(),o,a.deployment,r),await Hi(),w=!0;else await Ki(d.map((u)=>`${u.kind}:${u.name}`));if(!w&&l.length>0){let u=l.map((P)=>`${P.kind}:${P.name}`).join(", ");D(`${l.length} undeclared resource(s) kept remotely: ${u}. Re-declare in code or run \`deploy --prune\` to remove.`)}return await ho(e,t,a.deployment),vo(r,a),bo(a),a}function vo(e,n){let t=n.deployment;if(!t||e.length===0)return;let o=new N,r=new Map;for(let i of e){if(!n.ids.agents[i.agentName])continue;let a=r.get(i.type)??[];a.push(i.alias),r.set(i.type,a)}let s=t.stageKind===void 0||t.stageKind==="production";for(let[i,a]of r){let c=s?o.accountWebhookUrl(t.accountId,i):o.stageWebhookUrl(t.accountId,t.endpointId,i);console.log(`Channel ${a.join(", ")} (${i}): ${c}${i==="pancake"?"?secret=<PANCAKE_WEBHOOK_SECRET>":""}`)}}async function Kn(e,n){let t=yt(n).filter((r)=>!r.startsWith("BROODS_"));if(t.length===0)return[];let o=new Map((await e.listEnv(n.project,n.stage)).map((r)=>[r.name,r.valueDigest]));return t.map((r)=>({name:r,state:Gi(r,o)}))}async function So(e,n,t){let o=t.filter((r)=>r.state==="unset"||r.state==="drifted").map((r)=>r.name);if(o.length===0)return[];return await Promise.all(o.map((r)=>e.setEnv(n.project,n.stage,r,process.env[r]))),o}function Bi(e,n){let t=an(e,"drifted");if(t.length>0)D(`.env.local and ${n} disagree on ${t.length} variable(s): ${t.join(", ")}. Run \`broods env sync\` to push the local values.`)}function Gi(e,n){let t=process.env[e],o=n.get(e);if(t===void 0||t==="")return o===void 0?"unresolved":"stage-only";if(o===void 0)return"unset";return o===Wi(t)?"synced":"drifted"}function Wi(e){return lo("sha256").update(e).digest("hex")}function an(e,n){return e.filter((t)=>t.state===n).map((t)=>t.name)}async function ao(e){let n=m(),{manifest:t,config:o}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),r=await ae(R(e,"--base-url")??o.baseUrl);Gt({project:t.project,stage:t.stage,dashboardUrl:R(e,"--dashboard-url")??n.dashboardUrl??r.dashboardUrl??o.dashboardUrl??ue})}async function Fi(){let e=process.env.BROODS_DECLINED_FILE;if(!e)return new Set;let n=await $e(e);return new Set(n.split(/\r?\n/).map((t)=>t.trim()).filter(Boolean))}async function Ki(e){let n=process.env.BROODS_DECLINED_FILE;if(!n||e.length===0)return;await Se(n,`${e.join(`
451
+ `,!1),q(`Created starter ${y}/`)}async function Ti(e){let n=M(process.cwd(),".env.local"),t=await Re(n),o=x(t),r=o.BROODS_STAGE;if(["BROODS_DASHBOARD_URL","BROODS_BASE_URL","BROODS_PROJECT","BROODS_REGION"].filter((j)=>o[j]===void 0).length===0&&r!==void 0)return;let i=o.BROODS_PROJECT===void 0,a=r===void 0,c=o.BROODS_REGION===void 0,d=m(),l=R(e,"--dashboard-url")??d.dashboardUrl??ce,w=R(e,"--project")??process.env.BROODS_PROJECT??Pe(process.cwd()),u=R(e,"--stage")??S()??"development",P=R(e,"--region")??process.env.BROODS_REGION??Ae;if(process.stdin.isTTY&&i){let j=await xe(l,R(e,"--base-url")),I=new X({baseUrl:j.baseUrl,token:j.token}),W=await Ii(I,j),te=await Ni(I,W);if(w=await Mi(te,w),!w.trim())throw Error("Project name is required.")}if(process.stdin.isTTY&&a){if(u=await ke("Stage",u),!u.trim())throw Error("Stage is required.")}if(process.stdin.isTTY&&c){let j=si.filter((I)=>At.includes(I.region));P=await Me("Select service region",j,(I)=>I.label,j.findIndex((I)=>I.region===P)).then((I)=>I.region)}await zn({dashboardUrl:l,baseUrl:d.baseUrl??O(l),project:w,stage:u,region:P,force:!1})}async function xe(e,n){try{return await ae(n)}catch(t){if(!process.stdin.isTTY)throw t;return D(`${t instanceof Error?t.message:String(t)} Starting browser login.`),await xn(e)}}async function Ii(e,n){try{return await e.getOnboarding()}catch(t){if(!(t instanceof on)||!n.org)throw t;return D("This broods server cannot list your orgs yet; using the org from your login."),{currentOrgId:n.org.id,orgs:[{id:n.org.id,name:n.org.name,slug:n.org.slug,role:"admin",accountStatus:"active"}],projects:[]}}}async function io(e,n,t,o){let r=t.orgs.find((s)=>s.id===t.currentOrgId);if(!r)throw Error("Selected organization is not visible to this login");if(process.env.BROODS_TOKEN)D("BROODS_TOKEN is set, so the switch applies to this token only and was not stored.");else await F({...n,org:{id:r.id,name:r.name,slug:r.slug},...t.account?{account:{id:t.account.id,username:t.account.username}}:{}});console.log(`Org: ${Ke(r)}`),console.log(`Projects: ${t.projects.length>0?t.projects.map((s)=>s.name).join(", "):"none yet"}`),await Bn(e,Ve(o))}async function Bn(e,n){let t;try{t=await e.getRuntimeKey(n.project,n.stage)}catch(r){D(`Could not read the runtime key for ${n.project}/${n.stage} (${r instanceof Error?r.message:String(r)}). BROODS_API_KEY still points at the previous scope. Run \`broods whoami\` to check it.`);return}if(!t?.apiKey){D(`${n.project}/${n.stage} is not synced here yet, so BROODS_API_KEY still points at the previous scope. Run \`broods dev\`.`);return}let o=C("BROODS_API_KEY");if(!o&&process.env.BROODS_API_KEY===t.apiKey)return;await $e("BROODS_API_KEY",t.apiKey),q(`Wrote BROODS_API_KEY (${t.keyHint}) to .env.local`),He("BROODS_API_KEY",o)}function He(e,n){if(!n)return;D(`${e} is exported in your shell, which wins over .env.local. Run \`unset ${e}\` or the next broods command keeps the old value.`)}function Ke(e){let n=e.role==="owner"||e.role==="admin"?e.role:"member",t=e.plan?`, ${e.plan} plan`:"";return`${e.name} (${e.slug}, ${n}${t})`}function _i(e){return e.slug===e.name?e.name:`${e.name} (${e.slug})`}function ao(e,n){let t=R(e,n);if(t===void 0&&e.some((o)=>o.startsWith(n)))throw Error(`${n} needs a branch name, or none.`);return t==="none"?null:t}function Gn(e){return e.empty?"nothing (it is already empty)":`${e.stageCount} stage(s), ${e.agentCount} agent(s), ${e.variableCount} env var(s), ${e.deploymentCount} deployment(s), ${e.fileCount} workspace file(s)`}function ji(e,n){let t=e.empty?"empty":Gn(e);return Ce(`${e.name}: ${t}`,e.name===n||e.slug===n)}function co(e,n=[]){console.log(` folder ${e.rootDirectory||"/"}`);let t=[["Production",e.productionBranch],["Development",e.developmentBranch]];for(let[o,r]of t){if(!r)continue;let s=n.find((a)=>a.branch===r),i=!s?"no deploy yet":s.status!=="completed"?"deploying":s.conclusion==="success"?"deployed":"failed";console.log(` ${o.padEnd(12)} ${r} ${i}${s?` ${s.sha.slice(0,7)} ${s.url}`:""}`)}if(!e.protectedSecrets)D("This plan has no environments on private repos, so the deploy keys are repo secrets any branch's workflow can read.");if(e.setupPullRequestUrl)D(`A protected branch got the workflow as a pull request; merge it to deploy on push: ${e.setupPullRequestUrl}`)}function Di(e,n){return Ce(So(e),Wn(e.name,n))}function So(e){let n=e.deploymentRegion?`, ${e.deploymentRegion}`:"";return`${e.name} (${e.kind}${n}): ${e.agentCount} agent(s), ${e.variableCount} env var(s)`}function Wn(e,n){return e.trim().toLowerCase()===n.trim().toLowerCase()}function Ve(e){return m(),{project:R(e,"--project")??process.env.BROODS_PROJECT??Pe(process.cwd()),stage:R(e,"--stage")??S()??"development"}}async function Ni(e,n){let t=n.orgs.filter((s)=>s.accountStatus==="active"),o={kind:"create",name:"New organization"},r=await Me("Select organization",[...t,o],(s)=>("kind"in s)?"Create new organization":Ke(s),t.findIndex((s)=>s.id===n.currentOrgId));if("kind"in r){let s=await ke("Organization name",Pe(process.cwd()));if(!s.trim())throw Error("Organization name is required.");return await e.createOnboardingOrg(s)}return r.id===n.currentOrgId?n:await e.selectOnboardingOrg(r.id)}function Ui(e,n){return e.projects.find((o)=>o.name===n||o.slug===n)?.name??n}function Li(e,n){return e.projects.find((t)=>t.name===n||t.slug===n)}async function Mi(e,n){let t=Ui(e,n);if(e.projects.length===0)return ke("Project name",t);for(;;){let o=await zt("Select project",e.projects,_i,{hint:"type a new project name",defaultValue:t}),r=typeof o==="string"?o:o.name,s=Li(e,r);if(!s)return r;if(await Le(`Continue with the existing project ${s.name}?`))return s.name}}function Bi(e,n){return new Promise((t,o)=>{let r=process.argv[1]??"",s=po(process.execPath,[r,"dev","--once",...e],{stdio:"inherit",env:n});s.on("error",o),s.on("exit",(i,a)=>{if(i===0){t();return}o(Error(a?`Sync child exited from signal ${a}`:`Sync child exited with code ${i??"unknown"}`))})})}async function Gi(e){let n=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),t=await ae(R(e,"--base-url")??n.config.baseUrl),o=new X({baseUrl:t.baseUrl,token:t.token}),r=await Eo(o,n.manifest,await Hn(o,n.manifest));if(r.length>0)Cn(r);for(let s=1;;s+=1)try{return await Wi(o,n)}catch(i){if(!(i instanceof tn)||s===ri)throw i;D("Stage changed in another session. Re-reading...")}}async function Wi(e,n){let{manifest:t,resourceAliases:o,channels:r}=n,s=await e.getManifest(t.project,t.stage),i=$n(t,s?.manifest??null);an(i.filter((u)=>u.operation!=="delete"));let a=await e.putManifest(t,!1,!1,s===null?0:s.revision);await Ze(t,a.ids,process.cwd(),o,a.deployment,r),await Ao();let c=await Vi(),d=i.filter((u)=>u.operation==="delete"),l=d.filter((u)=>!c.has(`${u.kind}:${u.name}`)),w=!1;if(l.length>0)if(D("These remote resources are no longer declared locally:"),an(l),await Le(`Delete ${l.length} resource(s) from ${t.project}/${t.stage}?`))a=await e.putManifest(t,!0,!1,a.revision),await Ze(t,a.ids,process.cwd(),o,a.deployment,r),await zi(),w=!0;else await Yi(l.map((u)=>`${u.kind}:${u.name}`));if(!w&&d.length>0){let u=d.map((P)=>`${P.kind}:${P.name}`).join(", ");D(`${d.length} undeclared resource(s) kept remotely: ${u}. Re-declare in code or run \`deploy --prune\` to remove.`)}return await wo(e,t,a.deployment),ko(r,a),yo(a),a}function ko(e,n){let t=n.deployment;if(!t||e.length===0)return;let o=new N,r=new Map;for(let i of e){if(!n.ids.agents[i.agentName])continue;let a=r.get(i.type)??[];a.push(i.alias),r.set(i.type,a)}let s=t.stageKind===void 0||t.stageKind==="production";for(let[i,a]of r){let c=s?o.accountWebhookUrl(t.accountId,i):o.stageWebhookUrl(t.accountId,t.endpointId,i);console.log(`Channel ${a.join(", ")} (${i}): ${c}${i==="pancake"?"?secret=<PANCAKE_WEBHOOK_SECRET>":""}`)}}async function Hn(e,n){let t=yt(n).filter((r)=>!r.startsWith("BROODS_"));if(t.length===0)return[];let o=new Map((await e.listEnv(n.project,n.stage)).map((r)=>[r.name,r.valueDigest]));return t.map((r)=>({name:r,state:Hi(r,o)}))}async function Eo(e,n,t){let o=t.filter((r)=>r.state==="unset"||r.state==="drifted").map((r)=>r.name);if(o.length===0)return[];return await Promise.all(o.map((r)=>e.setEnv(n.project,n.stage,r,process.env[r]))),o}function Fi(e,n){let t=ln(e,"drifted");if(t.length>0)D(`.env.local and ${n} disagree on ${t.length} variable(s): ${t.join(", ")}. Run \`broods env sync\` to push the local values.`)}function Hi(e,n){let t=process.env[e],o=n.get(e);if(t===void 0||t==="")return o===void 0?"unresolved":"stage-only";if(o===void 0)return"unset";return o===Ki(t)?"synced":"drifted"}function Ki(e){return go("sha256").update(e).digest("hex")}function ln(e,n){return e.filter((t)=>t.state===n).map((t)=>t.name)}async function lo(e){let n=m(),{manifest:t,config:o}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),r=await ae(R(e,"--base-url")??o.baseUrl);Gt({project:t.project,stage:t.stage,dashboardUrl:R(e,"--dashboard-url")??n.dashboardUrl??r.dashboardUrl??o.dashboardUrl??ce})}async function Vi(){let e=process.env.BROODS_DECLINED_FILE;if(!e)return new Set;let n=await Re(e);return new Set(n.split(/\r?\n/).map((t)=>t.trim()).filter(Boolean))}async function Yi(e){let n=process.env.BROODS_DECLINED_FILE;if(!n||e.length===0)return;await Ee(n,`${e.join(`
424
452
  `)}
425
- `,{flag:"a"})}async function Hi(){let e=process.env.BROODS_DECLINED_FILE;if(!e)return;await Se(e,"","utf8")}async function Vi(e){let[n,t]=se(e);if(!n){console.log(ke("env",e));return}let o=n==="list"||n==="ls",r=n==="rm"||n==="remove",s=n==="get",i=n==="sync",a=n==="set"||r||s;if(!o&&!i&&!a)throw Error(`Unknown env subcommand: ${n}
453
+ `,{flag:"a"})}async function zi(){let e=process.env.BROODS_DECLINED_FILE;if(!e)return;await Ee(e,"","utf8")}async function Ji(e){let[n,t]=re(e);if(!n){console.log(be("env",e));return}let o=n==="list"||n==="ls",r=n==="rm"||n==="remove",s=n==="get",i=n==="sync",a=n==="set"||r||s;if(!o&&!i&&!a)throw Error(`Unknown env subcommand: ${n}
426
454
 
427
455
  ${oe("env")}`);if(a&&!t)throw Error(`broods env ${n} needs a variable name.
428
456
 
429
- ${oe("env")}`);let{manifest:c,config:l}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),d=await ae(R(e,"--base-url")??l.baseUrl),w=new q({baseUrl:d.baseUrl,token:d.token}),u=`${c.project}/${c.stage}`;if(i){await Yi(w,c,u);return}if(o){let j=await w.listEnv(c.project,c.stage);if(j.length===0){console.log(`No environment variables set for ${u}.`);return}console.log(`Environment variables for ${u} (values hidden):`);for(let I of j)console.log(` ${I.name}`);return}if(s){let j=await w.getEnv(c.project,c.stage,t);if(j===null){console.error(`${t} is not set for ${u}`),process.exitCode=1;return}console.log(j);return}if(r){await w.removeEnv(c.project,c.stage,t),X(`Removed ${t} from ${u}`);return}let P=await Yt(t);await w.setEnv(c.project,c.stage,t,P),X(`Stored ${t} for ${u}`)}async function Yi(e,n,t){let o=await Kn(e,n);if(o.length===0){console.log('No env("NAME") references in this project.');return}let r=await So(e,n,o);if(r.length>0)On(r);let s=an(o,"synced").length;console.log(r.length>0?`${s} other referenced variable(s) already in step with ${t}.`:`${s} referenced variable(s) already in step with ${t}.`);let i=an(o,"stage-only");if(i.length>0)console.log(`${i.length} referenced variable(s) live only on ${t}: ${i.join(", ")}`);let a=an(o,"unresolved");if(a.length>0)D(`${a.length} referenced variable(s) with no value here or on ${t}: ${a.join(", ")}. Put them in .env.local, or run \`broods env set <NAME> --stage ${n.stage}\`.`)}function Hn(e){if(V(e,"--all"))return"DEBUG";let n=R(e,"--level");if(n===void 0&&V(e,"--level"))throw Error("Missing value for --level. Use DEBUG, INFO, WARN, or ERROR.");if(!n)return"WARN";let t=n.toUpperCase();if(t==="DEBUG")return"DEBUG";if(t==="INFO")return"INFO";if(t==="WARN"||t==="WARNING")return"WARN";if(t==="ERROR")return"ERROR";throw Error(`Unknown log level: ${n}. Use DEBUG, INFO, WARN, or ERROR.`)}async function zi(e){m();let n=R(e,"--project")??process.env.BROODS_PROJECT,t=R(e,"--stage")??S();if(!n)throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT in .env.local.");if(!t)throw Error("Stage name is required. Pass --stage <name> or set BROODS_STAGE in .env.local.");return{project:n,stage:t}}async function Ke(e){let n=await zi(e),t=m(),o=await Fe(R(e,"--dashboard-url")??t.dashboardUrl??ue,R(e,"--base-url")),r=new q({baseUrl:o.baseUrl,token:o.token}),s=await r.mintStageSession(n.project,n.stage),i=s,a=async()=>{let c=i??await r.mintStageSession(n.project,n.stage);return i=void 0,c.token};return{baseUrl:o.baseUrl,credential:a,project:s.projectSlug,stage:s.stageSlug}}function Eo(e){return e==="WARN"?" (--all for INFO too)":""}function Vn(e,n){console.error(De(`Reconnecting to live logs (attempt ${e}): ${n}`,{stream:"stderr"}))}function Yn(e){let n=new Date(e.ts).toISOString().slice(11,23),t=e.level.padEnd(5),o=Un(e.message);return`${n} ${t} ${e.eventType} ${o}`}async function Ji(e){let n=await Ke(e),{project:t,stage:o}=n,r=Hn(e),s=new AbortController,i=()=>s.abort();process.on("SIGINT",i),console.log(`Streaming live logs for ${t}/${o} [${r}+]`+Eo(r)+", Ctrl+C to stop");try{for await(let a of Xe(n,{backfill:0,minLevel:r,signal:s.signal,onReconnect:Vn}))console.log(Yn(a))}catch(a){if(!s.signal.aborted)console.error(a instanceof Error?a.message:String(a)),process.exitCode=1}finally{process.off("SIGINT",i)}}async function qi(e){if(V(e,"--doctor")){await Xi(V(e,"--request"));return}let n=se(e)[0];if(!n){console.log(ke("machine",e));return}let{runMachineDaemon:t}=await import("../chunk-wamkxgcg.js"),{baseUrl:o,credential:r}=await Ke(e),s=M(R(e,"--cwd")??process.cwd()),i=V(e,"--computer"),a=R(e,"--mcp"),c=V(e,"--force"),l=new AbortController,d=()=>l.abort();process.on("SIGINT",d),console.log(`Connecting ${n} to ${o} (cwd ${s}${i?", computer use on":""}), Ctrl+C to stop`);try{await t({baseUrl:o,computer:i,credential:r,cwd:s,force:c,log:(w)=>console.log(w),mcpFile:a?M(a):void 0,sandbox:n,signal:l.signal})}catch(w){console.error(w instanceof Error?w.message:String(w)),process.exitCode=1}finally{process.off("SIGINT",d)}}async function Xi(e){try{let{startDesktop:n}=await import("../chunk-5tnnqapc.js"),{display:t,driver:o,permissions:r}=await n(e);o.stop();let s=(i)=>i?"granted":"missing";if(console.log(`screenshot frame ${t.width}x${t.height} (scale ${t.scale.toFixed(2)})`),console.log(`screen recording ${s(r.screenRecording)}`),console.log(`accessibility ${s(r.accessibility)}`),!r.screenRecording||!r.accessibility)console.log(e?"Approve the prompts, or add this terminal under System Settings > Privacy & Security, then run again.":"Run `broods machine --doctor --request` to show the macOS prompts."),process.exitCode=1}catch(n){console.error(n instanceof Error?n.message:String(n)),process.exitCode=1}}async function Zi(e){let n=await Ke(e),{project:t,stage:o}=n,r=R(e,"--sandbox");if(V(e,"--sandbox")&&!U(r))throw Error("--sandbox needs the instance log id, the UUID shown in the dashboard Instances sheet.");let s=r?"DEBUG":Hn(e),i=Number(R(e,"--limit")??R(e,"-n")??100);if(!Number.isInteger(i)||i<0||i>L)throw Error(`--limit must be an integer between 0 and ${L}`);let a=V(e,"--json"),c=new AbortController,l=()=>c.abort();process.on("SIGINT",l),console.log(`Logs for ${t}/${o}`+(r?` sandbox ${r}`:"")+` [${s}+]`+Eo(s)+` (backfill ${i}), Ctrl+C to stop`);try{for await(let d of Xe(n,{backfill:i,minLevel:s,...r?{sandboxId:r}:{},signal:c.signal,onReconnect:Vn}))if(a)console.log(JSON.stringify(d));else console.log(Yn(d))}catch(d){if(!c.signal.aborted)console.error(d instanceof Error?d.message:String(d)),process.exitCode=1}finally{process.off("SIGINT",l)}}async function Qi(e){let[n]=se(e);if(!F(n))throw Error(`Missing or malformed trace id: 32 lowercase hex characters, as the dashboard copies it.
457
+ ${oe("env")}`);let{manifest:c,config:d}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),l=await ae(R(e,"--base-url")??d.baseUrl),w=new X({baseUrl:l.baseUrl,token:l.token}),u=`${c.project}/${c.stage}`;if(i){await qi(w,c,u);return}if(o){let j=await w.listEnv(c.project,c.stage);if(j.length===0){console.log(`No environment variables set for ${u}.`);return}console.log(`Environment variables for ${u} (values hidden):`);for(let I of j)console.log(` ${I.name}`);return}if(s){let j=await w.getEnv(c.project,c.stage,t);if(j===null){console.error(`${t} is not set for ${u}`),process.exitCode=1;return}console.log(j);return}if(r){await w.removeEnv(c.project,c.stage,t),q(`Removed ${t} from ${u}`);return}let P=await Yt(t);await w.setEnv(c.project,c.stage,t,P),q(`Stored ${t} for ${u}`)}async function qi(e,n,t){let o=await Hn(e,n);if(o.length===0){console.log('No env("NAME") references in this project.');return}let r=await Eo(e,n,o);if(r.length>0)Cn(r);let s=ln(o,"synced").length;console.log(r.length>0?`${s} other referenced variable(s) already in step with ${t}.`:`${s} referenced variable(s) already in step with ${t}.`);let i=ln(o,"stage-only");if(i.length>0)console.log(`${i.length} referenced variable(s) live only on ${t}: ${i.join(", ")}`);let a=ln(o,"unresolved");if(a.length>0)D(`${a.length} referenced variable(s) with no value here or on ${t}: ${a.join(", ")}. Put them in .env.local, or run \`broods env set <NAME> --stage ${n.stage}\`.`)}function Kn(e){if(V(e,"--all"))return"DEBUG";let n=R(e,"--level");if(n===void 0&&V(e,"--level"))throw Error("Missing value for --level. Use DEBUG, INFO, WARN, or ERROR.");if(!n)return"WARN";let t=n.toUpperCase();if(t==="DEBUG")return"DEBUG";if(t==="INFO")return"INFO";if(t==="WARN"||t==="WARNING")return"WARN";if(t==="ERROR")return"ERROR";throw Error(`Unknown log level: ${n}. Use DEBUG, INFO, WARN, or ERROR.`)}async function Xi(e){m();let n=R(e,"--project")??process.env.BROODS_PROJECT,t=R(e,"--stage")??S();if(!n)throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT in .env.local.");if(!t)throw Error("Stage name is required. Pass --stage <name> or set BROODS_STAGE in .env.local.");return{project:n,stage:t}}async function Ye(e){let n=await Xi(e),t=m(),o=await xe(R(e,"--dashboard-url")??t.dashboardUrl??ce,R(e,"--base-url")),r=new X({baseUrl:o.baseUrl,token:o.token}),s=await r.mintStageSession(n.project,n.stage),i=s,a=async()=>{let c=i??await r.mintStageSession(n.project,n.stage);return i=void 0,c.token};return{baseUrl:o.baseUrl,credential:a,project:s.projectSlug,stage:s.stageSlug}}function $o(e){return e==="WARN"?" (--all for INFO too)":""}function Vn(e,n){console.error(Ne(`Reconnecting to live logs (attempt ${e}): ${n}`,{stream:"stderr"}))}function Yn(e){let n=new Date(e.ts).toISOString().slice(11,23),t=e.level.padEnd(5),o=Un(e.message);return`${n} ${t} ${e.eventType} ${o}`}async function Zi(e){let n=await Ye(e),{project:t,stage:o}=n,r=Kn(e),s=new AbortController,i=()=>s.abort();process.on("SIGINT",i),console.log(`Streaming live logs for ${t}/${o} [${r}+]`+$o(r)+", Ctrl+C to stop");try{for await(let a of en(n,{backfill:0,minLevel:r,signal:s.signal,onReconnect:Vn}))console.log(Yn(a))}catch(a){if(!s.signal.aborted)console.error(a instanceof Error?a.message:String(a)),process.exitCode=1}finally{process.off("SIGINT",i)}}async function Qi(e){if(V(e,"--doctor")){await ea(V(e,"--request"));return}let n=re(e)[0];if(!n){console.log(be("machine",e));return}let{runMachineDaemon:t}=await import("../chunk-fka39yjm.js"),{baseUrl:o,credential:r}=await Ye(e),s=M(R(e,"--cwd")??process.cwd()),i=V(e,"--computer"),a=R(e,"--mcp"),c=V(e,"--force"),d=new AbortController,l=()=>d.abort();process.on("SIGINT",l),console.log(`Connecting ${n} to ${o} (cwd ${s}${i?", computer use on":""}), Ctrl+C to stop`);try{await t({baseUrl:o,computer:i,credential:r,cwd:s,force:c,log:(w)=>console.log(w),mcpFile:a?M(a):void 0,sandbox:n,signal:d.signal})}catch(w){console.error(w instanceof Error?w.message:String(w)),process.exitCode=1}finally{process.off("SIGINT",l)}}async function ea(e){try{let{startDesktop:n}=await import("../chunk-5tnnqapc.js"),{display:t,driver:o,permissions:r}=await n(e);o.stop();let s=(i)=>i?"granted":"missing";if(console.log(`screenshot frame ${t.width}x${t.height} (scale ${t.scale.toFixed(2)})`),console.log(`screen recording ${s(r.screenRecording)}`),console.log(`accessibility ${s(r.accessibility)}`),!r.screenRecording||!r.accessibility)console.log(e?"Approve the prompts, or add this terminal under System Settings > Privacy & Security, then run again.":"Run `broods machine --doctor --request` to show the macOS prompts."),process.exitCode=1}catch(n){console.error(n instanceof Error?n.message:String(n)),process.exitCode=1}}async function na(e){let n=await Ye(e),{project:t,stage:o}=n,r=R(e,"--sandbox");if(V(e,"--sandbox")&&!U(r))throw Error("--sandbox needs the instance log id, the UUID shown in the dashboard Instances sheet.");let s=r?"DEBUG":Kn(e),i=Number(R(e,"--limit")??R(e,"-n")??100);if(!Number.isInteger(i)||i<0||i>L)throw Error(`--limit must be an integer between 0 and ${L}`);let a=V(e,"--json"),c=new AbortController,d=()=>c.abort();process.on("SIGINT",d),console.log(`Logs for ${t}/${o}`+(r?` sandbox ${r}`:"")+` [${s}+]`+$o(s)+` (backfill ${i}), Ctrl+C to stop`);try{for await(let l of en(n,{backfill:i,minLevel:s,...r?{sandboxId:r}:{},signal:c.signal,onReconnect:Vn}))if(a)console.log(JSON.stringify(l));else console.log(Yn(l))}catch(l){if(!c.signal.aborted)console.error(l instanceof Error?l.message:String(l)),process.exitCode=1}finally{process.off("SIGINT",d)}}async function ta(e){let[n]=re(e);if(!B(n))throw Error(`Missing or malformed trace id: 32 lowercase hex characters, as the dashboard copies it.
430
458
 
431
- ${oe("trace")}`);let t=await Ke(e),o=(await _t(t,n)).toSorted((a,c)=>a.startTimeMs-c.startTimeMs);if(V(e,"--json")){console.log(JSON.stringify(o,null,2));return}console.log(`Trace ${n} in ${t.project}/${t.stage}`);let r=new Set(o.map((a)=>a.spanId)),s=Map.groupBy(o,(a)=>a.parentSpanId&&a.parentSpanId!==a.spanId&&r.has(a.parentSpanId)?a.parentSpanId:""),i=(a,c)=>{for(let l of s.get(a)??[])console.log(ea(l,c)),i(l.spanId,c+1)};i("",0)}function ea(e,n){let t=new Date(e.startTimeMs).toISOString().slice(11,23),o=" ".repeat(n),r=e.attributes?.["tool.name"],s=typeof r==="string"?`${e.name} ${r}`:e.name,i=`${t} ${e.status.padEnd(11)} ${o}`,a=`${i}${s} ${Cn(e.durationMs)}`;if(!e.error)return Un(a);let c=" ".repeat(i.length),l=e.error.replaceAll(/\r\n?|\n/g,`
459
+ ${oe("trace")}`);let t=await Ye(e),o=(await It(t,n)).toSorted((a,c)=>a.startTimeMs-c.startTimeMs);if(V(e,"--json")){console.log(JSON.stringify(o,null,2));return}console.log(`Trace ${n} in ${t.project}/${t.stage}`);let r=new Set(o.map((a)=>a.spanId)),s=Map.groupBy(o,(a)=>a.parentSpanId&&a.parentSpanId!==a.spanId&&r.has(a.parentSpanId)?a.parentSpanId:""),i=(a,c)=>{for(let d of s.get(a)??[])console.log(oa(d,c)),i(d.spanId,c+1)};i("",0)}function oa(e,n){let t=new Date(e.startTimeMs).toISOString().slice(11,23),o=" ".repeat(n),r=e.attributes?.["tool.name"],s=typeof r==="string"?`${e.name} ${r}`:e.name,i=`${t} ${e.status.padEnd(11)} ${o}`,a=`${i}${s} ${An(e.durationMs)}`;if(!e.error)return Un(a);let c=" ".repeat(i.length),d=e.error.replaceAll(/\r\n?|\n/g,`
432
460
  ${c} `);return Un(`${a}
433
- ${c}error: ${l}`)}async function na(e){let[n,t]=se(e);if(!n){console.log(ke("agent",e));return}if(n==="list"||n==="ls"){await ta(e);return}if(n==="get"){await oa(t,e);return}throw Error(`Unknown agent subcommand: ${n}
461
+ ${c}error: ${d}`)}async function ra(e){let[n,t]=re(e);if(!n){console.log(be("agent",e));return}if(n==="list"||n==="ls"){await sa(e);return}if(n==="get"){await ia(t,e);return}throw Error(`Unknown agent subcommand: ${n}
434
462
 
435
- ${oe("agent")}`)}async function ko(e){let{manifest:n,config:t}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),o=await ae(R(e,"--base-url")??t.baseUrl),r=await new q({baseUrl:o.baseUrl,token:o.token}).getManifest(n.project,n.stage),s=n.resources.filter((i)=>i.kind==="agent").map((i)=>({name:i.name,config:i.config??{},agentId:r?.ids.agents[i.name]}));return{manifest:n,agents:s}}async function ta(e){let{manifest:n,agents:t}=await ko(e);if(t.length===0){console.log(`No agents declared in ${n.project}/${n.stage}.`);return}console.log(`Agents in ${n.project}/${n.stage}:`);for(let o of t){let r=$o(o.config),s=o.config.publicAccess===!0?"public":"private",i=o.agentId?o.agentId:"not deployed";console.log(` ${o.name} [${s}] ${r} (${i})`)}}async function oa(e,n){if(!e)throw Error(`Missing agent name.
463
+ ${oe("agent")}`)}async function Ro(e){let{manifest:n,config:t}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),o=await ae(R(e,"--base-url")??t.baseUrl),r=await new X({baseUrl:o.baseUrl,token:o.token}).getManifest(n.project,n.stage),s=n.resources.filter((i)=>i.kind==="agent").map((i)=>({name:i.name,config:i.config??{},agentId:r?.ids.agents[i.name]}));return{manifest:n,agents:s}}async function sa(e){let{manifest:n,agents:t}=await Ro(e);if(t.length===0){console.log(`No agents declared in ${n.project}/${n.stage}.`);return}console.log(`Agents in ${n.project}/${n.stage}:`);for(let o of t){let r=Oo(o.config),s=o.config.publicAccess===!0?"public":"private",i=o.agentId?o.agentId:"not deployed";console.log(` ${o.name} [${s}] ${r} (${i})`)}}async function ia(e,n){if(!e)throw Error(`Missing agent name.
436
464
 
437
- ${oe("agent")}`);let{manifest:t,agents:o}=await ko(n),r=o.find((u)=>u.name===e);if(!r)throw Error(`Unknown local agent: ${e}`);let s=r.config,i=[s.sandboxes].flat().filter((u)=>typeof u==="string").map((u,P)=>P===0?`${u} (default)`:u),a=Array.isArray(s.workspaces)?s.workspaces.map((u)=>typeof u==="string"?u:u.name).filter(Boolean):[],c=ye(s.tools)?Object.keys(s.tools):[],l=ye(s.channels)?Object.keys(s.channels):[],d=ye(s.subagent)&&Array.isArray(s.subagent.allowed)?s.subagent.allowed.map((u)=>typeof u==="string"?u:u.name).filter(Boolean):[],w=ye(s.hooks)&&Array.isArray(s.hooks.webhooks)?s.hooks.webhooks.filter(ye):[];if(console.log(`Agent: ${r.name}`),console.log(` Project/Stage: ${t.project}/${t.stage}`),console.log(` Deployed id: ${r.agentId??"not deployed"}`),console.log(` Public access: ${s.publicAccess===!0?"public (SSE/WebSocket enabled)":"private (secured by default)"}`),console.log(` Model: ${$o(s)}`),console.log(` Sandboxes: ${i.length>0?i.join(", "):"none"}`),console.log(` Workspaces: ${a.length>0?a.join(", "):"none"}`),console.log(` Tools: ${c.length>0?c.join(", "):"none"}`),console.log(` Subagents: ${d.length>0?d.join(", "):"none"}`),console.log(` Channels: ${l.length>0?l.join(", "):"none"}`),w.length>0)console.log(" Webhooks:"),w.forEach((u,P)=>{let j=Array.isArray(u.events)&&u.events.length>0?u.events.join(", "):"all events",I=u.enabled===!1?"disabled":"enabled",K=typeof u.url==="string"?u.url:"none";console.log(` [${P}] ${I} → ${K} (${j})`)})}function $o(e){let n=ye(e.model)?e.model:{},t=typeof n.provider==="string"?n.provider:void 0,o=typeof n.modelId==="string"?n.modelId:void 0;if(t&&o)return`${t}/${o}`;return o??t??"unconfigured model"}async function ra(e){let[n,...t]=se(e);if(!n)throw Error(`Missing agent name.
465
+ ${oe("agent")}`);let{manifest:t,agents:o}=await Ro(n),r=o.find((u)=>u.name===e);if(!r)throw Error(`Unknown local agent: ${e}`);let s=r.config,i=[s.sandboxes].flat().filter((u)=>typeof u==="string").map((u,P)=>P===0?`${u} (default)`:u),a=Array.isArray(s.workspaces)?s.workspaces.map((u)=>typeof u==="string"?u:u.name).filter(Boolean):[],c=Se(s.tools)?Object.keys(s.tools):[],d=Se(s.channels)?Object.keys(s.channels):[],l=Se(s.subagent)&&Array.isArray(s.subagent.allowed)?s.subagent.allowed.map((u)=>typeof u==="string"?u:u.name).filter(Boolean):[],w=Se(s.hooks)&&Array.isArray(s.hooks.webhooks)?s.hooks.webhooks.filter(Se):[];if(console.log(`Agent: ${r.name}`),console.log(` Project/Stage: ${t.project}/${t.stage}`),console.log(` Deployed id: ${r.agentId??"not deployed"}`),console.log(` Public access: ${s.publicAccess===!0?"public (SSE/WebSocket enabled)":"private (secured by default)"}`),console.log(` Model: ${Oo(s)}`),console.log(` Sandboxes: ${i.length>0?i.join(", "):"none"}`),console.log(` Workspaces: ${a.length>0?a.join(", "):"none"}`),console.log(` Tools: ${c.length>0?c.join(", "):"none"}`),console.log(` Subagents: ${l.length>0?l.join(", "):"none"}`),console.log(` Channels: ${d.length>0?d.join(", "):"none"}`),w.length>0)console.log(" Webhooks:"),w.forEach((u,P)=>{let j=Array.isArray(u.events)&&u.events.length>0?u.events.join(", "):"all events",I=u.enabled===!1?"disabled":"enabled",W=typeof u.url==="string"?u.url:"none";console.log(` [${P}] ${I} → ${W} (${j})`)})}function Oo(e){let n=Se(e.model)?e.model:{},t=typeof n.provider==="string"?n.provider:void 0,o=typeof n.modelId==="string"?n.modelId:void 0;if(t&&o)return`${t}/${o}`;return o??t??"unconfigured model"}async function aa(e){let[n,...t]=re(e);if(!n)throw Error(`Missing agent name.
438
466
 
439
- ${oe("run")}`);let o=t.join(" "),r=Boolean(process.stdin.isTTY&&process.stdout.isTTY);if(!r&&!o)throw Error("A prompt is required when output is redirected: broods run <agent> <prompt>. Run it in a terminal to chat without one.");let{manifest:s,config:i}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),a=await ae(R(e,"--base-url")??i.baseUrl),c=s.resources.find((te)=>te.kind==="agent"&&te.name===n);if(!c)throw Error(`Unknown local agent: ${n}`);let l=new q({baseUrl:a.baseUrl,token:a.token}),w=(await l.getManifest(s.project,s.stage))?.ids.agents[n];if(!w)throw Error(`Agent ${n} is not synced yet. Run broods dev --once or broods deploy first.`);let u=await l.getRuntimeKey(s.project,s.stage).catch(()=>null);if(u?.apiKey)await Ee("BROODS_API_KEY",u.apiKey);if(c.config.publicAccess!==!0)D(`Agent "${n}" does not set publicAccess: true. The public endpoint is secured by default; if the deployed agent has not enabled it, this run will be refused.`);let P=new N({baseUrl:R(e,"--base-url")??process.env.BROODS_BASE_URL??process.env.BROODS_HOST??a.baseUrl,...u?.apiKey?{apiKey:u.apiKey}:{}}),j={kind:"agent",name:n,id:w,project:s.project,stage:s.stage,...u?.endpointId?{endpointId:u.endpointId}:{},...u?.projectSlug?{projectSlug:u.projectSlug}:{},...u?.stageSlug?{stageSlug:u.stageSlug}:{}},{runAgentTui:I,streamAgentText:K}=await import("../chunk-qsx1j9kf.js");try{if(r){await I({client:P,agent:j,...o?{prompt:o}:{}});return}await K({client:P,agent:j,prompt:o})}catch(te){if((te instanceof Error?te.message:String(te)).includes("public_access_disabled"))throw Error(`Agent "${n}" is not publicly accessible (secured by default). Set publicAccess: true in its config and redeploy, or enable Public access in the dashboard.`);throw te}}async function cn(e,n,t){try{await Se(e,n,{flag:t?"w":"wx"})}catch(o){if(o.code==="EEXIST")return;throw o}}async function Ro(){let e=M(process.cwd(),".gitignore"),n=await $e(e);if(n.split(/\r?\n/).some((r)=>[".env.local","/.env.local",".env*.local",".env.*",".env*"].includes(r.trim())))return;let o=n?`${n.trimEnd()}
467
+ ${oe("run")}`);let o=t.join(" "),r=Boolean(process.stdin.isTTY&&process.stdout.isTTY);if(!r&&!o)throw Error("A prompt is required when output is redirected: broods run <agent> <prompt>. Run it in a terminal to chat without one.");let{manifest:s,config:i}=await pe({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),a=await ae(R(e,"--base-url")??i.baseUrl),c=s.resources.find((te)=>te.kind==="agent"&&te.name===n);if(!c)throw Error(`Unknown local agent: ${n}`);let d=new X({baseUrl:a.baseUrl,token:a.token}),w=(await d.getManifest(s.project,s.stage))?.ids.agents[n];if(!w)throw Error(`Agent ${n} is not synced yet. Run broods dev --once or broods deploy first.`);let u=await d.getRuntimeKey(s.project,s.stage).catch(()=>null);if(u?.apiKey)await $e("BROODS_API_KEY",u.apiKey);if(c.config.publicAccess!==!0)D(`Agent "${n}" does not set publicAccess: true. The public endpoint is secured by default; if the deployed agent has not enabled it, this run will be refused.`);let P=new N({baseUrl:R(e,"--base-url")??process.env.BROODS_BASE_URL??process.env.BROODS_HOST??a.baseUrl,...u?.apiKey?{apiKey:u.apiKey}:{}}),j={kind:"agent",name:n,id:w,project:s.project,stage:s.stage,...u?.endpointId?{endpointId:u.endpointId}:{},...u?.projectSlug?{projectSlug:u.projectSlug}:{},...u?.stageSlug?{stageSlug:u.stageSlug}:{}},{runAgentTui:I,streamAgentText:W}=await import("../chunk-qsx1j9kf.js");try{if(r){await I({client:P,agent:j,...o?{prompt:o}:{}});return}await W({client:P,agent:j,prompt:o})}catch(te){if((te instanceof Error?te.message:String(te)).includes("public_access_disabled"))throw Error(`Agent "${n}" is not publicly accessible (secured by default). Set publicAccess: true in its config and redeploy, or enable Public access in the dashboard.`);throw te}}async function dn(e,n,t){try{await Ee(e,n,{flag:t?"w":"wx"})}catch(o){if(o.code==="EEXIST")return;throw o}}async function Co(){let e=M(process.cwd(),".gitignore"),n=await Re(e);if(n.split(/\r?\n/).some((r)=>[".env.local","/.env.local",".env*.local",".env.*",".env*"].includes(r.trim())))return;let o=n?`${n.trimEnd()}
440
468
  .env*.local
441
469
  `:`.env*.local
442
- `;await Se(e,o,"utf8")}async function Oo(){let e=M(process.cwd(),y,".gitignore"),n=await $e(e),o=["_generated",".cache"].filter((s)=>!n.split(/\r?\n/).some((i)=>i.trim()===s));if(o.length===0)return;let r=n?n.trimEnd()+`
470
+ `;await Ee(e,o,"utf8")}async function Ao(){let e=M(process.cwd(),y,".gitignore"),n=await Re(e),o=["_generated",".cache"].filter((s)=>!n.split(/\r?\n/).some((i)=>i.trim()===s));if(o.length===0)return;let r=n?n.trimEnd()+`
443
471
  `+o.join(`
444
472
  `)+`
445
473
  `:o.join(`
446
474
  `)+`
447
- `;await Se(e,r,"utf8")}async function zn(e){let n=M(process.cwd(),".env.local"),t=await $e(n),o=x(t),r={BROODS_DASHBOARD_URL:e.dashboardUrl,BROODS_BASE_URL:e.baseUrl,BROODS_PROJECT:e.project,BROODS_STAGE:e.stage,BROODS_REGION:e.region},s=t?t.replace(/\n?$/,`
448
- `).split(/\n/):["# Local broods CLI settings. Tokens are stored outside the repo."],i=!1;for(let[c,l]of Object.entries(r)){if(!l)continue;if(o[c]!==void 0&&!e.force)continue;let d=s.findIndex((w)=>w.trim().startsWith(`${c}=`));if(d>=0)s[d]=`${c}=${ln(l)}`;else s.push(`${c}=${ln(l)}`);if(process.env[c]===void 0)process.env[c]=l;i=!0}if(!i&&t)return;let a=`${s.filter((c,l,d)=>!(c===""&&l===d.length-1)).join(`
475
+ `;await Ee(e,r,"utf8")}async function zn(e){let n=M(process.cwd(),".env.local"),t=await Re(n),o=x(t),r={BROODS_DASHBOARD_URL:e.dashboardUrl,BROODS_BASE_URL:e.baseUrl,BROODS_PROJECT:e.project,BROODS_STAGE:e.stage,BROODS_REGION:e.region},s=t?t.replace(/\n?$/,`
476
+ `).split(/\n/):["# Local broods CLI settings. Tokens are stored outside the repo."],i=!1;for(let[c,d]of Object.entries(r)){if(!d)continue;if(o[c]!==void 0&&!e.force)continue;let l=s.findIndex((w)=>w.trim().startsWith(`${c}=`));if(l>=0)s[l]=`${c}=${un(d)}`;else s.push(`${c}=${un(d)}`);if(process.env[c]===void 0)process.env[c]=d;i=!0}if(!i&&t)return;let a=`${s.filter((c,d,l)=>!(c===""&&d===l.length-1)).join(`
449
477
  `)}
450
- `;await H(n,a),await Ro()}async function Ee(e,n){let t=M(process.cwd(),".env.local"),o=await $e(t),r=o?o.replace(/\n?$/,`
451
- `).split(/\n/):["# Local broods CLI settings. Tokens are stored outside the repo."],s=r.findIndex((a)=>a.trim().startsWith(`${e}=`));if(s>=0)r[s]=`${e}=${ln(n)}`;else r.push(`${e}=${ln(n)}`);process.env[e]=n;let i=`${r.filter((a,c,l)=>!(a===""&&c===l.length-1)).join(`
478
+ `;await H(n,a),await Co()}async function $e(e,n){let t=M(process.cwd(),".env.local"),o=await Re(t),r=o?o.replace(/\n?$/,`
479
+ `).split(/\n/):["# Local broods CLI settings. Tokens are stored outside the repo."],s=r.findIndex((a)=>a.trim().startsWith(`${e}=`));if(s>=0)r[s]=`${e}=${un(n)}`;else r.push(`${e}=${un(n)}`);process.env[e]=n;let i=`${r.filter((a,c,d)=>!(a===""&&c===d.length-1)).join(`
452
480
  `)}
453
- `;await H(t,i),await Ro()}async function $e(e){try{return await co(e,"utf8")}catch(n){if(n.code==="ENOENT")return"";throw n}}function ln(e){return JSON.stringify(e)}function xe(e){return Xs(M(e)).replace(/^@/,"").replace(/\//g,"-").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"broods-app"}async function sa(){let e=M(process.cwd(),y),n=[];await Jn(e,n);let t=lo("sha256");for(let o of n.sort())t.update(Zs(e,o)),t.update("\x00"),t.update(await co(o)),t.update("\x00");return t.digest("hex")}async function Jn(e,n){let t=await zs(e,{withFileTypes:!0});for(let o of t){let r=Be(e,o.name);if(o.isDirectory()){if(o.name===b||o.name==="generated"||o.name===".cache")continue;await Jn(r,n);continue}if(o.isFile()&&(o.name.endsWith(".ts")||o.name.endsWith(".md")))n.push(r)}}function ia(e){return e.split(/[\\/]/).some((n)=>n===b||n==="generated"||n===".cache")}function Co(){return`import { defineAgent, defineSandbox, env } from "broods";
481
+ `;await H(t,i),await Co()}async function Re(e){try{return await uo(e,"utf8")}catch(n){if(n.code==="ENOENT")return"";throw n}}function un(e){return JSON.stringify(e)}function Pe(e){return Qs(M(e)).replace(/^@/,"").replace(/\//g,"-").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"broods-app"}async function ca(){let e=M(process.cwd(),y),n=[];await Jn(e,n);let t=go("sha256");for(let o of n.sort())t.update(ei(e,o)),t.update("\x00"),t.update(await uo(o)),t.update("\x00");return t.digest("hex")}async function Jn(e,n){let t=await qs(e,{withFileTypes:!0});for(let o of t){let r=Fe(e,o.name);if(o.isDirectory()){if(o.name===b||o.name==="generated"||o.name===".cache")continue;await Jn(r,n);continue}if(o.isFile()&&(o.name.endsWith(".ts")||o.name.endsWith(".md")))n.push(r)}}function la(e){return e.split(/[\\/]/).some((n)=>n===b||n==="generated"||n===".cache")}function xo(){return`import { defineAgent, defineSandbox, env } from "broods";
454
482
 
455
483
  // A Lambda sandbox: a fresh, ephemeral bash environment created per run.
456
484
  export const lambdaSandbox = defineSandbox({
@@ -479,4 +507,4 @@ export const myAgent = defineAgent({
479
507
  // only reachable via internal endpoints or channel webhooks.
480
508
  publicAccess: true,
481
509
  });
482
- `}function aa(){if("bun"in process.versions)return;if(typeof qs.registerHooks==="function")return;throw Error(`broods needs Node ${Le.engines.node.replace(">=","")} or newer, or Bun. This is Node ${process.version}.`)}function ca(e,n){if(e==="status")throw Error("status was renamed to whoami. Run `broods whoami`.");if(V(n,"--env")||R(n,"--env")!==void 0)throw Error("--env was renamed to --stage. Pass --stage <name> instead.");m();let t=process.env.BROODS_ENVIRONMENT;if(t!==void 0&&process.env.BROODS_STAGE===void 0)throw Error(`BROODS_ENVIRONMENT was renamed to BROODS_STAGE. Rename the key in .env.local (it is currently set to "${t}").`)}async function la(){let e=m(),n=k(),{createBroodsMcpServer:t,serveBroodsMcp:o}=await import("../chunk-7nrh4nqb.js"),r=n?new q({baseUrl:n.baseUrl,token:n.token}):null,s=t({allowDestructive:process.env.BROODS_MCP_ALLOW_DESTRUCTIVE==="1"&&C("BROODS_MCP_ALLOW_DESTRUCTIVE"),cli:r,scope:{project:e.project,stage:e.stage}});o(s),await new Promise((i)=>{process.stdin.on("close",i)})}ii().catch((e)=>{Wt(e instanceof Error?e.message:String(e)),process.exit(1)});export{ee,ie,A};
510
+ `}function da(){if("bun"in process.versions)return;if(typeof Zs.registerHooks==="function")return;throw Error(`broods needs Node ${Ge.engines.node.replace(">=","")} or newer, or Bun. This is Node ${process.version}.`)}function ua(e,n){if(e==="status")throw Error("status was renamed to whoami. Run `broods whoami`.");if(V(n,"--env")||R(n,"--env")!==void 0)throw Error("--env was renamed to --stage. Pass --stage <name> instead.");m();let t=process.env.BROODS_ENVIRONMENT;if(t!==void 0&&process.env.BROODS_STAGE===void 0)throw Error(`BROODS_ENVIRONMENT was renamed to BROODS_STAGE. Rename the key in .env.local (it is currently set to "${t}").`)}async function ga(){let e=m(),n=k(),{createBroodsMcpServer:t,serveBroodsMcp:o}=await import("../chunk-6e95e9kc.js"),r=n?new X({baseUrl:n.baseUrl,token:n.token}):null,s=t({allowDestructive:process.env.BROODS_MCP_ALLOW_DESTRUCTIVE==="1"&&C("BROODS_MCP_ALLOW_DESTRUCTIVE"),cli:r,scope:{project:e.project,stage:e.stage}});o(s),await new Promise((i)=>{process.stdin.on("close",i)})}ci().catch((e)=>{Wt(e instanceof Error?e.message:String(e)),process.exit(1)});export{ee,ie,A};