broods 0.54.0 → 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/account.d.ts +53 -615
- package/dist/account.js +1 -1
- package/dist/{chunk-b7pz9at2.js → chunk-2vxrctp1.js} +5 -5
- package/dist/{chunk-14wmsrrt.js → chunk-6e95e9kc.js} +9 -9
- package/dist/{chunk-b2485tsd.js → chunk-dgm6742m.js} +1 -1
- package/dist/chunk-fka39yjm.js +4 -0
- package/dist/{chunk-8zcgnjs8.js → chunk-pjvyrwbt.js} +14 -14
- package/dist/{chunk-1fn0c0fe.js → chunk-xv88e799.js} +2 -2
- package/dist/cli/index.js +121 -87
- package/dist/index.d.ts +126 -1175
- package/dist/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-fdkdmntk.js +0 -4
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
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,36 +37,42 @@ export const defineZaloChannel = passthrough;
|
|
|
39
37
|
export const defineZaloConnection = passthrough;
|
|
40
38
|
export const env = (name) => ({ __beeblastEnv: true, name });
|
|
41
39
|
export default {};
|
|
42
|
-
`,Ve=1e7,it=50000000,mn=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],gn={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 ue(e={}){let n=e.cwd??process.cwd();m(n);let t=He(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((P)=>h(P.value)).map((P)=>({exportName:P.exportName,file:P.file,resource:P.value})),a=i.map((P)=>P.resource);gt(a),gr(a);let c=fr(i,r),d=hr(a);for(let P of a)rr(P);for(let P of a)sr(P);for(let P of a)ir(P);ar(a),lr(a),mr(i,d);let l=pr(i),u=Zo(s,e.stage??(e.useRuntimeStage===!1?void 0:S()),e.command??"dev"),w=(await Promise.all(i.map((P)=>br(P,t,d)))).flat().sort((P,j)=>`${P.kind}:${P.name}`.localeCompare(`${j.kind}:${j.name}`)),O=new Map(w.filter((P)=>P.kind==="mcp").map((P)=>[P.name,P.config])),I=w.map((P)=>Ur(P,O));return gt(I),{config:s,resources:a,resourceAliases:l,channels:c,manifest:{version:1,project:s.project,stage:u,resources:I}}}function yt(e){let n=new Set;for(let t of e.resources){Pe(t.config,n,t.kind==="workspace");let o=t.config;if(t.kind==="agent")Pe(o.mcp,n,!0);if(t.kind==="mcp")Pe(o.headers,n,!0)}return[...n].sort()}function Pe(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)Pe(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))Pe(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=Ke(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)=>$e(e,o).localeCompare($e(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)=>te(i.value))?.value?.config??{},s=t??process.env.BROODS_PROJECT??r.project??Hr(Ko(He(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: ${un.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 l of s){let u=l.config,w=typeof u.id==="string"?u.id:void 0;if(w){if(i.has(w))throw Error(`Duplicate channel id: ${w}`);i.add(w)}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)=>cr(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 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"||!pn(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"||!pn(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 u=o.get(l);if(u&&u!==a.name)throw Error(`Channel ${l.type} is already attached to agent "${u}" 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 w=i!=="default"&&pn(i)?i:a.name,O=t.get(l)??`${w}${kt(l.type)}Channel`;if(r.has(O))throw Error(`Duplicate channel export alias: ${O}`);r.add(O),s.push({alias:O,type:l.type,id:O,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(xe))return[xe];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 pn(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!==xe)return;throw Error(`Channel "${e}" cannot use "${xe}" as its id: a record matches one exact room. To answer everywhere, set allowedChannelIds: ["${xe}"] 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 ie(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,ie(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 ie(o)}return ie(t.config)}var yr=new Set(["apiKey","base_url","baseURL","firstByteTimeoutMs","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==="firstbytetimeoutms")return'"firstByteTimeoutMs"';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(fn(e,t.activeTools,"activeTools"),fn(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`);fn(e,t.subsystems,"debug.subsystems")}function fn(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<=dn)return;throw Error(`Agent "${e.name}" config.skills.allowed must list at most ${dn} 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:ie(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(gn).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:gn[d],source:xr(l.toString())}]});if(o.length===0)return;let r=`${e}-hooks`,s=Pr(e,o),i=Buffer.byteLength(s);if(i>Ve)throw Error(`Agent "${e}" hook bundle is too large (${i} bytes, max ${Ve})`);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:Te(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 gn)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
|
|
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
|
|
50
|
-
`),c=o?r.map((d)=>{let l=encodeURIComponent(o.accountId),
|
|
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";
|
|
54
52
|
|
|
55
53
|
/** Typed references for resources defined in broods/. */
|
|
56
|
-
export const api = {
|
|
54
|
+
export const api = resourceApi({
|
|
57
55
|
agents: {
|
|
58
56
|
${a}
|
|
59
57
|
},
|
|
60
58
|
channels: {
|
|
61
59
|
${c}
|
|
62
60
|
},
|
|
63
|
-
workspaces: ${
|
|
64
|
-
sandboxes: ${
|
|
65
|
-
crons: ${
|
|
66
|
-
skills: ${
|
|
67
|
-
policies: ${
|
|
68
|
-
} as const
|
|
69
|
-
|
|
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)},
|
|
66
|
+
} as const);
|
|
67
|
+
|
|
68
|
+
/** Fails the build when generated output drifts from the SDK's contract,
|
|
69
|
+
* keeping the exact resource keys an annotation would widen. */
|
|
70
|
+
function resourceApi<T extends ResourceApi>(resources: T): T {
|
|
71
|
+
return resources;
|
|
72
|
+
}
|
|
73
|
+
`}function Xr(){return`// Generated by broods. Do not edit by hand.
|
|
70
74
|
export type { AgentReference, ChannelReference, AgentRunInput, AgentRunResult, ResourceApi } from "broods";
|
|
71
|
-
`}function
|
|
75
|
+
`}function Zr(e){return`// Generated by broods. Do not edit by hand.
|
|
72
76
|
export const ids = ${JSON.stringify(e,null,2)} as const;
|
|
73
77
|
export const agents = ids.agents;
|
|
74
78
|
export const workspaces = ids.workspaces;
|
|
@@ -76,19 +80,19 @@ export const sandboxes = ids.sandboxes;
|
|
|
76
80
|
export const crons = ids.crons;
|
|
77
81
|
export const skills = ids.skills;
|
|
78
82
|
export const policies = ids.policies;
|
|
79
|
-
`}function
|
|
83
|
+
`}function Qr(e){return`// Generated by broods. Do not edit by hand.
|
|
80
84
|
export const manifest = ${JSON.stringify(e,null,2)} as const;
|
|
81
|
-
`}function
|
|
82
|
-
${o.map((s)=>` ${
|
|
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(`
|
|
83
87
|
`)}
|
|
84
|
-
}`}function hn(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 bn=["ap-southeast-1","eu-west-1","us-east-1"],At=["eu-west-1"];var Pt=1,Tt=0,xt=60000,Je=15000;function Q(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 se(){let e=globalThis.WebSocket;if(!e)throw Error("WebSocket is not available in this environment.");return e}class x extends Error{}async function*qe(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 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 x||/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 Q(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=[],d=null,l=!1,u=null,w=()=>{u?.(),u=null},{socket:O,url:I}=It(e,await e.credential()),P=setTimeout(()=>{d=Error(`The observability gateway did not answer within ${Je/1000} s.`),l=!0,w()},Je),j=()=>{if(clearTimeout(P),O.readyState===Pt||O.readyState===Tt)O.close(1000,"client closed");i?.removeEventListener("abort",me)},me=()=>{l=!0,w(),j()};i?.addEventListener("abort",me,{once:!0}),O.onopen=()=>{if(i?.aborted){j();return}let Z={type:"subscribe",stream:"logs",...o>0?{backfill:o}:{},...a?{liveOnly:!0}:{},...r!==void 0?{minLevel:r}:{},...s!==void 0?{sandboxId:s}:{}};O.send(JSON.stringify(Z))},O.onmessage=(Z)=>{let he=Dt(Z.data);if(!he)return;if(clearTimeout(P),he.type!=="error")t();switch(he.type){case"backfill":if(he.stream==="logs"){for(let xo of he.entries)c.push(xo);w()}break;case"log":c.push(he.entry),w();break;case"error":d=Error(`Observability gateway error: ${he.error}`),l=!0,w();break;case"ready":break;default:break}},O.onerror=()=>{d=Error(`Cannot connect to the observability gateway at ${I}.`),l=!0,w()},O.onclose=(Z)=>{if(!l){if(Z.code!==1000)d=jt(Z);l=!0,w()}};try{while(!0){if(c.length>0){yield c.shift();continue}if(d)throw d;if(l)return;await new Promise((Z)=>{u=Z})}}finally{j()}}async function _t(e,n){let{socket:t,url:o}=It(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 ${Je/1000} s.`))},Je);t.onopen=()=>{let l={type:"fetchTrace",traceId:n};t.send(JSON.stringify(l))},t.onmessage=(l)=>{let u=Dt(l.data);if(u?.type==="error")c(Error(`Observability gateway error: ${u.error}`));else if(u?.type==="backfill"&&u.stream==="traces"){let w=u.entries;if(u.error)c(Error(u.error));else a(()=>r(w))}},t.onerror=()=>{c(Error(`Cannot connect to the observability gateway at ${o}.`))},t.onclose=(l)=>c(jt(l))})}function It(e,n){let t=Qr(e.baseUrl,e.project,e.stage);return{socket:new(se())(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`${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 es=new Set(["bundle","bundleStorageId","contentBase64"]),ns=new Set(["hook","mcp","skill"]),ts=30000;class Ze extends Error{}class Qe extends Error{}class J{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 V(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 V(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:Te(o)}}}));return{...e,resources:n}}async uploadMcpBundle(e,n,t){let o=await this.request(e,n,"/mcp-bundle-uploads",{method:"POST"});await V(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 V(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 V(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 V(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 V(r,"Set environment variable failed")}async listEnv(e,n){let t=await this.request(e,n,"/env",{method:"GET"});return await V(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 V(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 V(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 Re(e,"/v1/account/onboarding","broods org"),await V(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 V(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 Re(n,"/v1/account/stages","broods stage"),await V(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 Re(o,"/v1/account/stages","broods stage"),await V(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})});Re(t,"/v1/account/stage-session","broods logs");try{await V(t,"Open stage session failed")}catch(o){if(t.status===401||t.status===404)throw new x(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 Re(e,"/v1/account/projects","broods project"),await V(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(Re(n,"/v1/account/projects","broods project"),n.status===404)return null;return await V(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 V(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 en(e,n,{fetch:this.fetchImpl,timeoutMs:t})}}async function en(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 En(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 u=t.get(d);if(!u)s.push({key:d,resource:l});else if(Xe(yn(u))!==Xe(yn(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((u)=>!a.has(u.key)&&os(d.resource.kind)&&d.resource.kind===u.resource.kind&&Xe(Ut(d.resource))===Xe(Ut(u.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 os(e){return e==="agent"||e==="workspace"||e==="sandbox"||e==="policy"}function wn(e){if(Array.isArray(e))return e.map(wn);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,wn(o)]))}return e}function Ut(e){let n=yn(e),{name:t,...o}=n;return o}function yn(e){let n=wn(e);if(!ns.has(e.kind))return n;return{...n,config:Sn(n.config)}}function vn(e){if(Array.isArray(e))return e.map(vn);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>[n,vn(t)]));return e}function Xe(e){return JSON.stringify(vn(e))}function Sn(e){if(Array.isArray(e))return e.map(Sn);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).flatMap(([n,t])=>{if(es.has(n))return[];return[[n,Sn(t)]]}));return e}async function V(e,n){if(e.ok)return;let t=await e.text(),{message:o=t,code:r}=rs(t);if(r==="manifest_conflict")throw new Ze(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 Re(e,n,t){if(e.status!==404)return;if((e.headers.get("Content-Type")??"").includes("application/json"))return;throw new Qe(`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)>mn?n:null}var nn=["chatgpt"];var be={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 kn(e){return nn.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 De}from"node:readline/promises";import{stdin as ce,stdout as ae}from"node:process";import{Writable as ws}from"node:stream";function Oe(e,n,t={}){let o=`${n?"*":" "} ${e}`;return n?G(o,"\x1B[1m\x1B[36m",ne(t)):o}function Mt(e,n={}){let t=ne(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")}${Kt(e.stage,t)}`,` ${o("server")}${e.server}`]}function is(e,n={}){let t=ne(n),o=Ht(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(`
|
|
85
|
-
`)}function
|
|
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.
|
|
86
90
|
Check the browser tab and the dashboard logs for an error. If the browser shows
|
|
87
91
|
404 on /cli-auth/start, deploy the dashboard build that includes CLI auth or pass
|
|
88
92
|
--dashboard-url for the environment you deployed. Other common causes are missing
|
|
89
|
-
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
|
|
90
|
-
`);if(!s)throw Error(`${e} is required`);return s}finally{o.close(),
|
|
91
|
-
`)}}async function
|
|
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)}
|
|
92
96
|
`,"utf8")}catch{}}var no=`---
|
|
93
97
|
name: broods
|
|
94
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.
|
|
@@ -108,7 +112,7 @@ The \`broods\` CLI does the interaction: sign-in, project sync, env, logs, runni
|
|
|
108
112
|
|
|
109
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.
|
|
110
114
|
|
|
111
|
-
A project is the \`broods/\` directory. \`broods/index.ts\` exports resources built with the \`define*\` functions: \`defineAgent\`, \`defineSandbox\`, \`defineWorkspace\`, \`defineSkill\`, \`defineCron\`, \`defineMcp\`, \`definePolicy\`,
|
|
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.
|
|
112
116
|
|
|
113
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.
|
|
114
118
|
|
|
@@ -132,13 +136,13 @@ When the user hands you a trace id, or a prompt copied from the dashboard's Trac
|
|
|
132
136
|
|
|
133
137
|
## When the CLI has no command
|
|
134
138
|
|
|
135
|
-
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.
|
|
136
140
|
|
|
137
141
|
## Rules that keep you out of trouble
|
|
138
142
|
|
|
139
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.
|
|
140
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.
|
|
141
|
-
-
|
|
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.
|
|
142
146
|
- Deletes are confirmed, named, and singular. Never loop a delete over a list.
|
|
143
147
|
- Editing a manifest-declared resource outside the project drifts from the definition, and the next deploy silently reverts it.
|
|
144
148
|
`;var to=`#!/usr/bin/env bash
|
|
@@ -167,7 +171,9 @@ STATUS=$?
|
|
|
167
171
|
set -e
|
|
168
172
|
echo "$WHOAMI"
|
|
169
173
|
|
|
170
|
-
|
|
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
|
|
171
177
|
echo
|
|
172
178
|
echo "Opening the browser to sign in. Finish the login there."
|
|
173
179
|
broods login
|
|
@@ -176,23 +182,23 @@ elif [ "$STATUS" -ne 0 ]; then
|
|
|
176
182
|
# Not the expected signed-out state: surface the real failure.
|
|
177
183
|
exit "$STATUS"
|
|
178
184
|
fi
|
|
179
|
-
`;var
|
|
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:
|
|
180
186
|
--project <name> Project name override (default: package name or folder)
|
|
181
187
|
--stage <name> Target stage override (BROODS_STAGE otherwise)
|
|
182
188
|
--base-url <url> broods API base URL for sync/env calls (default: discovered at login)
|
|
183
|
-
--dashboard-url <url> Dashboard base URL for login and deep links (default: ${
|
|
184
|
-
-h, --help Show this help`,
|
|
189
|
+
--dashboard-url <url> Dashboard base URL for login and deep links (default: ${ce})
|
|
190
|
+
-h, --help Show this help`,ii=`Commands
|
|
185
191
|
Develop dev diff run logs stream
|
|
186
|
-
Ship deploy env stage
|
|
192
|
+
Ship deploy env stage github
|
|
187
193
|
Inspect agent trace whoami
|
|
188
194
|
Account login connect disconnect org project
|
|
189
|
-
Tools init machine mcp update`,
|
|
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]
|
|
190
196
|
|
|
191
197
|
Subcommands:
|
|
192
198
|
list List the agents in the current project/stage scope
|
|
193
199
|
get <name> Show an agent's model, sandboxes, workspaces, tools and channels
|
|
194
200
|
|
|
195
|
-
${
|
|
201
|
+
${J}`,connect:`Usage: broods connect [type]
|
|
196
202
|
|
|
197
203
|
Signs an external account in through the browser and keeps it on your
|
|
198
204
|
deployment, so agents act through it. Without a type, lists the account's
|
|
@@ -200,22 +206,23 @@ connections. Uses the account key in BROODS_ACCOUNT_SECRET when set, otherwise
|
|
|
200
206
|
your broods login.
|
|
201
207
|
|
|
202
208
|
Types:
|
|
203
|
-
${
|
|
209
|
+
${sn.map((e)=>` ${e.padEnd(11)} ${ve[e].description}`).join(`
|
|
204
210
|
`)}
|
|
205
211
|
|
|
206
|
-
${
|
|
212
|
+
${J}`,deploy:`Usage: broods deploy [options]
|
|
207
213
|
|
|
208
214
|
Syncs Production once and writes BROODS_API_KEY to .env.local, plus
|
|
209
|
-
BROODS_USER_TOKEN_SECRET when the stage has no signing secret yet.
|
|
210
|
-
BROODS_STAGE by design. Pass --stage to deploy
|
|
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.
|
|
211
218
|
|
|
212
219
|
Options:
|
|
213
220
|
--prune Allow deploy to delete undeclared remote resources
|
|
214
221
|
--rotate-key Mint a fresh runtime key and write it to .env.local
|
|
215
222
|
--region <region> Production's region, pinned by its first deploy
|
|
216
|
-
(default: ${
|
|
223
|
+
(default: ${Ae})
|
|
217
224
|
|
|
218
|
-
${
|
|
225
|
+
${J}`,dev:`Usage: broods dev [--once] [options]
|
|
219
226
|
|
|
220
227
|
Watches broods/, syncs the current stage (BROODS_STAGE, default Development)
|
|
221
228
|
and live-tails agent logs. Confirms before deleting, and auto-pushes
|
|
@@ -225,18 +232,18 @@ Options:
|
|
|
225
232
|
--once Sync a single time and exit (no watch, no log stream)
|
|
226
233
|
--level <lvl> Minimum level for the log tail DEBUG|INFO|WARN|ERROR (default: WARN)
|
|
227
234
|
--all Tail INFO and up (DEBUG is dashboard-only)
|
|
228
|
-
--region <region> Service region for a new project (default: ${
|
|
235
|
+
--region <region> Service region for a new project (default: ${Ae})
|
|
229
236
|
|
|
230
|
-
${
|
|
237
|
+
${J}`,diff:`Usage: broods diff [options]
|
|
231
238
|
|
|
232
239
|
Shows local desired state against the remote state of the current stage, and
|
|
233
240
|
warns when the stage's value for an env("NAME") ref no longer matches .env.local.
|
|
234
241
|
|
|
235
|
-
${
|
|
242
|
+
${J}`,disconnect:`Usage: broods disconnect <type>
|
|
236
243
|
|
|
237
244
|
Forgets the account's connection of that type and revokes it at the provider.
|
|
238
245
|
|
|
239
|
-
${
|
|
246
|
+
${J}`,env:`Usage: broods env <set|get|list|rm|sync> [name]
|
|
240
247
|
|
|
241
248
|
Subcommands:
|
|
242
249
|
set <name> Store an encrypted environment variable (value read from the prompt or stdin)
|
|
@@ -252,23 +259,23 @@ Subcommands:
|
|
|
252
259
|
those the stage does not already hold the local value for. \`dev\` runs the same
|
|
253
260
|
push on every sync; \`deploy\` never does, so Production stays explicit.
|
|
254
261
|
|
|
255
|
-
${
|
|
262
|
+
${J}`,init:`Usage: broods init [options]
|
|
256
263
|
|
|
257
264
|
Creates the broods/ project shell and .env.local defaults.
|
|
258
265
|
|
|
259
266
|
Options:
|
|
260
|
-
--region <region> Broods service region preference (default: ${
|
|
267
|
+
--region <region> Broods service region preference (default: ${Ae})
|
|
261
268
|
--force Overwrite existing starter files
|
|
262
269
|
|
|
263
|
-
${
|
|
270
|
+
${J}`,login:`Usage: broods login [options]
|
|
264
271
|
|
|
265
272
|
Authenticates through the dashboard and stores the token in
|
|
266
273
|
~/.broods/config.json.
|
|
267
274
|
|
|
268
275
|
Options:
|
|
269
|
-
--region <region> Broods service region preference (default: ${
|
|
276
|
+
--region <region> Broods service region preference (default: ${Ae})
|
|
270
277
|
|
|
271
|
-
${
|
|
278
|
+
${J}`,logs:`Usage: broods logs [options]
|
|
272
279
|
|
|
273
280
|
Backfills recent logs then live-tails. Warnings and errors, 100 lines by default.
|
|
274
281
|
|
|
@@ -281,7 +288,7 @@ Options:
|
|
|
281
288
|
is the last segment of the instance's log stream
|
|
282
289
|
(dashboard Instances sheet).
|
|
283
290
|
|
|
284
|
-
${
|
|
291
|
+
${J}`,machine:`Usage: broods machine <sandbox> [options]
|
|
285
292
|
|
|
286
293
|
Connects this computer to a sandbox record whose provider is "machine". Agents
|
|
287
294
|
on that sandbox run their bash tool here, as you, with your PATH and
|
|
@@ -305,7 +312,7 @@ Options:
|
|
|
305
312
|
--force Take the record over from another daemon, even one on this computer
|
|
306
313
|
--doctor [--request] Check the macOS permissions computer use needs; --request prompts for them
|
|
307
314
|
|
|
308
|
-
${
|
|
315
|
+
${J}`,org:`Usage: broods org <list|use|create> [name]
|
|
309
316
|
|
|
310
317
|
Subcommands:
|
|
311
318
|
list List the organizations this login can act on
|
|
@@ -314,13 +321,38 @@ Subcommands:
|
|
|
314
321
|
|
|
315
322
|
Only orgs where you are owner or admin can be selected from the CLI.
|
|
316
323
|
|
|
317
|
-
${
|
|
324
|
+
${J}`,run:`Usage: broods run <agent> [prompt]
|
|
318
325
|
|
|
319
326
|
Chats with an agent in a terminal UI (reasoning, tool cards, y/n approvals).
|
|
320
327
|
A prompt is sent as the first turn; redirected output streams plain text and
|
|
321
328
|
therefore requires a prompt.
|
|
322
329
|
|
|
323
|
-
${
|
|
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
|
+
|
|
355
|
+
${J}`,project:`Usage: broods project <list|delete> [name]
|
|
324
356
|
|
|
325
357
|
Subcommands:
|
|
326
358
|
list List the org's projects and what each one still holds
|
|
@@ -333,7 +365,7 @@ admin role. There is no undo.
|
|
|
333
365
|
Options:
|
|
334
366
|
--yes Skip the confirmation prompt
|
|
335
367
|
|
|
336
|
-
${
|
|
368
|
+
${J}`,stage:`Usage: broods stage <list|use|create> [name]
|
|
337
369
|
|
|
338
370
|
Subcommands:
|
|
339
371
|
list List the project's stages
|
|
@@ -344,7 +376,7 @@ Options:
|
|
|
344
376
|
--from <stage> Clone the source stage's architecture and env vars
|
|
345
377
|
--use Switch to the stage \`stage create\` just made
|
|
346
378
|
|
|
347
|
-
${
|
|
379
|
+
${J}`,stream:`Usage: broods stream [options]
|
|
348
380
|
|
|
349
381
|
Streams live logs for the whole project/stage until Ctrl+C. No backfill.
|
|
350
382
|
|
|
@@ -352,7 +384,7 @@ Options:
|
|
|
352
384
|
--level <lvl> Minimum log level DEBUG|INFO|WARN|ERROR (default: WARN)
|
|
353
385
|
--all Stream INFO and up (DEBUG is dashboard-only)
|
|
354
386
|
|
|
355
|
-
${
|
|
387
|
+
${J}`,trace:`Usage: broods trace <trace-id> [--json]
|
|
356
388
|
|
|
357
389
|
Prints one run's trace: every model step and tool call with its status,
|
|
358
390
|
duration and error. --json prints every span with its full attributes (system
|
|
@@ -364,7 +396,7 @@ Authenticates with your \`broods login\`, like \`broods logs\`.
|
|
|
364
396
|
Options:
|
|
365
397
|
--json Print the spans as a JSON array
|
|
366
398
|
|
|
367
|
-
${
|
|
399
|
+
${J}`,mcp:`Usage: broods mcp
|
|
368
400
|
|
|
369
401
|
Serves the account config plane to a development agent over MCP on stdio, so
|
|
370
402
|
Claude Code and friends drive broods through typed tools instead of curl. It
|
|
@@ -392,59 +424,61 @@ project the dependency is upgraded instead. A new major is only announced.`,whoa
|
|
|
392
424
|
|
|
393
425
|
Shows the login, server, org, plan, project and stage the next command uses.
|
|
394
426
|
|
|
395
|
-
${
|
|
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}
|
|
396
428
|
|
|
397
|
-
${
|
|
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)}
|
|
398
430
|
|
|
399
|
-
${t}`;let s=S(),i=s&&s!=="production"?`ignores stage ${s}`:void 0;return`${
|
|
431
|
+
${t}`;let s=S(),i=s&&s!=="production"?`ignores stage ${s}`:void 0;return`${On(r,"production",{...Ln,note:i})}
|
|
400
432
|
|
|
401
|
-
${t}`}function
|
|
402
|
-
`)}async function
|
|
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
|
|
403
435
|
.cache
|
|
404
|
-
`,n),await
|
|
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}
|
|
405
440
|
|
|
406
|
-
${
|
|
407
|
-
|
|
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}
|
|
408
443
|
|
|
409
|
-
${
|
|
410
|
-
|
|
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}
|
|
411
446
|
|
|
412
|
-
${
|
|
413
|
-
${P.length} empty project(s). Delete one with \`broods project delete <name>\`.`);return}let l=t??await ye("Project to delete","");if(!l.trim())throw Error("Project name is required.");let u=await d.listProjects(),w=u.find((I)=>I.name===l||I.slug===l);if(!w)throw Error(`No project named "${l}". Existing: ${u.map((I)=>I.name).join(", ")}.`);if(!W(e,"--yes")){if(console.log(`Deleting ${w.name} removes ${Bn(w)}.`),!await on(`Permanently delete project ${w.name}?`)){console.log("Left it alone. Pass --yes to skip this prompt.");return}}let O=await d.deleteProject(w.id);if(!O)throw Error(`Project ${w.name} was not found.`);if(X(`Deleted project ${O.name} (${Bn(O)})`),O.name===a.project||O.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]=oe(e);if(!n){console.log(Ee("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}
|
|
414
448
|
|
|
415
|
-
${
|
|
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
|
|
416
450
|
.cache
|
|
417
|
-
`,!1),
|
|
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(`
|
|
418
452
|
`)}
|
|
419
|
-
`,{flag:"a"})}async function
|
|
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}
|
|
420
454
|
|
|
421
|
-
${
|
|
455
|
+
${oe("env")}`);if(a&&!t)throw Error(`broods env ${n} needs a variable name.
|
|
422
456
|
|
|
423
|
-
${
|
|
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.
|
|
424
458
|
|
|
425
|
-
${
|
|
426
|
-
${c} `);return
|
|
427
|
-
${c}error: ${d}`)}async function
|
|
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,`
|
|
460
|
+
${c} `);return Un(`${a}
|
|
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}
|
|
428
462
|
|
|
429
|
-
${
|
|
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.
|
|
430
464
|
|
|
431
|
-
${
|
|
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.
|
|
432
466
|
|
|
433
|
-
${
|
|
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()}
|
|
434
468
|
.env*.local
|
|
435
469
|
`:`.env*.local
|
|
436
|
-
`;await
|
|
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()+`
|
|
437
471
|
`+o.join(`
|
|
438
472
|
`)+`
|
|
439
473
|
`:o.join(`
|
|
440
474
|
`)+`
|
|
441
|
-
`;await
|
|
442
|
-
`).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((
|
|
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(`
|
|
443
477
|
`)}
|
|
444
|
-
`;await
|
|
445
|
-
`).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}=${
|
|
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(`
|
|
446
480
|
`)}
|
|
447
|
-
`;await
|
|
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";
|
|
448
482
|
|
|
449
483
|
// A Lambda sandbox: a fresh, ephemeral bash environment created per run.
|
|
450
484
|
export const lambdaSandbox = defineSandbox({
|
|
@@ -473,4 +507,4 @@ export const myAgent = defineAgent({
|
|
|
473
507
|
// only reachable via internal endpoints or channel webhooks.
|
|
474
508
|
publicAccess: true,
|
|
475
509
|
});
|
|
476
|
-
`}function
|
|
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};
|