broods 0.40.0 → 0.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +1 -1
- package/dist/account.d.ts +25 -16
- package/dist/account.js +1 -1
- package/dist/chunk-0skcam6p.js +66 -0
- package/dist/chunk-5c27kpbz.js +1 -0
- package/dist/chunk-6en45n1d.js +19 -0
- package/dist/chunk-6fg5av4s.js +15 -0
- package/dist/chunk-a09r7men.js +2 -0
- package/dist/chunk-my7k41qq.js +4 -0
- package/dist/chunk-n50ycxj1.js +5 -0
- package/dist/{chunk-dmvntxs7.js → chunk-np588ty2.js} +1 -1
- package/dist/{chunk-jzasj71k.js → chunk-xsxy0gem.js} +1 -1
- package/dist/chunk-y3exzqph.js +1 -0
- package/dist/cli/index.js +80 -99
- package/dist/index.d.ts +36 -28
- package/dist/index.js +1 -1
- package/package.json +4 -4
- package/dist/chunk-ae3013v2.js +0 -15
- package/dist/chunk-evtz9fz0.js +0 -1
- package/dist/chunk-f294wr3z.js +0 -17
- package/dist/chunk-h06c1tg3.js +0 -2
- package/dist/chunk-kafpmgd4.js +0 -5
- package/dist/chunk-mf5em3wq.js +0 -4
- package/dist/chunk-ta62e9cc.js +0 -1
- package/dist/chunk-yw3ecd8t.js +0 -66
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{G,S,_,O,z,K,W,v,h,D,f,A,E,U,Y,C,ie,w,g}from"../chunk-n50ycxj1.js";import{chmod as Xr,lstat as Qr,mkdir as kn,readFile as jt,readdir as es,stat as ns,writeFile as ge}from"node:fs/promises";import{createHash as Pt}from"node:crypto";import{basename as ts,join as Pe,relative as os,resolve as x,sep as rs}from"node:path";import{watch as ss}from"node:fs";import{spawn as It}from"node:child_process";import{tmpdir as is}from"node:os";import{performance as $t}from"node:perf_hooks";import{stripVTControlCharacters as as}from"node:util";import{fileURLToPath as qt,pathToFileURL as Gn}from"node:url";import{createHash as Zt}from"node:crypto";import{readFileSync as Xt}from"node:fs";import{mkdtemp as Wn,readdir as Fn,readFile as Qt,rm as Kn,writeFile as qe}from"node:fs/promises";import In from"node:module";import{tmpdir as Hn}from"node:os";import{basename as eo,isAbsolute as no,join as oe,relative as ye,resolve as Te}from"node:path";import{build as to,transformSync as Vn}from"esbuild";var xn={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"},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"},minimax:{label:"MiniMax",modelPlaceholder:"MiniMax-M2.7"},mistral:{label:"Mistral",modelPlaceholder:"mistral-large-latest"},openai:{label:"OpenAI",modelPlaceholder:"gpt-4.1-mini"},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"}},jn=Object.keys(xn);function Pn(e){return Object.hasOwn(xn,e)}var $e="*",oo=`const passthrough = (input) => input;
|
|
3
3
|
export const defineAgent = passthrough;
|
|
4
4
|
export const defineBroods = passthrough;
|
|
5
5
|
export const defineCron = passthrough;
|
|
@@ -25,15 +25,15 @@ export const defineZaloChannel = passthrough;
|
|
|
25
25
|
export const defineZaloConnection = passthrough;
|
|
26
26
|
export const env = (name) => ({ __beeblastEnv: true, name });
|
|
27
27
|
export default {};
|
|
28
|
-
`,xe=1e7,An=50000000,Gn=1e7,xn=20000000,jn=200,Ht=new Set(["node_modules",".git"]),zt=[/^\.env(?:\.|$)/i,/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/i,/\.(?:pem|key|p12|pfx)$/i],ze={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 te(e={}){let n=e.cwd??process.cwd();h(n);let t=Ae(n,S),o=await Vt(t),r=await Jt(o),s=await Zt(r,n,e.project),i=r.filter((m)=>g(m.value)).map((m)=>({exportName:m.exportName,file:m.file,resource:m.value})),a=i.map((m)=>m.resource);Dn(a),co(a);let c=uo(i,r),d=fo(a);for(let m of a)Qt(m);for(let m of a)eo(m);for(let m of a)no(m);to(a),ro(a),go(i,d);let l=lo(i),u=Yt(s,e.stage??(e.useRuntimeStage===!1?void 0:_()),e.command??"dev"),p=(await Promise.all(i.map((m)=>po(m,t,d)))).flat().sort((m,v)=>`${m.kind}:${m.name}`.localeCompare(`${v.kind}:${v.name}`));return Dn(p),{config:s,resources:a,resourceAliases:l,channels:c,manifest:{version:1,project:s.project,stage:u,resources:p}}}function Wn(e){let n=new Set;for(let t of e.resources)Ye(t.config,n);return[...n].sort()}function Ye(e,n){if(Array.isArray(e)){for(let t of e)Ye(t,n);return}if(e&&typeof e==="object"){let t=e;if(t.__beeblastEnv===!0&&typeof t.name==="string"){n.add(t.name);return}for(let o of Object.values(t))Ye(o,n)}}function Yt(e,n,t){if(n)return n;let o=e.stages?.[t];if(o)return o;return t==="deploy"?"production":"development"}async function Vt(e){let n=[];async function t(o){let r=await Nn(o,{withFileTypes:!0});for(let s of r){let i=ee(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)=>ge(e,o).localeCompare(ge(e,r)))}async function Jt(e){qt();let n=[];for(let t of e){let r=await import(`${Un(t).href}?t=${Date.now()}`);n.push(...Object.entries(r).map(([s,i])=>({exportName:s,file:t,value:i})))}return n}var Pn=!1;function qt(){if(Pn)return;if(Pn=!0,typeof Cn.registerHooks!=="function")return;Cn.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=Lt(o);return{format:"module",shortCircuit:!0,source:Kn(Bt(r,"utf8"),{loader:"ts",format:"esm",sourcefile:r,sourcemap:"inline"}).code}}})}async function Zt(e,n,t){let r=e.find((i)=>ne(i.value))?.value?.config??{},s=t??process.env.BROODS_PROJECT??r.project??Ko(Kt(Ae(n)));if(!s.trim())throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT.");return{...r,project:s}}var In=new Set(["agent","harness","model","provider","session","hooks","connections","tools","mcp","denyTools","sandboxes","workspaces","subagent","skills","scheduler","policies","publicAccess","allowRunOverrides"]),Xt={workspace:"workspaces",skill:"skills",policy:"policies",tool:"tools",mcpServers:"mcp",channel:"connections",channels:"connections",hook:"hooks",subagents:"subagent",systemPrompt:"agent",system:"agent"};function Qt(e){if(e.kind!=="agent")return;let n=e.config;for(let t of Object.keys(n)){if(In.has(t))continue;if(t==="sandbox")throw Error(`Agent "${e.name}" config.sandbox was removed; use sandboxes, the first is the default`);let o=Xt[t],r=o?` Did you mean "${o}"?`:` Allowed keys: ${[...In].sort().join(", ")}.`;throw Error(`Agent "${e.name}" has an unknown config key "${t}".${r}`)}}function eo(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 no(e){if(e.kind!=="workspace")return;let n=e.config;if(typeof n.partitioned==="string")throw Error(`Workspace "${e.name}" config.partitioned must be a boolean; string modes are not supported.`);if(n.isolation!==void 0)throw Error(`Workspace "${e.name}" config.isolation is no longer supported; use partitioned: true.`)}function to(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(w):[],i=new Set;for(let l of s){let u=l.config,p=typeof u.id==="string"?u.id:void 0;if(p){if(i.has(p))throw Error(`Duplicate channel id: ${p}`);i.add(p)}if(l.partition)Fn(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)=>oo(l,n)).filter((l)=>Boolean(l)):[]).filter((l)=>l.config.partitioned===!0),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: true.`)}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 Fn(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 oo(e,n){if(g(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(g(t)&&t.kind==="workspace")return t;if(typeof t==="string")return n.get(t)}return}function ro(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=Hn(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=io(i),c=so(i,r,n);if(!c||ao(c))continue;throw Error(`Agent "${t.name}" workspace "${a}" uses sandbox "${c.name}" (${zn(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 Hn(e,n){if(g(e)&&e.kind==="sandbox")return e;if(typeof e==="string")return n.get(e);return}function so(e,n,t){if(e&&typeof e==="object"&&"sandbox"in e){let o=e.sandbox;if(o===null)return;return Hn(o,t)}return n}function io(e){if(g(e)&&e.kind==="workspace")return e.name;if(e&&typeof e==="object"&&"workspace"in e){let n=e.workspace;if(g(n))return n.name;if(typeof n==="string")return n}return"<unknown>"}function ao(e){let n=zn(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 zn(e){return typeof e.config.provider==="string"?e.config.provider:"sandbox"}function co(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=g(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 Dn(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 lo(e){let n={},t=new Set;for(let{exportName:o,resource:r}of e){if(o==="default"||!Ve(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 uo(e,n){let t=new Map;for(let i of n){if(!w(i.value)||i.exportName==="default"||!Ve(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(!w(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 p=i!=="default"&&Ve(i)?i:a.name,m=t.get(l)??`${p}${Vn(l.type)}Channel`;if(r.has(m))throw Error(`Duplicate channel export alias: ${m}`);r.add(m),s.push({alias:m,type:l.type,id:m,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 go(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(!w(r))continue;if(Yn(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 Yn(e,n){let t=e.config.allowedChannelIds??[];if(t.includes(we))return[we];return[...new Set([...n.get(e)??[],...t])]}function fo(e){let n=new Map;for(let t of e){if(t.kind!=="channelRecord")continue;let o=t.config;if(!w(o.connection))continue;let r=Jn(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 Vn(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ve(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}async function po(e,n,t){let o=e.resource;if(o.kind==="agent"){let r=$o(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=Jn(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:Uo(o.name,{...r,externalId:i})}))}return[{kind:o.kind,name:o.name,...o.description?{description:o.description}:{},config:await mo(e,n)}]}function Jn(e,n){if(n===void 0)return[];if(typeof n==="string")return _n(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`);_n(e,o),t.add(o)}return n}function _n(e,n){if(n!==we)return;throw Error(`Channel "${e}" cannot use "${we}" as its id: a record matches one exact room. To answer everywhere, set allowedChannelIds: ["${we}"] on the connection; undeclared rooms already fall back to its agent.`)}async function mo(e,n){let t=e.resource;if(t.kind==="skill")return await jo(t.config,n);if(t.kind==="workspace"){let o={...t.config};if(o.partitioned!==void 0){if(typeof o.partitioned!=="boolean")throw Error(`Workspace "${t.name}" config.partitioned must be a boolean`);let r=o.partitioned;if(delete o.partitioned,r)o.isolation=!0}return G(o)}if(t.kind==="mcp")return await Po(e,t.config,n);if(t.kind==="policy"){let o={...t.config};return o.version=o.version??1,G(o)}if(t.kind==="cron"){let o={...t.config},r=o.agent;if(o.agentId=g(r)?r.name:r,o.name=o.name??t.name,delete o.agent,typeof o.input==="string")o.events=[{role:"user",content:[{type:"text",text:o.input}]}],delete o.input;return G(o)}return G(t.config)}var ho=new Set(["apiKey","base_url","baseURL"]),bo=new Set(["activeTools","debug","inactiveTools","permissionMode","startupTimeoutMs","type","webSearch"]),wo=new Set(["enabled","level","subsystems"]);function yo(e){if(ho.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"';return""}function vo(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(!Rn(t))throw Error(`Agent "${e}" config.provider.${t} is not a supported provider (expected one of: ${On.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=yo(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 ko(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(!bo.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(Je(e,t.activeTools,"activeTools"),Je(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`);So(e,t.debug)}function So(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(!wo.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`);Je(e,t.subsystems,"debug.subsystems")}function Je(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 $o(e,n,t){let o={...e.config};vo(e.name,o.provider),ko(e.name,o.harness);let r=Array.isArray(o.sandboxes)?o.sandboxes.map((i)=>g(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`)});let s=Eo(e.name,o.hooks);if(s)o.hooks=s.agentHooksConfig;else if(o.hooks!==void 0)o.hooks=qn(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(!w(i))throw Error(`Agent "${e.name}" config.connections must contain connection definitions`);let a=`${e.name}${Vn(i.type)}Channel`,c=Yn(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)=>_o(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=Co(o.policies,e.name);if(i)o.policies=i;else delete o.policies}return{config:G(o),...s?.hookResource?{hookResource:s.hookResource}:{}}}function Eo(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(ze).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:ze[d],source:Oo(l.toString())}]});if(o.length===0)return;let r=`${e}-hooks`,s=Ro(e,o),i=Buffer.byteLength(s);if(i>xe)throw Error(`Agent "${e}" hook bundle is too large (${i} bytes, max ${xe})`);let a=o.map((d)=>d.event),c=qn(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:je(s)}}}}function qn(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 ze)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 Oo(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 Ro(e,n){let t=`export default {
|
|
28
|
+
`,_e=1e7,Dn=50000000,zn=1e7,Tn=20000000,_n=200,ro=new Set(["node_modules",".git"]),so=[/^\.env(?:\.|$)/i,/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/i,/\.(?:pem|key|p12|pfx)$/i],Ze={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 re(e={}){let n=e.cwd??process.cwd();f(n);let t=Te(n,S),o=await ao(t),r=await co(o),s=await uo(r,n,e.project),i=r.filter((m)=>g(m.value)).map((m)=>({exportName:m.exportName,file:m.file,resource:m.value})),a=i.map((m)=>m.resource);Nn(a),So(a);let l=Eo(i,r),d=Ro(a);for(let m of a)fo(m);for(let m of a)po(m);for(let m of a)mo(m);ho(a),wo(a),Oo(i,d);let c=$o(i),p=io(s,e.stage??(e.useRuntimeStage===!1?void 0:v()),e.command??"dev"),u=(await Promise.all(i.map((m)=>Co(m,t,d)))).flat().sort((m,y)=>`${m.kind}:${m.name}`.localeCompare(`${y.kind}:${y.name}`));return Nn(u),{config:s,resources:a,resourceAliases:c,channels:l,manifest:{version:1,project:s.project,stage:p,resources:u}}}function Yn(e){let n=new Set;for(let t of e.resources)Xe(t.config,n);return[...n].sort()}function Xe(e,n){if(Array.isArray(e)){for(let t of e)Xe(t,n);return}if(e&&typeof e==="object"){let t=e;if(t.__beeblastEnv===!0&&typeof t.name==="string"){n.add(t.name);return}for(let o of Object.values(t))Xe(o,n)}}function io(e,n,t){if(n)return n;let o=e.stages?.[t];if(o)return o;return t==="deploy"?"production":"development"}async function ao(e){let n=[];async function t(o){let r=await Fn(o,{withFileTypes:!0});for(let s of r){let i=oe(o,s.name);if(s.isDirectory()){if(s.name===_||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)=>ye(e,o).localeCompare(ye(e,r)))}async function co(e){lo();let n=[];for(let t of e){let r=await import(`${Gn(t).href}?t=${Date.now()}`);n.push(...Object.entries(r).map(([s,i])=>({exportName:s,file:t,value:i})))}return n}var Un=!1;function lo(){if(Un)return;if(Un=!0,typeof In.registerHooks!=="function")return;In.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=qt(o);return{format:"module",shortCircuit:!0,source:Vn(Xt(r,"utf8"),{loader:"ts",format:"esm",sourcefile:r,sourcemap:"inline"}).code}}})}async function uo(e,n,t){let r=e.find((i)=>ie(i.value))?.value?.config??{},s=t??process.env.BROODS_PROJECT??r.project??er(eo(Te(n)));if(!s.trim())throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT.");return{...r,project:s}}var Ln=new Set(["agent","harness","model","provider","session","hooks","connections","tools","mcp","denyTools","sandboxes","workspaces","subagent","skills","scheduler","policies","publicAccess","allowRunOverrides"]),go={workspace:"workspaces",skill:"skills",policy:"policies",tool:"tools",mcpServers:"mcp",channel:"connections",channels:"connections",hook:"hooks",subagents:"subagent",systemPrompt:"agent",system:"agent"};function fo(e){if(e.kind!=="agent")return;let n=e.config;for(let t of Object.keys(n)){if(Ln.has(t))continue;if(t==="sandbox")throw Error(`Agent "${e.name}" config.sandbox was removed; use sandboxes, the first is the default`);let o=go[t],r=o?` Did you mean "${o}"?`:` Allowed keys: ${[...Ln].sort().join(", ")}.`;throw Error(`Agent "${e.name}" has an unknown config key "${t}".${r}`)}}function po(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 mo(e){if(e.kind!=="workspace")return;let n=e.config;if(typeof n.partitioned==="string")throw Error(`Workspace "${e.name}" config.partitioned must be a boolean; string modes are not supported.`);if(n.isolation!==void 0)throw Error(`Workspace "${e.name}" config.isolation is no longer supported; use partitioned: true.`)}function ho(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(w):[],i=new Set;for(let c of s){let p=c.config,u=typeof p.id==="string"?p.id:void 0;if(u){if(i.has(u))throw Error(`Duplicate channel id: ${u}`);i.add(u)}if(c.partition)Jn(c.partition,`Agent "${t.name}" connection "${c.type}"`);if(c.config&&typeof c.config==="object"&&(("workspaceIsolationScope"in c.config)||("workspaceScope"in c.config)))throw Error(`Agent "${t.name}" connection "${c.type}" uses workspaceScope, which is no longer supported; use partition.`)}let l=(Array.isArray(o.workspaces)?o.workspaces.map((c)=>bo(c,n)).filter((c)=>Boolean(c)):[]).filter((c)=>c.config.partitioned===!0),d=s.filter((c)=>c.partition);if(d.length>0&&l.length===0){let c=d[0];throw Error(`Agent "${t.name}" connection "${c.type}" defines partition, but no attached workspace has partitioned: true.`)}if(l.length>0){for(let c of s)if(!c.partition)throw Error(`Agent "${t.name}" attaches partitioned workspace "${l[0].name}", but connection "${c.type}" does not define partition.`)}}}function Jn(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 bo(e,n){if(g(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(g(t)&&t.kind==="workspace")return t;if(typeof t==="string")return n.get(t)}return}function wo(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=qn(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=vo(i),l=yo(i,r,n);if(!l||ko(l))continue;throw Error(`Agent "${t.name}" workspace "${a}" uses sandbox "${l.name}" (${Zn(l)}) 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 qn(e,n){if(g(e)&&e.kind==="sandbox")return e;if(typeof e==="string")return n.get(e);return}function yo(e,n,t){if(e&&typeof e==="object"&&"sandbox"in e){let o=e.sandbox;if(o===null)return;return qn(o,t)}return n}function vo(e){if(g(e)&&e.kind==="workspace")return e.name;if(e&&typeof e==="object"&&"workspace"in e){let n=e.workspace;if(g(n))return n.name;if(typeof n==="string")return n}return"<unknown>"}function ko(e){let n=Zn(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 Zn(e){return typeof e.config.provider==="string"?e.config.provider:"sandbox"}function So(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,l=g(i)&&i.kind==="sandbox";if(!a&&!l)throw Error(`Agent "${t.name}" sandboxes[${s}] must be a sandbox resource or a non-empty name`);if(l&&!n.has(i.name))throw Error(`Agent "${t.name}" sandboxes references sandbox "${i.name}", but that sandbox is not exported from broods/`)}}}function Nn(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 $o(e){let n={},t=new Set;for(let{exportName:o,resource:r}of e){if(o==="default"||!Qe(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 Eo(e,n){let t=new Map;for(let i of n){if(!w(i.value)||i.exportName==="default"||!Qe(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 l=a.config.connections;if(l===void 0)continue;if(!Array.isArray(l))throw Error(`Agent "${a.name}" config.connections must be an array of connection definitions`);let d=new Set;for(let c of l){if(!w(c))throw Error(`Agent "${a.name}" config.connections must contain connection definitions`);let p=o.get(c);if(p&&p!==a.name)throw Error(`Channel ${c.type} is already attached to agent "${p}" and cannot also attach to "${a.name}"`);if(d.has(c.type))throw Error(`Agent "${a.name}" cannot configure more than one ${c.type} channel`);o.set(c,a.name),d.add(c.type);let u=i!=="default"&&Qe(i)?i:a.name,m=t.get(c)??`${u}${Qn(c.type)}Channel`;if(r.has(m))throw Error(`Duplicate channel export alias: ${m}`);r.add(m),s.push({alias:m,type:c.type,id:m,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 Oo(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(!w(r))continue;if(Xn(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 Xn(e,n){let t=e.config.allowedChannelIds??[];if(t.includes($e))return[$e];return[...new Set([...n.get(e)??[],...t])]}function Ro(e){let n=new Map;for(let t of e){if(t.kind!=="channelRecord")continue;let o=t.config;if(!w(o.connection))continue;let r=et(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 Qn(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Qe(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}async function Co(e,n,t){let o=e.resource;if(o.kind==="agent"){let r=Uo(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=et(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:Jo(o.name,{...r,externalId:i})}))}return[{kind:o.kind,name:o.name,...o.description?{description:o.description}:{},config:await Ao(e,n)}]}function et(e,n){if(n===void 0)return[];if(typeof n==="string")return Mn(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`);Mn(e,o),t.add(o)}return n}function Mn(e,n){if(n!==$e)return;throw Error(`Channel "${e}" cannot use "${$e}" as its id: a record matches one exact room. To answer everywhere, set allowedChannelIds: ["${$e}"] on the connection; undeclared rooms already fall back to its agent.`)}async function Ao(e,n){let t=e.resource;if(t.kind==="skill")return await Fo(t.config,n);if(t.kind==="workspace"){let o={...t.config};if(o.partitioned!==void 0){if(typeof o.partitioned!=="boolean")throw Error(`Workspace "${t.name}" config.partitioned must be a boolean`);let r=o.partitioned;if(delete o.partitioned,r)o.isolation=!0}return V(o)}if(t.kind==="mcp")return await Ko(e,t.config,n);if(t.kind==="policy"){let o={...t.config};return o.version=o.version??1,V(o)}if(t.kind==="cron"){let o={...t.config},r=o.agent;if(o.agentId=g(r)?r.name:r,o.name=o.name??t.name,delete o.agent,typeof o.input==="string")o.events=[{role:"user",content:[{type:"text",text:o.input}]}],delete o.input;return V(o)}return V(t.config)}var xo=new Set(["apiKey","base_url","baseURL"]),jo=new Set(["activeTools","debug","inactiveTools","permissionMode","startupTimeoutMs","type","webSearch"]),Po=new Set(["enabled","level","subsystems"]);function Io(e){if(xo.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"';return""}function Do(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(!Pn(t))throw Error(`Agent "${e}" config.provider.${t} is not a supported provider (expected one of: ${jn.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=Io(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 To(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(!jo.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(en(e,t.activeTools,"activeTools"),en(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`);_o(e,t.debug)}function _o(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(!Po.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`);en(e,t.subsystems,"debug.subsystems")}function en(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 Uo(e,n,t){let o={...e.config};Do(e.name,o.provider),To(e.name,o.harness);let r=Array.isArray(o.sandboxes)?o.sandboxes.map((i)=>g(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`)});let s=Lo(e.name,o.hooks);if(s)o.hooks=s.agentHooksConfig;else if(o.hooks!==void 0)o.hooks=nt(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(!w(i))throw Error(`Agent "${e.name}" config.connections must contain connection definitions`);let a=`${e.name}${Qn(i.type)}Channel`,l=Xn(i,t);return[i.type,{id:a,...i.config,...i.partition?{partition:i.partition}:{},allowedChannelIds:l}]})),delete o.connections}if(Array.isArray(o.workspaces)){let i=o.workspaces.map((a)=>zo(a,e.name));for(let a of i){let l=r?.indexOf(a.sandbox)??-1;if(l>=1)throw Error(`Agent "${e.name}" sandboxes[${l}] "${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=Bo(o.policies,e.name);if(i)o.policies=i;else delete o.policies}return{config:V(o),...s?.hookResource?{hookResource:s.hookResource}:{}}}function Lo(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(Ze).flatMap((d)=>{let c=t[d];if(c===void 0)return[];if(typeof c!=="function")throw Error(`Agent "${e}" config.hooks.${d} must be a function`);return[{name:d,event:Ze[d],source:No(c.toString())}]});if(o.length===0)return;let r=`${e}-hooks`,s=Mo(e,o),i=Buffer.byteLength(s);if(i>_e)throw Error(`Agent "${e}" hook bundle is too large (${i} bytes, max ${_e})`);let a=o.map((d)=>d.event),l=nt(t,e);return l.code=[{hookId:r}],{agentHooksConfig:l,hookResource:{kind:"hook",name:r,description:`Inline hooks for agent ${e}`,config:{events:a,bundle:s,sha256:Ee(s)}}}}function nt(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 Ze)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 No(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 Mo(e,n){let t=`export default {
|
|
29
29
|
${n.map((o)=>` ${JSON.stringify(o.event)}: ${o.source},`).join(`
|
|
30
30
|
`)}
|
|
31
31
|
};
|
|
32
|
-
`;try{return
|
|
32
|
+
`;try{return Vn(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 Bo(e,n){if(!Array.isArray(e))throw Error(`Agent "${n}" config.policies must be an array`);let t=e.map((o)=>{if(g(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 Go(e,n){let t=await Wn(oe(Hn(),"broods-mcp-"));try{let o=oe(t,"server.mjs");await qe(o,n,"utf8");let r;try{r=await import(Gn(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 Kn(t,{recursive:!0,force:!0})}}async function Wo(e){let n=await to({entryPoints:[e.entryPoint],bundle:!0,platform:"node",format:"esm",minify:!1,write:!1,logLevel:"silent",plugins:e.plugins??[]}).catch((t)=>{let o=Xo(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 Fo(e,n){let t=Yo(n,e.path,"Skill"),o=ye(n,t).split("\\").join("/"),r=await qo(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 Ko(e,n,t){let{handler:o,...r}=n,s=[o,n.url,n.sandbox].filter((c)=>c!==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 V(r)}let i=ye(t,e.file).split("\\").join("/");Zo(i,"MCP server");let a=await Wn(oe(Hn(),"broods-mcp-shim-")),l;try{let c=oe(a,"mcp-handler.mjs");await qe(c,Ho(e),"utf8"),await qe(oe(a,"broods-stub.mjs"),oo,"utf8"),l=await Wo({entryPoint:c,label:"MCP server bundle",manifestPath:i,plugins:[Vo(a)]})}finally{await Kn(a,{recursive:!0,force:!0})}let d=Buffer.byteLength(l);if(d>Dn)throw Error(`MCP server bundle ${i} is too large (${d} bytes, max ${Dn})`);return await Go(i,l),{...V(r),bundle:l,sha256:Ee(l)}}function Ho(e){return`import * as __exports from ${JSON.stringify(e.file)};
|
|
33
33
|
const __mcp = __exports[${JSON.stringify(e.exportName)}];
|
|
34
34
|
export default __mcp?.config?.handler ?? __mcp?.handler;
|
|
35
|
-
`}function
|
|
36
|
-
`),
|
|
35
|
+
`}function Vo(e){let n=oe(e,"broods-stub.mjs");return{name:"broods-sdk-stub",setup:function(t){t.onResolve({filter:/^broods(\/.*)?$/},()=>({path:n}))}}}function zo(e,n){if(g(e))return{name:e.name,workspaceId:e.name};if(e&&typeof e==="object"&&"workspace"in e){let t=e.workspace,o=g(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:g(s)?s.name:s}return r}throw Error(`Agent ${n} workspaces must be defineWorkspace(...) resources or { workspace, sandbox } refs`)}function Yo(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=Te(e),r=Te(o,n),s=ye(o,r);if(s===""||!s.startsWith("..")&&!no(s))return r;throw Error(`${t} path ${n} must stay inside ${S}/`)}function Jo(e,n){let t={...n},o=t.connection;if(!w(o))throw Error(`Channel "${e}" config.connection must be a connection definition`);return delete t.connection,t.platform=o.type,Jn(t.partition,`Channel "${e}"`),V(t)}function V(e){if(Array.isArray(e))return e.map((n)=>V(n));if(g(e))return e.name;if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).map(([n,t])=>[n,V(t)]));return e}async function qo(e){let n=[],t=0;async function o(r){let s=await Fn(r,{withFileTypes:!0});for(let i of s){let a=oe(r,i.name),l=ye(e,a).split("\\").join("/");if(i.isDirectory()){if(Bn(i.name))continue;await o(a)}else if(i.isFile()){if(Bn(i.name)||tt(l))continue;let d=await Qt(a);if(d.byteLength>_e)throw Error(`Skill bundle file ${l} is too large (${d.byteLength} bytes, max ${_e})`);if(t+=d.byteLength,t>Tn)throw Error(`Skill bundle at ${e} is too large (${t} bytes, max ${Tn})`);if(n.length>=_n)throw Error(`Skill bundle at ${e} has too many files (max ${_n})`);n.push({path:l,size:d.byteLength,sha256:Ee(d),contentBase64:d.toString("base64"),contentType:Qo(l)})}}}return await o(e),n.sort((r,s)=>String(r.path).localeCompare(String(s.path)))}function Bn(e){return e.startsWith(".")||ro.has(e)}function Zo(e,n){if(tt(e))throw Error(`${n} bundle path ${e} looks like a hidden file or secret and will not be bundled`)}function Xo(e){return e instanceof Error&&Array.isArray(e.errors)}function tt(e){return e.split("/").some((t)=>t.startsWith(".")||so.some((o)=>o.test(t)))}function Ee(e){return Zt("sha256").update(e).digest("hex")}function Qo(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 er(e){return e.replace(/^@/,"").replace(/\//g,"-").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}import{mkdir as nr,writeFile as Ue}from"node:fs/promises";import{resolve as Oe}from"node:path";async function Le(e,n,t=process.cwd(),o={},r=null,s=[]){let i=Oe(t,S,_),a=tr(n,e);await nr(i,{recursive:!0}),await Ue(Oe(i,"ids.ts"),sr(a),"utf8"),await Ue(Oe(i,"api.ts"),or(e,a,o,r,s),"utf8"),await Ue(Oe(i,"resources.ts"),ir(e),"utf8"),await Ue(Oe(i,"dataModel.ts"),rr(),"utf8")}function tr(e,n){let t={agents:ae(n,"agent"),workspaces:ae(n,"workspace"),sandboxes:ae(n,"sandbox"),crons:ae(n,"cron"),skills:ae(n,"skill"),mcp:ae(n,"mcp"),policies:ae(n,"policy"),channelRecords:ae(n,"channelRecord")};return{agents:ce(e.agents,t.agents),workspaces:ce(e.workspaces,t.workspaces),sandboxes:ce(e.sandboxes,t.sandboxes),crons:ce(e.crons,t.crons),skills:ce(e.skills,t.skills),hooks:{},mcp:ce(e.mcp,t.mcp),policies:ce(e.policies,t.policies),channelRecords:ce(e.channelRecords,t.channelRecords)}}function ae(e,n){return new Set(e.resources.filter((t)=>t.kind===n).map((t)=>t.name))}function ce(e,n){return Object.fromEntries(Object.entries(e??{}).filter(([t])=>n.has(t)))}function or(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)=>` ${nn(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(`
|
|
36
|
+
`),l=o?r.map((d)=>{let c=encodeURIComponent(o.accountId),p=o.stageKind===void 0||o.stageKind==="production"?`/v1/webhooks/${c}/${encodeURIComponent(d.type)}`:`/v1/webhooks/${c}/dev/${encodeURIComponent(o.endpointId)}/${encodeURIComponent(d.type)}`;return` ${nn(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(p)} },`}).join(`
|
|
37
37
|
`):"";return`// Generated by broods. Do not edit by hand.
|
|
38
38
|
import type { ResourceApi } from "broods";
|
|
39
39
|
import { ids } from "./ids";
|
|
@@ -44,17 +44,17 @@ export const api = {
|
|
|
44
44
|
${a}
|
|
45
45
|
},
|
|
46
46
|
channels: {
|
|
47
|
-
${
|
|
47
|
+
${l}
|
|
48
48
|
},
|
|
49
|
-
workspaces: ${
|
|
50
|
-
sandboxes: ${
|
|
51
|
-
crons: ${
|
|
52
|
-
skills: ${
|
|
53
|
-
policies: ${
|
|
49
|
+
workspaces: ${Re("workspaces",n.workspaces,t.workspace)},
|
|
50
|
+
sandboxes: ${Re("sandboxes",n.sandboxes,t.sandbox)},
|
|
51
|
+
crons: ${Re("crons",n.crons,t.cron)},
|
|
52
|
+
skills: ${Re("skills",n.skills,t.skill)},
|
|
53
|
+
policies: ${Re("policies",n.policies,t.policy)},
|
|
54
54
|
} as const satisfies ResourceApi;
|
|
55
|
-
`}function
|
|
55
|
+
`}function rr(){return`// Generated by broods. Do not edit by hand.
|
|
56
56
|
export type { AgentReference, ChannelReference, AgentRunInput, AgentRunResult, ResourceApi } from "broods";
|
|
57
|
-
`}function
|
|
57
|
+
`}function sr(e){return`// Generated by broods. Do not edit by hand.
|
|
58
58
|
export const ids = ${JSON.stringify(e,null,2)} as const;
|
|
59
59
|
export const agents = ids.agents;
|
|
60
60
|
export const workspaces = ids.workspaces;
|
|
@@ -62,18 +62,18 @@ export const sandboxes = ids.sandboxes;
|
|
|
62
62
|
export const crons = ids.crons;
|
|
63
63
|
export const skills = ids.skills;
|
|
64
64
|
export const policies = ids.policies;
|
|
65
|
-
`}function
|
|
65
|
+
`}function ir(e){return`// Generated by broods. Do not edit by hand.
|
|
66
66
|
export const manifest = ${JSON.stringify(e,null,2)} as const;
|
|
67
|
-
`}function
|
|
68
|
-
${o.map((s)=>` ${
|
|
67
|
+
`}function Re(e,n,t){let o=Object.keys(n);if(o.length===0)return"{}";return`{
|
|
68
|
+
${o.map((s)=>` ${nn(t?.[s]??s)}: ids.${e}[${JSON.stringify(s)}],`).join(`
|
|
69
69
|
`)}
|
|
70
|
-
}`}function qe(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}class U{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 T(t,"Fetch manifest failed"),await t.json()}async putManifest(e,n,t=!1){let o=await this.externalizeLargeMcpBundles(e),r=await this.request(e.project,e.stage,"/manifest",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({manifest:o,prune:n,rotateRuntimeKey:t})});return await T(r,"Sync manifest failed"),await r.json()}async externalizeLargeMcpBundles(e){if(e.resources.every((t)=>et(t)===null))return e;let n=await Promise.all(e.resources.map(async(t)=>{let o=et(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:je(o)}}}));return{...e,resources:n}}async uploadMcpBundle(e,n,t){let o=await this.request(e,n,"/mcp-bundle-uploads",{method:"POST"});await T(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.fetchImpl(r,{method:"POST",headers:{"Content-Type":"application/javascript"},body:t});await T(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 T(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 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 T(r,"Set environment variable failed")}async listEnv(e,n){let t=await this.request(e,n,"/env",{method:"GET"});return await T(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 T(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 T(o,"Remove environment variable failed")}async getOnboarding(){let e=await this.fetchImpl(`${this.baseUrl}/v1/account/onboarding`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return await T(e,"Fetch CLI onboarding context failed"),await e.json()}async selectOnboardingOrg(e){let n=await this.fetchImpl(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({orgId:e})});return await T(n,"Select CLI org failed"),await n.json()}async listStages(e){let n=await this.fetchImpl(`${this.baseUrl}/v1/account/stages?project=${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return _e(n,"/v1/account/stages","broods stage"),await T(n,"List stages failed"),(await n.json()).stages??[]}async createStage(e,n,t){let o=await this.fetchImpl(`${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 _e(o,"/v1/account/stages","broods stage"),await T(o,"Create stage failed"),await o.json()}async listProjects(){let e=await this.fetchImpl(`${this.baseUrl}/v1/account/projects`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return _e(e,"/v1/account/projects","broods project"),await T(e,"List projects failed"),(await e.json()).projects??[]}async deleteProject(e){let n=await this.fetchImpl(`${this.baseUrl}/v1/account/projects?projectId=${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`}});if(_e(n,"/v1/account/projects","broods project"),n.status===404)return null;return await T(n,"Delete project failed"),(await n.json()).deleted??null}async createOnboardingOrg(e){let n=await this.fetchImpl(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({createOrgName:e})});return await T(n,"Create CLI org failed"),await n.json()}async request(e,n,t,o){let r=`${this.baseUrl}/v1/account/projects/${encodeURIComponent(e)}/stages/${encodeURIComponent(n)}${t}`;return await this.fetchImpl(r,{...o,headers:{Authorization:`Bearer ${this.token}`,...o.headers}})}}function nn(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(De(Xe(u))!==De(Xe(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)&&Vo(d.resource.kind)&&d.resource.kind===u.resource.kind&&De(Qn(d.resource))===De(Qn(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)=>Xn(d).localeCompare(Xn(l)))}function Xn(e){return`${{create:0,rename:1,update:2,delete:3}[e.operation]}:${e.kind}:${e.previousName??""}:${e.name}`}function Vo(e){return e==="agent"||e==="workspace"||e==="sandbox"||e==="policy"}function Ze(e){if(Array.isArray(e))return e.map(Ze);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,Ze(o)]))}return e}function Qn(e){let n=Xe(e),{name:t,...o}=n;return o}function Xe(e){let n=Ze(e);if(e.kind!=="skill"&&e.kind!=="hook")return n;return{...n,config:en(n.config)}}function Qe(e){if(Array.isArray(e))return e.map(Qe);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>[n,Qe(t)]));return e}function De(e){return JSON.stringify(Qe(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(n==="contentBase64"||n==="bundle")return[];return[[n,en(t)]]}));return e}async function T(e,n){if(e.ok)return;let t=await e.text(),o=t;try{o=JSON.parse(t).error?.message??t}catch{}throw Error(`${n}: ${e.status} ${o}`)}function _e(e,n,t){if(e.status!==404)return;if((e.headers.get("Content-Type")??"").includes("application/json"))return;throw Error(`This broods deployment has no ${n} route yet. Update the backend to use \`${t}\`.`)}function et(e){if(e.kind!=="mcp")return null;let n=e.config?.bundle;if(typeof n!=="string")return null;return Buffer.byteLength(n)>Gn?n:null}var Jo=1,qo=0;async function nt(e,n,t=fetch){try{let o=await t(`${e.replace(/\/+$/,"")}/v1/internal/observability-scope`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(5000)});if(!o.ok)return null;let r=await o.json();if(typeof r?.projectSlug!=="string"||typeof r?.stageSlug!=="string"||r.projectSlug===""||r.stageSlug==="")return null;return r}catch{return null}}function de(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 pe(){let e=globalThis.WebSocket;if(!e)throw Error("WebSocket is not available in this environment.");return e}async function*Te(e,n={}){let t=new Set,o=500;while(!n.signal?.aborted){try{for await(let r of Zo(e,n)){let s=`${r.ts}|${r.eventType}|${r.message}`;if(t.has(s))continue;if(t.add(s),t.size>5000)t.delete(t.values().next().value);o=500,yield r}}catch(r){if(n.signal?.aborted)return;let s=r instanceof Error?r.message:String(r);if(/unauthorized|invalid websocket token|scope does not match/i.test(s))throw r}await de(o,n.signal),o=Math.min(o*2,5000)}}async function*Zo(e,n){let{baseUrl:t,apiKey:o,project:r,stage:s}=e,{backfill:i=0,minLevel:a,sandboxId:c,signal:d}=n,l=n.liveOnly??i<=0;if(d?.aborted)return;let u=Xo(t,r,s),p=u,m=pe(),v=[],k=null,R=!1,X=null,M=()=>{X?.(),X=null},Q=new m(u,E(o)),Fe=()=>{if(Q.readyState===Jo||Q.readyState===qo)Q.close(1000,"client closed");d?.removeEventListener("abort",$n)},$n=()=>{R=!0,M(),Fe()};d?.addEventListener("abort",$n,{once:!0}),Q.onopen=()=>{if(d?.aborted){Fe();return}let K={type:"subscribe",stream:"logs",...i>0?{backfill:i}:{},...l?{liveOnly:!0}:{},...a!==void 0?{minLevel:a}:{},...c!==void 0?{sandboxId:c}:{}};Q.send(JSON.stringify(K))},Q.onmessage=(K)=>{let ue=Qo(K.data);if(!ue)return;switch(ue.type){case"backfill":if(ue.stream==="logs"){for(let Ut of ue.entries)v.push(Ut);M()}break;case"log":v.push(ue.entry),M();break;case"error":k=Error(`Observability gateway error: ${ue.error}`),R=!0,M();break;case"ready":break;default:break}},Q.onerror=()=>{k=Error(`Cannot connect to the observability gateway at ${p}.`),R=!0,M()},Q.onclose=(K)=>{if(!R){if(K.code!==1000)k=Error(K.reason?`Observability WebSocket closed: ${K.reason}`:`Observability WebSocket closed with code ${K.code}.`);R=!0,M()}};try{while(!0){if(v.length>0){yield v.shift();continue}if(k)throw k;if(R)return;await new Promise((K)=>{X=K})}}finally{Fe()}}function Xo(e,n,t){return`${W(e)}/v1/projects/${encodeURIComponent(n)}/stages/${encodeURIComponent(t)}/observability/ws`}function Qo(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}}import{createServer as cr}from"node:http";import{createHash as lr,randomBytes as dr,randomUUID as ur}from"node:crypto";import{spawn as gr}from"node:child_process";import{createInterface as ke}from"node:readline/promises";import{stdin as Y,stdout as z}from"node:process";function fe(e,n,t={}){let o=`${n?"*":" "} ${e}`;return n?N(o,"\x1B[1m\x1B[36m",me(t)):o}function er(e,n={}){let t=me(n),o=ar(e.stage),r=o==="Development",s=N("▌",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?N("dashboard","\x1B[4m",t):"dashboard",c=`${e.dashboardUrl}?project=${encodeURIComponent(e.project)}&stage=${encodeURIComponent(e.stage)}`,d=N(c,"\x1B[2m\x1B[4m",t);return[`${s} Syncing ${o}: ${N(e.project,"",t)}`,`${s} ${i} ${e.stage} (${a})`,`${s} ${N("└─","\x1B[2m",t)} ${d}`].join(`
|
|
71
|
-
`)}function
|
|
70
|
+
}`}function nn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}var ar=1,cr=0;function se(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 he(){let e=globalThis.WebSocket;if(!e)throw Error("WebSocket is not available in this environment.");return e}class q extends Error{}async function*Ne(e,n={}){let t=new Set,o=500;while(!n.signal?.aborted){try{for await(let r of lr(e,n)){let s=`${r.ts}|${r.eventType}|${r.message}`;if(t.has(s))continue;if(t.add(s),t.size>5000)t.delete(t.values().next().value);o=500,yield r}}catch(r){if(n.signal?.aborted)return;let s=r instanceof Error?r.message:String(r);if(r instanceof q||/unauthorized|invalid websocket token|scope does not match/i.test(s))throw r}await se(o,n.signal),o=Math.min(o*2,5000)}}async function*lr(e,n){let{baseUrl:t,credential:o,project:r,stage:s}=e,{backfill:i=0,minLevel:a,sandboxId:l,signal:d}=n,c=n.liveOnly??i<=0;if(d?.aborted)return;let p=dr(t,r,s),u=p,m=he(),y=[],k=null,R=!1,ne=null,B=()=>{ne?.(),ne=null},te=new m(p,C(await o())),Je=()=>{if(te.readyState===ar||te.readyState===cr)te.close(1000,"client closed");d?.removeEventListener("abort",An)},An=()=>{R=!0,B(),Je()};d?.addEventListener("abort",An,{once:!0}),te.onopen=()=>{if(d?.aborted){Je();return}let H={type:"subscribe",stream:"logs",...i>0?{backfill:i}:{},...c?{liveOnly:!0}:{},...a!==void 0?{minLevel:a}:{},...l!==void 0?{sandboxId:l}:{}};te.send(JSON.stringify(H))},te.onmessage=(H)=>{let we=ur(H.data);if(!we)return;switch(we.type){case"backfill":if(we.stream==="logs"){for(let Jt of we.entries)y.push(Jt);B()}break;case"log":y.push(we.entry),B();break;case"error":k=Error(`Observability gateway error: ${we.error}`),R=!0,B();break;case"ready":break;default:break}},te.onerror=()=>{k=Error(`Cannot connect to the observability gateway at ${u}.`),R=!0,B()},te.onclose=(H)=>{if(!R){if(H.code!==1000)k=Error(H.reason?`Observability WebSocket closed: ${H.reason}`:`Observability WebSocket closed with code ${H.code}.`);R=!0,B()}};try{while(!0){if(y.length>0){yield y.shift();continue}if(k)throw k;if(R)return;await new Promise((H)=>{ne=H})}}finally{Je()}}function dr(e,n,t){return`${Y(e)}/v1/projects/${encodeURIComponent(n)}/stages/${encodeURIComponent(t)}/observability/ws`}function ur(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 gr=new Set(["bundle","bundleStorageId","contentBase64"]),fr=new Set(["hook","mcp","skill"]);class Be extends Error{}class T{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 I(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}:{}})});return await I(s,"Sync manifest failed"),await s.json()}async externalizeLargeMcpBundles(e){if(e.resources.every((t)=>st(t)===null))return e;let n=await Promise.all(e.resources.map(async(t)=>{let o=st(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:Ee(o)}}}));return{...e,resources:n}}async uploadMcpBundle(e,n,t){let o=await this.request(e,n,"/mcp-bundle-uploads",{method:"POST"});await I(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.fetchImpl(r,{method:"POST",headers:{"Content-Type":"application/javascript"},body:t});await I(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 I(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 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 I(r,"Set environment variable failed")}async listEnv(e,n){let t=await this.request(e,n,"/env",{method:"GET"});return await I(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 I(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 I(o,"Remove environment variable failed")}async getOnboarding(){let e=await this.fetchImpl(`${this.baseUrl}/v1/account/onboarding`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return await I(e,"Fetch CLI onboarding context failed"),await e.json()}async selectOnboardingOrg(e){let n=await this.fetchImpl(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({orgId:e})});return await I(n,"Select CLI org failed"),await n.json()}async listStages(e){let n=await this.fetchImpl(`${this.baseUrl}/v1/account/stages?project=${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Ce(n,"/v1/account/stages","broods stage"),await I(n,"List stages failed"),(await n.json()).stages??[]}async createStage(e,n,t){let o=await this.fetchImpl(`${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 Ce(o,"/v1/account/stages","broods stage"),await I(o,"Create stage failed"),await o.json()}async mintStageSession(e,n){let t=await this.fetchImpl(`${this.baseUrl}/v1/account/stage-session`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({project:e,stage:n})});Ce(t,"/v1/account/stage-session","broods logs");try{await I(t,"Open stage session failed")}catch(o){if(t.status===401||t.status===404)throw new q(o instanceof Error?o.message:String(o));throw o}return await t.json()}async listProjects(){let e=await this.fetchImpl(`${this.baseUrl}/v1/account/projects`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Ce(e,"/v1/account/projects","broods project"),await I(e,"List projects failed"),(await e.json()).projects??[]}async deleteProject(e){let n=await this.fetchImpl(`${this.baseUrl}/v1/account/projects?projectId=${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`}});if(Ce(n,"/v1/account/projects","broods project"),n.status===404)return null;return await I(n,"Delete project failed"),(await n.json()).deleted??null}async createOnboardingOrg(e){let n=await this.fetchImpl(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({createOrgName:e})});return await I(n,"Create CLI org failed"),await n.json()}async request(e,n,t,o){let r=`${this.baseUrl}/v1/account/projects/${encodeURIComponent(e)}/stages/${encodeURIComponent(n)}${t}`;return await this.fetchImpl(r,{...o,headers:{Authorization:`Bearer ${this.token}`,...o.headers}})}}function an(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,c]of o){let p=t.get(d);if(!p)s.push({key:d,resource:c});else if(Me(on(p))!==Me(on(c)))r.push({operation:"update",kind:c.kind,name:c.name})}for(let[d,c]of t)if(!o.has(d))i.push({key:d,resource:c});let a=new Set,l=new Set;for(let d of s){let c=i.find((p)=>!a.has(p.key)&&pr(d.resource.kind)&&d.resource.kind===p.resource.kind&&Me(rt(d.resource))===Me(rt(p.resource)));if(!c)continue;l.add(d.key),a.add(c.key),r.push({operation:"rename",kind:d.resource.kind,name:d.resource.name,previousName:c.resource.name})}for(let{key:d,resource:c}of s)if(!l.has(d))r.push({operation:"create",kind:c.kind,name:c.name});for(let{key:d,resource:c}of i)if(!a.has(d))r.push({operation:"delete",kind:c.kind,name:c.name});return r.sort((d,c)=>ot(d).localeCompare(ot(c)))}function ot(e){return`${{create:0,rename:1,update:2,delete:3}[e.operation]}:${e.kind}:${e.previousName??""}:${e.name}`}function pr(e){return e==="agent"||e==="workspace"||e==="sandbox"||e==="policy"}function tn(e){if(Array.isArray(e))return e.map(tn);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,tn(o)]))}return e}function rt(e){let n=on(e),{name:t,...o}=n;return o}function on(e){let n=tn(e);if(!fr.has(e.kind))return n;return{...n,config:sn(n.config)}}function rn(e){if(Array.isArray(e))return e.map(rn);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>[n,rn(t)]));return e}function Me(e){return JSON.stringify(rn(e))}function sn(e){if(Array.isArray(e))return e.map(sn);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).flatMap(([n,t])=>{if(gr.has(n))return[];return[[n,sn(t)]]}));return e}async function I(e,n){if(e.ok)return;let t=await e.text(),{message:o=t,code:r}=mr(t);if(r==="manifest_conflict")throw new Be(o);throw Error(`${n}: ${e.status} ${o}`)}function mr(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 Ce(e,n,t){if(e.status!==404)return;if((e.headers.get("Content-Type")??"").includes("application/json"))return;throw Error(`This broods deployment has no ${n} route yet. Update the backend to use \`${t}\`.`)}function st(e){if(e.kind!=="mcp")return null;let n=e.config?.bundle;if(typeof n!=="string")return null;return Buffer.byteLength(n)>zn?n:null}import{createServer as Or}from"node:http";import{createHash as Rr,randomBytes as Cr,randomUUID as Ar}from"node:crypto";import{spawn as xr}from"node:child_process";import{createInterface as Ae}from"node:readline/promises";import{stdin as Q,stdout as X}from"node:process";function ve(e,n,t={}){let o=`${n?"*":" "} ${e}`;return n?j(o,"\x1B[1m\x1B[36m",F(t)):o}function it(e,n={}){let t=F(n),o=(i)=>j(i.padEnd(9),"\x1B[2m",t),r=!e.loggedIn?j("not logged in","\x1B[33m",t):e.org??j("unknown, run broods whoami","\x1B[2m",t),s=e.project??`none ${j(`(${e.projectGuess} from folder name)`,"\x1B[2m",t)}`;return[` ${o("org")}${r}`,` ${o("project")}${s}`,` ${o("stage")}${ut(e.stage,t)}`,` ${o("server")}${e.server}`]}function hr(e,n={}){let t=F(n),o=gt(e.stage),r=o==="Development",s=j("▌",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?j("dashboard","\x1B[4m",t):"dashboard",l=`${e.dashboardUrl}?project=${encodeURIComponent(e.project)}&stage=${encodeURIComponent(e.stage)}`,d=j(l,"\x1B[2m\x1B[4m",t);return[`${s} Syncing ${o}: ${j(e.project,"",t)}`,`${s} ${i} ${e.stage} (${a})`,`${s} ${j("└─","\x1B[2m",t)} ${d}`].join(`
|
|
71
|
+
`)}function br(e,n={}){let t=F(n);return e.map((o)=>{let r=$r(o.operation,t);if(o.operation==="rename"&&o.previousName)return` ${r} ${o.kind}:${o.previousName} -> ${o.name}`;return` ${r} ${o.kind}:${o.name}`})}function wr(e,n={}){let t=F(n),o=j("▌","\x1B[32m",t),r=j("↑","\x1B[32m",t);return`${o} ${r} Synced ${e.length} env var(s) from .env.local: ${e.join(", ")}`}function yr(e,n={}){return`${j("✖","\x1B[31m",F(n))} ${e}`}function at(e,n={}){let t=F(n),o=Math.max(...e.map(([r])=>r.length))+2;return e.map(([r,s])=>` ${r.padEnd(o)}${j(s,"\x1B[2m",t)}`)}function vr(e,n={}){let t=(n.now??new Date).toTimeString().slice(0,8);return`${j("✔","\x1B[32m",F(n))} ${t} Resources ready! (${Er(e)})`}function kr(e,n={}){return`${j("✔","\x1B[32m",F(n))} ${e}`}function cn(e,n,t={}){let o=F(t),r=t.note?` ${j(`(${t.note})`,"\x1B[2m",o)}`:"";return` ${j("now","\x1B[2m",o)} ${e} → ${ut(n,o)}${r}`}function Sr(e,n={}){return j(`! ${e}`,"\x1B[33m",F(n))}function ct(e){console.error(hr(e))}function Ge(e){for(let n of br(e))console.log(n)}function ln(e){console.error(wr(e))}function lt(e){console.error(yr(e,{stream:"stderr"}))}function dt(e){console.error(vr(e))}function M(e){console.log(kr(e,{stream:"stdout"}))}function P(e){console.log(Sr(e,{stream:"stdout"}))}function $r(e,n){if(e==="create")return`[${j("+","\x1B[32m",n)}]`;if(e==="rename")return`[${j("~","\x1B[33m",n)}]`;if(e==="update")return`[${j("*","\x1B[36m",n)}]`;return`[${j("-","\x1B[31m",n)}]`}function Er(e){if(e>=1000)return`${(e/1000).toFixed(2)}s`;return`${Math.max(e,0).toFixed(1)}ms`}function j(e,n,t){return t?`${n}${e}\x1B[0m`:e}function ut(e,n){let t=gt(e)==="Development";return j(e,t?"\x1B[32m":"\x1B[33m",n)}function F(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 jr=180000,Pr=new Set(["--base-url","--cwd","--dashboard-url","--stage","--from","--level","--limit","--mcp","--project","--region","--sandbox","-n"]);function L(e,n){return e.includes(n)}function fe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function b(e,n){let t=e.indexOf(n);return t>=0?e[t+1]:void 0}function le(e){let n=[];for(let t=0;t<e.length;t+=1){let o=e[t];if(o===void 0)continue;if(Pr.has(o)){t+=1;continue}if(o.startsWith("-"))continue;n.push(o)}return n}async function dn(e){let n=Ar(),t=Cr(32).toString("base64url"),o=Rr("sha256").update(t).digest("base64url"),{code:r,close:s}=await _r(n);try{let i=r.callbackUrl,a=`${h(e)}/cli-auth/start?`+new URLSearchParams({callback:i,state:n,code_challenge:o});await Ir(a),Tr(a),console.log(`Opening ${a}`);let l=await Ur(r.promise,jr),d=await fetch(`${l.baseUrl}/v1/account/auth/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:l.code,code_verifier:t})});if(!d.ok)throw Error(`Login exchange failed: ${d.status} ${await d.text()}`);let c=await d.json(),p={baseUrl:l.baseUrl,dashboardUrl:h(e),token:c.token,createdAt:new Date().toISOString(),...c.user?{user:c.user}:{},...c.org?{org:c.org}:{},...c.account?{account:c.account}:{}};return await K(p),p}finally{s()}}async function J(e){f();let n=z(e);if(!n){let t=process.env.BROODS_DASHBOARD_URL,o=e??process.env.BROODS_BASE_URL??(t?D(t):void 0);throw Error(o?`Not logged in to ${h(o)}. Run \`broods login\`.`:"Run `broods login` first, or set BROODS_TOKEN and BROODS_BASE_URL.")}return n}async function We(e){if(!Q.isTTY)return!1;let n=Ae({input:Q,output:X});try{let t=(await n.question(`${e} [y/N] `)).trim().toLowerCase();return t==="y"||t==="yes"}finally{n.close()}}async function ft(e){let n=Ae({input:Q,output:X});try{let t=await n.question(`${e}: `);if(!t)throw Error(`${e} is required`);return t}finally{n.close()}}async function xe(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,l)=>{console.log(ve(`${l+1}. ${t(a)}`,l===r))});let s=r===void 0?`Choose 1-${n.length}: `:`Choose 1-${n.length} [${r+1}]: `,i=Ae({input:Q,output:X});try{for(;;){let a=(await i.question(s)).trim();if(a===""&&r!==void 0)return n[r];let l=Number(a);if(Number.isInteger(l)&&l>=1&&l<=n.length)return n[l-1];console.log(`Enter a number from 1 to ${n.length}.`)}}finally{i.close()}}async function pt(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=Ae({input:Q,output:X});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 pe(e,n){if(!Q.isTTY)return n??"";let t=Ae({input:Q,output:X});try{let o=t.question(`${e}: `);if(n){if(Q.isTTY&&X.isTTY)X.write("\x1B[90m");if(t.write(n),Q.isTTY&&X.isTTY)X.write("\x1B[0m")}return(await o).trim()||n||""}finally{t.close()}}async function Ir(e){let n=await fetch(e,{method:"GET",redirect:"manual"});if(n.status===404){let t=new URL(e);throw Error(`${t.origin} does not expose /cli-auth/start yet. Deploy the dashboard changes first, or use --dashboard-url http://localhost:3000 with a local dashboard dev server.`)}if(n.status>=500)throw Error(`Dashboard CLI auth route failed: ${n.status} ${await n.text()}`)}function Dr(){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 Tr(e){let n=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",t=process.platform==="win32"?["/c","start",e]:[e];xr(n,t,{stdio:"ignore",detached:!0}).unref()}function _r(e){return new Promise((n,t)=>{let o=Or((l,d)=>{try{let c=new URL(l.url??"/","http://127.0.0.1"),p=c.searchParams.get("state"),u=c.searchParams.get("code"),m=c.searchParams.get("base_url");if(p!==e||!u){d.writeHead(400).end("Invalid broods login callback.");return}if(!m){d.writeHead(400).end("Login callback omitted base_url; update the dashboard deployment."),s(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}d.writeHead(200,{"Content-Type":"text/plain"}).end("broods CLI login complete. You can close this tab."),r({code:u,baseUrl:h(m)})}catch(c){s(c)}}),r,s,i=new Promise((l,d)=>{r=l,s=d}),a=Dr();o.on("error",(l)=>{if(!process.env.BROODS_LOGIN_PORT&&a!==0&&l.code==="EADDRINUSE"){o.listen(0,"127.0.0.1");return}t(l)}),o.listen(a,"127.0.0.1",()=>{let l=o.address();if(!l||typeof l==="string"){t(Error("Failed to allocate callback port"));return}n({code:{callbackUrl:`http://127.0.0.1:${l.port}/callback`,promise:i},close:()=>o.close()})})})}async function Ur(e,n){let t,o=new Promise((r,s)=>{t=setTimeout(()=>s(Error(`Timed out waiting for browser login to complete.
|
|
72
72
|
Check the browser tab and the dashboard logs for an error. If the browser shows
|
|
73
73
|
404 on /cli-auth/start, deploy the dashboard build that includes CLI auth or pass
|
|
74
74
|
--dashboard-url for the environment you deployed. Other common causes are missing
|
|
75
|
-
cliAuth Convex functions or no active API account (Settings -> API Access).`)),n)});try{return await Promise.race([e,o])}finally{if(t)clearTimeout(t)}}import{existsSync as
|
|
76
|
-
`,"utf8")}catch{}}var
|
|
75
|
+
cliAuth Convex functions or no active API account (Settings -> API Access).`)),n)});try{return await Promise.race([e,o])}finally{if(t)clearTimeout(t)}}import{existsSync as mt}from"node:fs";import{mkdir as Lr,readFile as Nr,writeFile as Mr}from"node:fs/promises";import{dirname as wt,join as un,resolve as Br,sep as de}from"node:path";import{fileURLToPath as Gr}from"node:url";var gn=un(wt(O),"update-check.json"),Wr=86400000,Fr="https://registry.npmjs.org/broods/latest",Kr=2000;function fn(e,n){let t=bt(e),o=bt(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!ht(e)&&ht(n)}async function pn(e={}){let n=await zr(),t=e.maxAgeMs??Wr;if(n&&Date.now()-n.checkedAt<t)return n.latest;let o=await Hr();if(o===null)return n?.latest??null;return await Yr({checkedAt:Date.now(),latest:o}),o}function yt(e=Br(process.cwd()),n=Gr(import.meta.url)){let t=`${de}node_modules${de}`,o=n.lastIndexOf(t),r=o===-1?null:n.slice(0,o),s=r===null?n.startsWith(`${e}${de}`):e===r||e.startsWith(`${r}${de}`),a=n.includes(`${de}.bun${de}install${de}global${de}`)||s&&Vr(r??e)?"bun":"npm",l=a==="bun"?"add":"install";return{manager:a,global:!s,command:a,args:s?[l,"broods@latest"]:[l,"-g","broods@latest"]}}async function Hr(){try{let e=await fetch(Fr,{signal:AbortSignal.timeout(Kr),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 Vr(e){return mt(un(e,"bun.lock"))||mt(un(e,"bun.lockb"))}function ht(e){return e.includes("-")}async function zr(){try{let e=JSON.parse(await Nr(gn,"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 bt(e){let[n]=e.trim().replace(/^v/,"").split("-");return(n??"").split(".").slice(0,3).map((t)=>Number.parseInt(t,10)||0)}async function Yr(e){try{await Lr(wt(gn),{recursive:!0}),await Mr(gn,`${JSON.stringify(e)}
|
|
76
|
+
`,"utf8")}catch{}}var vt={name:"broods",version:"0.41.0",description:"CLI + TypeScript SDK for the broods agent platform.",keywords:["agents","ai","broods","cli","sdk"],homepage:"https://github.com/beeblastco/broods#readme",bugs:{url:"https://github.com/beeblastco/broods/issues"},license:"MIT",repository:{type:"git",url:"git+https://github.com/beeblastco/broods.git",directory:"packages/broods"},bin:{broods:"dist/cli/index.js"},files:["dist","README.md","LICENSE.md"],type:"module",main:"./dist/index.js",types:"./dist/index.d.ts",typesVersions:{"*":{account:["./dist/account.d.ts"]}},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./account":{types:"./dist/account.d.ts",import:"./dist/account.js"}},scripts:{build:"bun scripts/build.ts && rollup -c rollup.dts.config.mjs && rm -rf .dts-temp",check:"tsc --noEmit","pack:check":"bun run build && publint && attw --pack .",test:"bun test"},dependencies:{"@modelcontextprotocol/client":"^2.0.0",esbuild:"^0.28.2"},devDependencies:{"@ai-sdk/tui":"1.0.121","@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.0.0","@types/bun":"^1.3.14","@typescript/typescript6":"6.0.2",ai:"^7.0.120",publint:"^0.3.23",rollup:"^4.62.4","rollup-plugin-dts":"^6.5.1",typescript:"^7.0.2",zod:"^4.4.3"},peerDependencies:{ai:"^7.0.120"},engines:{node:">=22.15"}};var kt=`---
|
|
77
77
|
name: broods
|
|
78
78
|
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.
|
|
79
79
|
---
|
|
@@ -92,7 +92,7 @@ The \`broods\` CLI does the interaction: sign-in, project sync, env, logs, runni
|
|
|
92
92
|
|
|
93
93
|
\`broods dev\` on first run does everything: scaffolds \`broods/\` with a starter agent, runs the browser login if needed, pushes model keys from \`.env.local\` to the cloud env store, syncs to the \`development\` stage, then watches for changes and tails logs. \`broods init\` and \`broods login\` exist standalone when you want the steps separate.
|
|
94
94
|
|
|
95
|
-
A project is the \`broods/\` directory. \`broods/index.ts\` exports resources built with the \`define*\` functions: \`defineAgent\`, \`defineSandbox\`, \`defineWorkspace\`, \`defineSkill\`, \`defineCron\`, \`defineMcp\`, \`definePolicy\`, and the channel helpers. An optional \`export default defineBroods({...})\` sets project defaults like project name and stage mapping. The full reference is
|
|
95
|
+
A project is the \`broods/\` directory. \`broods/index.ts\` exports resources built with the \`define*\` functions: \`defineAgent\`, \`defineSandbox\`, \`defineWorkspace\`, \`defineSkill\`, \`defineCron\`, \`defineMcp\`, \`definePolicy\`, and the channel helpers. An optional \`export default defineBroods({...})\` sets project defaults like project name and stage mapping. The full reference is https://docs.broods.app/reference/configuration; the starter agent in \`broods/index.ts\` shows the minimum shape.
|
|
96
96
|
|
|
97
97
|
To create an agent, add a \`defineAgent\` to the project and sync. Talk to it with \`broods run <agent> "prompt"\`. Day to day: \`broods dev\` watches, \`broods diff\` previews, \`broods deploy\` syncs the production stage. Always \`diff\` before the first \`deploy\` on a stage you did not create.
|
|
98
98
|
|
|
@@ -108,11 +108,11 @@ const client = new BroodsClient();
|
|
|
108
108
|
const result = await client.run(api.agents.myAgent, { input: "..." });
|
|
109
109
|
\`\`\`
|
|
110
110
|
|
|
111
|
-
\`client.stream(...)\` and \`client.runAsync(...)\` cover streaming and async runs. \`_generated/\` is empty until a sync has run at least once.
|
|
111
|
+
\`client.stream(...)\` and \`client.runAsync(...)\` cover streaming and async runs. \`_generated/\` is empty until a sync has run at least once. https://docs.broods.app/reference/sdk has the full client, including account operations through \`BroodsAccountClient\`.
|
|
112
112
|
|
|
113
113
|
## When the CLI has no command
|
|
114
114
|
|
|
115
|
-
Crons, skills, sandboxes, policies, roles, channels, and hooks have no CLI verb. Prefer changing them in the project definition and syncing. For one-off reads and operations a manifest cannot say, use the MCP server. \`claude mcp add broods -- broods mcp\` adds it, and its tool names mirror the SDK: \`list-agents\`, \`create-cron\`, \`update-agent\`, and so on. For scoped automation credentials, read
|
|
115
|
+
Crons, skills, sandboxes, policies, roles, channels, and hooks have no CLI verb. Prefer changing them in the project definition and syncing. For one-off reads and operations a manifest cannot say, use the MCP server. \`claude mcp add broods -- broods mcp\` adds it, and its tool names mirror the SDK: \`list-agents\`, \`create-cron\`, \`update-agent\`, and so on. For scoped automation credentials, read the roles section of https://docs.broods.app/guides/security.
|
|
116
116
|
|
|
117
117
|
## Rules that keep you out of trouble
|
|
118
118
|
|
|
@@ -121,7 +121,7 @@ Crons, skills, sandboxes, policies, roles, channels, and hooks have no CLI verb.
|
|
|
121
121
|
- Env values are write-only. Reference them from configs as \`\${NAME}\`. If the user pastes a secret at you, put it in the env store and use the ref.
|
|
122
122
|
- Deletes are confirmed, named, and singular. Never loop a delete over a list.
|
|
123
123
|
- Editing a manifest-declared resource outside the project drifts from the definition, and the next deploy silently reverts it.
|
|
124
|
-
`;var
|
|
124
|
+
`;var St=`#!/usr/bin/env bash
|
|
125
125
|
# Onboard this machine onto broods: check the CLI, check auth, and run the
|
|
126
126
|
# browser login when needed. Login is a human step, so run this where the
|
|
127
127
|
# user can see the browser open and finish it themselves.
|
|
@@ -156,51 +156,23 @@ elif [ "$STATUS" -ne 0 ]; then
|
|
|
156
156
|
# Not the expected signed-out state: surface the real failure.
|
|
157
157
|
exit "$STATUS"
|
|
158
158
|
fi
|
|
159
|
-
`;var
|
|
159
|
+
`;var ue=vt.version,Fe=Pe(".agents","skills","broods"),Z="https://dashboard.broods.app",cs=60000,ls=3,je="eu-west-1",ds=[{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)"}],N=`Global options:
|
|
160
160
|
--project <name> Project name override (default: package name or folder)
|
|
161
161
|
--stage <name> Target stage override (BROODS_STAGE otherwise)
|
|
162
162
|
--base-url <url> broods API base URL for sync/env calls (default: discovered at login)
|
|
163
163
|
--dashboard-url <url> Dashboard base URL for login and deep links (default: ${Z})
|
|
164
|
-
-h, --help Show this help`,
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
init
|
|
170
|
-
project List the org's projects, or delete one
|
|
171
|
-
dev Watch + sync the current stage and live-tail agent logs
|
|
172
|
-
diff Show local desired state vs remote state
|
|
173
|
-
deploy Sync Production once and write BROODS_API_KEY to .env.local
|
|
174
|
-
|
|
175
|
-
Account:
|
|
176
|
-
login Authenticate through the dashboard
|
|
177
|
-
whoami Show the login, server, org, plan, project and stage in use
|
|
178
|
-
org List, switch or create organizations
|
|
179
|
-
stage List, switch or create stages
|
|
180
|
-
env Store, reveal, list, remove or sync encrypted environment variables
|
|
181
|
-
|
|
182
|
-
Runtime:
|
|
183
|
-
agent Inspect the agents declared in the current scope
|
|
184
|
-
run <agent> [prompt] Chat with an agent in a terminal UI
|
|
185
|
-
logs Backfill recent logs then live-tail
|
|
186
|
-
stream Stream live logs for the whole project/stage (Ctrl+C to stop)
|
|
187
|
-
machine <sandbox> Make this computer the sandbox behind a "machine" record
|
|
188
|
-
|
|
189
|
-
CLI:
|
|
190
|
-
mcp Serve the account config plane to an agent over MCP (stdio)
|
|
191
|
-
update Install the newest broods release over this one
|
|
192
|
-
|
|
193
|
-
Options:
|
|
194
|
-
-h, --help Show help for a command (e.g. \`broods org --help\`)
|
|
195
|
-
-v, --version Print the CLI version
|
|
196
|
-
|
|
197
|
-
Run \`broods <command> --help\` to see a command's subcommands and flags.`,mn={agent:`Usage: broods agent <list|get> [name]
|
|
164
|
+
-h, --help Show this help`,us=`Commands
|
|
165
|
+
Develop dev diff run logs stream
|
|
166
|
+
Ship deploy env stage
|
|
167
|
+
Inspect agent whoami
|
|
168
|
+
Account login org project
|
|
169
|
+
Tools init machine mcp update`,mn={stream:"stdout"},Dt={color:!1},gs=new Set(["agent","deploy","dev","diff","env","logs","machine","run","stage","stream"]),Tt={agent:`Usage: broods agent <list|get> [name]
|
|
198
170
|
|
|
199
171
|
Subcommands:
|
|
200
172
|
list List the agents in the current project/stage scope
|
|
201
173
|
get <name> Show an agent's model, sandboxes, workspaces, tools and channels
|
|
202
174
|
|
|
203
|
-
${
|
|
175
|
+
${N}`,deploy:`Usage: broods deploy [options]
|
|
204
176
|
|
|
205
177
|
Syncs Production once and writes BROODS_API_KEY to .env.local. Ignores
|
|
206
178
|
BROODS_STAGE by design. Pass --stage to deploy anywhere else.
|
|
@@ -208,9 +180,8 @@ BROODS_STAGE by design. Pass --stage to deploy anywhere else.
|
|
|
208
180
|
Options:
|
|
209
181
|
--prune Allow deploy to delete undeclared remote resources
|
|
210
182
|
--rotate-key Mint a fresh runtime API key and write it to .env.local
|
|
211
|
-
--region <region> Broods service region preference (default: ${$e})
|
|
212
183
|
|
|
213
|
-
${
|
|
184
|
+
${N}`,dev:`Usage: broods dev [--once] [options]
|
|
214
185
|
|
|
215
186
|
Watches broods/, syncs the current stage (BROODS_STAGE, default Development)
|
|
216
187
|
and live-tails agent logs. Confirms before deleting, and auto-pushes
|
|
@@ -220,13 +191,14 @@ Options:
|
|
|
220
191
|
--once Sync a single time and exit (no watch, no log stream)
|
|
221
192
|
--level <lvl> Minimum level for the log tail DEBUG|INFO|WARN|ERROR (default: WARN)
|
|
222
193
|
--all Tail INFO and up (DEBUG is dashboard-only)
|
|
194
|
+
--region <region> Service region for a new project (default: ${je})
|
|
223
195
|
|
|
224
|
-
${
|
|
196
|
+
${N}`,diff:`Usage: broods diff [options]
|
|
225
197
|
|
|
226
198
|
Shows local desired state against the remote state of the current stage, and
|
|
227
199
|
warns when the stage's value for an env("NAME") ref no longer matches .env.local.
|
|
228
200
|
|
|
229
|
-
${
|
|
201
|
+
${N}`,env:`Usage: broods env <set|get|list|rm|sync> [name]
|
|
230
202
|
|
|
231
203
|
Subcommands:
|
|
232
204
|
set <name> Store an encrypted environment variable (value read from the prompt or stdin)
|
|
@@ -242,23 +214,23 @@ Subcommands:
|
|
|
242
214
|
those the stage does not already hold the local value for. \`dev\` runs the same
|
|
243
215
|
push on every sync; \`deploy\` never does, so Production stays explicit.
|
|
244
216
|
|
|
245
|
-
${
|
|
217
|
+
${N}`,init:`Usage: broods init [options]
|
|
246
218
|
|
|
247
219
|
Creates the broods/ project shell and .env.local defaults.
|
|
248
220
|
|
|
249
221
|
Options:
|
|
250
|
-
--region <region> Broods service region preference (default: ${
|
|
222
|
+
--region <region> Broods service region preference (default: ${je})
|
|
251
223
|
--force Overwrite existing starter files
|
|
252
224
|
|
|
253
|
-
${
|
|
225
|
+
${N}`,login:`Usage: broods login [options]
|
|
254
226
|
|
|
255
227
|
Authenticates through the dashboard and stores the token in
|
|
256
228
|
~/.broods/config.json.
|
|
257
229
|
|
|
258
230
|
Options:
|
|
259
|
-
--region <region> Broods service region preference (default: ${
|
|
231
|
+
--region <region> Broods service region preference (default: ${je})
|
|
260
232
|
|
|
261
|
-
${
|
|
233
|
+
${N}`,logs:`Usage: broods logs [options]
|
|
262
234
|
|
|
263
235
|
Backfills recent logs then live-tails. Warnings and errors, 100 lines by default.
|
|
264
236
|
|
|
@@ -271,7 +243,7 @@ Options:
|
|
|
271
243
|
is the last segment of the instance's log stream
|
|
272
244
|
(dashboard Instances sheet).
|
|
273
245
|
|
|
274
|
-
${
|
|
246
|
+
${N}`,machine:`Usage: broods machine <sandbox> [options]
|
|
275
247
|
|
|
276
248
|
Connects this computer to a sandbox record whose provider is "machine". Agents
|
|
277
249
|
on that sandbox run their bash tool here, as you, with your PATH and
|
|
@@ -285,7 +257,8 @@ With --mcp <file>, the stdio MCP servers in that file run here for MCP rows
|
|
|
285
257
|
whose sandbox is this record. The file has the .mcp.json shape Claude Code and
|
|
286
258
|
Cursor read, and it never leaves this computer.
|
|
287
259
|
|
|
288
|
-
Authenticates with
|
|
260
|
+
Authenticates with your \`broods login\`, like \`broods logs\`, and needs a
|
|
261
|
+
deployed stage. The stage runtime key cannot open the machine socket.
|
|
289
262
|
|
|
290
263
|
Options:
|
|
291
264
|
--cwd <dir> Working directory for commands (default: current directory)
|
|
@@ -294,7 +267,7 @@ Options:
|
|
|
294
267
|
--force Take the record over from another daemon, even one on this computer
|
|
295
268
|
--doctor [--request] Check the macOS permissions computer use needs; --request prompts for them
|
|
296
269
|
|
|
297
|
-
${
|
|
270
|
+
${N}`,org:`Usage: broods org <list|use|create> [name]
|
|
298
271
|
|
|
299
272
|
Subcommands:
|
|
300
273
|
list List the organizations this login can act on
|
|
@@ -303,13 +276,13 @@ Subcommands:
|
|
|
303
276
|
|
|
304
277
|
Only orgs where you are owner or admin can be selected from the CLI.
|
|
305
278
|
|
|
306
|
-
${
|
|
279
|
+
${N}`,run:`Usage: broods run <agent> [prompt]
|
|
307
280
|
|
|
308
281
|
Chats with an agent in a terminal UI (reasoning, tool cards, y/n approvals).
|
|
309
282
|
A prompt is sent as the first turn; redirected output streams plain text and
|
|
310
283
|
therefore requires a prompt.
|
|
311
284
|
|
|
312
|
-
${
|
|
285
|
+
${N}`,project:`Usage: broods project <list|delete> [name]
|
|
313
286
|
|
|
314
287
|
Subcommands:
|
|
315
288
|
list List the org's projects and what each one still holds
|
|
@@ -322,7 +295,7 @@ admin role. There is no undo.
|
|
|
322
295
|
Options:
|
|
323
296
|
--yes Skip the confirmation prompt
|
|
324
297
|
|
|
325
|
-
${
|
|
298
|
+
${N}`,stage:`Usage: broods stage <list|use|create> [name]
|
|
326
299
|
|
|
327
300
|
Subcommands:
|
|
328
301
|
list List the project's stages
|
|
@@ -333,7 +306,7 @@ Options:
|
|
|
333
306
|
--from <stage> Clone the source stage's architecture and env vars
|
|
334
307
|
--use Switch to the stage \`stage create\` just made
|
|
335
308
|
|
|
336
|
-
${
|
|
309
|
+
${N}`,stream:`Usage: broods stream [options]
|
|
337
310
|
|
|
338
311
|
Streams live logs for the whole project/stage until Ctrl+C. No backfill.
|
|
339
312
|
|
|
@@ -341,7 +314,7 @@ Options:
|
|
|
341
314
|
--level <lvl> Minimum log level DEBUG|INFO|WARN|ERROR (default: WARN)
|
|
342
315
|
--all Stream INFO and up (DEBUG is dashboard-only)
|
|
343
316
|
|
|
344
|
-
${
|
|
317
|
+
${N}`,mcp:`Usage: broods mcp
|
|
345
318
|
|
|
346
319
|
Serves the account config plane to a development agent over MCP on stdio, so
|
|
347
320
|
Claude Code and friends drive broods through typed tools instead of curl. It
|
|
@@ -367,45 +340,53 @@ place; inside a project the dependency is upgraded instead.`,whoami:`Usage: broo
|
|
|
367
340
|
|
|
368
341
|
Shows the login, server, org, plan, project and stage the next command uses.
|
|
369
342
|
|
|
370
|
-
${
|
|
343
|
+
${N}`};async function fs(){let[,,e,...n]=process.argv;switch(e){case void 0:case"--help":case"-h":console.log(hn(n,mn));return;case"--version":case"-v":console.log(ue);return}if(ii(e,n),Tt[e]&&(L(n,"--help")||L(n,"-h"))){console.log(me(e,n));return}switch(e){case"init":await ms(n);return;case"login":await hs(n);return;case"whoami":await ws(n);return;case"org":await vs(n);return;case"project":await ks(n);return;case"stage":await Ss(n);return;case"diff":await $s(n);return;case"deploy":await Es(n);return;case"dev":await Rs(n);return;case"env":await Ys(n);return;case"stream":await Zs(n);return;case"logs":await ei(n);return;case"machine":await Xs(n);return;case"agent":await ni(n);return;case"run":await ri(n);return;case"mcp":await ai();return;case"update":await Os();return;default:throw Error(`Unknown command: ${e}
|
|
344
|
+
|
|
345
|
+
${hn(n,Dt)}`)}}function ee(e){return Tt[e]??hn([],Dt)}function _t(e){let n=f(),t=b(e,"--base-url")??n.baseUrl,o=z(t),r=h(t??o?.baseUrl??E);return{loggedIn:o!==null,org:o?.org?.name,project:b(e,"--project")??n.project,projectGuess:Se(process.cwd()),server:r.replace(/^https?:\/\//,""),stage:b(e,"--stage")??n.stage??"development"}}function ps(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 me(e,n){let t=ee(e);if(!gs.has(e))return t;let o=_t(n),r=o.project??o.projectGuess;if(e!=="deploy"||b(n,"--stage")!==void 0)return`${cn(r,o.stage,mn)}
|
|
346
|
+
|
|
347
|
+
${t}`;let s=v(),i=s&&s!=="production"?`ignores stage ${s}`:void 0;return`${cn(r,"production",{...mn,note:i})}
|
|
371
348
|
|
|
372
|
-
${
|
|
349
|
+
${t}`}function hn(e,n){let t=_t(e);return[`broods v${ue}`,"",...it(t,n),"","Next",...at(ps(t),n),"",us,"","Usage: broods <command> [options] -h, --help -v, --version","Run `broods <command> --help` for a command's flags."].join(`
|
|
350
|
+
`)}async function ms(e){let n=L(e,"--force"),t=x(process.cwd(),S);await kn(x(t,_),{recursive:!0}),await He(x(t,"index.ts"),Yt(),n),await He(x(t,".gitignore"),`_generated
|
|
373
351
|
.cache
|
|
374
|
-
`,n),await
|
|
352
|
+
`,n),await Nt(n);let o=b(e,"--dashboard-url")??Z;await Rn({dashboardUrl:o,baseUrl:D(o),project:b(e,"--project")??Se(process.cwd()),stage:b(e,"--stage")??"development",region:b(e,"--region")??je,force:n}),await On(),M(`Created ${S}/`)}async function hs(e){let n=f(),t=b(e,"--dashboard-url")??n.dashboardUrl??Z,o=await dn(t);await Rn({dashboardUrl:o.dashboardUrl??t,baseUrl:o.baseUrl,project:b(e,"--project"),stage:b(e,"--stage"),region:b(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(M(`Logged in to ${o.dashboardUrl}`),r)console.log(`User: ${r}`);if(s)console.log(`Org: ${s}`);if(i)console.log(`Account: ${i}`);let a=b(e,"--project")??process.env.BROODS_PROJECT;if(!a)return;let l=b(e,"--stage")??v()??"development";await bs(o.baseUrl,o.token,a,l)}async function bs(e,n,t,o){try{let s=await new T({baseUrl:e,token:n}).getRuntimeKey(t,o);if(s?.apiKey)await ke("BROODS_API_KEY",s.apiKey),M(`Wrote BROODS_API_KEY (${s.keyHint}) to .env.local`)}catch{}}async function ws(e){let n=f(),t=ze(e),o=b(e,"--dashboard-url")??n.dashboardUrl??Z,r=Boolean(b(e,"--project")??n.project);console.log(`broods v${ue}`),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 J(b(e,"--base-url"))}catch(c){P(c instanceof Error?c.message:String(c));return}console.log(`Server: ${s.baseUrl}`);let i=new T({baseUrl:s.baseUrl,token:s.token}),a=await i.getOnboarding(),l=a.orgs.find((c)=>c.id===a.currentOrgId);if(a.user)console.log(`User: ${a.user.email}`);if(console.log(`Org: ${l?Ie(l):a.currentOrgId}`),a.account)console.log(`Account: ${a.account.username} (${a.account.status})`);if(!r){P("No project set. `broods dev` picks one.");return}await ys(i,t,l?.name);let d=a.projects.map((c)=>c.name);if(!d.includes(t.project))P(`This org has no project named ${t.project}. It has: ${d.length>0?d.join(", "):"none"}.`)}async function ys(e,n,t){let o=process.env.BROODS_API_KEY,r=A("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"),P(`Could not read the runtime key: ${i}`);else if(!s?.apiKey)console.log("Runtime key: none for this scope"),P(`${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)`),P("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`),P(`BROODS_API_KEY from ${r} belongs to a different org or stage. Run \`broods stage use ${n.stage}\` to repoint it.`)}async function vs(e){let[n,t]=le(e);if(!n){console.log(me("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}
|
|
375
353
|
|
|
376
|
-
${
|
|
377
|
-
Only orgs where you are owner or admin can be selected from the CLI.`);return}if(r){let
|
|
354
|
+
${ee("org")}`);let i=f(),a=b(e,"--dashboard-url")??i.dashboardUrl??Z,l=await De(a,b(e,"--base-url")),d=new T({baseUrl:l.baseUrl,token:l.token}),c=await d.getOnboarding();if(o){for(let u of c.orgs){let m=u.accountStatus==="active"?"":` [${u.accountStatus} account]`;console.log(ve(`${Ie(u)}${m}`,u.id===c.currentOrgId))}console.log(`
|
|
355
|
+
Only orgs where you are owner or admin can be selected from the CLI.`);return}if(r){let u=c.orgs.filter((y)=>y.accountStatus==="active"),m=t?u.find((y)=>y.slug===t||y.name===t||y.id===t):await xe("Select organization",u,Ie,u.findIndex((y)=>y.id===c.currentOrgId));if(!m)throw Error(`No selectable organization matches "${t}". Run \`broods org list\`.`);await Rt(d,l,await d.selectOnboardingOrg(m.id),e);return}let p=t??await pe("Organization name",Se(process.cwd()));if(!p.trim())throw Error("Organization name is required.");await Rt(d,l,await d.createOnboardingOrg(p),e)}async function ks(e){let[n,t]=le(e);if(!n){console.log(me("project",e));return}let o=n==="list"||n==="ls";if(!o&&!(n==="delete"||n==="rm"))throw Error(`Unknown project subcommand: ${n}
|
|
378
356
|
|
|
379
|
-
${
|
|
380
|
-
${k.length} empty project(s). Delete one with \`broods project delete <name>\`.`);return}let
|
|
357
|
+
${ee("project")}`);let s=f(),i=b(e,"--dashboard-url")??s.dashboardUrl??Z,a=ze(e),l=await De(i,b(e,"--base-url")),d=new T({baseUrl:l.baseUrl,token:l.token});if(o){let y=await d.listProjects();if(y.length===0){console.log("This org has no projects yet. `broods dev` creates one.");return}console.log("Projects:");for(let R of y)console.log(Ts(R,a.project));let k=y.filter((R)=>R.empty);if(k.length>0)console.log(`
|
|
358
|
+
${k.length} empty project(s). Delete one with \`broods project delete <name>\`.`);return}let c=t??await pe("Project to delete","");if(!c.trim())throw Error("Project name is required.");let p=await d.listProjects(),u=p.find((y)=>y.name===c||y.slug===c);if(!u)throw Error(`No project named "${c}". Existing: ${p.map((y)=>y.name).join(", ")}.`);if(!L(e,"--yes")){if(console.log(`Deleting ${u.name} removes ${yn(u)}.`),!await We(`Permanently delete project ${u.name}?`)){console.log("Left it alone. Pass --yes to skip this prompt.");return}}let m=await d.deleteProject(u.id);if(!m)throw Error(`Project ${u.name} was not found.`);if(M(`Deleted project ${m.name} (${yn(m)})`),m.name===a.project||m.slug===a.project)console.log("That was the project this directory points at. Update BROODS_PROJECT in .env.local.")}async function Ss(e){let[n,t]=le(e);if(!n){console.log(me("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}
|
|
381
359
|
|
|
382
|
-
${
|
|
360
|
+
${ee("stage")}`);let i=f(),a=b(e,"--dashboard-url")??i.dashboardUrl??Z,l=ze(e),d=await De(a,b(e,"--base-url")),c=new T({baseUrl:d.baseUrl,token:d.token});if(o){let k=await c.listStages(l.project);if(k.length===0){console.log(`${l.project} has no stages yet. \`broods dev\` creates Development.`);return}console.log(`Stages for ${l.project}:`);for(let R of k)console.log(_s(R,l.stage));return}if(r){let k=await c.listStages(l.project),R=t?k.find((B)=>vn(B.name,t)):await xe("Select stage",k,Mt,k.findIndex((B)=>vn(B.name,l.stage)));if(!R)throw Error(`${l.project} has no stage "${t}". Existing: ${k.map((B)=>B.name).join(", ")}. Create it with \`broods stage create ${t} --from ${l.stage}\`.`);let ne=A("BROODS_STAGE");await ke("BROODS_STAGE",R.name),console.log(`Stage: ${R.name} (wrote BROODS_STAGE)`),wn("BROODS_STAGE",ne),await bn(c,{project:l.project,stage:R.name});return}let p=t??await pe("Stage name","staging");if(!p.trim())throw Error("Stage name is required.");let u=b(e,"--from"),m=await c.createStage(l.project,p,u);if(M(`Created stage ${m.stage.name} in ${l.project}${m.clonedFrom?` from ${m.clonedFrom}`:""}`),m.clonedFrom)console.log(` ${m.stage.agentCount} agent(s), ${m.stage.variableCount} env var(s) copied`);if(!L(e,"--use")){console.log(`Switch to it with \`broods stage use ${m.stage.name}\`.`);return}let y=A("BROODS_STAGE");await ke("BROODS_STAGE",m.stage.name),console.log(`Stage: ${m.stage.name} (wrote BROODS_STAGE)`),wn("BROODS_STAGE",y),await bn(c,{project:l.project,stage:m.stage.name})}async function $s(e){let{manifest:n,config:t}=await re({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),o=await J(b(e,"--base-url")??t.baseUrl),r=new T({baseUrl:o.baseUrl,token:o.token}),s=await r.getManifest(n.project,n.stage);Ge(an(n,s?.manifest??null)),Ws(await Sn(r,n),`${n.project}/${n.stage}`)}async function Es(e){let{manifest:n,config:t,resourceAliases:o,channels:r}=await re({project:b(e,"--project"),stage:b(e,"--stage"),command:"deploy",useRuntimeStage:!1}),s=await J(b(e,"--base-url")??t.baseUrl),a=await new T({baseUrl:s.baseUrl,token:s.token}).putManifest(n,L(e,"--prune"),L(e,"--rotate-key"));await Le(n,a.ids,process.cwd(),o,a.deployment,r),await Vt(),await On(),M(`Synced ${a.manifest.resources.length} resources to ${n.project}/${n.stage}`),await Ut(a.deployment),Bt(r,a),Lt(a)}async function Ut(e){if(!e)return;if(e.apiKey){await ke("BROODS_API_KEY",e.apiKey),M(`Wrote BROODS_API_KEY (${e.keyHint}) to .env.local`);return}}function Lt(e){let n=e.warnings?.missingPolicies??[];if(n.length>0)P(`${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)P(`Kept on prune, a reserved sandbox instance is still live: ${t.join(", ")}. Terminate it from the dashboard, then deploy again.`)}async function Os(){let e=await pn({maxAgeMs:0});if(e===null)throw Error("Could not reach the npm registry to check for a newer broods.");if(!fn(e,ue)){console.log(`broods v${ue} is already the newest release.`);return}let n=yt();console.log(`Updating broods ${ue} → ${e} ${n.global?"globally":"in this project"}`),console.log(`$ ${[n.command,...n.args].join(" ")}`),await new Promise((t,o)=>{let r=It(n.command,n.args,{stdio:"inherit"});r.on("error",o),r.on("exit",(s)=>{if(s===0){t();return}o(Error(`${n.command} exited with code ${s??"unknown"}`))})}),console.log(`broods ${e} installed.`)}async function Et(){let e=await pn();if(e===null||!fn(e,ue))return;P(`broods ${e} is out, you are on ${ue}. Run \`broods update\`.`)}async function Rs(e){if(await As(e),L(e,"--once")){if(!process.env.BROODS_SUPPRESS_DEV_TARGET)await At(e),await Et();let c=$t.now();await Bs(e),dt($t.now()-c);return}let n=Pe(is(),`broods-declined-${process.pid}.txt`),t={...process.env,BROODS_DECLINED_FILE:n,BROODS_SUPPRESS_DEV_TARGET:"1",BROODS_RELOAD_ENV:"1"};await At(e),await Et(),await Ct(e,t);let o,r=!1,s=!1,i=await xt(),a=()=>{if(r){s=!0;return}r=!0,xt().then(async(c)=>{if(c===i)return;i=c,await Ct(e,t)}).catch((c)=>console.error(c instanceof Error?c.message:String(c))).finally(()=>{if(r=!1,s)s=!1,a()})},l=ss(x(process.cwd(),S),{recursive:!0},(c,p)=>{if(!p||si(p))return;clearTimeout(o),o=setTimeout(a,150)}),d=new AbortController;Cs(e,d.signal),process.on("SIGINT",()=>{d.abort(),l.close(),process.exit(0)})}async function Cs(e,n){let t;try{t=await Ye(e)}catch(r){console.log(`· live logs off. ${r instanceof Error?r.message:String(r)}`);return}let o=$n(e);try{for await(let r of Ne(t,{backfill:0,minLevel:o,signal:n}))console.log(En(r))}catch(r){if(!n.aborted)console.error(`live logs: ${r instanceof Error?r.message:String(r)}`)}}async function As(e){await js(),await Nt(!1),await Ps(e)}async function Nt(e){let n=process.cwd();if(!(await Promise.all([".agent",".agents",".claude","AGENTS.md","CLAUDE.md"].map((l)=>Ot(x(n,l))))).includes(!0))return;let r=x(n,Fe);if(!e&&await Ot(x(r,"SKILL.md")))return;let s=Pe(Fe,"SKILL.md"),i=Pe(Fe,"scripts","onboard.sh");for(let l of[s,i])if(await xs(n,l)){P(`Skipped the agent skill: ${l} crosses a symlink.`);return}await kn(x(r,"scripts"),{recursive:!0}),await ge(x(r,"SKILL.md"),kt);let a=x(r,"scripts","onboard.sh");await ge(a,St),await Xr(a,493),M(`Installed the broods agent skill at ${Fe}/`)}async function xs(e,n){let t=e;for(let o of n.split(rs)){t=x(t,o);try{if((await Qr(t)).isSymbolicLink())return!0}catch{return!1}}return!1}async function Ot(e){try{return await ns(e),!0}catch{return!1}}async function js(){let e=x(process.cwd(),S);await kn(x(e,_),{recursive:!0});let n=[];if(await Cn(e,n),n.length>0)return;await He(x(e,"index.ts"),Yt(),!1),await He(x(e,".gitignore"),`_generated
|
|
383
361
|
.cache
|
|
384
|
-
`,!1),
|
|
362
|
+
`,!1),M(`Created starter ${S}/`)}async function Ps(e){let n=x(process.cwd(),".env.local"),t=await be(n),o=zt(t),r=o.BROODS_STAGE;if(["BROODS_DASHBOARD_URL","BROODS_BASE_URL","BROODS_PROJECT","BROODS_REGION"].filter((y)=>o[y]===void 0).length===0&&r!==void 0)return;let i=o.BROODS_PROJECT===void 0,a=r===void 0,l=o.BROODS_REGION===void 0,d=f(),c=b(e,"--dashboard-url")??d.dashboardUrl??Z,p=b(e,"--project")??process.env.BROODS_PROJECT??Se(process.cwd()),u=b(e,"--stage")??v()??"development",m=b(e,"--region")??process.env.BROODS_REGION??je;if(process.stdin.isTTY&&i){let y=await De(c,b(e,"--base-url")),k=new T({baseUrl:y.baseUrl,token:y.token}),R=await Is(k,y),ne=await Us(k,R);if(p=await Ms(ne,p),!p.trim())throw Error("Project name is required.")}if(process.stdin.isTTY&&a){if(u=await pe("Stage",u),!u.trim())throw Error("Stage is required.")}if(process.stdin.isTTY&&l){let y=[...ds];m=await xe("Select service region",y,(k)=>k.label,y.findIndex((k)=>k.region===m)).then((k)=>k.region)}await Rn({dashboardUrl:c,baseUrl:d.baseUrl??D(c),project:p,stage:u,region:m,force:!1})}async function De(e,n){try{return await J(n)}catch(t){if(!process.stdin.isTTY)throw t;return P(`${t instanceof Error?t.message:String(t)} Starting browser login.`),await dn(e)}}async function Is(e,n){try{return await e.getOnboarding()}catch(t){if(!n.org)throw t;return P("CLI onboarding endpoint is not available yet; using the org from the current 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 Rt(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)P("BROODS_TOKEN is set, so the switch applies to this token only and was not stored.");else await K({...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: ${Ie(r)}`),console.log(`Projects: ${t.projects.length>0?t.projects.map((s)=>s.name).join(", "):"none yet"}`),await bn(e,ze(o))}async function bn(e,n){let t;try{t=await e.getRuntimeKey(n.project,n.stage)}catch(r){P(`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){P(`${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=A("BROODS_API_KEY");if(!o&&process.env.BROODS_API_KEY===t.apiKey)return;await ke("BROODS_API_KEY",t.apiKey),M(`Wrote BROODS_API_KEY (${t.keyHint}) to .env.local`),wn("BROODS_API_KEY",o)}function wn(e,n){if(!n)return;P(`${e} is exported in your shell, which wins over .env.local. Run \`unset ${e}\` or the next broods command keeps the old value.`)}function Ie(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 Ds(e){return e.slug===e.name?e.name:`${e.name} (${e.slug})`}function yn(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 Ts(e,n){let t=e.empty?"empty":yn(e);return ve(`${e.name}: ${t}`,e.name===n||e.slug===n)}function _s(e,n){return ve(Mt(e),vn(e.name,n))}function Mt(e){let n=e.deploymentRegion?`, ${e.deploymentRegion}`:"";return`${e.name} (${e.kind}${n}): ${e.agentCount} agent(s), ${e.variableCount} env var(s)`}function vn(e,n){return e.trim().toLowerCase()===n.trim().toLowerCase()}function ze(e){return f(),{project:b(e,"--project")??process.env.BROODS_PROJECT??Se(process.cwd()),stage:b(e,"--stage")??v()??"development"}}async function Us(e,n){let t=n.orgs.filter((s)=>s.accountStatus==="active"),o={kind:"create",name:"New organization"},r=await xe("Select organization",[...t,o],(s)=>("kind"in s)?"Create new organization":Ie(s),t.findIndex((s)=>s.id===n.currentOrgId));if("kind"in r){let s=await pe("Organization name",Se(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 Ls(e,n){return e.projects.find((o)=>o.name===n||o.slug===n)?.name??n}function Ns(e,n){return e.projects.find((t)=>t.name===n||t.slug===n)}async function Ms(e,n){let t=Ls(e,n);if(e.projects.length===0)return pe("Project name",t);for(;;){let o=await pt("Select project",e.projects,Ds,{hint:"type a new project name",defaultValue:t}),r=typeof o==="string"?o:o.name,s=Ns(e,r);if(!s)return r;if(await We(`Continue with the existing project ${s.name}?`))return s.name}}function Ct(e,n){return new Promise((t,o)=>{let r=process.argv[1]??"",s=It(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 Bs(e){let n=await re({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),t=await J(b(e,"--base-url")??n.config.baseUrl),o=new T({baseUrl:t.baseUrl,token:t.token}),r=await Gt(o,n.manifest,await Sn(o,n.manifest));if(r.length>0)ln(r);for(let s=1;;s+=1)try{return await Gs(o,n)}catch(i){if(!(i instanceof Be)||s===ls)throw i;P("Stage changed in another session. Re-reading...")}}async function Gs(e,n){let{manifest:t,resourceAliases:o,channels:r}=n,s=await e.getManifest(t.project,t.stage),i=an(t,s?.manifest??null);Ge(i.filter((u)=>u.operation!=="delete"));let a=await e.putManifest(t,!1,!1,s===null?0:s.revision);await Le(t,a.ids,process.cwd(),o,a.deployment,r),await Vt(),await On();let l=await Hs(),d=i.filter((u)=>u.operation==="delete"),c=d.filter((u)=>!l.has(`${u.kind}:${u.name}`)),p=!1;if(c.length>0)if(P("These remote resources are no longer declared locally:"),Ge(c),await We(`Delete ${c.length} resource(s) from ${t.project}/${t.stage}?`))a=await e.putManifest(t,!0,!1,a.revision),await Le(t,a.ids,process.cwd(),o,a.deployment,r),await zs(),p=!0;else await Vs(c.map((u)=>`${u.kind}:${u.name}`));if(!p&&d.length>0){let u=d.map((m)=>`${m.kind}:${m.name}`).join(", ");P(`${d.length} undeclared resource(s) kept remotely: ${u}. Re-declare in code or run \`deploy --prune\` to remove.`)}return await Ut(a.deployment),Bt(r,a),Lt(a),a}function Bt(e,n){let t=n.deployment;if(!t||e.length===0)return;let o=new U,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 l=s?o.accountWebhookUrl(t.accountId,i):o.stageWebhookUrl(t.accountId,t.endpointId,i);console.log(`Channel ${a.join(", ")} (${i}): ${l}${i==="pancake"?"?secret=<PANCAKE_WEBHOOK_SECRET>":""}`)}}async function Sn(e,n){let t=Yn(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:Fs(r,o)}))}async function Gt(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 Ws(e,n){let t=Ke(e,"drifted");if(t.length>0)P(`.env.local and ${n} disagree on ${t.length} variable(s): ${t.join(", ")}. Run \`broods env sync\` to push the local values.`)}function Fs(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===Ks(t)?"synced":"drifted"}function Ks(e){return Pt("sha256").update(e).digest("hex")}function Ke(e,n){return e.filter((t)=>t.state===n).map((t)=>t.name)}async function At(e){let n=f(),{manifest:t,config:o}=await re({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),r=await J(b(e,"--base-url")??o.baseUrl);ct({project:t.project,stage:t.stage,dashboardUrl:b(e,"--dashboard-url")??n.dashboardUrl??r.dashboardUrl??o.dashboardUrl??Z})}async function Hs(){let e=process.env.BROODS_DECLINED_FILE;if(!e)return new Set;let n=await be(e);return new Set(n.split(/\r?\n/).map((t)=>t.trim()).filter(Boolean))}async function Vs(e){let n=process.env.BROODS_DECLINED_FILE;if(!n||e.length===0)return;await ge(n,`${e.join(`
|
|
385
363
|
`)}
|
|
386
|
-
`,{flag:"a"})}async function
|
|
364
|
+
`,{flag:"a"})}async function zs(){let e=process.env.BROODS_DECLINED_FILE;if(!e)return;await ge(e,"","utf8")}async function Ys(e){let[n,t]=le(e);if(!n){console.log(me("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}
|
|
387
365
|
|
|
388
|
-
${
|
|
366
|
+
${ee("env")}`);if(a&&!t)throw Error(`broods env ${n} needs a variable name.
|
|
389
367
|
|
|
390
|
-
${
|
|
368
|
+
${ee("env")}`);let{manifest:l,config:d}=await re({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),c=await J(b(e,"--base-url")??d.baseUrl),p=new T({baseUrl:c.baseUrl,token:c.token}),u=`${l.project}/${l.stage}`;if(i){await Js(p,l,u);return}if(o){let y=await p.listEnv(l.project,l.stage);if(y.length===0){console.log(`No environment variables set for ${u}.`);return}console.log(`Environment variables for ${u} (values hidden):`);for(let k of y)console.log(` ${k.name}`);return}if(s){let y=await p.getEnv(l.project,l.stage,t);if(y===null){console.error(`${t} is not set for ${u}`),process.exitCode=1;return}console.log(y);return}if(r){await p.removeEnv(l.project,l.stage,t),M(`Removed ${t} from ${u}`);return}let m=await ft(t);await p.setEnv(l.project,l.stage,t,m),M(`Stored ${t} for ${u}`)}async function Js(e,n,t){let o=await Sn(e,n);if(o.length===0){console.log('No env("NAME") references in this project.');return}let r=await Gt(e,n,o);if(r.length>0)ln(r);let s=Ke(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=Ke(o,"stage-only");if(i.length>0)console.log(`${i.length} referenced variable(s) live only on ${t}: ${i.join(", ")}`);let a=Ke(o,"unresolved");if(a.length>0)P(`${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>\`.`)}function $n(e){if(L(e,"--all"))return"DEBUG";let n=b(e,"--level");if(n===void 0&&L(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 qs(e){f();let n=b(e,"--project")??process.env.BROODS_PROJECT,t=b(e,"--stage")??v();if(!n)throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT in .env.local.");if(!t)throw Error("Stage name is required. Pass --stage <name> or set BROODS_STAGE in .env.local.");return{project:n,stage:t}}async function Ye(e){let n=await qs(e),t=f(),o=await De(b(e,"--dashboard-url")??t.dashboardUrl??Z,b(e,"--base-url")),r=new T({baseUrl:o.baseUrl,token:o.token}),s=await r.mintStageSession(n.project,n.stage),i=async()=>{if(s.expiresAt-Date.now()<cs)s=await r.mintStageSession(n.project,n.stage);return s.token};return{baseUrl:process.env.BROODS_BASE_URL??process.env.BROODS_HOST??E,credential:i,project:s.projectSlug,stage:s.stageSlug}}function Wt(e){return e==="WARN"?" (--all for INFO too)":""}function En(e){let n=new Date(e.ts).toISOString().slice(11,23),t=e.level.padEnd(5),o=as(e.message);return`${n} ${t} ${e.eventType} ${o}`}async function Zs(e){let n=await Ye(e),{project:t,stage:o}=n,r=$n(e),s=new AbortController,i=()=>s.abort();process.on("SIGINT",i),console.log(`Streaming live logs for ${t}/${o} [${r}+]`+Wt(r)+", Ctrl+C to stop");try{for await(let a of Ne(n,{backfill:0,minLevel:r,signal:s.signal}))console.log(En(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 Xs(e){if(L(e,"--doctor")){await Qs(L(e,"--request"));return}let n=le(e)[0];if(!n){console.log(me("machine",e));return}let{runMachineDaemon:t}=await import("../chunk-my7k41qq.js"),{baseUrl:o,credential:r}=await Ye(e),s=x(b(e,"--cwd")??process.cwd()),i=L(e,"--computer"),a=b(e,"--mcp"),l=L(e,"--force"),d=new AbortController,c=()=>d.abort();process.on("SIGINT",c),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:l,log:(p)=>console.log(p),mcpFile:a?x(a):void 0,sandbox:n,signal:d.signal})}catch(p){console.error(p instanceof Error?p.message:String(p)),process.exitCode=1}finally{process.off("SIGINT",c)}}async function Qs(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 ei(e){let n=await Ye(e),{project:t,stage:o}=n,r=b(e,"--sandbox");if(L(e,"--sandbox")&&!G(r))throw Error("--sandbox needs the instance log id, the UUID shown in the dashboard Instances sheet.");let s=r?"DEBUG":$n(e),i=Number(b(e,"--limit")??b(e,"-n")??100),a=L(e,"--json"),l=new AbortController,d=()=>l.abort();process.on("SIGINT",d),console.log(`Logs for ${t}/${o}`+(r?` sandbox ${r}`:"")+` [${s}+]`+Wt(s)+` (backfill ${i}), Ctrl+C to stop`);try{for await(let c of Ne(n,{backfill:i,minLevel:s,...r?{sandboxId:r}:{},signal:l.signal}))if(a)console.log(JSON.stringify(c));else console.log(En(c))}catch(c){if(!l.signal.aborted)console.error(c instanceof Error?c.message:String(c)),process.exitCode=1}finally{process.off("SIGINT",d)}}async function ni(e){let[n,t]=le(e);if(!n){console.log(me("agent",e));return}if(n==="list"||n==="ls"){await ti(e);return}if(n==="get"){await oi(t,e);return}throw Error(`Unknown agent subcommand: ${n}
|
|
391
369
|
|
|
392
|
-
${
|
|
370
|
+
${ee("agent")}`)}async function Ft(e){let{manifest:n,config:t}=await re({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),o=await J(b(e,"--base-url")??t.baseUrl),r=await new T({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 ti(e){let{manifest:n,agents:t}=await Ft(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=Kt(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 oi(e,n){if(!e)throw Error(`Missing agent name.
|
|
393
371
|
|
|
394
|
-
${
|
|
372
|
+
${ee("agent")}`);let{manifest:t,agents:o}=await Ft(n),r=o.find((u)=>u.name===e);if(!r)throw Error(`Unknown local agent: ${e}`);let s=r.config,i=[s.sandboxes].flat().filter((u)=>typeof u==="string").map((u,m)=>m===0?`${u} (default)`:u),a=Array.isArray(s.workspaces)?s.workspaces.map((u)=>typeof u==="string"?u:u.name).filter(Boolean):[],l=fe(s.tools)?Object.keys(s.tools):[],d=fe(s.channels)?Object.keys(s.channels):[],c=fe(s.subagent)&&Array.isArray(s.subagent.allowed)?s.subagent.allowed.map((u)=>typeof u==="string"?u:u.name).filter(Boolean):[],p=fe(s.hooks)&&Array.isArray(s.hooks.webhooks)?s.hooks.webhooks.filter(fe):[];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: ${Kt(s)}`),console.log(` Sandboxes: ${i.length>0?i.join(", "):"none"}`),console.log(` Workspaces: ${a.length>0?a.join(", "):"none"}`),console.log(` Tools: ${l.length>0?l.join(", "):"none"}`),console.log(` Subagents: ${c.length>0?c.join(", "):"none"}`),console.log(` Channels: ${d.length>0?d.join(", "):"none"}`),p.length>0)console.log(" Webhooks:"),p.forEach((u,m)=>{let y=Array.isArray(u.events)&&u.events.length>0?u.events.join(", "):"all events",k=u.enabled===!1?"disabled":"enabled";console.log(` [${m}] ${k} → ${u.url??"none"} (${y})`)})}function Kt(e){let n=fe(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 ri(e){let[n,...t]=le(e);if(!n)throw Error(`Missing agent name.
|
|
395
373
|
|
|
396
|
-
${
|
|
374
|
+
${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 re({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),a=await J(b(e,"--base-url")??i.baseUrl),l=s.resources.find((R)=>R.kind==="agent"&&R.name===n);if(!l)throw Error(`Unknown local agent: ${n}`);let c=(await new T({baseUrl:a.baseUrl,token:a.token}).getManifest(s.project,s.stage))?.ids.agents[n];if(!c)throw Error(`Agent ${n} is not synced yet. Run broods dev --once or broods deploy first.`);let p=await new T({baseUrl:a.baseUrl,token:a.token}).getRuntimeKey(s.project,s.stage).catch(()=>null);if(p?.apiKey)await ke("BROODS_API_KEY",p.apiKey);if(l.config.publicAccess!==!0)P(`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 u=new U({baseUrl:b(e,"--base-url")??process.env.BROODS_BASE_URL??process.env.BROODS_HOST??a.baseUrl,...p?.apiKey?{apiKey:p.apiKey}:{}}),m={kind:"agent",name:n,id:c,project:s.project,stage:s.stage,...p?.endpointId?{endpointId:p.endpointId}:{},...p?.projectSlug?{projectSlug:p.projectSlug}:{},...p?.stageSlug?{stageSlug:p.stageSlug}:{}},{runAgentTui:y,streamAgentText:k}=await import("../chunk-6en45n1d.js");try{if(r){await y({client:u,agent:m,...o?{prompt:o}:{}});return}await k({client:u,agent:m,prompt:o})}catch(R){if((R instanceof Error?R.message:String(R)).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 R}}async function He(e,n,t){try{await ge(e,n,{flag:t?"w":"wx"})}catch(o){if(o.code==="EEXIST")return;throw o}}async function Ht(){let e=x(process.cwd(),".gitignore"),n=await be(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()}
|
|
375
|
+
.env*.local
|
|
376
|
+
`:`.env*.local
|
|
377
|
+
`;await ge(e,o,"utf8")}async function Vt(){let e=x(process.cwd(),S,".gitignore"),n=await be(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()+`
|
|
397
378
|
`+o.join(`
|
|
398
379
|
`)+`
|
|
399
380
|
`:o.join(`
|
|
400
381
|
`)+`
|
|
401
|
-
`;await
|
|
402
|
-
`,"utf8")}async function
|
|
403
|
-
`).split(/\n/):["# Local broods CLI settings. Tokens are stored outside the repo."],i=!1;for(let[
|
|
382
|
+
`;await ge(e,r,"utf8")}async function On(){let e=x(process.cwd(),"package.json"),n=await be(e);if(!n)return;let t;try{t=JSON.parse(n)}catch{return}if(t.type)return;t.type="module",await ge(e,JSON.stringify(t,null,2)+`
|
|
383
|
+
`,"utf8")}async function Rn(e){let n=x(process.cwd(),".env.local"),t=await be(n),o=zt(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?$/,`
|
|
384
|
+
`).split(/\n/):["# Local broods CLI settings. Tokens are stored outside the repo."],i=!1;for(let[l,d]of Object.entries(r)){if(!d)continue;if(o[l]!==void 0&&!e.force)continue;let c=s.findIndex((p)=>p.trim().startsWith(`${l}=`));if(c>=0)s[c]=`${l}=${Ve(d)}`;else s.push(`${l}=${Ve(d)}`);if(process.env[l]===void 0)process.env[l]=d;i=!0}if(!i&&t)return;let a=`${s.filter((l,d,c)=>!(l===""&&d===c.length-1)).join(`
|
|
404
385
|
`)}
|
|
405
|
-
`;await
|
|
406
|
-
`).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}=${
|
|
386
|
+
`;await W(n,a),await Ht()}async function ke(e,n){let t=x(process.cwd(),".env.local"),o=await be(t),r=o?o.replace(/\n?$/,`
|
|
387
|
+
`).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}=${Ve(n)}`;else r.push(`${e}=${Ve(n)}`);process.env[e]=n;let i=`${r.filter((a,l,d)=>!(a===""&&l===d.length-1)).join(`
|
|
407
388
|
`)}
|
|
408
|
-
`;await
|
|
389
|
+
`;await W(t,i),await Ht()}async function be(e){try{return await jt(e,"utf8")}catch(n){if(n.code==="ENOENT")return"";throw n}}function zt(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 Ve(e){return JSON.stringify(e)}function Se(e){return ts(x(e)).replace(/^@/,"").replace(/\//g,"-").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"broods-app"}async function xt(){let e=x(process.cwd(),S),n=[];await Cn(e,n);let t=Pt("sha256");for(let o of n.sort())t.update(os(e,o)),t.update("\x00"),t.update(await jt(o)),t.update("\x00");return t.digest("hex")}async function Cn(e,n){let t=await es(e,{withFileTypes:!0});for(let o of t){let r=Pe(e,o.name);if(o.isDirectory()){if(o.name===_||o.name==="generated"||o.name===".cache")continue;await Cn(r,n);continue}if(o.isFile()&&(o.name.endsWith(".ts")||o.name.endsWith(".md")))n.push(r)}}function si(e){return e.split(/[\\/]/).some((n)=>n===_||n==="generated"||n===".cache")}function Yt(){return`import { defineAgent, defineSandbox, env } from "broods";
|
|
409
390
|
|
|
410
391
|
// A Lambda sandbox: a fresh, ephemeral bash environment created per run.
|
|
411
392
|
export const lambdaSandbox = defineSandbox({
|
|
@@ -434,4 +415,4 @@ export const myAgent = defineAgent({
|
|
|
434
415
|
// only reachable via internal endpoints or channel webhooks.
|
|
435
416
|
publicAccess: true,
|
|
436
417
|
});
|
|
437
|
-
`}function
|
|
418
|
+
`}function ii(e,n){if(e==="status")throw Error("status was renamed to whoami. Run `broods whoami`.");if(n.includes("--env"))throw Error("--env was renamed to --stage. Pass --stage <name> instead.");f();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 ai(){let e=f(),[{createBroodsMcpServer:n},{serveStdio:t},o]=await Promise.all([import("../chunk-np588ty2.js"),import("../chunk-5c27kpbz.js"),z()]),r=o?new T({baseUrl:o.baseUrl,token:o.token}):null,s=n({allowDestructive:process.env.BROODS_MCP_ALLOW_DESTRUCTIVE==="1"&&A("BROODS_MCP_ALLOW_DESTRUCTIVE"),cli:r,scope:{project:e.project,stage:e.stage}});t(()=>s),await new Promise((i)=>{process.stdin.on("close",i)})}fs().catch((e)=>{lt(e instanceof Error?e.message:String(e)),process.exit(1)});export{se,he,q};
|