broods 0.52.1 → 0.52.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account.d.ts +5 -1
- package/dist/account.js +1 -1
- package/dist/{chunk-a8zhzzj7.js → chunk-1fn0c0fe.js} +2 -2
- package/dist/{chunk-pfvvdwms.js → chunk-5njt640x.js} +1 -1
- package/dist/chunk-e4ts6eg7.js +14 -0
- package/dist/chunk-fd02pxtq.js +0 -0
- package/dist/chunk-njamyfye.js +5 -0
- package/dist/{chunk-d960xefn.js → chunk-ynnv4vw7.js} +4 -4
- package/dist/chunk-zx8r5k20.js +58 -0
- package/dist/cli/index.js +57 -57
- package/dist/index.d.ts +5 -1
- package/dist/index.js +1 -1
- package/package.json +5 -5
- package/dist/chunk-9th6spww.js +0 -65
- package/dist/chunk-ckqc09s3.js +0 -14
- package/dist/chunk-kc1md1rd.js +0 -1
- package/dist/chunk-yqbtb9cd.js +0 -5
- /package/dist/{chunk-5esx8msr.js → chunk-hkbecyy0.js} +0 -0
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{D,L,y,b,I,k,U,B,S,f,A,m,C,F,Z,g,T,M,K,E,te,v,h}from"../chunk-njamyfye.js";import{p,_}from"../chunk-1fn0c0fe.js";import{chmod as Fs,lstat as Ks,mkdir as Wn,readFile as ro,readdir as Hs,stat as Ys,writeFile as ve}from"node:fs/promises";import{createHash as so}from"node:crypto";import Vs from"node:module";import{basename as zs,join as Me,relative as Js,resolve as W,sep as qs}from"node:path";import{watch as Zs}from"node:fs";import{spawn as io}from"node:child_process";import{tmpdir as Xs}from"node:os";import{performance as Qt}from"node:perf_hooks";import{stripVTControlCharacters as Un}from"node:util";import{fileURLToPath as Po,pathToFileURL as ut}from"node:url";import{createHash as Io}from"node:crypto";import{existsSync as _o,readFileSync as jo}from"node:fs";import{mkdtemp as Do,readdir as gt,readFile as Uo,rm as No,writeFile as Lo}from"node:fs/promises";import nt from"node:module";import{tmpdir as Mo}from"node:os";import{basename as Bo,extname as Go,isAbsolute as Wo,join as Ke,relative as $e,resolve as He}from"node:path";import{build as Fo,transformSync as pt}from"esbuild";var Jn=/\$\{([A-Z][A-Z0-9_]*)\}/;var qn={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"}},Zn=Object.keys(qn);function Xn(e){return Object.hasOwn(qn,e)}var Co=/(?:^|[\n;])\s*import\s+(?:[^;"'`]*?\s+from\s*)?["'](?!\.{1,2}\/|\/|node:)[^"']+["']|import\s*\(\s*["'](?!\.{1,2}\/|\/|node:)[^"']+["']\s*\)/,Oo=/(?:import\s+(?:[^;"'`]*?\s+from\s*)?["']node:|import\s*\(\s*["']node:)/,Ao=/(?<![.\w$])(?:process|Buffer)\s*(?:\?\.|\.|\[)/,xo=[/\b(?:__)?require\s*\(/,/(?<![.\w$])setImmediate\s*\(/,Oo,Ao,/\b__dirname\b/,Co],To=/(?<![.\w$])eval\s*\(|\bnew\s+Function\s*\(/;function Qn(e){return![...xo,To].some((n)=>n.test(e))}var dn=32;var un=["conversation","agent"];function et(e){return un.some((n)=>n===e)}var xe="*",Ko=new RegExp(Jn.source,"g"),Ho=`const passthrough = (input) => input;
|
|
3
3
|
export const defineAgent = passthrough;
|
|
4
4
|
export const defineBroods = passthrough;
|
|
5
5
|
export const defineCron = passthrough;
|
|
@@ -39,14 +39,14 @@ export const defineZaloChannel = passthrough;
|
|
|
39
39
|
export const defineZaloConnection = passthrough;
|
|
40
40
|
export const env = (name) => ({ __beeblastEnv: true, name });
|
|
41
41
|
export default {};
|
|
42
|
-
`,Ye=1e7,tt=50000000,mn=1e7,ot=20000000,rt=200,Ho=new Set(["node_modules",".git"]),Yo=[/^\.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(!_o(t))throw Error(`No ${y}/ folder in ${n}. Run \`broods dev\` to scaffold one.`);let o=await zo(t),r=await Jo(o),s=await Zo(r,n,e.project),i=r.filter((A)=>f(A.value)).map((A)=>({exportName:A.exportName,file:A.file,resource:A.value})),a=i.map((A)=>A.resource);at(a),cr(a);let c=dr(i,r),d=gr(a);for(let A of a)Qo(A);for(let A of a)er(A);for(let A of a)nr(A);tr(a),rr(a),ur(i,d);let l=lr(i),u=Vo(s,e.stage??(e.useRuntimeStage===!1?void 0:b()),e.command??"dev"),S=(await Promise.all(i.map((A)=>pr(A,t,d)))).flat().sort((A,I)=>`${A.kind}:${A.name}`.localeCompare(`${I.kind}:${I.name}`)),C=new Map(S.filter((A)=>A.kind==="mcp").map((A)=>[A.name,A.config])),P=S.map((A)=>_r(A,C));return at(P),{config:s,resources:a,resourceAliases:l,channels:c,manifest:{version:1,project:s.project,stage:u,resources:P}}}function ft(e){let n=new Set;for(let t of e.resources){Te(t.config,n,t.kind==="workspace");let o=t.config;if(t.kind==="agent")Te(o.mcp,n,!0);if(t.kind==="mcp")Te(o.headers,n,!0)}return[...n].sort()}function Te(e,n,t){if(t&&typeof e==="string"){for(let o of e.matchAll(Fo))n.add(o[1]);return}if(Array.isArray(e)){for(let o of e)Te(o,n,t);return}if(e&&typeof e==="object"){let o=e;if(o.__beeblastEnv===!0&&typeof o.name==="string"){n.add(o.name);return}for(let r of Object.values(o))Te(r,n,t)}}function Vo(e,n,t){if(n)return n;let o=e.stages?.[t];if(o)return o;return t==="deploy"?"production":"development"}async function zo(e){let n=[];async function t(o){let r=await gt(o,{withFileTypes:!0});for(let s of r){let i=Ke(o,s.name);if(s.isDirectory()){if(s.name===v||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 Jo(e){qo();let n=[];for(let t of e){let r=await import(`${ut(t).href}?t=${Date.now()}`);n.push(...Object.entries(r).map(([s,i])=>({exportName:s,file:t,value:i})))}return n}var st=!1;function qo(){if(st)return;if(st=!0,typeof nt.registerHooks!=="function")return;nt.registerHooks({load:(e,n,t)=>{let[o]=e.split("?");if(o===void 0||!o.startsWith("file:")||!o.endsWith(".ts"))return t(e,n);let r=Po(o);return{format:"module",shortCircuit:!0,source:pt(jo(r,"utf8"),{loader:"ts",format:"esm",sourcefile:r,sourcemap:"inline"}).code}}})}async function Zo(e,n,t){let r=e.find((i)=>te(i.value))?.value?.config??{},s=t??process.env.BROODS_PROJECT??r.project??Gr(Bo(He(n)));if(!s.trim())throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT.");return{...r,project:s}}var it=new Set(["agent","harness","model","provider","session","hooks","connections","tools","mcp","denyTools","sandboxes","workspaces","subagent","skills","scheduler","browser","policies","publicAccess","allowRunOverrides"]),Xo={workspace:"workspaces",skill:"skills",policy:"policies",tool:"tools",mcpServers:"mcp",channel:"connections",channels:"connections",hook:"hooks",subagents:"subagent",systemPrompt:"agent",system:"agent"};function Qo(e){if(e.kind!=="agent")return;let n=e.config;for(let t of Object.keys(n)){if(it.has(t))continue;if(t==="sandbox")throw Error(`Agent "${e.name}" config.sandbox was removed; use sandboxes, the first is the default`);let o=Xo[t],r=o?` Did you mean "${o}"?`:` Allowed keys: ${[...it].sort().join(", ")}.`;throw Error(`Agent "${e.name}" has an unknown config key "${t}".${r}`)}}function er(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 nr(e){if(e.kind!=="workspace")return;let n=e.config;if(n.partitioned!==void 0&&!et(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 tr(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(_):[],i=new Set;for(let l of s){let u=l.config,S=typeof u.id==="string"?u.id:void 0;if(S){if(i.has(S))throw Error(`Duplicate channel id: ${S}`);i.add(S)}if(l.partition)mt(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)=>or(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 mt(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 or(e,n){if(f(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(f(t)&&t.kind==="workspace")return t;if(typeof t==="string")return n.get(t)}return}function rr(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=ht(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=ir(i),c=sr(i,r,n);if(!c||ar(c))continue;throw Error(`Agent "${t.name}" workspace "${a}" uses sandbox "${c.name}" (${wt(c)}) which does not support S3 workspace mounts. Use lambda/sandbox, or daytona with options.mountAwsS3Buckets: true, or set this workspace ref to sandbox: null for read-only S3 access.`)}}}function ht(e,n){if(f(e)&&e.kind==="sandbox")return e;if(typeof e==="string")return n.get(e);return}function sr(e,n,t){if(e&&typeof e==="object"&&"sandbox"in e){let o=e.sandbox;if(o===null)return;return ht(o,t)}return n}function ir(e){if(f(e)&&e.kind==="workspace")return e.name;if(e&&typeof e==="object"&&"workspace"in e){let n=e.workspace;if(f(n))return n.name;if(typeof n==="string")return n}return"<unknown>"}function ar(e){let n=wt(e);if(n==="lambda"||n==="sandbox")return!0;if(n!=="daytona")return!1;let t=e.config.options;return Boolean(t&&typeof t==="object"&&!Array.isArray(t)&&t.mountAwsS3Buckets===!0)}function wt(e){return typeof e.config.provider==="string"?e.config.provider:"lambda"}function cr(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=f(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 at(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 lr(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 dr(e,n){let t=new Map;for(let i of n){if(!_(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(!_(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 S=i!=="default"&&pn(i)?i:a.name,C=t.get(l)??`${S}${yt(l.type)}Channel`;if(r.has(C))throw Error(`Duplicate channel export alias: ${C}`);r.add(C),s.push({alias:C,type:l.type,id:C,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 ur(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(!_(r))continue;if(bt(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 bt(e,n){let t=e.config.allowedChannelIds??[];if(t.includes(xe))return[xe];return[...new Set([...n.get(e)??[],...t])]}function gr(e){let n=new Map;for(let t of e){if(t.kind!=="channelRecord")continue;let o=t.config;if(!_(o.connection))continue;let r=vt(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 yt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function pn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}async function pr(e,n,t){let o=e.resource;if(o.kind==="agent"){let r=Sr(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=vt(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:Ur(o.name,{...r,externalId:i})}))}return[{kind:o.kind,name:o.name,...o.description?{description:o.description}:{},config:await fr(e,n)}]}function vt(e,n){if(n===void 0)return[];if(typeof n==="string")return ct(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`);ct(e,o),t.add(o)}return n}function ct(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 fr(e,n){let t=e.resource;if(t.kind==="skill")return await xr(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 se(o)}if(t.kind==="mcp")return await Tr(e,t.config,n);if(t.kind==="policy"){let o={...t.config};return o.version=o.version??1,se(o)}if(t.kind==="cron"){let o={...t.config},r=o.agent;if(o.agentId=f(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 se(o)}return se(t.config)}var mr=new Set(["apiKey","base_url","baseURL","gatewayId"]),hr=new Set(["activeTools","debug","inactiveTools","permissionMode","startupTimeoutMs","type","webSearch"]),wr=new Set(["enabled","level","subsystems"]);function br(e){if(mr.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 yr(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(!Xn(t))throw Error(`Agent "${e}" config.provider.${t} is not a supported provider (expected one of: ${Zn.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=br(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 vr(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(!hr.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`);Er(e,t.debug)}function Er(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(!wr.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 kr(e){if(new Set(e.config.skills?.allowed?.map((t)=>f(t)?t.name:t)).size<=dn)return;throw Error(`Agent "${e.name}" config.skills.allowed must list at most ${dn} skills`)}function Sr(e,n,t){let o={...e.config};yr(e.name,o.provider),vr(e.name,o.harness);let r=Array.isArray(o.sandboxes)?o.sandboxes.map((i)=>f(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`)}),kr(e);let s=$r(e.name,o.hooks);if(s)o.hooks=s.agentHooksConfig;else if(o.hooks!==void 0)o.hooks=Et(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(!_(i))throw Error(`Agent "${e.name}" config.connections must contain connection definitions`);let a=`${e.name}${yt(i.type)}Channel`,c=bt(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)=>jr(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=Or(o.policies,e.name);if(i)o.policies=i;else delete o.policies}return{config:se(o),...s?.hookResource?{hookResource:s.hookResource}:{}}}function $r(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:Rr(l.toString())}]});if(o.length===0)return;let r=`${e}-hooks`,s=Cr(e,o),i=Buffer.byteLength(s);if(i>Ye)throw Error(`Agent "${e}" hook bundle is too large (${i} bytes, max ${Ye})`);let a=o.map((d)=>d.event),c=Et(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:Pe(s)}}}}function Et(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 Rr(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 Cr(e,n){let t=`export default {
|
|
42
|
+
`,Ye=1e7,tt=50000000,mn=1e7,ot=20000000,rt=200,Yo=new Set(["node_modules",".git"]),Vo=[/^\.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(!_o(t))throw Error(`No ${y}/ folder in ${n}. Run \`broods dev\` to scaffold one.`);let o=await Jo(t),r=await qo(o),s=await Xo(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);at(a),lr(a);let c=ur(i,r),d=pr(a);for(let P of a)er(P);for(let P of a)nr(P);for(let P of a)tr(P);or(a),sr(a),gr(i,d);let l=dr(i),u=zo(s,e.stage??(e.useRuntimeStage===!1?void 0:S()),e.command??"dev"),w=(await Promise.all(i.map((P)=>fr(P,t,d)))).flat().sort((P,N)=>`${P.kind}:${P.name}`.localeCompare(`${N.kind}:${N.name}`)),O=new Map(w.filter((P)=>P.kind==="mcp").map((P)=>[P.name,P.config])),j=w.map((P)=>jr(P,O));return at(j),{config:s,resources:a,resourceAliases:l,channels:c,manifest:{version:1,project:s.project,stage:u,resources:j}}}function ft(e){let n=new Set;for(let t of e.resources){Te(t.config,n,t.kind==="workspace");let o=t.config;if(t.kind==="agent")Te(o.mcp,n,!0);if(t.kind==="mcp")Te(o.headers,n,!0)}return[...n].sort()}function Te(e,n,t){if(t&&typeof e==="string"){for(let o of e.matchAll(Ko))n.add(o[1]);return}if(Array.isArray(e)){for(let o of e)Te(o,n,t);return}if(e&&typeof e==="object"){let o=e;if(o.__beeblastEnv===!0&&typeof o.name==="string"){n.add(o.name);return}for(let r of Object.values(o))Te(r,n,t)}}function zo(e,n,t){if(n)return n;let o=e.stages?.[t];if(o)return o;return t==="deploy"?"production":"development"}async function Jo(e){let n=[];async function t(o){let r=await gt(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 qo(e){Zo();let n=[];for(let t of e){let r=await import(`${ut(t).href}?t=${Date.now()}`);n.push(...Object.entries(r).map(([s,i])=>({exportName:s,file:t,value:i})))}return n}var st=!1;function Zo(){if(st)return;if(st=!0,typeof nt.registerHooks!=="function")return;nt.registerHooks({resolve:(e,n,t)=>{try{return t(e,n)}catch(o){if(!/^\.{1,2}\//.test(e))throw o;let r=Go(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=Po(o);return{format:"module",shortCircuit:!0,source:pt(jo(r,"utf8"),{loader:"ts",format:"esm",sourcefile:r,sourcemap:"inline"}).code}}})}async function Xo(e,n,t){let r=e.find((i)=>te(i.value))?.value?.config??{},s=t??process.env.BROODS_PROJECT??r.project??Wr(Bo(He(n)));if(!s.trim())throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT.");return{...r,project:s}}var it=new Set(["agent","harness","model","provider","session","hooks","connections","tools","mcp","denyTools","sandboxes","workspaces","subagent","skills","scheduler","browser","policies","publicAccess","allowRunOverrides"]),Qo={workspace:"workspaces",skill:"skills",policy:"policies",tool:"tools",mcpServers:"mcp",channel:"connections",channels:"connections",hook:"hooks",subagents:"subagent",systemPrompt:"agent",system:"agent"};function er(e){if(e.kind!=="agent")return;let n=e.config;for(let t of Object.keys(n)){if(it.has(t))continue;if(t==="sandbox")throw Error(`Agent "${e.name}" config.sandbox was removed; use sandboxes, the first is the default`);let o=Qo[t],r=o?` Did you mean "${o}"?`:` Allowed keys: ${[...it].sort().join(", ")}.`;throw Error(`Agent "${e.name}" has an unknown config key "${t}".${r}`)}}function nr(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 tr(e){if(e.kind!=="workspace")return;let n=e.config;if(n.partitioned!==void 0&&!et(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 or(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)mt(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)=>rr(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 mt(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 rr(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 sr(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=ht(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=ar(i),c=ir(i,r,n);if(!c||cr(c))continue;throw Error(`Agent "${t.name}" workspace "${a}" uses sandbox "${c.name}" (${wt(c)}) which does not support S3 workspace mounts. Use lambda/sandbox, or daytona with options.mountAwsS3Buckets: true, or set this workspace ref to sandbox: null for read-only S3 access.`)}}}function ht(e,n){if(h(e)&&e.kind==="sandbox")return e;if(typeof e==="string")return n.get(e);return}function ir(e,n,t){if(e&&typeof e==="object"&&"sandbox"in e){let o=e.sandbox;if(o===null)return;return ht(o,t)}return n}function ar(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 cr(e){let n=wt(e);if(n==="lambda"||n==="sandbox")return!0;if(n!=="daytona")return!1;let t=e.config.options;return Boolean(t&&typeof t==="object"&&!Array.isArray(t)&&t.mountAwsS3Buckets===!0)}function wt(e){return typeof e.config.provider==="string"?e.config.provider:"lambda"}function lr(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 at(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 dr(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 ur(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}${yt(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 gr(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(bt(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 bt(e,n){let t=e.config.allowedChannelIds??[];if(t.includes(xe))return[xe];return[...new Set([...n.get(e)??[],...t])]}function pr(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=vt(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 yt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function pn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}async function fr(e,n,t){let o=e.resource;if(o.kind==="agent"){let r=$r(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=vt(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:Nr(o.name,{...r,externalId:i})}))}return[{kind:o.kind,name:o.name,...o.description?{description:o.description}:{},config:await mr(e,n)}]}function vt(e,n){if(n===void 0)return[];if(typeof n==="string")return ct(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`);ct(e,o),t.add(o)}return n}function ct(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 mr(e,n){let t=e.resource;if(t.kind==="skill")return await Tr(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 Pr(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 hr=new Set(["apiKey","base_url","baseURL","gatewayId"]),wr=new Set(["activeTools","debug","inactiveTools","permissionMode","startupTimeoutMs","type","webSearch"]),br=new Set(["enabled","level","subsystems"]);function yr(e){if(hr.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 vr(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(!Xn(t))throw Error(`Agent "${e}" config.provider.${t} is not a supported provider (expected one of: ${Zn.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=yr(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 Er(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(!wr.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`);kr(e,t.debug)}function kr(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(!br.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 Sr(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 $r(e,n,t){let o={...e.config};vr(e.name,o.provider),Er(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`)}),Sr(e);let s=Rr(e.name,o.hooks);if(s)o.hooks=s.agentHooksConfig;else if(o.hooks!==void 0)o.hooks=Et(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}${yt(i.type)}Channel`,c=bt(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)=>Dr(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=Ar(o.policies,e.name);if(i)o.policies=i;else delete o.policies}return{config:ie(o),...s?.hookResource?{hookResource:s.hookResource}:{}}}function Rr(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:Cr(l.toString())}]});if(o.length===0)return;let r=`${e}-hooks`,s=Or(e,o),i=Buffer.byteLength(s);if(i>Ye)throw Error(`Agent "${e}" hook bundle is too large (${i} bytes, max ${Ye})`);let a=o.map((d)=>d.event),c=Et(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:Pe(s)}}}}function Et(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 Cr(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 Or(e,n){let t=`export default {
|
|
43
43
|
${n.map((o)=>` ${JSON.stringify(o.event)}: ${o.source},`).join(`
|
|
44
44
|
`)}
|
|
45
45
|
};
|
|
46
|
-
`;try{return pt(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
|
|
46
|
+
`;try{return pt(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 Ar(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 lt(e,n){let t=await Do(Ke(Mo(),"broods-mcp-"));try{let o=Ke(t,"server.mjs");await Lo(o,n,"utf8");let r;try{r=await import(ut(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 No(t,{recursive:!0,force:!0})}}async function xr(e){let n=await Fo({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=Br(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 Tr(e,n){let t=Ur(n,e.path,"Skill"),o=$e(n,t).split("\\").join("/"),r=await Lr(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 Pr(e,n,t){let{handler:o,...r}=n,s=[o,n.url,n.sandbox].filter((u)=>u!==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 ie(r)}let i=$e(t,e.file).split("\\").join("/");Mr(i,"MCP server");let a=(u)=>xr({stdin:{contents:Ir(e),resolveDir:t,sourcefile:"mcp-handler.mjs",loader:"js"},label:"MCP server bundle",manifestPath:i,plugins:[_r()],workers:u}),c=n.runtime==="lambda"?void 0:await a(!0).catch(()=>{return}),d=c!==void 0&&Buffer.byteLength(c)<=mn&&Qn(c)&&await lt(i,c).then(()=>!0,()=>!1)?c:await a(!1),l=Buffer.byteLength(d);if(l>tt)throw Error(`MCP server bundle ${i} is too large (${l} bytes, max ${tt})`);return await lt(i,d),{...ie(r),bundle:d,sha256:Pe(d)}}function Ir(e){return`import * as __exports from ${JSON.stringify(e.file)};
|
|
47
47
|
const __mcp = __exports[${JSON.stringify(e.exportName)}];
|
|
48
48
|
export default __mcp?.config?.handler ?? __mcp?.handler;
|
|
49
|
-
`}function
|
|
49
|
+
`}function _r(){return{name:"broods-sdk-stub",setup:function(e){e.onResolve({filter:/^broods(\/.*)?$/},()=>({path:"broods",namespace:"broods-stub"})),e.onLoad({filter:/.*/,namespace:"broods-stub"},()=>({contents:Ho,loader:"js"}))}}}function jr(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((u)=>u.toLowerCase())),c=Object.entries(i?.headers??{}).filter(([u])=>!a.has(u.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 Dr(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 Ur(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=He(e),r=He(o,n),s=$e(o,r);if(s===""||!s.startsWith("..")&&!Wo(s))return r;throw Error(`${t} path ${n} must stay inside ${y}/`)}function Nr(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,mt(t.partition,`Channel "${e}"`),ie(t)}function ie(e){if(Array.isArray(e))return e.map((n)=>ie(n));if(h(e))return e.name;if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).map(([n,t])=>[n,ie(t)]));return e}async function Lr(e){let n=[],t=0;async function o(r){let s=await gt(r,{withFileTypes:!0});for(let i of s){let a=Ke(r,i.name),c=$e(e,a).split("\\").join("/");if(i.isDirectory()){if(dt(i.name))continue;await o(a)}else if(i.isFile()){if(dt(i.name)||kt(c))continue;let d=await Uo(a);if(d.byteLength>Ye)throw Error(`Skill bundle file ${c} is too large (${d.byteLength} bytes, max ${Ye})`);if(t+=d.byteLength,t>ot)throw Error(`Skill bundle at ${e} is too large (${t} bytes, max ${ot})`);if(n.length>=rt)throw Error(`Skill bundle at ${e} has too many files (max ${rt})`);n.push({path:c,size:d.byteLength,sha256:Pe(d),contentBase64:d.toString("base64"),contentType:Gr(c)})}}}return await o(e),n.sort((r,s)=>String(r.path).localeCompare(String(s.path)))}function dt(e){return e.startsWith(".")||Yo.has(e)}function Mr(e,n){if(kt(e))throw Error(`${n} bundle path ${e} looks like a hidden file or secret and will not be bundled`)}function Br(e){return e instanceof Error&&Array.isArray(e.errors)}function kt(e){return e.split("/").some((t)=>t.startsWith(".")||Vo.some((o)=>o.test(t)))}function Pe(e){return Io("sha256").update(e).digest("hex")}function Gr(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 Wr(e){return e.replace(/^@/,"").replace(/\//g,"-").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}import{mkdir as Fr,writeFile as Ve}from"node:fs/promises";import{resolve as Ie}from"node:path";async function ze(e,n,t=process.cwd(),o={},r=null,s=[]){let i=Ie(t,y,b),a=Kr(n,e);await Fr(i,{recursive:!0}),await Ve(Ie(i,"ids.ts"),Vr(a),"utf8"),await Ve(Ie(i,"api.ts"),Hr(e,a,o,r,s),"utf8"),await Ve(Ie(i,"resources.ts"),zr(e),"utf8"),await Ve(Ie(i,"dataModel.ts"),Yr(),"utf8")}function Kr(e,n){let t={agents:ge(n,"agent"),workspaces:ge(n,"workspace"),sandboxes:ge(n,"sandbox"),crons:ge(n,"cron"),skills:ge(n,"skill"),mcp:ge(n,"mcp"),policies:ge(n,"policy"),channelRecords:ge(n,"channelRecord")};return{agents:pe(e.agents,t.agents),workspaces:pe(e.workspaces,t.workspaces),sandboxes:pe(e.sandboxes,t.sandboxes),crons:pe(e.crons,t.crons),skills:pe(e.skills,t.skills),hooks:{},mcp:pe(e.mcp,t.mcp),policies:pe(e.policies,t.policies),channelRecords:pe(e.channelRecords,t.channelRecords)}}function ge(e,n){return new Set(e.resources.filter((t)=>t.kind===n).map((t)=>t.name))}function pe(e,n){return Object.fromEntries(Object.entries(e??{}).filter(([t])=>n.has(t)))}function Hr(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)=>` ${hn(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(`
|
|
50
50
|
`),c=o?r.map((d)=>{let l=encodeURIComponent(o.accountId),u=o.stageKind===void 0||o.stageKind==="production"?`/v1/webhooks/${l}/${encodeURIComponent(d.type)}`:`/v1/webhooks/${l}/dev/${encodeURIComponent(o.endpointId)}/${encodeURIComponent(d.type)}`;return` ${hn(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(u)} },`}).join(`
|
|
51
51
|
`):"";return`// Generated by broods. Do not edit by hand.
|
|
52
52
|
import type { ResourceApi } from "broods";
|
|
@@ -66,9 +66,9 @@ ${c}
|
|
|
66
66
|
skills: ${_e("skills",n.skills,t.skill)},
|
|
67
67
|
policies: ${_e("policies",n.policies,t.policy)},
|
|
68
68
|
} as const satisfies ResourceApi;
|
|
69
|
-
`}function
|
|
69
|
+
`}function Yr(){return`// Generated by broods. Do not edit by hand.
|
|
70
70
|
export type { AgentReference, ChannelReference, AgentRunInput, AgentRunResult, ResourceApi } from "broods";
|
|
71
|
-
`}function
|
|
71
|
+
`}function Vr(e){return`// Generated by broods. Do not edit by hand.
|
|
72
72
|
export const ids = ${JSON.stringify(e,null,2)} as const;
|
|
73
73
|
export const agents = ids.agents;
|
|
74
74
|
export const workspaces = ids.workspaces;
|
|
@@ -76,18 +76,18 @@ export const sandboxes = ids.sandboxes;
|
|
|
76
76
|
export const crons = ids.crons;
|
|
77
77
|
export const skills = ids.skills;
|
|
78
78
|
export const policies = ids.policies;
|
|
79
|
-
`}function
|
|
79
|
+
`}function zr(e){return`// Generated by broods. Do not edit by hand.
|
|
80
80
|
export const manifest = ${JSON.stringify(e,null,2)} as const;
|
|
81
81
|
`}function _e(e,n,t){let o=Object.keys(n);if(o.length===0)return"{}";return`{
|
|
82
82
|
${o.map((s)=>` ${hn(t?.[s]??s)}: ids.${e}[${JSON.stringify(s)}],`).join(`
|
|
83
83
|
`)}
|
|
84
|
-
}`}function hn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function St(e,n){return`${e}…${n.slice(-4)}`}var wn=["ap-southeast-1","eu-west-1","us-east-1"],$t=["eu-west-1"];var Ct=1,Ot=0,Rt=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 ie(){let e=globalThis.WebSocket;if(!e)throw Error("WebSocket is not available in this environment.");return e}class O 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 O||/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>=Rt)throw Error(`Gave up reconnecting to the live logs after ${Rt/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,S=()=>{u?.(),u=null},{socket:C,url:P}=xt(e,await e.credential()),A=setTimeout(()=>{d=Error(`The observability gateway did not answer within ${Je/1000} s.`),l=!0,S()},Je),I=()=>{if(clearTimeout(A),C.readyState===Ct||C.readyState===Ot)C.close(1000,"client closed");i?.removeEventListener("abort",me)},me=()=>{l=!0,S(),I()};i?.addEventListener("abort",me,{once:!0}),C.onopen=()=>{if(i?.aborted){I();return}let X={type:"subscribe",stream:"logs",...o>0?{backfill:o}:{},...a?{liveOnly:!0}:{},...r!==void 0?{minLevel:r}:{},...s!==void 0?{sandboxId:s}:{}};C.send(JSON.stringify(X))},C.onmessage=(X)=>{let he=Pt(X.data);if(!he)return;if(clearTimeout(A),he.type!=="error")t();switch(he.type){case"backfill":if(he.stream==="logs"){for(let Ro of he.entries)c.push(Ro);S()}break;case"log":c.push(he.entry),S();break;case"error":d=Error(`Observability gateway error: ${he.error}`),l=!0,S();break;case"ready":break;default:break}},C.onerror=()=>{d=Error(`Cannot connect to the observability gateway at ${P}.`),l=!0,S()},C.onclose=(X)=>{if(!l){if(X.code!==1000)d=Tt(X);l=!0,S()}};try{while(!0){if(c.length>0){yield c.shift();continue}if(d)throw d;if(l)return;await new Promise((X)=>{u=X})}}finally{I()}}async function At(e,n){let{socket:t,url:o}=xt(e,await e.credential());return new Promise((r,s)=>{let i=!1,a=(l)=>{if(i)return;if(i=!0,clearTimeout(d),t.readyState===Ct||t.readyState===Ot)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=Pt(l.data);if(u?.type==="error")c(Error(`Observability gateway error: ${u.error}`));else if(u?.type==="backfill"&&u.stream==="traces"){let S=u.entries;if(u.error)c(Error(u.error));else a(()=>r(S))}},t.onerror=()=>{c(Error(`Cannot connect to the observability gateway at ${o}.`))},t.onclose=(l)=>c(Tt(l))})}function xt(e,n){let t=Jr(e.baseUrl,e.project,e.stage);return{socket:new(ie())(t,k(n)),url:t}}function Tt(e){return Error(e.reason?`Observability WebSocket closed: ${e.reason}`:`Observability WebSocket closed with code ${e.code}.`)}function Jr(e,n,t){return`${W(e)}/v1/projects/${encodeURIComponent(n)}/stages/${encodeURIComponent(t)}/observability/ws`}function Pt(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 qr=new Set(["bundle","bundleStorageId","contentBase64"]),Zr=new Set(["hook","mcp","skill"]),Xr=30000;class Xe extends Error{}class Qe extends Error{}class J{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=h(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 K(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 K(s,"Sync manifest failed"),await s.json()}async externalizeLargeMcpBundles(e){if(e.resources.every((t)=>jt(t)===null))return e;let n=await Promise.all(e.resources.map(async(t)=>{let o=jt(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:Pe(o)}}}));return{...e,resources:n}}async uploadMcpBundle(e,n,t){let o=await this.request(e,n,"/mcp-bundle-uploads",{method:"POST"});await K(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 K(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 K(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 K(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 K(r,"Set environment variable failed")}async listEnv(e,n){let t=await this.request(e,n,"/env",{method:"GET"});return await K(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 K(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 K(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 K(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 K(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 K(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 K(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 K(t,"Open stage session failed")}catch(o){if(t.status===401||t.status===404)throw new O(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 K(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 K(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 K(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?Xr: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}: ${ns(s,r)}`,{cause:s})}}function kn(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(Ze(yn(u))!==Ze(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)&&Qr(d.resource.kind)&&d.resource.kind===u.resource.kind&&Ze(_t(d.resource))===Ze(_t(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)=>It(d).localeCompare(It(l)))}function It(e){return`${{create:0,rename:1,update:2,delete:3}[e.operation]}:${e.kind}:${e.previousName??""}:${e.name}`}function Qr(e){return e==="agent"||e==="workspace"||e==="sandbox"||e==="policy"}function bn(e){if(Array.isArray(e))return e.map(bn);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,bn(o)]))}return e}function _t(e){let n=yn(e),{name:t,...o}=n;return o}function yn(e){let n=bn(e);if(!Zr.has(e.kind))return n;return{...n,config:En(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 Ze(e){return JSON.stringify(vn(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(qr.has(n))return[];return[[n,En(t)]]}));return e}async function K(e,n){if(e.ok)return;let t=await e.text(),{message:o=t,code:r}=es(t);if(r==="manifest_conflict")throw new Xe(o);let s=e.status===401?"\nRun `broods login` to sign in again.":"";throw Error(`${n}: ${e.status} ${o}${s}`)}function es(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 ns(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 jt(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 we={chatgpt:{label:"ChatGPT plan",description:"Run agents on model.provider chatgpt with your ChatGPT plan",authorizeUrl:"https://auth.openai.com/api/accounts/authorize",tokenUrl:"https://auth.openai.com/api/accounts/oauth/token",revokeUrl:"https://auth.openai.com/api/accounts/oauth/revoke",jwksUrl:"https://auth.openai.com/.well-known/jwks.json",issuer:"https://auth.openai.com",scopes:["openid","profile","email","offline_access","resource.invoke","chatgpt.tokens.use.direct"],resource:"https://api.openai.com/v1",requiredScope:"chatgpt.tokens.use.direct",selfHostedOnly:"ChatGPT plan usage is only available on self-hosted Broods for now. Use an OpenAI API key with the `openai` provider instead.",managedOptIn:"CHATGPT_PLAN_ENABLED",modelsUrl:"https://api.openai.com/v1/models",usageUrl:"https://chatgpt.com/settings/usage"}};function Sn(e){return nn.some((n)=>n===e)}import{createHash as Es,randomBytes as ks,randomUUID as Ht}from"node:crypto";import{createServer as ls}from"node:http";import{createHash as ds,randomBytes as us,randomUUID as gs}from"node:crypto";import{spawn as ps}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 fs}from"node:stream";function Ce(e,n,t={}){let o=`${n?"*":" "} ${e}`;return n?L(o,"\x1B[1m\x1B[36m",ne(t)):o}function Dt(e,n={}){let t=ne(n),o=(i)=>L(i.padEnd(9),"\x1B[2m",t),r=!e.loggedIn?L("not logged in","\x1B[33m",t):e.org??L("unknown, run broods whoami","\x1B[2m",t),s=e.project??`none ${L(`(${e.projectGuess} from folder name)`,"\x1B[2m",t)}`;return[` ${o("org")}${r}`,` ${o("project")}${s}`,` ${o("stage")}${Bt(e.stage,t)}`,` ${o("server")}${e.server}`]}function ts(e,n={}){let t=ne(n),o=Gt(e.stage),r=o==="Development",s=L("▌",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?L("dashboard","\x1B[4m",t):"dashboard",c=`${e.dashboardUrl}?project=${encodeURIComponent(e.project)}&stage=${encodeURIComponent(e.stage)}`,d=L(c,"\x1B[2m\x1B[4m",t);return[`${s} Syncing ${o}: ${L(e.project,"",t)}`,`${s} ${i} ${e.stage} (${a})`,`${s} ${L("└─","\x1B[2m",t)} ${d}`].join(`
|
|
85
|
-
`)}function
|
|
84
|
+
}`}function hn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function St(e,n){return`${e}…${n.slice(-4)}`}var wn=["ap-southeast-1","eu-west-1","us-east-1"],$t=["eu-west-1"];var Ct=1,Ot=0,Rt=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 Jr(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>=Rt)throw Error(`Gave up reconnecting to the live logs after ${Rt/1000} s. Last error: ${a}`);r+=1,n.onReconnect?.(r,a),await Q(o,n.signal),o=Math.min(o*2,5000)}}async function*Jr(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:j}=xt(e,await e.credential()),P=setTimeout(()=>{d=Error(`The observability gateway did not answer within ${Je/1000} s.`),l=!0,w()},Je),N=()=>{if(clearTimeout(P),O.readyState===Ct||O.readyState===Ot)O.close(1000,"client closed");i?.removeEventListener("abort",me)},me=()=>{l=!0,w(),N()};i?.addEventListener("abort",me,{once:!0}),O.onopen=()=>{if(i?.aborted){N();return}let X={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(X))},O.onmessage=(X)=>{let he=Pt(X.data);if(!he)return;if(clearTimeout(P),he.type!=="error")t();switch(he.type){case"backfill":if(he.stream==="logs"){for(let Ro of he.entries)c.push(Ro);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 ${j}.`),l=!0,w()},O.onclose=(X)=>{if(!l){if(X.code!==1000)d=Tt(X);l=!0,w()}};try{while(!0){if(c.length>0){yield c.shift();continue}if(d)throw d;if(l)return;await new Promise((X)=>{u=X})}}finally{N()}}async function At(e,n){let{socket:t,url:o}=xt(e,await e.credential());return new Promise((r,s)=>{let i=!1,a=(l)=>{if(i)return;if(i=!0,clearTimeout(d),t.readyState===Ct||t.readyState===Ot)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=Pt(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(Tt(l))})}function xt(e,n){let t=qr(e.baseUrl,e.project,e.stage);return{socket:new(se())(t,E(n)),url:t}}function Tt(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 Pt(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 Zr=new Set(["bundle","bundleStorageId","contentBase64"]),Xr=new Set(["hook","mcp","skill"]),Qr=30000;class Xe 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)=>jt(t)===null))return e;let n=await Promise.all(e.resources.map(async(t)=>{let o=jt(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:Pe(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?Qr: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}: ${ts(s,r)}`,{cause:s})}}function kn(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(Ze(yn(u))!==Ze(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)&&es(d.resource.kind)&&d.resource.kind===u.resource.kind&&Ze(_t(d.resource))===Ze(_t(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)=>It(d).localeCompare(It(l)))}function It(e){return`${{create:0,rename:1,update:2,delete:3}[e.operation]}:${e.kind}:${e.previousName??""}:${e.name}`}function es(e){return e==="agent"||e==="workspace"||e==="sandbox"||e==="policy"}function bn(e){if(Array.isArray(e))return e.map(bn);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,bn(o)]))}return e}function _t(e){let n=yn(e),{name:t,...o}=n;return o}function yn(e){let n=bn(e);if(!Xr.has(e.kind))return n;return{...n,config:En(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 Ze(e){return JSON.stringify(vn(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(Zr.has(n))return[];return[[n,En(t)]]}));return e}async function V(e,n){if(e.ok)return;let t=await e.text(),{message:o=t,code:r}=ns(t);if(r==="manifest_conflict")throw new Xe(o);let s=e.status===401?"\nRun `broods login` to sign in again.":"";throw Error(`${n}: ${e.status} ${o}${s}`)}function ns(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 ts(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 jt(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 we={chatgpt:{label:"ChatGPT plan",description:"Run agents on model.provider chatgpt with your ChatGPT plan",authorizeUrl:"https://auth.openai.com/api/accounts/authorize",tokenUrl:"https://auth.openai.com/api/accounts/oauth/token",revokeUrl:"https://auth.openai.com/api/accounts/oauth/revoke",jwksUrl:"https://auth.openai.com/.well-known/jwks.json",issuer:"https://auth.openai.com",scopes:["openid","profile","email","offline_access","resource.invoke","chatgpt.tokens.use.direct"],resource:"https://api.openai.com/v1",requiredScope:"chatgpt.tokens.use.direct",selfHostedOnly:"ChatGPT plan usage is only available on self-hosted Broods for now. Use an OpenAI API key with the `openai` provider instead.",managedOptIn:"CHATGPT_PLAN_ENABLED",modelsUrl:"https://api.openai.com/v1/models",usageUrl:"https://chatgpt.com/settings/usage"}};function Sn(e){return nn.some((n)=>n===e)}import{createHash as ks,randomBytes as Ss,randomUUID as Ht}from"node:crypto";import{createServer as ds}from"node:http";import{createHash as us,randomBytes as gs,randomUUID as ps}from"node:crypto";import{spawn as fs}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 ms}from"node:stream";function Ce(e,n,t={}){let o=`${n?"*":" "} ${e}`;return n?H(o,"\x1B[1m\x1B[36m",ne(t)):o}function Dt(e,n={}){let t=ne(n),o=(i)=>H(i.padEnd(9),"\x1B[2m",t),r=!e.loggedIn?H("not logged in","\x1B[33m",t):e.org??H("unknown, run broods whoami","\x1B[2m",t),s=e.project??`none ${H(`(${e.projectGuess} from folder name)`,"\x1B[2m",t)}`;return[` ${o("org")}${r}`,` ${o("project")}${s}`,` ${o("stage")}${Bt(e.stage,t)}`,` ${o("server")}${e.server}`]}function os(e,n={}){let t=ne(n),o=Gt(e.stage),r=o==="Development",s=H("▌",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?H("dashboard","\x1B[4m",t):"dashboard",c=`${e.dashboardUrl}?project=${encodeURIComponent(e.project)}&stage=${encodeURIComponent(e.stage)}`,d=H(c,"\x1B[2m\x1B[4m",t);return[`${s} Syncing ${o}: ${H(e.project,"",t)}`,`${s} ${i} ${e.stage} (${a})`,`${s} ${H("└─","\x1B[2m",t)} ${d}`].join(`
|
|
85
|
+
`)}function rs(e,n={}){let t=ne(n);return e.map((o)=>{let r=ls(o.operation,t);if(o.operation==="rename"&&o.previousName)return` ${r} ${o.kind}:${o.previousName} -> ${o.name}`;return` ${r} ${o.kind}:${o.name}`})}function ss(e,n={}){let t=ne(n),o=H("▌","\x1B[32m",t),r=H("↑","\x1B[32m",t);return`${o} ${r} Synced ${e.length} env var(s) from .env.local: ${e.join(", ")}`}function is(e,n={}){return`${H("✖","\x1B[31m",ne(n))} ${e}`}function Ut(e,n={}){let t=ne(n),o=Math.max(...e.map(([r])=>r.length))+2;return e.map(([r,s])=>` ${r.padEnd(o)}${H(s,"\x1B[2m",t)}`)}function as(e,n={}){let t=(n.now??new Date).toTimeString().slice(0,8);return`${H("✔","\x1B[32m",ne(n))} ${t} Resources ready! (${Cn(e)})`}function cs(e,n={}){return`${H("✔","\x1B[32m",ne(n))} ${e}`}function $n(e,n,t={}){let o=ne(t),r=t.note?` ${H(`(${t.note})`,"\x1B[2m",o)}`:"";return` ${H("now","\x1B[2m",o)} ${e} → ${Bt(n,o)}${r}`}function je(e,n={}){return H(`! ${e}`,"\x1B[33m",ne(n))}function Nt(e){console.error(os(e))}function tn(e){for(let n of rs(e))console.log(n)}function Rn(e){console.error(ss(e))}function Lt(e){console.error(is(e,{stream:"stderr"}))}function Mt(e){console.error(as(e))}function q(e){console.log(cs(e,{stream:"stdout"}))}function G(e){console.log(je(e,{stream:"stdout"}))}function ls(e,n){if(e==="create")return`[${H("+","\x1B[32m",n)}]`;if(e==="rename")return`[${H("~","\x1B[33m",n)}]`;if(e==="update")return`[${H("*","\x1B[36m",n)}]`;return`[${H("-","\x1B[31m",n)}]`}function Cn(e){if(e>=1000)return`${(e/1000).toFixed(2)}s`;return`${Math.max(e,0).toFixed(1)}ms`}function H(e,n,t){return t?`${n}${e}\x1B[0m`:e}function Bt(e,n){let t=Gt(e)==="Development";return H(e,t?"\x1B[32m":"\x1B[33m",n)}function ne(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 Gt(e){let n=e.trim().toLowerCase();if(n==="development")return"Development";if(n==="production")return"Production";return e.trim()}var hs=180000,ws=`Timed out waiting for browser login to complete.
|
|
86
86
|
Check the browser tab and the dashboard logs for an error. If the browser shows
|
|
87
87
|
404 on /cli-auth/start, deploy the dashboard build that includes CLI auth or pass
|
|
88
88
|
--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).`,Wt=new Set(["--base-url","--cwd","--dashboard-url","--stage","--from","--level","--limit","--mcp","--project","--region","--sandbox","-n"]);function
|
|
90
|
-
`)}}async function Ue(e,n,t,o){if(n.length===0)throw Error(`${e}: no options available`);if(n.length===1)return n[0];let r=o!==void 0&&o>=0&&o<n.length?o:void 0;console.log(e),n.forEach((a,c)=>{console.log(Ce(`${c+1}. ${t(a)}`,c===r))});let s=r===void 0?`Choose 1-${n.length}: `:`Choose 1-${n.length} [${r+1}]: `,i=De({input:ce,output:ae});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 Kt(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=De({input:ce,output:ae});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 ye(e,n){if(!ce.isTTY)return n??"";let t=De({input:ce,output:ae});try{let o=t.question(`${e}: `);if(n){if(ce.isTTY&&ae.isTTY)ae.write("\x1B[90m");if(t.write(n),ce.isTTY&&ae.isTTY)ae.write("\x1B[0m")}return(await o).trim()||n||""}finally{t.close()}}function An(e){let{command:n,args:t}=
|
|
89
|
+
cliAuth Convex functions or no active API account (Organization settings -> API access).`,Wt=new Set(["--base-url","--cwd","--dashboard-url","--stage","--from","--level","--limit","--mcp","--project","--region","--sandbox","-n"]);function bs(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 Y(e,n){let t=Wt.has(n)?`${n}=`:null;return e.some((o)=>o===n||t!==null&&o.startsWith(t))}function be(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 oe(e){let n=[];for(let t=0;t<e.length;t+=1){let o=e[t];if(o===void 0)continue;if(Wt.has(o)){t+=1;continue}if(o.startsWith("-"))continue;n.push(o)}return n}async function On(e){let n=ps(),t=gs(32).toString("base64url"),o=us("sha256").update(t).digest("base64url"),{code:r,close:s}=await xn(n,{port:vs(),fixedPort:Boolean(process.env.BROODS_LOGIN_PORT),path:"/callback",read:Es,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 ys(a),console.log(`Opening ${a}`),An(a);let c=await Tn(r.promise),d=await en(`${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(),u={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 U(u),u}finally{s()}}async function re(e){m();let n=k(e);if(!n){let t=process.env.BROODS_DASHBOARD_URL,o=e??process.env.BROODS_BASE_URL??(t?A(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 on(e){if(!ce.isTTY)return!1;let n=De({input:ce,output:ae});try{let t=(await n.question(`${e} [y/N] `)).trim().toLowerCase();return t==="y"||t==="yes"}finally{n.close()}}async function Ft(e){ae.write(`${e}: `);let n=new ms({write:(o,r,s)=>s()}),t=De({input:ce,output:n,terminal:ce.isTTY===!0});try{let o=await t.question("");if(!o)throw Error(`${e} is required`);return o}finally{t.close(),ae.write(`
|
|
90
|
+
`)}}async function Ue(e,n,t,o){if(n.length===0)throw Error(`${e}: no options available`);if(n.length===1)return n[0];let r=o!==void 0&&o>=0&&o<n.length?o:void 0;console.log(e),n.forEach((a,c)=>{console.log(Ce(`${c+1}. ${t(a)}`,c===r))});let s=r===void 0?`Choose 1-${n.length}: `:`Choose 1-${n.length} [${r+1}]: `,i=De({input:ce,output:ae});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 Kt(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=De({input:ce,output:ae});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 ye(e,n){if(!ce.isTTY)return n??"";let t=De({input:ce,output:ae});try{let o=t.question(`${e}: `);if(n){if(ce.isTTY&&ae.isTTY)ae.write("\x1B[90m");if(t.write(n),ce.isTTY&&ae.isTTY)ae.write("\x1B[0m")}return(await o).trim()||n||""}finally{t.close()}}function An(e){let{command:n,args:t}=bs(e),o=fs(n,t,{stdio:"ignore",detached:!0});o.on("error",(r)=>{console.error(je(`Could not open a browser (${r.message}). Open the URL above to continue.`,{stream:"stderr"}))}),o.unref()}function xn(e,n){return new Promise((t,o)=>{let r=ds((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 u=n.read(l.searchParams);d.writeHead(200,{"Content-Type":"text/plain"}).end(n.done),s(u)}catch(u){d.writeHead(400,{"Content-Type":"text/plain"}).end(u instanceof Error?u.message:String(u)),i(u)}}),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=ws){let t,o=new Promise((r,s)=>{t=setTimeout(()=>s(Error(n)),hs)});try{return await Promise.race([e,o])}finally{if(t)clearTimeout(t)}}async function ys(e){let n=await en(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 vs(){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 Es(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 $s=1455,Rs="/auth/callback";async function Yt(e,n,t=An){let o=we[n].label,r=Ht(),s=Ht(),i=Ss(32).toString("base64url"),{code:a,close:c}=await xn(r,{port:$s,fixedPort:!1,path:Rs,read:Cs,done:`${o} is connected to broods. You can close this tab.`});try{let d=a.callbackUrl,l=await e.startConnection(n,{redirectUri:d,codeChallenge:ks("sha256").update(i).digest("base64url"),state:r,nonce:s});t(l.authorizeUrl),console.log(`Opening ${l.authorizeUrl}`);let u=await Tn(a.promise,`Timed out waiting for the ${o} sign-in to finish in the browser.`);return await e.connect(n,{code:u.code,codeVerifier:i,redirectUri:d,nonce:s,clientId:u.clientId??l.clientId,hostId:l.hostId})}finally{c()}}function Cs(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 As,readFile as xs,writeFile as Ts}from"node:fs/promises";import{dirname as Jt,join as _n,resolve as Ps,sep as fe}from"node:path";import{fileURLToPath as Is}from"node:url";var Ne={name:"broods",version:"0.52.3",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.2.0",esbuild:"^0.28.2"},devDependencies:{"@ai-sdk/tui":"1.0.154","@arethetypeswrong/cli":"^0.18.5","@chat-adapter/discord":"^4.38.1","@chat-adapter/github":"^4.38.1","@chat-adapter/slack":"^4.38.1","@chat-adapter/telegram":"^4.38.1","@modelcontextprotocol/server":"2.3.1","@types/bun":"^1.3.14","@typescript/typescript6":"6.0.2",ai:"^7.0.153",publint:"^0.3.23",rollup:"^4.62.4","rollup-plugin-dts":"^6.5.1",typescript:"^7.0.2",zod:"^4.6.7"},peerDependencies:{ai:"^7.0.153"},engines:{node:">=22.15"}};var Pn=_n(Jt(I),"update-check.json"),_s=86400000,js="https://registry.npmjs.org/broods/latest",Ds=2000,Us=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"]];function jn(e,n){let t=In(e),o=In(n);for(let r=0;r<3;r+=1){let s=t[r]??0,i=o[r]??0;if(s!==i)return s>i}return!Vt(e)&&Vt(n)}async function Dn(e={}){let n=await Ls(),t=e.maxAgeMs??_s;if(n&&Date.now()-n.checkedAt<t)return n.latest;let o=await Ns();if(o===null)return n?.latest??null;return await Bs({checkedAt:Date.now(),latest:o}),o}function Le(e){return In(e)[0]??0}function qt(e=Ps(process.cwd()),n=Is(import.meta.url),t=Ne.version){let o=`${fe}node_modules${fe}`,r=n.indexOf(o),s=r===-1?null:n.slice(0,r),i=s===null?n.startsWith(`${e}${fe}`):e===s||e.startsWith(`${s}${fe}`),a=n.includes(`${fe}.bun${fe}install${fe}global${fe}`),c=s??e,d=i?Ms(c):a?"bun":"npm",l=d==="npm"?"install":"add",u=d==="pnpm"&&zt(_n(c,"pnpm-workspace.yaml"))?["-w"]:[],w=`broods@${Le(t)}`;return{manager:d,global:!i,command:d,cwd:i?c:e,args:i?[l,...u,w]:[l,"-g",w]}}async function Ns(){try{let e=await fetch(js,{signal:AbortSignal.timeout(Ds),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 Vt(e){return e.includes("-")}async function Ls(){try{let e=JSON.parse(await xs(Pn,"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 Ms(e){return Us.find(([t])=>zt(_n(e,t)))?.[1]??"npm"}function In(e){let[n]=e.trim().replace(/^v/,"").split("-");return(n??"").split(".").slice(0,3).map((t)=>Number.parseInt(t,10)||0)}async function Bs(e){try{await As(Jt(Pn),{recursive:!0}),await Ts(Pn,`${JSON.stringify(e)}
|
|
91
91
|
`,"utf8")}catch{}}var Zt=`---
|
|
92
92
|
name: broods
|
|
93
93
|
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.
|
|
@@ -175,23 +175,23 @@ elif [ "$STATUS" -ne 0 ]; then
|
|
|
175
175
|
# Not the expected signed-out state: surface the real failure.
|
|
176
176
|
exit "$STATUS"
|
|
177
177
|
fi
|
|
178
|
-
`;var de=Ne.version,rn=Me(".agents","skills","broods"),le="https://dashboard.broods.app",
|
|
178
|
+
`;var de=Ne.version,rn=Me(".agents","skills","broods"),le="https://dashboard.broods.app",Qs=3,Oe="eu-west-1",ei=[{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)"}],z=`Global options:
|
|
179
179
|
--project <name> Project name override (default: package name or folder)
|
|
180
180
|
--stage <name> Target stage override (BROODS_STAGE otherwise)
|
|
181
181
|
--base-url <url> broods API base URL for sync/env calls (default: discovered at login)
|
|
182
182
|
--dashboard-url <url> Dashboard base URL for login and deep links (default: ${le})
|
|
183
|
-
-h, --help Show this help`,
|
|
183
|
+
-h, --help Show this help`,ni=`Commands
|
|
184
184
|
Develop dev diff run logs stream
|
|
185
185
|
Ship deploy env stage
|
|
186
186
|
Inspect agent trace whoami
|
|
187
187
|
Account login connect disconnect org project
|
|
188
|
-
Tools init machine mcp update`,Nn={stream:"stdout"},ao={color:!1},
|
|
188
|
+
Tools init machine mcp update`,Nn={stream:"stdout"},ao={color:!1},ti=new Set(["agent","deploy","dev","diff","env","logs","machine","run","stage","stream","trace"]),co={agent:`Usage: broods agent <list|get> [name]
|
|
189
189
|
|
|
190
190
|
Subcommands:
|
|
191
191
|
list List the agents in the current project/stage scope
|
|
192
192
|
get <name> Show an agent's model, sandboxes, workspaces, tools and channels
|
|
193
193
|
|
|
194
|
-
${
|
|
194
|
+
${z}`,connect:`Usage: broods connect [type]
|
|
195
195
|
|
|
196
196
|
Signs an external account in through the browser and keeps it on your
|
|
197
197
|
deployment, so agents act through it. Without a type, lists the account's
|
|
@@ -202,7 +202,7 @@ Types:
|
|
|
202
202
|
${nn.map((e)=>` ${e.padEnd(11)} ${we[e].description}`).join(`
|
|
203
203
|
`)}
|
|
204
204
|
|
|
205
|
-
${
|
|
205
|
+
${z}`,deploy:`Usage: broods deploy [options]
|
|
206
206
|
|
|
207
207
|
Syncs Production once and writes BROODS_API_KEY to .env.local, plus
|
|
208
208
|
BROODS_USER_TOKEN_SECRET when the stage has no signing secret yet. Ignores
|
|
@@ -214,7 +214,7 @@ Options:
|
|
|
214
214
|
--region <region> Production's region, pinned by its first deploy
|
|
215
215
|
(default: ${Oe})
|
|
216
216
|
|
|
217
|
-
${
|
|
217
|
+
${z}`,dev:`Usage: broods dev [--once] [options]
|
|
218
218
|
|
|
219
219
|
Watches broods/, syncs the current stage (BROODS_STAGE, default Development)
|
|
220
220
|
and live-tails agent logs. Confirms before deleting, and auto-pushes
|
|
@@ -226,16 +226,16 @@ Options:
|
|
|
226
226
|
--all Tail INFO and up (DEBUG is dashboard-only)
|
|
227
227
|
--region <region> Service region for a new project (default: ${Oe})
|
|
228
228
|
|
|
229
|
-
${
|
|
229
|
+
${z}`,diff:`Usage: broods diff [options]
|
|
230
230
|
|
|
231
231
|
Shows local desired state against the remote state of the current stage, and
|
|
232
232
|
warns when the stage's value for an env("NAME") ref no longer matches .env.local.
|
|
233
233
|
|
|
234
|
-
${
|
|
234
|
+
${z}`,disconnect:`Usage: broods disconnect <type>
|
|
235
235
|
|
|
236
236
|
Forgets the account's connection of that type and revokes it at the provider.
|
|
237
237
|
|
|
238
|
-
${
|
|
238
|
+
${z}`,env:`Usage: broods env <set|get|list|rm|sync> [name]
|
|
239
239
|
|
|
240
240
|
Subcommands:
|
|
241
241
|
set <name> Store an encrypted environment variable (value read from the prompt or stdin)
|
|
@@ -251,7 +251,7 @@ Subcommands:
|
|
|
251
251
|
those the stage does not already hold the local value for. \`dev\` runs the same
|
|
252
252
|
push on every sync; \`deploy\` never does, so Production stays explicit.
|
|
253
253
|
|
|
254
|
-
${
|
|
254
|
+
${z}`,init:`Usage: broods init [options]
|
|
255
255
|
|
|
256
256
|
Creates the broods/ project shell and .env.local defaults.
|
|
257
257
|
|
|
@@ -259,7 +259,7 @@ Options:
|
|
|
259
259
|
--region <region> Broods service region preference (default: ${Oe})
|
|
260
260
|
--force Overwrite existing starter files
|
|
261
261
|
|
|
262
|
-
${
|
|
262
|
+
${z}`,login:`Usage: broods login [options]
|
|
263
263
|
|
|
264
264
|
Authenticates through the dashboard and stores the token in
|
|
265
265
|
~/.broods/config.json.
|
|
@@ -267,7 +267,7 @@ Authenticates through the dashboard and stores the token in
|
|
|
267
267
|
Options:
|
|
268
268
|
--region <region> Broods service region preference (default: ${Oe})
|
|
269
269
|
|
|
270
|
-
${
|
|
270
|
+
${z}`,logs:`Usage: broods logs [options]
|
|
271
271
|
|
|
272
272
|
Backfills recent logs then live-tails. Warnings and errors, 100 lines by default.
|
|
273
273
|
|
|
@@ -280,7 +280,7 @@ Options:
|
|
|
280
280
|
is the last segment of the instance's log stream
|
|
281
281
|
(dashboard Instances sheet).
|
|
282
282
|
|
|
283
|
-
${
|
|
283
|
+
${z}`,machine:`Usage: broods machine <sandbox> [options]
|
|
284
284
|
|
|
285
285
|
Connects this computer to a sandbox record whose provider is "machine". Agents
|
|
286
286
|
on that sandbox run their bash tool here, as you, with your PATH and
|
|
@@ -304,7 +304,7 @@ Options:
|
|
|
304
304
|
--force Take the record over from another daemon, even one on this computer
|
|
305
305
|
--doctor [--request] Check the macOS permissions computer use needs; --request prompts for them
|
|
306
306
|
|
|
307
|
-
${
|
|
307
|
+
${z}`,org:`Usage: broods org <list|use|create> [name]
|
|
308
308
|
|
|
309
309
|
Subcommands:
|
|
310
310
|
list List the organizations this login can act on
|
|
@@ -313,13 +313,13 @@ Subcommands:
|
|
|
313
313
|
|
|
314
314
|
Only orgs where you are owner or admin can be selected from the CLI.
|
|
315
315
|
|
|
316
|
-
${
|
|
316
|
+
${z}`,run:`Usage: broods run <agent> [prompt]
|
|
317
317
|
|
|
318
318
|
Chats with an agent in a terminal UI (reasoning, tool cards, y/n approvals).
|
|
319
319
|
A prompt is sent as the first turn; redirected output streams plain text and
|
|
320
320
|
therefore requires a prompt.
|
|
321
321
|
|
|
322
|
-
${
|
|
322
|
+
${z}`,project:`Usage: broods project <list|delete> [name]
|
|
323
323
|
|
|
324
324
|
Subcommands:
|
|
325
325
|
list List the org's projects and what each one still holds
|
|
@@ -332,7 +332,7 @@ admin role. There is no undo.
|
|
|
332
332
|
Options:
|
|
333
333
|
--yes Skip the confirmation prompt
|
|
334
334
|
|
|
335
|
-
${
|
|
335
|
+
${z}`,stage:`Usage: broods stage <list|use|create> [name]
|
|
336
336
|
|
|
337
337
|
Subcommands:
|
|
338
338
|
list List the project's stages
|
|
@@ -343,7 +343,7 @@ Options:
|
|
|
343
343
|
--from <stage> Clone the source stage's architecture and env vars
|
|
344
344
|
--use Switch to the stage \`stage create\` just made
|
|
345
345
|
|
|
346
|
-
${
|
|
346
|
+
${z}`,stream:`Usage: broods stream [options]
|
|
347
347
|
|
|
348
348
|
Streams live logs for the whole project/stage until Ctrl+C. No backfill.
|
|
349
349
|
|
|
@@ -351,7 +351,7 @@ Options:
|
|
|
351
351
|
--level <lvl> Minimum log level DEBUG|INFO|WARN|ERROR (default: WARN)
|
|
352
352
|
--all Stream INFO and up (DEBUG is dashboard-only)
|
|
353
353
|
|
|
354
|
-
${
|
|
354
|
+
${z}`,trace:`Usage: broods trace <trace-id> [--json]
|
|
355
355
|
|
|
356
356
|
Prints one run's trace: every model step and tool call with its status,
|
|
357
357
|
duration and error. --json prints every span with its full attributes (system
|
|
@@ -363,7 +363,7 @@ Authenticates with your \`broods login\`, like \`broods logs\`.
|
|
|
363
363
|
Options:
|
|
364
364
|
--json Print the spans as a JSON array
|
|
365
365
|
|
|
366
|
-
${
|
|
366
|
+
${z}`,mcp:`Usage: broods mcp
|
|
367
367
|
|
|
368
368
|
Serves the account config plane to a development agent over MCP on stdio, so
|
|
369
369
|
Claude Code and friends drive broods through typed tools instead of curl. It
|
|
@@ -391,59 +391,59 @@ project the dependency is upgraded instead. A new major is only announced.`,whoa
|
|
|
391
391
|
|
|
392
392
|
Shows the login, server, org, plan, project and stage the next command uses.
|
|
393
393
|
|
|
394
|
-
${
|
|
394
|
+
${z}`};async function oi(){ra();let[,,e,...n]=process.argv;switch(e){case void 0:case"--help":case"-h":console.log(Ln(n,Nn));return;case"--version":case"-v":console.log(de);return}if(sa(e,n),co[e]&&(Y(n,"--help")||Y(n,"-h"))){console.log(ke(e,n));return}switch(e){case"init":await si(n);return;case"login":await ii(n);return;case"connect":await ci(n);return;case"disconnect":await li(n);return;case"whoami":await gi(n);return;case"org":await fi(n);return;case"project":await mi(n);return;case"stage":await hi(n);return;case"diff":await wi(n);return;case"deploy":await bi(n);return;case"dev":await vi(n);return;case"env":await Fi(n);return;case"stream":await Yi(n);return;case"logs":await Ji(n);return;case"trace":await qi(n);return;case"machine":await Vi(n);return;case"agent":await Xi(n);return;case"run":await na(n);return;case"mcp":await ia();return;case"update":await yi();return;default:throw Error(`Unknown command: ${e}
|
|
395
395
|
|
|
396
|
-
${Ln(n,ao)}`)}}function ee(e){return co[e]??Ln([],ao)}function lo(e){let n=m(),t=R(e,"--base-url")??n.baseUrl,o=
|
|
396
|
+
${Ln(n,ao)}`)}}function ee(e){return co[e]??Ln([],ao)}function lo(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:Ae(process.cwd()),server:r.replace(/^https?:\/\//,""),stage:R(e,"--stage")??n.stage??"development"}}function ri(e){if(!e.loggedIn)return[["broods login","sign in through the dashboard"]];if(!e.project)return[["broods dev","create a project and sync on save"]];return[["broods dev","sync on save, tail logs"],["broods run <agent>","chat with an agent"]]}function ke(e,n){let t=ee(e);if(!ti.has(e))return t;let o=lo(n),r=o.project??o.projectGuess;if(e!=="deploy"||R(n,"--stage")!==void 0)return`${$n(r,o.stage,Nn)}
|
|
397
397
|
|
|
398
|
-
${t}`;let s=
|
|
398
|
+
${t}`;let s=S(),i=s&&s!=="production"?`ignores stage ${s}`:void 0;return`${$n(r,"production",{...Nn,note:i})}
|
|
399
399
|
|
|
400
|
-
${t}`}function Ln(e,n){let t=lo(e);return[`broods v${de}`,"",...Dt(t,n),"","Next",...Ut(
|
|
401
|
-
`)}async function
|
|
400
|
+
${t}`}function Ln(e,n){let t=lo(e);return[`broods v${de}`,"",...Dt(t,n),"","Next",...Ut(ri(t),n),"",ni,"","Usage: broods <command> [options] -h, --help -v, --version","Run `broods <command> --help` for a command's flags."].join(`
|
|
401
|
+
`)}async function si(e){let n=Y(e,"--force"),t=W(process.cwd(),y);await Wn(W(t,b),{recursive:!0}),await an(W(t,"index.ts"),$o(),n),await an(W(t,".gitignore"),`_generated
|
|
402
402
|
.cache
|
|
403
|
-
`,n),await fo(n);let o=R(e,"--dashboard-url")??le;await Vn({dashboardUrl:o,baseUrl:
|
|
403
|
+
`,n),await fo(n);let o=R(e,"--dashboard-url")??le;await Vn({dashboardUrl:o,baseUrl:A(o),project:R(e,"--project")??Ae(process.cwd()),stage:R(e,"--stage")??"development",region:R(e,"--region")??Oe,force:n}),q(`Created ${y}/`)}async function ii(e){let n=m(),t=R(e,"--dashboard-url")??n.dashboardUrl??le,o=await On(t);await Vn({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 ui(o.baseUrl,o.token,a,c)}function ai(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 ci(e){let[n]=oe(e),t=await uo(e);if(n===void 0){await di(t);return}if(!Sn(n))throw Error(`Unknown connection type ${n}.
|
|
404
404
|
|
|
405
|
-
${ee("connect")}`);let o=we[n],r=await Yt(t,n).catch((s)=>{throw Error(
|
|
406
|
-
Connect one: broods connect <${nn.join("|")}>`)}async function
|
|
405
|
+
${ee("connect")}`);let o=we[n],r=await Yt(t,n).catch((s)=>{throw Error(ai(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 uo(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 re(n);return new _({accountSecret:o.token,baseUrl:n??o.baseUrl})}async function li(e){let[n]=oe(e);if(!n||!Sn(n))throw Error(ee("disconnect"));if(await(await uo(e)).disconnect(n)){q(`Disconnected ${we[n].label}`);return}console.log(`No ${n} connection.`)}async function di(e){let n=await e.listConnections();if(n.length===0)console.log("No connections yet.");else console.log(`${"TYPE".padEnd(16)} ACCOUNT`);for(let t of n)console.log(`${we[t.type].label.padEnd(16)} ${t.email??t.clientId}`);console.log(`
|
|
406
|
+
Connect one: broods connect <${nn.join("|")}>`)}async function ui(e,n,t,o){try{let s=await new J({baseUrl:e,token:n}).getRuntimeKey(t,o);if(s?.apiKey)await Ee("BROODS_API_KEY",s.apiKey),q(`Wrote BROODS_API_KEY (${s.keyHint}) to .env.local`)}catch{}}async function gi(e){let n=m(),t=ln(e),o=R(e,"--dashboard-url")??n.dashboardUrl??le,r=Boolean(R(e,"--project")??n.project);console.log(`broods v${de}`),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 re(R(e,"--base-url"))}catch(l){G(l instanceof Error?l.message:String(l));return}console.log(`Server: ${s.baseUrl}`);let i=new J({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?Ge(c):a.currentOrgId}`),a.account)console.log(`Account: ${a.account.username} (${a.account.status})`);if(!r){G("No project set. `broods dev` picks one.");return}await pi(i,t,c?.name);let d=a.projects.map((l)=>l.name);if(!d.includes(t.project))G(`This org has no project named ${t.project}. It has: ${d.length>0?d.join(", "):"none"}.`)}async function pi(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"),G(`Could not read the runtime key: ${i}`);else if(!s?.apiKey)console.log("Runtime key: none for this scope"),G(`${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)`),G("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`),G(`BROODS_API_KEY from ${r} belongs to a different org or stage. Run \`broods stage use ${n.stage}\` to repoint it.`)}async function fi(e){let[n,t]=oe(e);if(!n){console.log(ke("org",e));return}let o=n==="list"||n==="ls",r=n==="use"||n==="select";if(!o&&!r&&!(n==="create"||n==="new"))throw Error(`Unknown org subcommand: ${n}
|
|
407
407
|
|
|
408
|
-
${ee("org")}`);let i=m(),a=R(e,"--dashboard-url")??i.dashboardUrl??le,c=await We(a,R(e,"--base-url")),d=new J({baseUrl:c.baseUrl,token:c.token}),l=await d.getOnboarding();if(o){for(let
|
|
409
|
-
Only orgs where you are owner or admin can be selected from the CLI.`);return}if(r){let
|
|
408
|
+
${ee("org")}`);let i=m(),a=R(e,"--dashboard-url")??i.dashboardUrl??le,c=await We(a,R(e,"--base-url")),d=new J({baseUrl:c.baseUrl,token:c.token}),l=await d.getOnboarding();if(o){for(let w of l.orgs){let O=w.accountStatus==="active"?"":` [${w.accountStatus} account]`;console.log(Ce(`${Ge(w)}${O}`,w.id===l.currentOrgId))}console.log(`
|
|
409
|
+
Only orgs where you are owner or admin can be selected from the CLI.`);return}if(r){let w=l.orgs.filter((j)=>j.accountStatus==="active"),O=t?w.find((j)=>j.slug===t||j.name===t||j.id===t):await Ue("Select organization",w,Ge,w.findIndex((j)=>j.id===l.currentOrgId));if(!O)throw Error(`No selectable organization matches "${t}". Run \`broods org list\`.`);await to(d,c,await d.selectOnboardingOrg(O.id),e);return}let u=t??await ye("Organization name",Ae(process.cwd()));if(!u.trim())throw Error("Organization name is required.");await to(d,c,await d.createOnboardingOrg(u),e)}async function mi(e){let[n,t]=oe(e);if(!n){console.log(ke("project",e));return}let o=n==="list"||n==="ls";if(!o&&!(n==="delete"||n==="rm"))throw Error(`Unknown project subcommand: ${n}
|
|
410
410
|
|
|
411
|
-
${ee("project")}`);let s=m(),i=R(e,"--dashboard-url")??s.dashboardUrl??le,a=ln(e),c=await We(i,R(e,"--base-url")),d=new J({baseUrl:c.baseUrl,token:c.token});if(o){let
|
|
412
|
-
${
|
|
411
|
+
${ee("project")}`);let s=m(),i=R(e,"--dashboard-url")??s.dashboardUrl??le,a=ln(e),c=await We(i,R(e,"--base-url")),d=new J({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 N of j)console.log(Ai(N,a.project));let P=j.filter((N)=>N.empty);if(P.length>0)console.log(`
|
|
412
|
+
${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((j)=>j.name===l||j.slug===l);if(!w)throw Error(`No project named "${l}". Existing: ${u.map((j)=>j.name).join(", ")}.`);if(!Y(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(q(`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 hi(e){let[n,t]=oe(e);if(!n){console.log(ke("stage",e));return}let o=n==="list"||n==="ls",r=n==="use"||n==="select";if(!o&&!r&&!(n==="create"||n==="new"))throw Error(`Unknown stage subcommand: ${n}
|
|
413
413
|
|
|
414
|
-
${ee("stage")}`);let i=m(),a=R(e,"--dashboard-url")??i.dashboardUrl??le,c=ln(e),d=await We(a,R(e,"--base-url")),l=new J({baseUrl:d.baseUrl,token:d.token});if(o){let
|
|
414
|
+
${ee("stage")}`);let i=m(),a=R(e,"--dashboard-url")??i.dashboardUrl??le,c=ln(e),d=await We(a,R(e,"--base-url")),l=new J({baseUrl:d.baseUrl,token:d.token});if(o){let P=await l.listStages(c.project);if(P.length===0){console.log(`${c.project} has no stages yet. \`broods dev\` creates Development.`);return}console.log(`Stages for ${c.project}:`);for(let N of P)console.log(xi(N,c.stage));return}if(r){let P=await l.listStages(c.project),N=t?P.find((X)=>Gn(X.name,t)):await Ue("Select stage",P,mo,P.findIndex((X)=>Gn(X.name,c.stage)));if(!N)throw Error(`${c.project} has no stage "${t}". Existing: ${P.map((X)=>X.name).join(", ")}. Create it with \`broods stage create ${t} --from ${c.stage}\`.`);let me=C("BROODS_STAGE");await Ee("BROODS_STAGE",N.name),console.log(`Stage: ${N.name} (wrote BROODS_STAGE)`),Be("BROODS_STAGE",me),await Mn(l,{project:c.project,stage:N.name});return}let u=t??await ye("Stage name","staging");if(!u.trim())throw Error("Stage name is required.");let w=R(e,"--from"),O=await l.createStage(c.project,u,w);if(q(`Created stage ${O.stage.name} in ${c.project}${O.clonedFrom?` from ${O.clonedFrom}`:""}`),O.clonedFrom)console.log(` ${O.stage.agentCount} agent(s), ${O.stage.variableCount} env var(s) copied`);if(!Y(e,"--use")){console.log(`Switch to it with \`broods stage use ${O.stage.name}\`.`);return}let j=C("BROODS_STAGE");await Ee("BROODS_STAGE",O.stage.name),console.log(`Stage: ${O.stage.name} (wrote BROODS_STAGE)`),Be("BROODS_STAGE",j),await Mn(l,{project:c.project,stage:O.stage.name})}async function wi(e){let{manifest:n,config:t}=await ue({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),o=await re(R(e,"--base-url")??t.baseUrl),r=new J({baseUrl:o.baseUrl,token:o.token}),s=await r.getManifest(n.project,n.stage);tn(kn(n,s?.manifest??null)),Ni(await Fn(r,n),`${n.project}/${n.stage}`)}async function bi(e){let{manifest:n,config:t,resourceAliases:o,channels:r}=await ue({project:R(e,"--project"),stage:R(e,"--stage"),command:"deploy",useRuntimeStage:!1}),s=await re(R(e,"--base-url")??t.baseUrl),i=new J({baseUrl:s.baseUrl,token:s.token}),a=R(e,"--region"),c=wn.find((l)=>l===a);if(Y(e,"--region")&&!c)throw Error(`Unknown region ${a??"(empty)"}. Use one of: ${wn.join(", ")}`);let d=await i.putManifest(c?{...n,region:c}:n,Y(e,"--prune"),Y(e,"--rotate-key"));await ze(n,d.ids,process.cwd(),o,d.deployment,r),await ko(),q(`Synced ${d.manifest.resources.length} resources to ${n.project}/${n.stage}`),await go(i,n,d.deployment),ho(r,d),po(d)}async function go(e,n,t){if(!t)return;if(t.apiKey)await Ee("BROODS_API_KEY",t.apiKey),q(`Wrote BROODS_API_KEY (${t.keyHint}) to .env.local`);let o=t.userTokenSecretHint,r=(c)=>c!==void 0&&St(Z,c)===o,s=F(await Se(W(process.cwd(),".env.local")))[g];if(o&&(r(process.env[g])||r(s))){Be(g,!r(process.env[g])&&C(g));return}if(o){G(`${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)=>(G(`${c instanceof Error?c.message:String(c)}. Set ${g} from the dashboard's Runtime key tab to sign user tokens.`),null));if(!i)return;let a=C(g);await Ee(g,i.secret),q(`Wrote a new user token signing secret to ${g} in .env.local`),Be(g,a)}function po(e){let n=e.warnings?.missingPolicies??[];if(n.length>0)G(`${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)G(`Kept on prune, a reserved sandbox instance is still live: ${t.join(", ")}. Terminate it from the dashboard, then deploy again.`)}async function yi(){let e=await Dn({maxAgeMs:0});if(e===null)throw Error("Could not reach the npm registry to check for a newer broods.");if(!jn(e,de)){console.log(`broods v${de} is already the newest release.`);return}let n=qt(),t=Le(de),o=Le(e)===t,r=o?e:`the newest ${t}.x`;if(console.log(`Updating broods ${de} → ${r} ${n.global?"globally":"in this project"}`),console.log(`$ ${[n.command,...n.args].join(" ")}`),await new Promise((s,i)=>{let a=io(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)G(`broods ${e} is a new major version. Install broods@${Le(e)} yourself to move to it.`)}async function eo(){let e=await Dn();if(e===null||!jn(e,de))return;G(`broods ${e} is out, you are on ${de}. Run \`broods update\`.`)}async function vi(e){if(await ki(e),Y(e,"--once")){if(!process.env.BROODS_SUPPRESS_DEV_TARGET)await oo(e),await eo();let w=Qt.now();await Di(e),Mt(Qt.now()-w);return}let n=Me(Xs(),`broods-declined-${process.pid}.txt`),t={...process.env,BROODS_DECLINED_FILE:n,BROODS_SUPPRESS_DEV_TARGET:"1",BROODS_RELOAD_ENV:"1"};await oo(e),await eo();let o,r=!1,s=!1,i,a=async()=>{let w=await ta();if(w===i)return;await ji(e,t),i=w},c=(w)=>console.error(w instanceof Error?w.message:String(w));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=Zs(W(process.cwd(),y),{recursive:!0},(w,O)=>{if(!O||oa(O))return;clearTimeout(o),o=setTimeout(d,150)}),u=new AbortController;Ei(e,u.signal),process.on("SIGINT",()=>{u.abort(),l.close(),process.exit(0)})}async function Ei(e,n){let t;try{t=await Fe(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 qe(t,{backfill:0,keepReconnecting:!0,minLevel:o,signal:n,onReconnect:Hn}))console.log(Yn(r))}catch(r){if(!n.aborted)console.error(`live logs: ${r instanceof Error?r.message:String(r)}`)}}async function ki(e){await $i(),await fo(!1),await Ri(e)}async function fo(e){let n=process.cwd();if(!(await Promise.all([".agent",".agents",".claude","AGENTS.md","CLAUDE.md"].map((c)=>no(W(n,c))))).includes(!0))return;let r=W(n,rn);if(!e&&await no(W(r,"SKILL.md")))return;let s=Me(rn,"SKILL.md"),i=Me(rn,"scripts","onboard.sh");for(let c of[s,i])if(await Si(n,c)){G(`Skipped the agent skill: ${c} crosses a symlink.`);return}await Wn(W(r,"scripts"),{recursive:!0}),await ve(W(r,"SKILL.md"),Zt);let a=W(r,"scripts","onboard.sh");await ve(a,Xt),await Fs(a,493),q(`Installed the broods agent skill at ${rn}/`)}async function Si(e,n){let t=e;for(let o of n.split(qs)){t=W(t,o);try{if((await Ks(t)).isSymbolicLink())return!0}catch{return!1}}return!1}async function no(e){try{return await Ys(e),!0}catch{return!1}}async function $i(){let e=W(process.cwd(),y);await Wn(W(e,b),{recursive:!0});let n=[];if(await zn(e,n),n.length>0)return;await an(W(e,"index.ts"),$o(),!1),await an(W(e,".gitignore"),`_generated
|
|
415
415
|
.cache
|
|
416
|
-
`,!1),q(`Created starter ${y}/`)}async function
|
|
416
|
+
`,!1),q(`Created starter ${y}/`)}async function Ri(e){let n=W(process.cwd(),".env.local"),t=await Se(n),o=So(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??le,u=R(e,"--project")??process.env.BROODS_PROJECT??Ae(process.cwd()),w=R(e,"--stage")??S()??"development",O=R(e,"--region")??process.env.BROODS_REGION??Oe;if(process.stdin.isTTY&&i){let j=await We(l,R(e,"--base-url")),P=new J({baseUrl:j.baseUrl,token:j.token}),N=await Ci(P,j),me=await Ti(P,N);if(u=await _i(me,u),!u.trim())throw Error("Project name is required.")}if(process.stdin.isTTY&&a){if(w=await ye("Stage",w),!w.trim())throw Error("Stage is required.")}if(process.stdin.isTTY&&c){let j=ei.filter((P)=>$t.includes(P.region));O=await Ue("Select service region",j,(P)=>P.label,j.findIndex((P)=>P.region===O)).then((P)=>P.region)}await Vn({dashboardUrl:l,baseUrl:d.baseUrl??A(l),project:u,stage:w,region:O,force:!1})}async function We(e,n){try{return await re(n)}catch(t){if(!process.stdin.isTTY)throw t;return G(`${t instanceof Error?t.message:String(t)} Starting browser login.`),await On(e)}}async function Ci(e,n){try{return await e.getOnboarding()}catch(t){if(!(t instanceof Qe)||!n.org)throw t;return G("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 to(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)G("BROODS_TOKEN is set, so the switch applies to this token only and was not stored.");else await U({...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: ${Ge(r)}`),console.log(`Projects: ${t.projects.length>0?t.projects.map((s)=>s.name).join(", "):"none yet"}`),await Mn(e,ln(o))}async function Mn(e,n){let t;try{t=await e.getRuntimeKey(n.project,n.stage)}catch(r){G(`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){G(`${n.project}/${n.stage} is not synced here yet, so BROODS_API_KEY still points at the previous scope. Run \`broods dev\`.`);return}let o=C("BROODS_API_KEY");if(!o&&process.env.BROODS_API_KEY===t.apiKey)return;await Ee("BROODS_API_KEY",t.apiKey),q(`Wrote BROODS_API_KEY (${t.keyHint}) to .env.local`),Be("BROODS_API_KEY",o)}function Be(e,n){if(!n)return;G(`${e} is exported in your shell, which wins over .env.local. Run \`unset ${e}\` or the next broods command keeps the old value.`)}function Ge(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 Oi(e){return e.slug===e.name?e.name:`${e.name} (${e.slug})`}function Bn(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 Ai(e,n){let t=e.empty?"empty":Bn(e);return Ce(`${e.name}: ${t}`,e.name===n||e.slug===n)}function xi(e,n){return Ce(mo(e),Gn(e.name,n))}function mo(e){let n=e.deploymentRegion?`, ${e.deploymentRegion}`:"";return`${e.name} (${e.kind}${n}): ${e.agentCount} agent(s), ${e.variableCount} env var(s)`}function Gn(e,n){return e.trim().toLowerCase()===n.trim().toLowerCase()}function ln(e){return m(),{project:R(e,"--project")??process.env.BROODS_PROJECT??Ae(process.cwd()),stage:R(e,"--stage")??S()??"development"}}async function Ti(e,n){let t=n.orgs.filter((s)=>s.accountStatus==="active"),o={kind:"create",name:"New organization"},r=await Ue("Select organization",[...t,o],(s)=>("kind"in s)?"Create new organization":Ge(s),t.findIndex((s)=>s.id===n.currentOrgId));if("kind"in r){let s=await ye("Organization name",Ae(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 Pi(e,n){return e.projects.find((o)=>o.name===n||o.slug===n)?.name??n}function Ii(e,n){return e.projects.find((t)=>t.name===n||t.slug===n)}async function _i(e,n){let t=Pi(e,n);if(e.projects.length===0)return ye("Project name",t);for(;;){let o=await Kt("Select project",e.projects,Oi,{hint:"type a new project name",defaultValue:t}),r=typeof o==="string"?o:o.name,s=Ii(e,r);if(!s)return r;if(await on(`Continue with the existing project ${s.name}?`))return s.name}}function ji(e,n){return new Promise((t,o)=>{let r=process.argv[1]??"",s=io(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 Di(e){let n=await ue({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),t=await re(R(e,"--base-url")??n.config.baseUrl),o=new J({baseUrl:t.baseUrl,token:t.token}),r=await wo(o,n.manifest,await Fn(o,n.manifest));if(r.length>0)Rn(r);for(let s=1;;s+=1)try{return await Ui(o,n)}catch(i){if(!(i instanceof Xe)||s===Qs)throw i;G("Stage changed in another session. Re-reading...")}}async function Ui(e,n){let{manifest:t,resourceAliases:o,channels:r}=n,s=await e.getManifest(t.project,t.stage),i=kn(t,s?.manifest??null);tn(i.filter((w)=>w.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 ko();let c=await Bi(),d=i.filter((w)=>w.operation==="delete"),l=d.filter((w)=>!c.has(`${w.kind}:${w.name}`)),u=!1;if(l.length>0)if(G("These remote resources are no longer declared locally:"),tn(l),await on(`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 Wi(),u=!0;else await Gi(l.map((w)=>`${w.kind}:${w.name}`));if(!u&&d.length>0){let w=d.map((O)=>`${O.kind}:${O.name}`).join(", ");G(`${d.length} undeclared resource(s) kept remotely: ${w}. Re-declare in code or run \`deploy --prune\` to remove.`)}return await go(e,t,a.deployment),ho(r,a),po(a),a}function ho(e,n){let t=n.deployment;if(!t||e.length===0)return;let o=new M,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 Fn(e,n){let t=ft(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:Li(r,o)}))}async function wo(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 Ni(e,n){let t=sn(e,"drifted");if(t.length>0)G(`.env.local and ${n} disagree on ${t.length} variable(s): ${t.join(", ")}. Run \`broods env sync\` to push the local values.`)}function Li(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===Mi(t)?"synced":"drifted"}function Mi(e){return so("sha256").update(e).digest("hex")}function sn(e,n){return e.filter((t)=>t.state===n).map((t)=>t.name)}async function oo(e){let n=m(),{manifest:t,config:o}=await ue({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),r=await re(R(e,"--base-url")??o.baseUrl);Nt({project:t.project,stage:t.stage,dashboardUrl:R(e,"--dashboard-url")??n.dashboardUrl??r.dashboardUrl??o.dashboardUrl??le})}async function Bi(){let e=process.env.BROODS_DECLINED_FILE;if(!e)return new Set;let n=await Se(e);return new Set(n.split(/\r?\n/).map((t)=>t.trim()).filter(Boolean))}async function Gi(e){let n=process.env.BROODS_DECLINED_FILE;if(!n||e.length===0)return;await ve(n,`${e.join(`
|
|
417
417
|
`)}
|
|
418
|
-
`,{flag:"a"})}async function
|
|
418
|
+
`,{flag:"a"})}async function Wi(){let e=process.env.BROODS_DECLINED_FILE;if(!e)return;await ve(e,"","utf8")}async function Fi(e){let[n,t]=oe(e);if(!n){console.log(ke("env",e));return}let o=n==="list"||n==="ls",r=n==="rm"||n==="remove",s=n==="get",i=n==="sync",a=n==="set"||r||s;if(!o&&!i&&!a)throw Error(`Unknown env subcommand: ${n}
|
|
419
419
|
|
|
420
420
|
${ee("env")}`);if(a&&!t)throw Error(`broods env ${n} needs a variable name.
|
|
421
421
|
|
|
422
|
-
${ee("env")}`);let{manifest:c,config:d}=await ue({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),l=await re(R(e,"--base-url")??d.baseUrl),u=new J({baseUrl:l.baseUrl,token:l.token}),
|
|
422
|
+
${ee("env")}`);let{manifest:c,config:d}=await ue({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),l=await re(R(e,"--base-url")??d.baseUrl),u=new J({baseUrl:l.baseUrl,token:l.token}),w=`${c.project}/${c.stage}`;if(i){await Ki(u,c,w);return}if(o){let j=await u.listEnv(c.project,c.stage);if(j.length===0){console.log(`No environment variables set for ${w}.`);return}console.log(`Environment variables for ${w} (values hidden):`);for(let P of j)console.log(` ${P.name}`);return}if(s){let j=await u.getEnv(c.project,c.stage,t);if(j===null){console.error(`${t} is not set for ${w}`),process.exitCode=1;return}console.log(j);return}if(r){await u.removeEnv(c.project,c.stage,t),q(`Removed ${t} from ${w}`);return}let O=await Ft(t);await u.setEnv(c.project,c.stage,t,O),q(`Stored ${t} for ${w}`)}async function Ki(e,n,t){let o=await Fn(e,n);if(o.length===0){console.log('No env("NAME") references in this project.');return}let r=await wo(e,n,o);if(r.length>0)Rn(r);let s=sn(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=sn(o,"stage-only");if(i.length>0)console.log(`${i.length} referenced variable(s) live only on ${t}: ${i.join(", ")}`);let a=sn(o,"unresolved");if(a.length>0)G(`${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(Y(e,"--all"))return"DEBUG";let n=R(e,"--level");if(n===void 0&&Y(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 Hi(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 Fe(e){let n=await Hi(e),t=m(),o=await We(R(e,"--dashboard-url")??t.dashboardUrl??le,R(e,"--base-url")),r=new J({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 bo(e){return e==="WARN"?" (--all for INFO too)":""}function Hn(e,n){console.error(je(`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 Yi(e){let n=await Fe(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}+]`+bo(r)+", Ctrl+C to stop");try{for await(let a of qe(n,{backfill:0,minLevel:r,signal:s.signal,onReconnect:Hn}))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 Vi(e){if(Y(e,"--doctor")){await zi(Y(e,"--request"));return}let n=oe(e)[0];if(!n){console.log(ke("machine",e));return}let{runMachineDaemon:t}=await import("../chunk-ynnv4vw7.js"),{baseUrl:o,credential:r}=await Fe(e),s=W(R(e,"--cwd")??process.cwd()),i=Y(e,"--computer"),a=R(e,"--mcp"),c=Y(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:(u)=>console.log(u),mcpFile:a?W(a):void 0,sandbox:n,signal:d.signal})}catch(u){console.error(u instanceof Error?u.message:String(u)),process.exitCode=1}finally{process.off("SIGINT",l)}}async function zi(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 Ji(e){let n=await Fe(e),{project:t,stage:o}=n,r=R(e,"--sandbox");if(Y(e,"--sandbox")&&!D(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),a=Y(e,"--json"),c=new AbortController,d=()=>c.abort();process.on("SIGINT",d),console.log(`Logs for ${t}/${o}`+(r?` sandbox ${r}`:"")+` [${s}+]`+bo(s)+` (backfill ${i}), Ctrl+C to stop`);try{for await(let l of qe(n,{backfill:i,minLevel:s,...r?{sandboxId:r}:{},signal:c.signal,onReconnect:Hn}))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 qi(e){let[n]=oe(e);if(!L(n))throw Error(`Missing or malformed trace id: 32 lowercase hex characters, as the dashboard copies it.
|
|
423
423
|
|
|
424
|
-
${ee("trace")}`);let t=await Fe(e),o=(await At(t,n)).toSorted((a,c)=>a.startTimeMs-c.startTimeMs);if(
|
|
424
|
+
${ee("trace")}`);let t=await Fe(e),o=(await At(t,n)).toSorted((a,c)=>a.startTimeMs-c.startTimeMs);if(Y(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(Zi(d,c)),i(d.spanId,c+1)};i("",0)}function Zi(e,n){let t=new Date(e.startTimeMs).toISOString().slice(11,23),o=" ".repeat(n),r=e.attributes?.["tool.name"],s=typeof r==="string"?`${e.name} ${r}`:e.name,i=`${t} ${e.status.padEnd(11)} ${o}`,a=`${i}${s} ${Cn(e.durationMs)}`;if(!e.error)return Un(a);let c=" ".repeat(i.length),d=e.error.replaceAll(/\r\n?|\n/g,`
|
|
425
425
|
${c} `);return Un(`${a}
|
|
426
|
-
${c}error: ${d}`)}async function
|
|
426
|
+
${c}error: ${d}`)}async function Xi(e){let[n,t]=oe(e);if(!n){console.log(ke("agent",e));return}if(n==="list"||n==="ls"){await Qi(e);return}if(n==="get"){await ea(t,e);return}throw Error(`Unknown agent subcommand: ${n}
|
|
427
427
|
|
|
428
|
-
${ee("agent")}`)}async function yo(e){let{manifest:n,config:t}=await ue({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),o=await re(R(e,"--base-url")??t.baseUrl),r=await new J({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
|
|
428
|
+
${ee("agent")}`)}async function yo(e){let{manifest:n,config:t}=await ue({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),o=await re(R(e,"--base-url")??t.baseUrl),r=await new J({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 Qi(e){let{manifest:n,agents:t}=await yo(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=vo(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 ea(e,n){if(!e)throw Error(`Missing agent name.
|
|
429
429
|
|
|
430
|
-
${ee("agent")}`);let{manifest:t,agents:o}=await yo(n),r=o.find((
|
|
430
|
+
${ee("agent")}`);let{manifest:t,agents:o}=await yo(n),r=o.find((w)=>w.name===e);if(!r)throw Error(`Unknown local agent: ${e}`);let s=r.config,i=[s.sandboxes].flat().filter((w)=>typeof w==="string").map((w,O)=>O===0?`${w} (default)`:w),a=Array.isArray(s.workspaces)?s.workspaces.map((w)=>typeof w==="string"?w:w.name).filter(Boolean):[],c=be(s.tools)?Object.keys(s.tools):[],d=be(s.channels)?Object.keys(s.channels):[],l=be(s.subagent)&&Array.isArray(s.subagent.allowed)?s.subagent.allowed.map((w)=>typeof w==="string"?w:w.name).filter(Boolean):[],u=be(s.hooks)&&Array.isArray(s.hooks.webhooks)?s.hooks.webhooks.filter(be):[];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: ${vo(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"}`),u.length>0)console.log(" Webhooks:"),u.forEach((w,O)=>{let j=Array.isArray(w.events)&&w.events.length>0?w.events.join(", "):"all events",P=w.enabled===!1?"disabled":"enabled",N=typeof w.url==="string"?w.url:"none";console.log(` [${O}] ${P} → ${N} (${j})`)})}function vo(e){let n=be(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 na(e){let[n,...t]=oe(e);if(!n)throw Error(`Missing agent name.
|
|
431
431
|
|
|
432
|
-
${ee("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 ue({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),a=await re(R(e,"--base-url")??i.baseUrl),c=s.resources.find((
|
|
432
|
+
${ee("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 ue({project:R(e,"--project"),stage:R(e,"--stage"),command:"dev"}),a=await re(R(e,"--base-url")??i.baseUrl),c=s.resources.find((N)=>N.kind==="agent"&&N.name===n);if(!c)throw Error(`Unknown local agent: ${n}`);let l=(await new J({baseUrl:a.baseUrl,token:a.token}).getManifest(s.project,s.stage))?.ids.agents[n];if(!l)throw Error(`Agent ${n} is not synced yet. Run broods dev --once or broods deploy first.`);let u=await new J({baseUrl:a.baseUrl,token:a.token}).getRuntimeKey(s.project,s.stage).catch(()=>null);if(u?.apiKey)await Ee("BROODS_API_KEY",u.apiKey);if(c.config.publicAccess!==!0)G(`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 w=new M({baseUrl:R(e,"--base-url")??process.env.BROODS_BASE_URL??process.env.BROODS_HOST??a.baseUrl,...u?.apiKey?{apiKey:u.apiKey}:{}}),O={kind:"agent",name:n,id:l,project:s.project,stage:s.stage,...u?.endpointId?{endpointId:u.endpointId}:{},...u?.projectSlug?{projectSlug:u.projectSlug}:{},...u?.stageSlug?{stageSlug:u.stageSlug}:{}},{runAgentTui:j,streamAgentText:P}=await import("../chunk-hkbecyy0.js");try{if(r){await j({client:w,agent:O,...o?{prompt:o}:{}});return}await P({client:w,agent:O,prompt:o})}catch(N){if((N instanceof Error?N.message:String(N)).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 N}}async function an(e,n,t){try{await ve(e,n,{flag:t?"w":"wx"})}catch(o){if(o.code==="EEXIST")return;throw o}}async function Eo(){let e=W(process.cwd(),".gitignore"),n=await Se(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()}
|
|
433
433
|
.env*.local
|
|
434
434
|
`:`.env*.local
|
|
435
|
-
`;await ve(e,o,"utf8")}async function ko(){let e=
|
|
435
|
+
`;await ve(e,o,"utf8")}async function ko(){let e=W(process.cwd(),y,".gitignore"),n=await Se(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()+`
|
|
436
436
|
`+o.join(`
|
|
437
437
|
`)+`
|
|
438
438
|
`:o.join(`
|
|
439
439
|
`)+`
|
|
440
|
-
`;await ve(e,r,"utf8")}async function Vn(e){let n=
|
|
440
|
+
`;await ve(e,r,"utf8")}async function Vn(e){let n=W(process.cwd(),".env.local"),t=await Se(n),o=So(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?$/,`
|
|
441
441
|
`).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((u)=>u.trim().startsWith(`${c}=`));if(l>=0)s[l]=`${c}=${cn(d)}`;else s.push(`${c}=${cn(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(`
|
|
442
442
|
`)}
|
|
443
|
-
`;await
|
|
443
|
+
`;await B(n,a),await Eo()}async function Ee(e,n){let t=W(process.cwd(),".env.local"),o=await Se(t),r=o?o.replace(/\n?$/,`
|
|
444
444
|
`).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}=${cn(n)}`;else r.push(`${e}=${cn(n)}`);process.env[e]=n;let i=`${r.filter((a,c,d)=>!(a===""&&c===d.length-1)).join(`
|
|
445
445
|
`)}
|
|
446
|
-
`;await
|
|
446
|
+
`;await B(t,i),await Eo()}async function Se(e){try{return await ro(e,"utf8")}catch(n){if(n.code==="ENOENT")return"";throw n}}function So(e){let n={};for(let t of e.split(/\r?\n/)){let o=t.trim();if(!o||o.startsWith("#"))continue;let r=o.indexOf("=");if(r<=0)continue;n[o.slice(0,r).trim()]=o.slice(r+1).trim()}return n}function cn(e){return JSON.stringify(e)}function Ae(e){return zs(W(e)).replace(/^@/,"").replace(/\//g,"-").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"broods-app"}async function ta(){let e=W(process.cwd(),y),n=[];await zn(e,n);let t=so("sha256");for(let o of n.sort())t.update(Js(e,o)),t.update("\x00"),t.update(await ro(o)),t.update("\x00");return t.digest("hex")}async function zn(e,n){let t=await Hs(e,{withFileTypes:!0});for(let o of t){let r=Me(e,o.name);if(o.isDirectory()){if(o.name===b||o.name==="generated"||o.name===".cache")continue;await zn(r,n);continue}if(o.isFile()&&(o.name.endsWith(".ts")||o.name.endsWith(".md")))n.push(r)}}function oa(e){return e.split(/[\\/]/).some((n)=>n===b||n==="generated"||n===".cache")}function $o(){return`import { defineAgent, defineSandbox, env } from "broods";
|
|
447
447
|
|
|
448
448
|
// A Lambda sandbox: a fresh, ephemeral bash environment created per run.
|
|
449
449
|
export const lambdaSandbox = defineSandbox({
|
|
@@ -472,4 +472,4 @@ export const myAgent = defineAgent({
|
|
|
472
472
|
// only reachable via internal endpoints or channel webhooks.
|
|
473
473
|
publicAccess: true,
|
|
474
474
|
});
|
|
475
|
-
`}function
|
|
475
|
+
`}function ra(){if("bun"in process.versions)return;if(typeof Vs.registerHooks==="function")return;throw Error(`broods needs Node ${Ne.engines.node.replace(">=","")} or newer, or Bun. This is Node ${process.version}.`)}function sa(e,n){if(e==="status")throw Error("status was renamed to whoami. Run `broods whoami`.");if(Y(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 ia(){let e=m(),n=k(),{createBroodsMcpServer:t,serveBroodsMcp:o}=await import("../chunk-e4ts6eg7.js"),r=n?new J({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)})}oi().catch((e)=>{Lt(e instanceof Error?e.message:String(e)),process.exit(1)});export{Q,se,x};
|