broods 0.49.1 → 0.49.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account.d.ts +6 -0
- package/dist/chunk-0057x2fk.js +1 -0
- package/dist/chunk-17zpcz3t.js +4 -0
- package/dist/{chunk-vjg21a4e.js → chunk-6kgtx9kv.js} +4 -4
- package/dist/{chunk-z4cbw6v7.js → chunk-ctt7r720.js} +1 -1
- package/dist/chunk-kx38nst5.js +15 -0
- package/dist/{chunk-bbgvyp29.js → chunk-m96g7766.js} +1 -1
- package/dist/cli/index.js +57 -57
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1 -1
- package/package.json +7 -7
- package/dist/chunk-k0w9vdnm.js +0 -4
- package/dist/chunk-kjccsy1h.js +0 -1
- package/dist/chunk-r86n05ec.js +0 -15
- /package/dist/{chunk-m7ws7kqc.js → chunk-5esx8msr.js} +0 -0
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{G,y,_,O,z,W,K,v,f,L,h,M,T,
|
|
2
|
+
import{G,y,_,O,z,W,K,v,f,L,h,M,T,B,Y,E,ie,w,g}from"../chunk-6kgtx9kv.js";import{m,R}from"../chunk-bb3jfhv3.js";import{chmod as Ns,lstat as Ls,mkdir as Ln,readFile as Jt,readdir as Ms,stat as Bs,writeFile as ye}from"node:fs/promises";import{createHash as qt}from"node:crypto";import Gs from"node:module";import{basename as Ws,join as Le,relative as Fs,resolve as P,sep as Ks}from"node:path";import{watch as Hs}from"node:fs";import{spawn as Zt}from"node:child_process";import{tmpdir as Vs}from"node:os";import{performance as Kt}from"node:perf_hooks";import{stripVTControlCharacters as Ys}from"node:util";import{fileURLToPath as Eo,pathToFileURL as lt}from"node:url";import{createHash as So}from"node:crypto";import{existsSync as $o,readFileSync as Co}from"node:fs";import{mkdtemp as Ro,readdir as dt,readFile as Oo,rm as Ao,writeFile as xo}from"node:fs/promises";import Qn from"node:module";import{tmpdir as Po}from"node:os";import{basename as To,isAbsolute as jo,join as Ge,relative as ke,resolve as We}from"node:path";import{build as Io,transformSync as ut}from"esbuild";var Yn=/\$\{([A-Z][A-Z0-9_]*)\}/;var zn={alibaba:{label:"Alibaba Qwen",modelPlaceholder:"qwen3-max"},anthropic:{label:"Anthropic",modelPlaceholder:"claude-sonnet-4-5-20250929"},azure:{label:"Azure OpenAI",modelPlaceholder:"gpt-4.1-mini"},baseten:{label:"Baseten",modelPlaceholder:"deepseek-ai/DeepSeek-V3"},bedrock:{label:"Amazon Bedrock",modelPlaceholder:"anthropic.claude-sonnet-4-5-20250929-v1:0"},cerebras:{label:"Cerebras",modelPlaceholder:"llama3.1-8b"},chatgpt:{label:"ChatGPT plan",modelPlaceholder:"gpt-5.5"},cloudflare:{label:"Cloudflare",modelPlaceholder:"@cf/meta/llama-3.3-70b-instruct-fp8-fast"},cohere:{label:"Cohere",modelPlaceholder:"command-a-03-2025"},custom:{label:"Custom OpenAI-compatible",modelPlaceholder:"gpt-oss-120b"},deepinfra:{label:"DeepInfra",modelPlaceholder:"deepseek-ai/DeepSeek-V3"},deepseek:{label:"DeepSeek",modelPlaceholder:"deepseek-chat"},fireworks:{label:"Fireworks",modelPlaceholder:"accounts/fireworks/models/deepseek-v3"},google:{label:"Google",modelPlaceholder:"gemini-2.5-flash"},groq:{label:"Groq",modelPlaceholder:"llama-3.3-70b-versatile"},huggingface:{label:"Hugging Face",modelPlaceholder:"meta-llama/Llama-3.3-70B-Instruct"},llmgateway:{label:"LLM Gateway",modelPlaceholder:"openai/gpt-4.1-mini"},minimax:{label:"MiniMax",modelPlaceholder:"MiniMax-M2.7"},mistral:{label:"Mistral",modelPlaceholder:"mistral-large-latest"},moonshotai:{label:"Moonshot AI Kimi",modelPlaceholder:"kimi-k2.6"},ollama:{label:"Ollama",modelPlaceholder:"gpt-oss:120b"},openai:{label:"OpenAI",modelPlaceholder:"gpt-4.1-mini"},openrouter:{label:"OpenRouter",modelPlaceholder:"anthropic/claude-sonnet-4.5"},perplexity:{label:"Perplexity",modelPlaceholder:"low"},togetherai:{label:"Together.ai",modelPlaceholder:"deepseek-ai/DeepSeek-V3"},v0:{label:"Vercel v0",modelPlaceholder:"v0-1.0-md"},vercel:{label:"Vercel AI Gateway",modelPlaceholder:"openai/gpt-4.1-mini"},vertex:{label:"Google Vertex AI",modelPlaceholder:"gemini-2.5-flash"},xai:{label:"xAI Grok",modelPlaceholder:"grok-4"},zai:{label:"Z.ai GLM",modelPlaceholder:"glm-4.7"}},Jn=Object.keys(zn);function qn(e){return Object.hasOwn(zn,e)}var wo=/(?:^|[\n;])\s*import\s+(?:[^;"'`]*?\s+from\s*)?["'](?!\.{1,2}\/|\/|node:)[^"']+["']|import\s*\(\s*["'](?!\.{1,2}\/|\/|node:)[^"']+["']\s*\)/,bo=/(?:import\s+(?:[^;"'`]*?\s+from\s*)?["']node:|import\s*\(\s*["']node:)/,yo=/(?<![.\w$])(?:process|Buffer)\s*(?:\?\.|\.|\[)/,vo=[/\b(?:__)?require\s*\(/,/(?<![.\w$])setImmediate\s*\(/,bo,yo,/\b__dirname\b/,wo],ko=/(?<![.\w$])eval\s*\(|\bnew\s+Function\s*\(/;function Zn(e){return![...vo,ko].some((n)=>n.test(e))}var cn=32;var ln=["conversation","agent"];function Xn(e){return ln.some((n)=>n===e)}var Oe="*",_o=new RegExp(Yn.source,"g"),Do=`const passthrough = (input) => input;
|
|
3
3
|
export const defineAgent = passthrough;
|
|
4
4
|
export const defineBroods = passthrough;
|
|
5
5
|
export const defineCron = passthrough;
|
|
@@ -39,15 +39,15 @@ export const defineZaloChannel = passthrough;
|
|
|
39
39
|
export const defineZaloConnection = passthrough;
|
|
40
40
|
export const env = (name) => ({ __beeblastEnv: true, name });
|
|
41
41
|
export default {};
|
|
42
|
-
`,Fe=1e7,Qn=50000000,gn=1e7,et=20000000,nt=200,Do=new Set(["node_modules",".git"]),Uo=[/^\.env(?:\.|$)/i,/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/i,/\.(?:pem|key|p12|pfx)$/i],ln={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 le(e={}){let n=e.cwd??process.cwd();h(n);let t=We(n,y);if(!So(t))throw Error(`No ${y}/ folder in ${n}. Run \`broods dev\` to scaffold one.`);let o=await Lo(t),r=await Mo(o),s=await Go(r,n,e.project),i=r.filter((k)=>g(k.value)).map((k)=>({exportName:k.exportName,file:k.file,resource:k.value})),a=i.map((k)=>k.resource);rt(a),Xo(a);let c=er(i,r),d=tr(a);for(let k of a)Fo(k);for(let k of a)Ko(k);for(let k of a)Ho(k);Vo(a),zo(a),nr(i,d);let l=Qo(i),p=No(s,e.stage??(e.useRuntimeStage===!1?void 0:v()),e.command??"dev"),u=(await Promise.all(i.map((k)=>or(k,t,d)))).flat().sort((k,A)=>`${k.kind}:${k.name}`.localeCompare(`${A.kind}:${A.name}`)),S=new Map(u.filter((k)=>k.kind==="mcp").map((k)=>[k.name,k.config])),C=u.map((k)=>Er(k,S));return rt(C),{config:s,resources:a,resourceAliases:l,channels:c,manifest:{version:1,project:s.project,stage:p,resources:C}}}function ut(e){let n=new Set;for(let t of e.resources){Ae(t.config,n,t.kind==="workspace");let o=t.config;if(t.kind==="agent")Ae(o.mcp,n,!0);if(t.kind==="mcp")Ae(o.headers,n,!0)}return[...n].sort()}function Ae(e,n,t){if(t&&typeof e==="string"){for(let o of e.matchAll(Io))n.add(o[1]);return}if(Array.isArray(e)){for(let o of e)Ae(o,n,t);return}if(e&&typeof e==="object"){let o=e;if(o.__beeblastEnv===!0&&typeof o.name==="string"){n.add(o.name);return}for(let r of Object.values(o))Ae(r,n,t)}}function No(e,n,t){if(n)return n;let o=e.stages?.[t];if(o)return o;return t==="deploy"?"production":"development"}async function Lo(e){let n=[];async function t(o){let r=await lt(o,{withFileTypes:!0});for(let s of r){let i=Ge(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)=>ke(e,o).localeCompare(ke(e,r)))}async function Mo(e){Bo();let n=[];for(let t of e){let r=await import(`${ct(t).href}?t=${Date.now()}`);n.push(...Object.entries(r).map(([s,i])=>({exportName:s,file:t,value:i})))}return n}var tt=!1;function Bo(){if(tt)return;if(tt=!0,typeof Xn.registerHooks!=="function")return;Xn.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=ko(o);return{format:"module",shortCircuit:!0,source:dt($o(r,"utf8"),{loader:"ts",format:"esm",sourcefile:r,sourcemap:"inline"}).code}}})}async function Go(e,n,t){let r=e.find((i)=>ie(i.value))?.value?.config??{},s=t??process.env.BROODS_PROJECT??r.project??Pr(Po(We(n)));if(!s.trim())throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT.");return{...r,project:s}}var ot=new Set(["agent","harness","model","provider","session","hooks","connections","tools","mcp","denyTools","sandboxes","workspaces","subagent","skills","scheduler","browser","policies","publicAccess","allowRunOverrides"]),Wo={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(ot.has(t))continue;if(t==="sandbox")throw Error(`Agent "${e.name}" config.sandbox was removed; use sandboxes, the first is the default`);let o=Wo[t],r=o?` Did you mean "${o}"?`:` Allowed keys: ${[...ot].sort().join(", ")}.`;throw Error(`Agent "${e.name}" has an unknown config key "${t}".${r}`)}}function Ko(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 Ho(e){if(e.kind!=="workspace")return;let n=e.config;if(n.partitioned!==void 0&&!Zn(n.partitioned))throw Error(`Workspace "${e.name}" config.partitioned must be one of: ${cn.join(", ")}`);if(n.isolation!==void 0)throw Error(`Workspace "${e.name}" config.isolation is no longer supported; use partitioned.`)}function Vo(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 p=l.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(l.partition)gt(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)=>Yo(l,n)).filter((l)=>Boolean(l)):[]).filter((l)=>l.config.partitioned==="conversation"),d=s.filter((l)=>l.partition);if(d.length>0&&c.length===0){let l=d[0];throw Error(`Agent "${t.name}" connection "${l.type}" defines partition, but no attached workspace has partitioned: "conversation".`)}if(c.length>0){for(let l of s)if(!l.partition)throw Error(`Agent "${t.name}" attaches partitioned workspace "${c[0].name}", but connection "${l.type}" does not define partition.`)}}}function gt(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 Yo(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 zo(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=pt(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=qo(i),c=Jo(i,r,n);if(!c||Zo(c))continue;throw Error(`Agent "${t.name}" workspace "${a}" uses sandbox "${c.name}" (${ft(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 pt(e,n){if(g(e)&&e.kind==="sandbox")return e;if(typeof e==="string")return n.get(e);return}function Jo(e,n,t){if(e&&typeof e==="object"&&"sandbox"in e){let o=e.sandbox;if(o===null)return;return pt(o,t)}return n}function qo(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 Zo(e){let n=ft(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 ft(e){return typeof e.config.provider==="string"?e.config.provider:"lambda"}function Xo(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 rt(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 Qo(e){let n={},t=new Set;for(let{exportName:o,resource:r}of e){if(o==="default"||!dn(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 er(e,n){let t=new Map;for(let i of n){if(!w(i.value)||i.exportName==="default"||!dn(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 p=o.get(l);if(p&&p!==a.name)throw Error(`Channel ${l.type} is already attached to agent "${p}" and cannot also attach to "${a.name}"`);if(d.has(l.type))throw Error(`Agent "${a.name}" cannot configure more than one ${l.type} channel`);o.set(l,a.name),d.add(l.type);let u=i!=="default"&&dn(i)?i:a.name,S=t.get(l)??`${u}${ht(l.type)}Channel`;if(r.has(S))throw Error(`Duplicate channel export alias: ${S}`);r.add(S),s.push({alias:S,type:l.type,id:S,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 nr(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(mt(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 mt(e,n){let t=e.config.allowedChannelIds??[];if(t.includes(Oe))return[Oe];return[...new Set([...n.get(e)??[],...t])]}function tr(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=wt(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 ht(e){return e.charAt(0).toUpperCase()+e.slice(1)}function dn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}async function or(e,n,t){let o=e.resource;if(o.kind==="agent"){let r=gr(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=wt(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:Cr(o.name,{...r,externalId:i})}))}return[{kind:o.kind,name:o.name,...o.description?{description:o.description}:{},config:await rr(e,n)}]}function wt(e,n){if(n===void 0)return[];if(typeof n==="string")return st(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`);st(e,o),t.add(o)}return n}function st(e,n){if(n!==Oe)return;throw Error(`Channel "${e}" cannot use "${Oe}" as its id: a record matches one exact room. To answer everywhere, set allowedChannelIds: ["${Oe}"] on the connection; undeclared rooms already fall back to its agent.`)}async function rr(e,n){let t=e.resource;if(t.kind==="skill")return await br(t.config,n);if(t.kind==="workspace"){let o={...t.config},r=o.partitioned;if(delete o.partitioned,r!==void 0)o.isolation=r;return Q(o)}if(t.kind==="mcp")return await yr(e,t.config,n);if(t.kind==="policy"){let o={...t.config};return o.version=o.version??1,Q(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,o.status===void 0)o.status="active";if(delete o.agent,typeof o.input==="string")o.events=[{role:"user",content:[{type:"text",text:o.input}]}],delete o.input;return Q(o)}return Q(t.config)}var sr=new Set(["apiKey","base_url","baseURL","gatewayId"]),ir=new Set(["activeTools","debug","inactiveTools","permissionMode","startupTimeoutMs","type","webSearch"]),ar=new Set(["enabled","level","subsystems"]);function cr(e){if(sr.has(e))return"";let n=e.replace(/[^a-z0-9]/gi,"").toLowerCase();if(n==="baseurl")return'"base_url" or "baseURL"';if(n==="apikey")return'"apiKey"';if(n==="gatewayid")return'"gatewayId"';return""}function lr(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(!Jn(t))throw Error(`Agent "${e}" config.provider.${t} is not a supported provider (expected one of: ${zn.join(", ")})`);if(typeof o!=="object"||o===null||Array.isArray(o))throw Error(`Agent "${e}" config.provider.${t} must be an object`);let r=o;for(let s of Object.keys(r)){let i=cr(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 dr(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(!ir.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(un(e,t.activeTools,"activeTools"),un(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`);ur(e,t.debug)}function ur(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(!ar.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`);un(e,t.subsystems,"debug.subsystems")}function un(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 gr(e,n,t){let o={...e.config};lr(e.name,o.provider),dr(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=pr(e.name,o.hooks);if(s)o.hooks=s.agentHooksConfig;else if(o.hooks!==void 0)o.hooks=bt(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}${ht(i.type)}Channel`,c=mt(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)=>Sr(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=hr(o.policies,e.name);if(i)o.policies=i;else delete o.policies}return{config:Q(o),...s?.hookResource?{hookResource:s.hookResource}:{}}}function pr(e,n){if(n===void 0)return;if(!n||typeof n!=="object"||Array.isArray(n))throw Error(`Agent "${e}" config.hooks must be an object`);let t=n,o=Object.keys(ln).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:ln[d],source:fr(l.toString())}]});if(o.length===0)return;let r=`${e}-hooks`,s=mr(e,o),i=Buffer.byteLength(s);if(i>Fe)throw Error(`Agent "${e}" hook bundle is too large (${i} bytes, max ${Fe})`);let a=o.map((d)=>d.event),c=bt(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:xe(s)}}}}function bt(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 ln)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 fr(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 mr(e,n){let t=`export default {
|
|
42
|
+
`,Fe=1e7,et=50000000,pn=1e7,nt=20000000,tt=200,Uo=new Set(["node_modules",".git"]),No=[/^\.env(?:\.|$)/i,/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/i,/\.(?:pem|key|p12|pfx)$/i],dn={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 le(e={}){let n=e.cwd??process.cwd();h(n);let t=We(n,y);if(!$o(t))throw Error(`No ${y}/ folder in ${n}. Run \`broods dev\` to scaffold one.`);let o=await Mo(t),r=await Bo(o),s=await Wo(r,n,e.project),i=r.filter((k)=>g(k.value)).map((k)=>({exportName:k.exportName,file:k.file,resource:k.value})),a=i.map((k)=>k.resource);st(a),Qo(a);let c=nr(i,r),d=or(a);for(let k of a)Ko(k);for(let k of a)Ho(k);for(let k of a)Vo(k);Yo(a),Jo(a),tr(i,d);let l=er(i),p=Lo(s,e.stage??(e.useRuntimeStage===!1?void 0:v()),e.command??"dev"),u=(await Promise.all(i.map((k)=>rr(k,t,d)))).flat().sort((k,A)=>`${k.kind}:${k.name}`.localeCompare(`${A.kind}:${A.name}`)),S=new Map(u.filter((k)=>k.kind==="mcp").map((k)=>[k.name,k.config])),C=u.map((k)=>$r(k,S));return st(C),{config:s,resources:a,resourceAliases:l,channels:c,manifest:{version:1,project:s.project,stage:p,resources:C}}}function gt(e){let n=new Set;for(let t of e.resources){Ae(t.config,n,t.kind==="workspace");let o=t.config;if(t.kind==="agent")Ae(o.mcp,n,!0);if(t.kind==="mcp")Ae(o.headers,n,!0)}return[...n].sort()}function Ae(e,n,t){if(t&&typeof e==="string"){for(let o of e.matchAll(_o))n.add(o[1]);return}if(Array.isArray(e)){for(let o of e)Ae(o,n,t);return}if(e&&typeof e==="object"){let o=e;if(o.__beeblastEnv===!0&&typeof o.name==="string"){n.add(o.name);return}for(let r of Object.values(o))Ae(r,n,t)}}function Lo(e,n,t){if(n)return n;let o=e.stages?.[t];if(o)return o;return t==="deploy"?"production":"development"}async function Mo(e){let n=[];async function t(o){let r=await dt(o,{withFileTypes:!0});for(let s of r){let i=Ge(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)=>ke(e,o).localeCompare(ke(e,r)))}async function Bo(e){Go();let n=[];for(let t of e){let r=await import(`${lt(t).href}?t=${Date.now()}`);n.push(...Object.entries(r).map(([s,i])=>({exportName:s,file:t,value:i})))}return n}var ot=!1;function Go(){if(ot)return;if(ot=!0,typeof Qn.registerHooks!=="function")return;Qn.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=Eo(o);return{format:"module",shortCircuit:!0,source:ut(Co(r,"utf8"),{loader:"ts",format:"esm",sourcefile:r,sourcemap:"inline"}).code}}})}async function Wo(e,n,t){let r=e.find((i)=>ie(i.value))?.value?.config??{},s=t??process.env.BROODS_PROJECT??r.project??jr(To(We(n)));if(!s.trim())throw Error("Project name is required. Pass --project <name> or set BROODS_PROJECT.");return{...r,project:s}}var rt=new Set(["agent","harness","model","provider","session","hooks","connections","tools","mcp","denyTools","sandboxes","workspaces","subagent","skills","scheduler","browser","policies","publicAccess","allowRunOverrides"]),Fo={workspace:"workspaces",skill:"skills",policy:"policies",tool:"tools",mcpServers:"mcp",channel:"connections",channels:"connections",hook:"hooks",subagents:"subagent",systemPrompt:"agent",system:"agent"};function Ko(e){if(e.kind!=="agent")return;let n=e.config;for(let t of Object.keys(n)){if(rt.has(t))continue;if(t==="sandbox")throw Error(`Agent "${e.name}" config.sandbox was removed; use sandboxes, the first is the default`);let o=Fo[t],r=o?` Did you mean "${o}"?`:` Allowed keys: ${[...rt].sort().join(", ")}.`;throw Error(`Agent "${e.name}" has an unknown config key "${t}".${r}`)}}function Ho(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 Vo(e){if(e.kind!=="workspace")return;let n=e.config;if(n.partitioned!==void 0&&!Xn(n.partitioned))throw Error(`Workspace "${e.name}" config.partitioned must be one of: ${ln.join(", ")}`);if(n.isolation!==void 0)throw Error(`Workspace "${e.name}" config.isolation is no longer supported; use partitioned.`)}function Yo(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 p=l.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(l.partition)pt(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)=>zo(l,n)).filter((l)=>Boolean(l)):[]).filter((l)=>l.config.partitioned==="conversation"),d=s.filter((l)=>l.partition);if(d.length>0&&c.length===0){let l=d[0];throw Error(`Agent "${t.name}" connection "${l.type}" defines partition, but no attached workspace has partitioned: "conversation".`)}if(c.length>0){for(let l of s)if(!l.partition)throw Error(`Agent "${t.name}" attaches partitioned workspace "${c[0].name}", but connection "${l.type}" does not define partition.`)}}}function pt(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 zo(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 Jo(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=ft(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=Zo(i),c=qo(i,r,n);if(!c||Xo(c))continue;throw Error(`Agent "${t.name}" workspace "${a}" uses sandbox "${c.name}" (${mt(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 ft(e,n){if(g(e)&&e.kind==="sandbox")return e;if(typeof e==="string")return n.get(e);return}function qo(e,n,t){if(e&&typeof e==="object"&&"sandbox"in e){let o=e.sandbox;if(o===null)return;return ft(o,t)}return n}function Zo(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 Xo(e){let n=mt(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 mt(e){return typeof e.config.provider==="string"?e.config.provider:"lambda"}function Qo(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 st(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 er(e){let n={},t=new Set;for(let{exportName:o,resource:r}of e){if(o==="default"||!un(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 nr(e,n){let t=new Map;for(let i of n){if(!w(i.value)||i.exportName==="default"||!un(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 p=o.get(l);if(p&&p!==a.name)throw Error(`Channel ${l.type} is already attached to agent "${p}" and cannot also attach to "${a.name}"`);if(d.has(l.type))throw Error(`Agent "${a.name}" cannot configure more than one ${l.type} channel`);o.set(l,a.name),d.add(l.type);let u=i!=="default"&&un(i)?i:a.name,S=t.get(l)??`${u}${wt(l.type)}Channel`;if(r.has(S))throw Error(`Duplicate channel export alias: ${S}`);r.add(S),s.push({alias:S,type:l.type,id:S,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 tr(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(ht(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 ht(e,n){let t=e.config.allowedChannelIds??[];if(t.includes(Oe))return[Oe];return[...new Set([...n.get(e)??[],...t])]}function or(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=bt(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 wt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function un(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}async function rr(e,n,t){let o=e.resource;if(o.kind==="agent"){let r=fr(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=bt(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:Or(o.name,{...r,externalId:i})}))}return[{kind:o.kind,name:o.name,...o.description?{description:o.description}:{},config:await sr(e,n)}]}function bt(e,n){if(n===void 0)return[];if(typeof n==="string")return it(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`);it(e,o),t.add(o)}return n}function it(e,n){if(n!==Oe)return;throw Error(`Channel "${e}" cannot use "${Oe}" as its id: a record matches one exact room. To answer everywhere, set allowedChannelIds: ["${Oe}"] on the connection; undeclared rooms already fall back to its agent.`)}async function sr(e,n){let t=e.resource;if(t.kind==="skill")return await vr(t.config,n);if(t.kind==="workspace"){let o={...t.config},r=o.partitioned;if(delete o.partitioned,r!==void 0)o.isolation=r;return Q(o)}if(t.kind==="mcp")return await kr(e,t.config,n);if(t.kind==="policy"){let o={...t.config};return o.version=o.version??1,Q(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,o.status===void 0)o.status="active";if(delete o.agent,typeof o.input==="string")o.events=[{role:"user",content:[{type:"text",text:o.input}]}],delete o.input;return Q(o)}return Q(t.config)}var ir=new Set(["apiKey","base_url","baseURL","gatewayId"]),ar=new Set(["activeTools","debug","inactiveTools","permissionMode","startupTimeoutMs","type","webSearch"]),cr=new Set(["enabled","level","subsystems"]);function lr(e){if(ir.has(e))return"";let n=e.replace(/[^a-z0-9]/gi,"").toLowerCase();if(n==="baseurl")return'"base_url" or "baseURL"';if(n==="apikey")return'"apiKey"';if(n==="gatewayid")return'"gatewayId"';return""}function dr(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(!qn(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=lr(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 ur(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(!ar.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(gn(e,t.activeTools,"activeTools"),gn(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`);gr(e,t.debug)}function gr(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(!cr.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`);gn(e,t.subsystems,"debug.subsystems")}function gn(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 pr(e){if(new Set(e.config.skills?.allowed?.map((t)=>g(t)?t.name:t)).size<=cn)return;throw Error(`Agent "${e.name}" config.skills.allowed must list at most ${cn} skills`)}function fr(e,n,t){let o={...e.config};dr(e.name,o.provider),ur(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`)}),pr(e);let s=mr(e.name,o.hooks);if(s)o.hooks=s.agentHooksConfig;else if(o.hooks!==void 0)o.hooks=yt(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}${wt(i.type)}Channel`,c=ht(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)=>Cr(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=br(o.policies,e.name);if(i)o.policies=i;else delete o.policies}return{config:Q(o),...s?.hookResource?{hookResource:s.hookResource}:{}}}function mr(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(dn).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:dn[d],source:hr(l.toString())}]});if(o.length===0)return;let r=`${e}-hooks`,s=wr(e,o),i=Buffer.byteLength(s);if(i>Fe)throw Error(`Agent "${e}" hook bundle is too large (${i} bytes, max ${Fe})`);let a=o.map((d)=>d.event),c=yt(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:xe(s)}}}}function yt(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 dn)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 hr(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 wr(e,n){let t=`export default {
|
|
43
43
|
${n.map((o)=>` ${JSON.stringify(o.event)}: ${o.source},`).join(`
|
|
44
44
|
`)}
|
|
45
45
|
};
|
|
46
|
-
`;try{return
|
|
46
|
+
`;try{return ut(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 br(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 at(e,n){let t=await Ro(Ge(Po(),"broods-mcp-"));try{let o=Ge(t,"server.mjs");await xo(o,n,"utf8");let r;try{r=await import(lt(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 Ao(t,{recursive:!0,force:!0})}}async function yr(e){let n=await Io({stdin:e.stdin,absWorkingDir:e.stdin.resolveDir,bundle:!0,...e.workers?{platform:"browser",conditions:["workerd","worker","browser"]}:{platform:"node"},format:"esm",minify:!1,write:!1,logLevel:"silent",plugins:e.plugins??[]}).catch((t)=>{let o=Pr(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 vr(e,n){let t=Rr(n,e.path,"Skill"),o=ke(n,t).split("\\").join("/"),r=await Ar(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 kr(e,n,t){let{handler:o,...r}=n,s=[o,n.url,n.sandbox].filter((p)=>p!==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 Q(r)}let i=ke(t,e.file).split("\\").join("/");xr(i,"MCP server");let a=(p)=>yr({stdin:{contents:Er(e),resolveDir:t,sourcefile:"mcp-handler.mjs",loader:"js"},label:"MCP server bundle",manifestPath:i,plugins:[Sr()],workers:p}),c=n.runtime==="lambda"?void 0:await a(!0).catch(()=>{return}),d=c!==void 0&&Buffer.byteLength(c)<=pn&&Zn(c)&&await at(i,c).then(()=>!0,()=>!1)?c:await a(!1),l=Buffer.byteLength(d);if(l>et)throw Error(`MCP server bundle ${i} is too large (${l} bytes, max ${et})`);return await at(i,d),{...Q(r),bundle:d,sha256:xe(d)}}function Er(e){return`import * as __exports from ${JSON.stringify(e.file)};
|
|
47
47
|
const __mcp = __exports[${JSON.stringify(e.exportName)}];
|
|
48
48
|
export default __mcp?.config?.handler ?? __mcp?.handler;
|
|
49
|
-
`}function
|
|
50
|
-
`),c=o?r.map((d)=>{let l=encodeURIComponent(o.accountId),p=o.stageKind===void 0||o.stageKind==="production"?`/v1/webhooks/${l}/${encodeURIComponent(d.type)}`:`/v1/webhooks/${l}/dev/${encodeURIComponent(o.endpointId)}/${encodeURIComponent(d.type)}`;return` ${
|
|
49
|
+
`}function Sr(){return{name:"broods-sdk-stub",setup:function(e){e.onResolve({filter:/^broods(\/.*)?$/},()=>({path:"broods",namespace:"broods-stub"})),e.onLoad({filter:/.*/,namespace:"broods-stub"},()=>({contents:Do,loader:"js"}))}}}function $r(e,n){if(e.kind!=="agent")return e;let t=e.config.mcp;if(!t)return e;let o=Object.entries(t).map(([r,s])=>{let i=n.get(r),a=new Set(Object.keys(s.headers??{}).map((p)=>p.toLowerCase())),c=Object.entries(i?.headers??{}).filter(([p])=>!a.has(p.toLowerCase())),{tokenUrl:d,...l}=i?.oauth??{};return[r,{...s,...c.length>0?{headers:{...Object.fromEntries(c),...s.headers}}:{},...i?.oauth?{oauth:{...l,...s.oauth}}:{}}]});return{...e,config:{...e.config,mcp:Object.fromEntries(o)}}}function Cr(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 Rr(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=We(e),r=We(o,n),s=ke(o,r);if(s===""||!s.startsWith("..")&&!jo(s))return r;throw Error(`${t} path ${n} must stay inside ${y}/`)}function Or(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,pt(t.partition,`Channel "${e}"`),Q(t)}function Q(e){if(Array.isArray(e))return e.map((n)=>Q(n));if(g(e))return e.name;if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).map(([n,t])=>[n,Q(t)]));return e}async function Ar(e){let n=[],t=0;async function o(r){let s=await dt(r,{withFileTypes:!0});for(let i of s){let a=Ge(r,i.name),c=ke(e,a).split("\\").join("/");if(i.isDirectory()){if(ct(i.name))continue;await o(a)}else if(i.isFile()){if(ct(i.name)||vt(c))continue;let d=await Oo(a);if(d.byteLength>Fe)throw Error(`Skill bundle file ${c} is too large (${d.byteLength} bytes, max ${Fe})`);if(t+=d.byteLength,t>nt)throw Error(`Skill bundle at ${e} is too large (${t} bytes, max ${nt})`);if(n.length>=tt)throw Error(`Skill bundle at ${e} has too many files (max ${tt})`);n.push({path:c,size:d.byteLength,sha256:xe(d),contentBase64:d.toString("base64"),contentType:Tr(c)})}}}return await o(e),n.sort((r,s)=>String(r.path).localeCompare(String(s.path)))}function ct(e){return e.startsWith(".")||Uo.has(e)}function xr(e,n){if(vt(e))throw Error(`${n} bundle path ${e} looks like a hidden file or secret and will not be bundled`)}function Pr(e){return e instanceof Error&&Array.isArray(e.errors)}function vt(e){return e.split("/").some((t)=>t.startsWith(".")||No.some((o)=>o.test(t)))}function xe(e){return So("sha256").update(e).digest("hex")}function Tr(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 jr(e){return e.replace(/^@/,"").replace(/\//g,"-").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}import{mkdir as Ir,writeFile as Ke}from"node:fs/promises";import{resolve as Pe}from"node:path";async function He(e,n,t=process.cwd(),o={},r=null,s=[]){let i=Pe(t,y,_),a=_r(n,e);await Ir(i,{recursive:!0}),await Ke(Pe(i,"ids.ts"),Nr(a),"utf8"),await Ke(Pe(i,"api.ts"),Dr(e,a,o,r,s),"utf8"),await Ke(Pe(i,"resources.ts"),Lr(e),"utf8"),await Ke(Pe(i,"dataModel.ts"),Ur(),"utf8")}function _r(e,n){let t={agents:de(n,"agent"),workspaces:de(n,"workspace"),sandboxes:de(n,"sandbox"),crons:de(n,"cron"),skills:de(n,"skill"),mcp:de(n,"mcp"),policies:de(n,"policy"),channelRecords:de(n,"channelRecord")};return{agents:ue(e.agents,t.agents),workspaces:ue(e.workspaces,t.workspaces),sandboxes:ue(e.sandboxes,t.sandboxes),crons:ue(e.crons,t.crons),skills:ue(e.skills,t.skills),hooks:{},mcp:ue(e.mcp,t.mcp),policies:ue(e.policies,t.policies),channelRecords:ue(e.channelRecords,t.channelRecords)}}function de(e,n){return new Set(e.resources.filter((t)=>t.kind===n).map((t)=>t.name))}function ue(e,n){return Object.fromEntries(Object.entries(e??{}).filter(([t])=>n.has(t)))}function Dr(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)=>` ${fn(t.agent?.[d]??d)}: { kind: "agent", name: ${JSON.stringify(d)}, id: ids.agents[${JSON.stringify(d)}], project: ${JSON.stringify(e.project)}, stage: ${JSON.stringify(e.stage)}${i} },`).join(`
|
|
50
|
+
`),c=o?r.map((d)=>{let l=encodeURIComponent(o.accountId),p=o.stageKind===void 0||o.stageKind==="production"?`/v1/webhooks/${l}/${encodeURIComponent(d.type)}`:`/v1/webhooks/${l}/dev/${encodeURIComponent(o.endpointId)}/${encodeURIComponent(d.type)}`;return` ${fn(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(`
|
|
51
51
|
`):"";return`// Generated by broods. Do not edit by hand.
|
|
52
52
|
import type { ResourceApi } from "broods";
|
|
53
53
|
import { ids } from "./ids";
|
|
@@ -66,9 +66,9 @@ ${c}
|
|
|
66
66
|
skills: ${Te("skills",n.skills,t.skill)},
|
|
67
67
|
policies: ${Te("policies",n.policies,t.policy)},
|
|
68
68
|
} as const satisfies ResourceApi;
|
|
69
|
-
`}function
|
|
69
|
+
`}function Ur(){return`// Generated by broods. Do not edit by hand.
|
|
70
70
|
export type { AgentReference, ChannelReference, AgentRunInput, AgentRunResult, ResourceApi } from "broods";
|
|
71
|
-
`}function
|
|
71
|
+
`}function Nr(e){return`// Generated by broods. Do not edit by hand.
|
|
72
72
|
export const ids = ${JSON.stringify(e,null,2)} as const;
|
|
73
73
|
export const agents = ids.agents;
|
|
74
74
|
export const workspaces = ids.workspaces;
|
|
@@ -76,19 +76,19 @@ export const sandboxes = ids.sandboxes;
|
|
|
76
76
|
export const crons = ids.crons;
|
|
77
77
|
export const skills = ids.skills;
|
|
78
78
|
export const policies = ids.policies;
|
|
79
|
-
`}function
|
|
79
|
+
`}function Lr(e){return`// Generated by broods. Do not edit by hand.
|
|
80
80
|
export const manifest = ${JSON.stringify(e,null,2)} as const;
|
|
81
81
|
`}function Te(e,n,t){let o=Object.keys(n);if(o.length===0)return"{}";return`{
|
|
82
|
-
${o.map((s)=>` ${
|
|
82
|
+
${o.map((s)=>` ${fn(t?.[s]??s)}: ids.${e}[${JSON.stringify(s)}],`).join(`
|
|
83
83
|
`)}
|
|
84
|
-
}`}function pn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}var Nr=1,Lr=0,vt=60000,kt=15000;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 fe(){let e=globalThis.WebSocket;if(!e)throw Error("WebSocket is not available in this environment.");return e}class D extends Error{}async function*Ve(e,n={}){let t=new Set,o=500,r=0,s=Date.now();while(!n.signal?.aborted){let i=!1,a="the log stream closed";try{for await(let c of Mr(e,n,()=>{i=!0})){let d=`${c.ts}|${c.eventType}|${c.message}`;if(t.has(d))continue;if(t.add(d),t.size>5000)t.delete(t.values().next().value);yield c}}catch(c){if(n.signal?.aborted)return;if(a=c instanceof Error?c.message:String(c),c instanceof D||/unauthorized|invalid websocket token|scope does not match/i.test(a))throw c}if(n.signal?.aborted)return;if(i)o=500,r=0,s=Date.now();if(!n.keepReconnecting&&Date.now()-s>=vt)throw Error(`Gave up reconnecting to the live logs after ${vt/1000} s. Last error: ${a}`);r+=1,n.onReconnect?.(r,a),await se(o,n.signal),o=Math.min(o*2,5000)}}async function*Mr(e,n,t){let{baseUrl:o,credential:r,project:s,stage:i}=e,{backfill:a=0,minLevel:c,sandboxId:d,signal:l}=n,p=n.liveOnly??a<=0;if(l?.aborted)return;let u=Br(o,s,i),S=u,C=fe(),k=[],A=null,V=!1,re=null,pe=()=>{re?.(),re=null},ce=new C(u,E(await r())),Kn=setTimeout(()=>{A=Error(`The observability gateway did not answer within ${kt/1000} s.`),V=!0,pe()},kt),an=()=>{if(clearTimeout(Kn),ce.readyState===Nr||ce.readyState===Lr)ce.close(1000,"client closed");l?.removeEventListener("abort",Hn)},Hn=()=>{V=!0,pe(),an()};l?.addEventListener("abort",Hn,{once:!0}),ce.onopen=()=>{if(l?.aborted){an();return}let X={type:"subscribe",stream:"logs",...a>0?{backfill:a}:{},...p?{liveOnly:!0}:{},...c!==void 0?{minLevel:c}:{},...d!==void 0?{sandboxId:d}:{}};ce.send(JSON.stringify(X))},ce.onmessage=(X)=>{let me=Gr(X.data);if(!me)return;if(clearTimeout(Kn),me.type!=="error")t();switch(me.type){case"backfill":if(me.stream==="logs"){for(let mo of me.entries)k.push(mo);pe()}break;case"log":k.push(me.entry),pe();break;case"error":A=Error(`Observability gateway error: ${me.error}`),V=!0,pe();break;case"ready":break;default:break}},ce.onerror=()=>{A=Error(`Cannot connect to the observability gateway at ${S}.`),V=!0,pe()},ce.onclose=(X)=>{if(!V){if(X.code!==1000)A=Error(X.reason?`Observability WebSocket closed: ${X.reason}`:`Observability WebSocket closed with code ${X.code}.`);V=!0,pe()}};try{while(!0){if(k.length>0){yield k.shift();continue}if(A)throw A;if(V)return;await new Promise((X)=>{re=X})}}finally{an()}}function Br(e,n,t){return`${Y(e)}/v1/projects/${encodeURIComponent(n)}/stages/${encodeURIComponent(t)}/observability/ws`}function Gr(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 Wr=new Set(["bundle","bundleStorageId","contentBase64"]),Fr=new Set(["hook","mcp","skill"]),Kr=30000;class ze extends Error{}class Je extends Error{}class N{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 U(t,"Fetch manifest failed"),await t.json()}async putManifest(e,n,t=!1,o){let r=await this.externalizeLargeMcpBundles(e),s=await this.request(e.project,e.stage,"/manifest",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({manifest:r,prune:n,rotateRuntimeKey:t,...o!==void 0?{revision:o}:{}})},null);return await U(s,"Sync manifest failed"),await s.json()}async externalizeLargeMcpBundles(e){if(e.resources.every((t)=>$t(t)===null))return e;let n=await Promise.all(e.resources.map(async(t)=>{let o=$t(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:xe(o)}}}));return{...e,resources:n}}async uploadMcpBundle(e,n,t){let o=await this.request(e,n,"/mcp-bundle-uploads",{method:"POST"});await U(o,"Mint bundle upload URL failed");let{uploadUrl:r}=await o.json();if(!r)throw Error("Mint bundle upload URL failed: response omitted uploadUrl");let s=await this.send(r,{method:"POST",headers:{"Content-Type":"application/javascript"},body:t},null);await U(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 U(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 U(r,"Set environment variable failed")}async listEnv(e,n){let t=await this.request(e,n,"/env",{method:"GET"});return await U(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 U(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 U(o,"Remove environment variable failed")}async getOnboarding(){let e=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Ee(e,"/v1/account/onboarding","broods org"),await U(e,"Fetch CLI onboarding context failed"),await e.json()}async selectOnboardingOrg(e){let n=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({orgId:e})});return await U(n,"Select CLI org failed"),await n.json()}async listStages(e){let n=await this.send(`${this.baseUrl}/v1/account/stages?project=${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Ee(n,"/v1/account/stages","broods stage"),await U(n,"List stages failed"),(await n.json()).stages??[]}async createStage(e,n,t){let o=await this.send(`${this.baseUrl}/v1/account/stages`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({project:e,name:n,...t?{from:t}:{}})});return Ee(o,"/v1/account/stages","broods stage"),await U(o,"Create stage failed"),await o.json()}async mintStageSession(e,n){let t=await this.send(`${this.baseUrl}/v1/account/stage-session`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({project:e,stage:n})});Ee(t,"/v1/account/stage-session","broods logs");try{await U(t,"Open stage session failed")}catch(o){if(t.status===401||t.status===404)throw new D(o instanceof Error?o.message:String(o));throw o}return await t.json()}async listProjects(){let e=await this.send(`${this.baseUrl}/v1/account/projects`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Ee(e,"/v1/account/projects","broods project"),await U(e,"List projects failed"),(await e.json()).projects??[]}async deleteProject(e){let n=await this.send(`${this.baseUrl}/v1/account/projects?projectId=${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`}});if(Ee(n,"/v1/account/projects","broods project"),n.status===404)return null;return await U(n,"Delete project failed"),(await n.json()).deleted??null}async createOnboardingOrg(e){let n=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({createOrgName:e})});return await U(n,"Create CLI org failed"),await n.json()}async request(e,n,t,o,r){let s=`${this.baseUrl}/v1/account/projects/${encodeURIComponent(e)}/stages/${encodeURIComponent(n)}${t}`;return await this.send(s,{...o,headers:{Authorization:`Bearer ${this.token}`,...o.headers}},r)}async send(e,n,t){return await qe(e,n,{fetch:this.fetchImpl,timeoutMs:t})}}async function qe(e,n,t={}){let o=t.fetch??fetch,r=t.timeoutMs===void 0?Kr:t.timeoutMs;try{return await o(e,r===null?n:{...n,signal:AbortSignal.timeout(r)})}catch(s){throw Error(`Cannot reach ${new URL(e).origin}: ${Yr(s,r)}`,{cause:s})}}function bn(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 p=t.get(d);if(!p)s.push({key:d,resource:l});else if(Ye(mn(p))!==Ye(mn(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((p)=>!a.has(p.key)&&Hr(d.resource.kind)&&d.resource.kind===p.resource.kind&&Ye(St(d.resource))===Ye(St(p.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)=>Et(d).localeCompare(Et(l)))}function Et(e){return`${{create:0,rename:1,update:2,delete:3}[e.operation]}:${e.kind}:${e.previousName??""}:${e.name}`}function Hr(e){return e==="agent"||e==="workspace"||e==="sandbox"||e==="policy"}function fn(e){if(Array.isArray(e))return e.map(fn);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,fn(o)]))}return e}function St(e){let n=mn(e),{name:t,...o}=n;return o}function mn(e){let n=fn(e);if(!Fr.has(e.kind))return n;return{...n,config:wn(n.config)}}function hn(e){if(Array.isArray(e))return e.map(hn);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>[n,hn(t)]));return e}function Ye(e){return JSON.stringify(hn(e))}function wn(e){if(Array.isArray(e))return e.map(wn);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).flatMap(([n,t])=>{if(Wr.has(n))return[];return[[n,wn(t)]]}));return e}async function U(e,n){if(e.ok)return;let t=await e.text(),{message:o=t,code:r}=Vr(t);if(r==="manifest_conflict")throw new ze(o);let s=e.status===401?"\nRun `broods login` to sign in again.":"";throw Error(`${n}: ${e.status} ${o}${s}`)}function Vr(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 Ee(e,n,t){if(e.status!==404)return;if((e.headers.get("Content-Type")??"").includes("application/json"))return;throw new Je(`This broods server is older than your CLI and does not support \`${t}\` yet (no ${n} route).`)}function Yr(e,n){if(!(e instanceof Error))return String(e);if(e.name==="TimeoutError"&&n!==null)return`no answer within ${n/1000} s`;let t=e.cause;if(!(t instanceof Error))return e.message;if(t.message)return t.message;return"code"in t&&typeof t.code==="string"?t.code:e.message}function $t(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 Ze=["chatgpt"];var he={chatgpt:{label:"ChatGPT plan",description:"Run agents on model.provider chatgpt with your ChatGPT plan",authorizeUrl:"https://auth.openai.com/api/accounts/authorize",tokenUrl:"https://auth.openai.com/api/accounts/oauth/token",revokeUrl:"https://auth.openai.com/api/accounts/oauth/revoke",jwksUrl:"https://auth.openai.com/.well-known/jwks.json",issuer:"https://auth.openai.com",scopes:["openid","profile","email","offline_access","resource.invoke","chatgpt.tokens.use.direct"],resource:"https://api.openai.com/v1",requiredScope:"chatgpt.tokens.use.direct",selfHostedOnly:"ChatGPT plan usage is only available on self-hosted Broods for now. Use an OpenAI API key with the `openai` provider instead.",managedOptIn:"CHATGPT_PLAN_ENABLED",modelsUrl:"https://api.openai.com/v1/models",usageUrl:"https://chatgpt.com/settings/usage"}};function yn(e){return Ze.some((n)=>n===e)}import{createHash as fs,randomBytes as ms,randomUUID as Dt}from"node:crypto";import{createServer as ts}from"node:http";import{createHash as os,randomBytes as rs,randomUUID as ss}from"node:crypto";import{spawn as is}from"node:child_process";import{createInterface as Ie}from"node:readline/promises";import{stdin as ne,stdout as ee}from"node:process";import{Writable as as}from"node:stream";function Se(e,n,t={}){let o=`${n?"*":" "} ${e}`;return n?j(o,"\x1B[1m\x1B[36m",J(t)):o}function Ct(e,n={}){let t=J(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")}${Pt(e.stage,t)}`,` ${o("server")}${e.server}`]}function zr(e,n={}){let t=J(n),o=Tt(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",c=`${e.dashboardUrl}?project=${encodeURIComponent(e.project)}&stage=${encodeURIComponent(e.stage)}`,d=j(c,"\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(`
|
|
85
|
-
`)}function
|
|
84
|
+
}`}function fn(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}var Mr=1,Br=0,kt=60000,Et=15000;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 fe(){let e=globalThis.WebSocket;if(!e)throw Error("WebSocket is not available in this environment.");return e}class D extends Error{}async function*Ve(e,n={}){let t=new Set,o=500,r=0,s=Date.now();while(!n.signal?.aborted){let i=!1,a="the log stream closed";try{for await(let c of Gr(e,n,()=>{i=!0})){let d=`${c.ts}|${c.eventType}|${c.message}`;if(t.has(d))continue;if(t.add(d),t.size>5000)t.delete(t.values().next().value);yield c}}catch(c){if(n.signal?.aborted)return;if(a=c instanceof Error?c.message:String(c),c instanceof D||/unauthorized|invalid websocket token|scope does not match/i.test(a))throw c}if(n.signal?.aborted)return;if(i)o=500,r=0,s=Date.now();if(!n.keepReconnecting&&Date.now()-s>=kt)throw Error(`Gave up reconnecting to the live logs after ${kt/1000} s. Last error: ${a}`);r+=1,n.onReconnect?.(r,a),await se(o,n.signal),o=Math.min(o*2,5000)}}async function*Gr(e,n,t){let{baseUrl:o,credential:r,project:s,stage:i}=e,{backfill:a=0,minLevel:c,sandboxId:d,signal:l}=n,p=n.liveOnly??a<=0;if(l?.aborted)return;let u=Wr(o,s,i),S=u,C=fe(),k=[],A=null,V=!1,re=null,pe=()=>{re?.(),re=null},ce=new C(u,E(await r())),Hn=setTimeout(()=>{A=Error(`The observability gateway did not answer within ${Et/1000} s.`),V=!0,pe()},Et),an=()=>{if(clearTimeout(Hn),ce.readyState===Mr||ce.readyState===Br)ce.close(1000,"client closed");l?.removeEventListener("abort",Vn)},Vn=()=>{V=!0,pe(),an()};l?.addEventListener("abort",Vn,{once:!0}),ce.onopen=()=>{if(l?.aborted){an();return}let X={type:"subscribe",stream:"logs",...a>0?{backfill:a}:{},...p?{liveOnly:!0}:{},...c!==void 0?{minLevel:c}:{},...d!==void 0?{sandboxId:d}:{}};ce.send(JSON.stringify(X))},ce.onmessage=(X)=>{let me=Fr(X.data);if(!me)return;if(clearTimeout(Hn),me.type!=="error")t();switch(me.type){case"backfill":if(me.stream==="logs"){for(let ho of me.entries)k.push(ho);pe()}break;case"log":k.push(me.entry),pe();break;case"error":A=Error(`Observability gateway error: ${me.error}`),V=!0,pe();break;case"ready":break;default:break}},ce.onerror=()=>{A=Error(`Cannot connect to the observability gateway at ${S}.`),V=!0,pe()},ce.onclose=(X)=>{if(!V){if(X.code!==1000)A=Error(X.reason?`Observability WebSocket closed: ${X.reason}`:`Observability WebSocket closed with code ${X.code}.`);V=!0,pe()}};try{while(!0){if(k.length>0){yield k.shift();continue}if(A)throw A;if(V)return;await new Promise((X)=>{re=X})}}finally{an()}}function Wr(e,n,t){return`${Y(e)}/v1/projects/${encodeURIComponent(n)}/stages/${encodeURIComponent(t)}/observability/ws`}function Fr(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 Kr=new Set(["bundle","bundleStorageId","contentBase64"]),Hr=new Set(["hook","mcp","skill"]),Vr=30000;class ze extends Error{}class Je extends Error{}class N{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 U(t,"Fetch manifest failed"),await t.json()}async putManifest(e,n,t=!1,o){let r=await this.externalizeLargeMcpBundles(e),s=await this.request(e.project,e.stage,"/manifest",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({manifest:r,prune:n,rotateRuntimeKey:t,...o!==void 0?{revision:o}:{}})},null);return await U(s,"Sync manifest failed"),await s.json()}async externalizeLargeMcpBundles(e){if(e.resources.every((t)=>Ct(t)===null))return e;let n=await Promise.all(e.resources.map(async(t)=>{let o=Ct(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:xe(o)}}}));return{...e,resources:n}}async uploadMcpBundle(e,n,t){let o=await this.request(e,n,"/mcp-bundle-uploads",{method:"POST"});await U(o,"Mint bundle upload URL failed");let{uploadUrl:r}=await o.json();if(!r)throw Error("Mint bundle upload URL failed: response omitted uploadUrl");let s=await this.send(r,{method:"POST",headers:{"Content-Type":"application/javascript"},body:t},null);await U(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 U(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 U(r,"Set environment variable failed")}async listEnv(e,n){let t=await this.request(e,n,"/env",{method:"GET"});return await U(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 U(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 U(o,"Remove environment variable failed")}async getOnboarding(){let e=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Ee(e,"/v1/account/onboarding","broods org"),await U(e,"Fetch CLI onboarding context failed"),await e.json()}async selectOnboardingOrg(e){let n=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({orgId:e})});return await U(n,"Select CLI org failed"),await n.json()}async listStages(e){let n=await this.send(`${this.baseUrl}/v1/account/stages?project=${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Ee(n,"/v1/account/stages","broods stage"),await U(n,"List stages failed"),(await n.json()).stages??[]}async createStage(e,n,t){let o=await this.send(`${this.baseUrl}/v1/account/stages`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({project:e,name:n,...t?{from:t}:{}})});return Ee(o,"/v1/account/stages","broods stage"),await U(o,"Create stage failed"),await o.json()}async mintStageSession(e,n){let t=await this.send(`${this.baseUrl}/v1/account/stage-session`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({project:e,stage:n})});Ee(t,"/v1/account/stage-session","broods logs");try{await U(t,"Open stage session failed")}catch(o){if(t.status===401||t.status===404)throw new D(o instanceof Error?o.message:String(o));throw o}return await t.json()}async listProjects(){let e=await this.send(`${this.baseUrl}/v1/account/projects`,{method:"GET",headers:{Authorization:`Bearer ${this.token}`}});return Ee(e,"/v1/account/projects","broods project"),await U(e,"List projects failed"),(await e.json()).projects??[]}async deleteProject(e){let n=await this.send(`${this.baseUrl}/v1/account/projects?projectId=${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`}});if(Ee(n,"/v1/account/projects","broods project"),n.status===404)return null;return await U(n,"Delete project failed"),(await n.json()).deleted??null}async createOnboardingOrg(e){let n=await this.send(`${this.baseUrl}/v1/account/onboarding`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({createOrgName:e})});return await U(n,"Create CLI org failed"),await n.json()}async request(e,n,t,o,r){let s=`${this.baseUrl}/v1/account/projects/${encodeURIComponent(e)}/stages/${encodeURIComponent(n)}${t}`;return await this.send(s,{...o,headers:{Authorization:`Bearer ${this.token}`,...o.headers}},r)}async send(e,n,t){return await qe(e,n,{fetch:this.fetchImpl,timeoutMs:t})}}async function qe(e,n,t={}){let o=t.fetch??fetch,r=t.timeoutMs===void 0?Vr:t.timeoutMs;try{return await o(e,r===null?n:{...n,signal:AbortSignal.timeout(r)})}catch(s){throw Error(`Cannot reach ${new URL(e).origin}: ${Jr(s,r)}`,{cause:s})}}function yn(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 p=t.get(d);if(!p)s.push({key:d,resource:l});else if(Ye(hn(p))!==Ye(hn(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((p)=>!a.has(p.key)&&Yr(d.resource.kind)&&d.resource.kind===p.resource.kind&&Ye($t(d.resource))===Ye($t(p.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)=>St(d).localeCompare(St(l)))}function St(e){return`${{create:0,rename:1,update:2,delete:3}[e.operation]}:${e.kind}:${e.previousName??""}:${e.name}`}function Yr(e){return e==="agent"||e==="workspace"||e==="sandbox"||e==="policy"}function mn(e){if(Array.isArray(e))return e.map(mn);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,mn(o)]))}return e}function $t(e){let n=hn(e),{name:t,...o}=n;return o}function hn(e){let n=mn(e);if(!Hr.has(e.kind))return n;return{...n,config:bn(n.config)}}function wn(e){if(Array.isArray(e))return e.map(wn);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>[n,wn(t)]));return e}function Ye(e){return JSON.stringify(wn(e))}function bn(e){if(Array.isArray(e))return e.map(bn);if(e&&typeof e==="object")return Object.fromEntries(Object.entries(e).flatMap(([n,t])=>{if(Kr.has(n))return[];return[[n,bn(t)]]}));return e}async function U(e,n){if(e.ok)return;let t=await e.text(),{message:o=t,code:r}=zr(t);if(r==="manifest_conflict")throw new ze(o);let s=e.status===401?"\nRun `broods login` to sign in again.":"";throw Error(`${n}: ${e.status} ${o}${s}`)}function zr(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 Ee(e,n,t){if(e.status!==404)return;if((e.headers.get("Content-Type")??"").includes("application/json"))return;throw new Je(`This broods server is older than your CLI and does not support \`${t}\` yet (no ${n} route).`)}function Jr(e,n){if(!(e instanceof Error))return String(e);if(e.name==="TimeoutError"&&n!==null)return`no answer within ${n/1000} s`;let t=e.cause;if(!(t instanceof Error))return e.message;if(t.message)return t.message;return"code"in t&&typeof t.code==="string"?t.code:e.message}function Ct(e){if(e.kind!=="mcp")return null;let n=e.config?.bundle;if(typeof n!=="string")return null;return Buffer.byteLength(n)>pn?n:null}var Ze=["chatgpt"];var he={chatgpt:{label:"ChatGPT plan",description:"Run agents on model.provider chatgpt with your ChatGPT plan",authorizeUrl:"https://auth.openai.com/api/accounts/authorize",tokenUrl:"https://auth.openai.com/api/accounts/oauth/token",revokeUrl:"https://auth.openai.com/api/accounts/oauth/revoke",jwksUrl:"https://auth.openai.com/.well-known/jwks.json",issuer:"https://auth.openai.com",scopes:["openid","profile","email","offline_access","resource.invoke","chatgpt.tokens.use.direct"],resource:"https://api.openai.com/v1",requiredScope:"chatgpt.tokens.use.direct",selfHostedOnly:"ChatGPT plan usage is only available on self-hosted Broods for now. Use an OpenAI API key with the `openai` provider instead.",managedOptIn:"CHATGPT_PLAN_ENABLED",modelsUrl:"https://api.openai.com/v1/models",usageUrl:"https://chatgpt.com/settings/usage"}};function vn(e){return Ze.some((n)=>n===e)}import{createHash as hs,randomBytes as ws,randomUUID as Ut}from"node:crypto";import{createServer as rs}from"node:http";import{createHash as ss,randomBytes as is,randomUUID as as}from"node:crypto";import{spawn as cs}from"node:child_process";import{createInterface as Ie}from"node:readline/promises";import{stdin as ne,stdout as ee}from"node:process";import{Writable as ls}from"node:stream";function Se(e,n,t={}){let o=`${n?"*":" "} ${e}`;return n?j(o,"\x1B[1m\x1B[36m",J(t)):o}function Rt(e,n={}){let t=J(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")}${Tt(e.stage,t)}`,` ${o("server")}${e.server}`]}function qr(e,n={}){let t=J(n),o=jt(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",c=`${e.dashboardUrl}?project=${encodeURIComponent(e.project)}&stage=${encodeURIComponent(e.stage)}`,d=j(c,"\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(`
|
|
85
|
+
`)}function Zr(e,n={}){let t=J(n);return e.map((o)=>{let r=ts(o.operation,t);if(o.operation==="rename"&&o.previousName)return` ${r} ${o.kind}:${o.previousName} -> ${o.name}`;return` ${r} ${o.kind}:${o.name}`})}function Xr(e,n={}){let t=J(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 Qr(e,n={}){return`${j("✖","\x1B[31m",J(n))} ${e}`}function Ot(e,n={}){let t=J(n),o=Math.max(...e.map(([r])=>r.length))+2;return e.map(([r,s])=>` ${r.padEnd(o)}${j(s,"\x1B[2m",t)}`)}function es(e,n={}){let t=(n.now??new Date).toTimeString().slice(0,8);return`${j("✔","\x1B[32m",J(n))} ${t} Resources ready! (${os(e)})`}function ns(e,n={}){return`${j("✔","\x1B[32m",J(n))} ${e}`}function kn(e,n,t={}){let o=J(t),r=t.note?` ${j(`(${t.note})`,"\x1B[2m",o)}`:"";return` ${j("now","\x1B[2m",o)} ${e} → ${Tt(n,o)}${r}`}function je(e,n={}){return j(`! ${e}`,"\x1B[33m",J(n))}function At(e){console.error(qr(e))}function Xe(e){for(let n of Zr(e))console.log(n)}function En(e){console.error(Xr(e))}function xt(e){console.error(Qr(e,{stream:"stderr"}))}function Pt(e){console.error(es(e))}function H(e){console.log(ns(e,{stream:"stdout"}))}function x(e){console.log(je(e,{stream:"stdout"}))}function ts(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 os(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 Tt(e,n){let t=jt(e)==="Development";return j(e,t?"\x1B[32m":"\x1B[33m",n)}function J(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 jt(e){let n=e.trim().toLowerCase();if(n==="development")return"Development";if(n==="production")return"Production";return e.trim()}var ds=180000,us=`Timed out waiting for browser login to complete.
|
|
86
86
|
Check the browser tab and the dashboard logs for an error. If the browser shows
|
|
87
87
|
404 on /cli-auth/start, deploy the dashboard build that includes CLI auth or pass
|
|
88
88
|
--dashboard-url for the environment you deployed. Other common causes are missing
|
|
89
|
-
cliAuth Convex functions or no active API account (Organization settings -> API access).`,
|
|
90
|
-
`)}}async function _e(e,n,t,o){if(n.length===0)throw Error(`${e}: no options available`);if(n.length===1)return n[0];let r=o!==void 0&&o>=0&&o<n.length?o:void 0;console.log(e),n.forEach((a,c)=>{console.log(Se(`${c+1}. ${t(a)}`,c===r))});let s=r===void 0?`Choose 1-${n.length}: `:`Choose 1-${n.length} [${r+1}]: `,i=Ie({input:ne,output:ee});try{for(;;){let a=(await i.question(s)).trim();if(a===""&&r!==void 0)return n[r];let c=Number(a);if(Number.isInteger(c)&&c>=1&&c<=n.length)return n[c-1];console.log(`Enter a number from 1 to ${n.length}.`)}}finally{i.close()}}async function
|
|
91
|
-
`,"utf8")}catch{}}var
|
|
89
|
+
cliAuth Convex functions or no active API account (Organization settings -> API access).`,It=new Set(["--base-url","--cwd","--dashboard-url","--stage","--from","--level","--limit","--mcp","--project","--region","--sandbox","-n"]);function gs(e,n=process.platform){if(n==="darwin")return{command:"open",args:[e]};if(n==="win32")return{command:"rundll32",args:["url.dll,FileProtocolHandler",e]};return{command:"xdg-open",args:[e]}}function I(e,n){let t=It.has(n)?`${n}=`:null;return e.some((o)=>o===n||t!==null&&o.startsWith(t))}function we(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function b(e,n){for(let t=0;t<e.length;t+=1){let o=e[t];if(o===n)return e[t+1];if(o?.startsWith(`${n}=`))return o.slice(n.length+1)||void 0}return}function te(e){let n=[];for(let t=0;t<e.length;t+=1){let o=e[t];if(o===void 0)continue;if(It.has(o)){t+=1;continue}if(o.startsWith("-"))continue;n.push(o)}return n}async function Sn(e){let n=as(),t=is(32).toString("base64url"),o=ss("sha256").update(t).digest("base64url"),{code:r,close:s}=await Cn(n,{port:fs(),fixedPort:Boolean(process.env.BROODS_LOGIN_PORT),path:"/callback",read:ms,done:"broods CLI login complete. You can close this tab."});try{let i=r.callbackUrl,a=`${f(e)}/cli-auth/start?`+new URLSearchParams({callback:i,state:n,code_challenge:o});await ps(a),console.log(`Opening ${a}`),$n(a);let c=await Rn(r.promise),d=await qe(`${c.baseUrl}/v1/account/auth/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:c.code,code_verifier:t})});if(!d.ok)throw Error(`Login exchange failed: ${d.status} ${await d.text()}`);let l=await d.json(),p={baseUrl:c.baseUrl,dashboardUrl:f(e),token:l.token,createdAt:new Date().toISOString(),...l.user?{user:l.user}:{},...l.org?{org:l.org}:{},...l.account?{account:l.account}:{}};return await W(p),p}finally{s()}}async function q(e){h();let n=z(e);if(!n){let t=process.env.BROODS_DASHBOARD_URL,o=e??process.env.BROODS_BASE_URL??(t?L(t):void 0);throw Error(o?`Not logged in to ${f(o)}. Run \`broods login\`.`:"Run `broods login` first, or set BROODS_TOKEN and BROODS_BASE_URL.")}return n}async function Qe(e){if(!ne.isTTY)return!1;let n=Ie({input:ne,output:ee});try{let t=(await n.question(`${e} [y/N] `)).trim().toLowerCase();return t==="y"||t==="yes"}finally{n.close()}}async function _t(e){ee.write(`${e}: `);let n=new ls({write:(o,r,s)=>s()}),t=Ie({input:ne,output:n,terminal:ne.isTTY===!0});try{let o=await t.question("");if(!o)throw Error(`${e} is required`);return o}finally{t.close(),ee.write(`
|
|
90
|
+
`)}}async function _e(e,n,t,o){if(n.length===0)throw Error(`${e}: no options available`);if(n.length===1)return n[0];let r=o!==void 0&&o>=0&&o<n.length?o:void 0;console.log(e),n.forEach((a,c)=>{console.log(Se(`${c+1}. ${t(a)}`,c===r))});let s=r===void 0?`Choose 1-${n.length}: `:`Choose 1-${n.length} [${r+1}]: `,i=Ie({input:ne,output:ee});try{for(;;){let a=(await i.question(s)).trim();if(a===""&&r!==void 0)return n[r];let c=Number(a);if(Number.isInteger(c)&&c>=1&&c<=n.length)return n[c-1];console.log(`Enter a number from 1 to ${n.length}.`)}}finally{i.close()}}async function Dt(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=Ie({input:ne,output:ee});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 be(e,n){if(!ne.isTTY)return n??"";let t=Ie({input:ne,output:ee});try{let o=t.question(`${e}: `);if(n){if(ne.isTTY&&ee.isTTY)ee.write("\x1B[90m");if(t.write(n),ne.isTTY&&ee.isTTY)ee.write("\x1B[0m")}return(await o).trim()||n||""}finally{t.close()}}function $n(e){let{command:n,args:t}=gs(e),o=cs(n,t,{stdio:"ignore",detached:!0});o.on("error",(r)=>{console.error(je(`Could not open a browser (${r.message}). Open the URL above to continue.`,{stream:"stderr"}))}),o.unref()}function Cn(e,n){return new Promise((t,o)=>{let r=rs((c,d)=>{let l=new URL(c.url??"/","http://127.0.0.1");if(l.pathname!==n.path||l.searchParams.get("state")!==e){d.writeHead(400).end("Invalid callback.");return}try{let p=n.read(l.searchParams);d.writeHead(200,{"Content-Type":"text/plain"}).end(n.done),s(p)}catch(p){d.writeHead(400,{"Content-Type":"text/plain"}).end(p instanceof Error?p.message:String(p)),i(p)}}),s,i,a=new Promise((c,d)=>{s=c,i=d});r.on("error",(c)=>{if(!n.fixedPort&&n.port!==0&&c.code==="EADDRINUSE"){r.listen(0,"127.0.0.1");return}o(c)}),r.listen(n.port,"127.0.0.1",()=>{let c=r.address();if(!c||typeof c==="string"){o(Error("Failed to allocate callback port"));return}t({code:{callbackUrl:`http://127.0.0.1:${c.port}${n.path}`,promise:a},close:()=>r.close()})})})}async function Rn(e,n=us){let t,o=new Promise((r,s)=>{t=setTimeout(()=>s(Error(n)),ds)});try{return await Promise.race([e,o])}finally{if(t)clearTimeout(t)}}async function ps(e){let n=await qe(e,{method:"GET",redirect:"manual"});if(n.status===404){let t=new URL(e);throw Error(`${t.origin} has no broods login page. Check that --dashboard-url points at your broods dashboard.`)}if(n.status>=500)throw Error(`The broods login page failed: ${n.status} ${await n.text()}`)}function fs(){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 ms(e){let n=e.get("error");if(n)throw Error(`Login failed: ${n}`);let t=e.get("code");if(!t)throw Error("Login callback carried no code.");let o=e.get("base_url");if(!o)throw Error("Login callback did not advertise the API base URL (base_url). Deploy a dashboard build that includes the Convex-direct CLI auth flow.");return{code:t,baseUrl:f(o)}}var bs=1455,ys="/auth/callback";async function Nt(e,n,t=$n){let o=he[n].label,r=Ut(),s=Ut(),i=ws(32).toString("base64url"),{code:a,close:c}=await Cn(r,{port:bs,fixedPort:!1,path:ys,read:vs,done:`${o} is connected to broods. You can close this tab.`});try{let d=a.callbackUrl,l=await e.startConnection(n,{redirectUri:d,codeChallenge:hs("sha256").update(i).digest("base64url"),state:r,nonce:s});t(l.authorizeUrl),console.log(`Opening ${l.authorizeUrl}`);let p=await Rn(a.promise,`Timed out waiting for the ${o} sign-in to finish in the browser.`);return await e.connect(n,{code:p.code,codeVerifier:i,redirectUri:d,nonce:s,clientId:p.clientId??l.clientId,hostId:l.hostId})}finally{c()}}function vs(e){let n=e.get("error");if(n)throw Error(`Sign-in failed: ${e.get("error_description")??n}`);let t=e.get("code");if(!t)throw Error("Sign-in callback carried no code.");return{code:t,clientId:e.get("client_id")??void 0}}import{existsSync as Mt}from"node:fs";import{mkdir as Es,readFile as Ss,writeFile as $s}from"node:fs/promises";import{dirname as Bt,join as xn,resolve as Cs,sep as ge}from"node:path";import{fileURLToPath as Rs}from"node:url";var De={name:"broods",version:"0.49.3",description:"CLI + TypeScript SDK for the broods agent platform.",keywords:["agents","ai","broods","cli","sdk"],homepage:"https://github.com/beeblastco/broods#readme",bugs:{url:"https://github.com/beeblastco/broods/issues"},license:"MIT",repository:{type:"git",url:"git+https://github.com/beeblastco/broods.git",directory:"packages/broods"},bin:{broods:"dist/cli/index.js"},files:["dist","README.md","LICENSE.md"],type:"module",main:"./dist/index.js",types:"./dist/index.d.ts",typesVersions:{"*":{account:["./dist/account.d.ts"]}},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./account":{types:"./dist/account.d.ts",import:"./dist/account.js"}},scripts:{build:"bun scripts/build.ts && rollup -c rollup.dts.config.mjs && rm -rf .dts-temp",check:"tsc --noEmit && tsc --noEmit -p tsconfig.scripts.json","pack:check":"bun run build && publint && attw --pack .",prepublishOnly:"bun run build",test:"bun test"},dependencies:{"@modelcontextprotocol/client":"^2.2.0",esbuild:"^0.28.2"},devDependencies:{"@ai-sdk/tui":"1.0.138","@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.2.0","@types/bun":"^1.3.14","@typescript/typescript6":"6.0.2",ai:"^7.0.137",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.137"},engines:{node:">=22.15"}};var On=xn(Bt(O),"update-check.json"),Os=86400000,As="https://registry.npmjs.org/broods/latest",xs=2000,Ps=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"]];function Pn(e,n){let t=An(e),o=An(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!Lt(e)&&Lt(n)}async function Tn(e={}){let n=await js(),t=e.maxAgeMs??Os;if(n&&Date.now()-n.checkedAt<t)return n.latest;let o=await Ts();if(o===null)return n?.latest??null;return await _s({checkedAt:Date.now(),latest:o}),o}function Ue(e){return An(e)[0]??0}function Gt(e=Cs(process.cwd()),n=Rs(import.meta.url),t=De.version){let o=`${ge}node_modules${ge}`,r=n.indexOf(o),s=r===-1?null:n.slice(0,r),i=s===null?n.startsWith(`${e}${ge}`):e===s||e.startsWith(`${s}${ge}`),a=n.includes(`${ge}.bun${ge}install${ge}global${ge}`),c=s??e,d=i?Is(c):a?"bun":"npm",l=d==="npm"?"install":"add",p=d==="pnpm"&&Mt(xn(c,"pnpm-workspace.yaml"))?["-w"]:[],u=`broods@${Ue(t)}`;return{manager:d,global:!i,command:d,cwd:i?c:e,args:i?[l,...p,u]:[l,"-g",u]}}async function Ts(){try{let e=await fetch(As,{signal:AbortSignal.timeout(xs),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 Lt(e){return e.includes("-")}async function js(){try{let e=JSON.parse(await Ss(On,"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 Is(e){return Ps.find(([t])=>Mt(xn(e,t)))?.[1]??"npm"}function An(e){let[n]=e.trim().replace(/^v/,"").split("-");return(n??"").split(".").slice(0,3).map((t)=>Number.parseInt(t,10)||0)}async function _s(e){try{await Es(Bt(On),{recursive:!0}),await $s(On,`${JSON.stringify(e)}
|
|
91
|
+
`,"utf8")}catch{}}var Wt=`---
|
|
92
92
|
name: broods
|
|
93
93
|
description: Work on a broods account alongside a developer from Claude Code or a development agent. Covers onboarding and sign-in, creating a broods project, defining and deploying agents and their resources with the CLI, and integrating a deployed agent into existing code with the SDK. Use when asked to set up broods, create or work on a broods project, create or manage agents or any account resource, or call a deployed agent from application code.
|
|
94
94
|
---
|
|
@@ -136,7 +136,7 @@ Crons, skills, sandboxes, policies, roles, channels, and hooks have no CLI verb.
|
|
|
136
136
|
- 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.
|
|
137
137
|
- Deletes are confirmed, named, and singular. Never loop a delete over a list.
|
|
138
138
|
- Editing a manifest-declared resource outside the project drifts from the definition, and the next deploy silently reverts it.
|
|
139
|
-
`;var
|
|
139
|
+
`;var Ft=`#!/usr/bin/env bash
|
|
140
140
|
# Onboard this machine onto broods: check the CLI, check auth, and run the
|
|
141
141
|
# browser login when needed. Login is a human step, so run this where the
|
|
142
142
|
# user can see the browser open and finish it themselves.
|
|
@@ -171,23 +171,23 @@ elif [ "$STATUS" -ne 0 ]; then
|
|
|
171
171
|
# Not the expected signed-out state: surface the real failure.
|
|
172
172
|
exit "$STATUS"
|
|
173
173
|
fi
|
|
174
|
-
`;var ae=De.version,en=Le(".agents","skills","broods"),oe="https://dashboard.broods.app",
|
|
174
|
+
`;var ae=De.version,en=Le(".agents","skills","broods"),oe="https://dashboard.broods.app",zs=3,Ne="eu-west-1",Js=[{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)"}],F=`Global options:
|
|
175
175
|
--project <name> Project name override (default: package name or folder)
|
|
176
176
|
--stage <name> Target stage override (BROODS_STAGE otherwise)
|
|
177
177
|
--base-url <url> broods API base URL for sync/env calls (default: discovered at login)
|
|
178
178
|
--dashboard-url <url> Dashboard base URL for login and deep links (default: ${oe})
|
|
179
|
-
-h, --help Show this help`,
|
|
179
|
+
-h, --help Show this help`,qs=`Commands
|
|
180
180
|
Develop dev diff run logs stream
|
|
181
181
|
Ship deploy env stage
|
|
182
182
|
Inspect agent whoami
|
|
183
183
|
Account login connect disconnect org project
|
|
184
|
-
Tools init machine mcp update`,
|
|
184
|
+
Tools init machine mcp update`,jn={stream:"stdout"},Xt={color:!1},Zs=new Set(["agent","deploy","dev","diff","env","logs","machine","run","stage","stream"]),Qt={agent:`Usage: broods agent <list|get> [name]
|
|
185
185
|
|
|
186
186
|
Subcommands:
|
|
187
187
|
list List the agents in the current project/stage scope
|
|
188
188
|
get <name> Show an agent's model, sandboxes, workspaces, tools and channels
|
|
189
189
|
|
|
190
|
-
${
|
|
190
|
+
${F}`,connect:`Usage: broods connect [type]
|
|
191
191
|
|
|
192
192
|
Signs an external account in through the browser and keeps it on your
|
|
193
193
|
deployment, so agents act through it. Without a type, lists the account's
|
|
@@ -198,7 +198,7 @@ Types:
|
|
|
198
198
|
${Ze.map((e)=>` ${e.padEnd(11)} ${he[e].description}`).join(`
|
|
199
199
|
`)}
|
|
200
200
|
|
|
201
|
-
${
|
|
201
|
+
${F}`,deploy:`Usage: broods deploy [options]
|
|
202
202
|
|
|
203
203
|
Syncs Production once and writes BROODS_API_KEY to .env.local. Ignores
|
|
204
204
|
BROODS_STAGE by design. Pass --stage to deploy anywhere else.
|
|
@@ -207,7 +207,7 @@ Options:
|
|
|
207
207
|
--prune Allow deploy to delete undeclared remote resources
|
|
208
208
|
--rotate-key Mint a fresh runtime key and write it to .env.local
|
|
209
209
|
|
|
210
|
-
${
|
|
210
|
+
${F}`,dev:`Usage: broods dev [--once] [options]
|
|
211
211
|
|
|
212
212
|
Watches broods/, syncs the current stage (BROODS_STAGE, default Development)
|
|
213
213
|
and live-tails agent logs. Confirms before deleting, and auto-pushes
|
|
@@ -219,16 +219,16 @@ Options:
|
|
|
219
219
|
--all Tail INFO and up (DEBUG is dashboard-only)
|
|
220
220
|
--region <region> Service region for a new project (default: ${Ne})
|
|
221
221
|
|
|
222
|
-
${
|
|
222
|
+
${F}`,diff:`Usage: broods diff [options]
|
|
223
223
|
|
|
224
224
|
Shows local desired state against the remote state of the current stage, and
|
|
225
225
|
warns when the stage's value for an env("NAME") ref no longer matches .env.local.
|
|
226
226
|
|
|
227
|
-
${
|
|
227
|
+
${F}`,disconnect:`Usage: broods disconnect <type>
|
|
228
228
|
|
|
229
229
|
Forgets the account's connection of that type and revokes it at the provider.
|
|
230
230
|
|
|
231
|
-
${
|
|
231
|
+
${F}`,env:`Usage: broods env <set|get|list|rm|sync> [name]
|
|
232
232
|
|
|
233
233
|
Subcommands:
|
|
234
234
|
set <name> Store an encrypted environment variable (value read from the prompt or stdin)
|
|
@@ -244,7 +244,7 @@ Subcommands:
|
|
|
244
244
|
those the stage does not already hold the local value for. \`dev\` runs the same
|
|
245
245
|
push on every sync; \`deploy\` never does, so Production stays explicit.
|
|
246
246
|
|
|
247
|
-
${
|
|
247
|
+
${F}`,init:`Usage: broods init [options]
|
|
248
248
|
|
|
249
249
|
Creates the broods/ project shell and .env.local defaults.
|
|
250
250
|
|
|
@@ -252,7 +252,7 @@ Options:
|
|
|
252
252
|
--region <region> Broods service region preference (default: ${Ne})
|
|
253
253
|
--force Overwrite existing starter files
|
|
254
254
|
|
|
255
|
-
${
|
|
255
|
+
${F}`,login:`Usage: broods login [options]
|
|
256
256
|
|
|
257
257
|
Authenticates through the dashboard and stores the token in
|
|
258
258
|
~/.broods/config.json.
|
|
@@ -260,7 +260,7 @@ Authenticates through the dashboard and stores the token in
|
|
|
260
260
|
Options:
|
|
261
261
|
--region <region> Broods service region preference (default: ${Ne})
|
|
262
262
|
|
|
263
|
-
${
|
|
263
|
+
${F}`,logs:`Usage: broods logs [options]
|
|
264
264
|
|
|
265
265
|
Backfills recent logs then live-tails. Warnings and errors, 100 lines by default.
|
|
266
266
|
|
|
@@ -273,7 +273,7 @@ Options:
|
|
|
273
273
|
is the last segment of the instance's log stream
|
|
274
274
|
(dashboard Instances sheet).
|
|
275
275
|
|
|
276
|
-
${
|
|
276
|
+
${F}`,machine:`Usage: broods machine <sandbox> [options]
|
|
277
277
|
|
|
278
278
|
Connects this computer to a sandbox record whose provider is "machine". Agents
|
|
279
279
|
on that sandbox run their bash tool here, as you, with your PATH and
|
|
@@ -297,7 +297,7 @@ Options:
|
|
|
297
297
|
--force Take the record over from another daemon, even one on this computer
|
|
298
298
|
--doctor [--request] Check the macOS permissions computer use needs; --request prompts for them
|
|
299
299
|
|
|
300
|
-
${
|
|
300
|
+
${F}`,org:`Usage: broods org <list|use|create> [name]
|
|
301
301
|
|
|
302
302
|
Subcommands:
|
|
303
303
|
list List the organizations this login can act on
|
|
@@ -306,13 +306,13 @@ Subcommands:
|
|
|
306
306
|
|
|
307
307
|
Only orgs where you are owner or admin can be selected from the CLI.
|
|
308
308
|
|
|
309
|
-
${
|
|
309
|
+
${F}`,run:`Usage: broods run <agent> [prompt]
|
|
310
310
|
|
|
311
311
|
Chats with an agent in a terminal UI (reasoning, tool cards, y/n approvals).
|
|
312
312
|
A prompt is sent as the first turn; redirected output streams plain text and
|
|
313
313
|
therefore requires a prompt.
|
|
314
314
|
|
|
315
|
-
${
|
|
315
|
+
${F}`,project:`Usage: broods project <list|delete> [name]
|
|
316
316
|
|
|
317
317
|
Subcommands:
|
|
318
318
|
list List the org's projects and what each one still holds
|
|
@@ -325,7 +325,7 @@ admin role. There is no undo.
|
|
|
325
325
|
Options:
|
|
326
326
|
--yes Skip the confirmation prompt
|
|
327
327
|
|
|
328
|
-
${
|
|
328
|
+
${F}`,stage:`Usage: broods stage <list|use|create> [name]
|
|
329
329
|
|
|
330
330
|
Subcommands:
|
|
331
331
|
list List the project's stages
|
|
@@ -336,7 +336,7 @@ Options:
|
|
|
336
336
|
--from <stage> Clone the source stage's architecture and env vars
|
|
337
337
|
--use Switch to the stage \`stage create\` just made
|
|
338
338
|
|
|
339
|
-
${
|
|
339
|
+
${F}`,stream:`Usage: broods stream [options]
|
|
340
340
|
|
|
341
341
|
Streams live logs for the whole project/stage until Ctrl+C. No backfill.
|
|
342
342
|
|
|
@@ -344,7 +344,7 @@ Options:
|
|
|
344
344
|
--level <lvl> Minimum log level DEBUG|INFO|WARN|ERROR (default: WARN)
|
|
345
345
|
--all Stream INFO and up (DEBUG is dashboard-only)
|
|
346
346
|
|
|
347
|
-
${
|
|
347
|
+
${F}`,mcp:`Usage: broods mcp
|
|
348
348
|
|
|
349
349
|
Serves the account config plane to a development agent over MCP on stdio, so
|
|
350
350
|
Claude Code and friends drive broods through typed tools instead of curl. It
|
|
@@ -372,55 +372,55 @@ project the dependency is upgraded instead. A new major is only announced.`,whoa
|
|
|
372
372
|
|
|
373
373
|
Shows the login, server, org, plan, project and stage the next command uses.
|
|
374
374
|
|
|
375
|
-
${
|
|
375
|
+
${F}`};async function Xs(){Zi();let[,,e,...n]=process.argv;switch(e){case void 0:case"--help":case"-h":console.log(In(n,jn));return;case"--version":case"-v":console.log(ae);return}if(Xi(e,n),Qt[e]&&(I(n,"--help")||I(n,"-h"))){console.log(ve(e,n));return}switch(e){case"init":await ei(n);return;case"login":await ni(n);return;case"connect":await oi(n);return;case"disconnect":await ri(n);return;case"whoami":await ai(n);return;case"org":await li(n);return;case"project":await di(n);return;case"stage":await ui(n);return;case"diff":await gi(n);return;case"deploy":await pi(n);return;case"dev":await mi(n);return;case"env":await Li(n);return;case"stream":await Gi(n);return;case"logs":await Ki(n);return;case"machine":await Wi(n);return;case"agent":await Hi(n);return;case"run":await zi(n);return;case"mcp":await Qi();return;case"update":await fi();return;default:throw Error(`Unknown command: ${e}
|
|
376
376
|
|
|
377
|
-
${
|
|
377
|
+
${In(n,Xt)}`)}}function Z(e){return Qt[e]??In([],Xt)}function eo(e){let n=h(),t=b(e,"--base-url")??n.baseUrl,o=z(t),r=f(t??o?.baseUrl??T);return{loggedIn:o!==null,org:o?.org?.name,project:b(e,"--project")??n.project,projectGuess:Re(process.cwd()),server:r.replace(/^https?:\/\//,""),stage:b(e,"--stage")??n.stage??"development"}}function Qs(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 ve(e,n){let t=Z(e);if(!Zs.has(e))return t;let o=eo(n),r=o.project??o.projectGuess;if(e!=="deploy"||b(n,"--stage")!==void 0)return`${kn(r,o.stage,jn)}
|
|
378
378
|
|
|
379
|
-
${t}`;let s=v(),i=s&&s!=="production"?`ignores stage ${s}`:void 0;return`${
|
|
379
|
+
${t}`;let s=v(),i=s&&s!=="production"?`ignores stage ${s}`:void 0;return`${kn(r,"production",{...jn,note:i})}
|
|
380
380
|
|
|
381
|
-
${t}`}function
|
|
382
|
-
`)}async function
|
|
381
|
+
${t}`}function In(e,n){let t=eo(e);return[`broods v${ae}`,"",...Rt(t,n),"","Next",...Ot(Qs(t),n),"",qs,"","Usage: broods <command> [options] -h, --help -v, --version","Run `broods <command> --help` for a command's flags."].join(`
|
|
382
|
+
`)}async function ei(e){let n=I(e,"--force"),t=P(process.cwd(),y);await Ln(P(t,_),{recursive:!0}),await tn(P(t,"index.ts"),mo(),n),await tn(P(t,".gitignore"),`_generated
|
|
383
383
|
.cache
|
|
384
|
-
`,n),await
|
|
384
|
+
`,n),await ro(n);let o=b(e,"--dashboard-url")??oe;await Fn({dashboardUrl:o,baseUrl:L(o),project:b(e,"--project")??Re(process.cwd()),stage:b(e,"--stage")??"development",region:b(e,"--region")??Ne,force:n}),H(`Created ${y}/`)}async function ni(e){let n=h(),t=b(e,"--dashboard-url")??n.dashboardUrl??oe,o=await Sn(t);await Fn({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(H(`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 c=b(e,"--stage")??v()??"development";await ii(o.baseUrl,o.token,a,c)}function ti(e){if(!(e instanceof m))return e instanceof Error?e.message:String(e);try{return JSON.parse(e.body).error?.message??e.message}catch{return e.message}}async function oi(e){let[n]=te(e),t=await no(e);if(n===void 0){await si(t);return}if(!vn(n))throw Error(`Unknown connection type ${n}.
|
|
385
385
|
|
|
386
|
-
${Z("connect")}`);let o=he[n],r=await
|
|
387
|
-
Connect one: broods connect <${Ze.join("|")}>`)}async function
|
|
386
|
+
${Z("connect")}`);let o=he[n],r=await Nt(t,n).catch((s)=>{throw Error(ti(s))});if(H(`Connected ${o.label}${r.email?` as ${r.email}`:""}.`),console.log(`Agents on model.provider "${n}" now run on it.`),o.usageUrl)console.log(`Manage usage: ${o.usageUrl}`);if(!r.models?.length)return;console.log("Models (use the id as model.modelId):");for(let s of r.models)console.log(` ${s}`)}async function no(e){h();let n=b(e,"--base-url"),t=process.env.BROODS_ACCOUNT_SECRET;if(t)return new R({accountSecret:t,...n?{baseUrl:n}:{}});let o=await q(n);return new R({accountSecret:o.token,baseUrl:n??o.baseUrl})}async function ri(e){let[n]=te(e);if(!n||!vn(n))throw Error(Z("disconnect"));if(await(await no(e)).disconnect(n)){H(`Disconnected ${he[n].label}`);return}console.log(`No ${n} connection.`)}async function si(e){let n=await e.listConnections();if(n.length===0)console.log("No connections yet.");else console.log(`${"TYPE".padEnd(16)} ACCOUNT`);for(let t of n)console.log(`${he[t.type].label.padEnd(16)} ${t.email??t.clientId}`);console.log(`
|
|
387
|
+
Connect one: broods connect <${Ze.join("|")}>`)}async function ii(e,n,t,o){try{let s=await new N({baseUrl:e,token:n}).getRuntimeKey(t,o);if(s?.apiKey)await $e("BROODS_API_KEY",s.apiKey),H(`Wrote BROODS_API_KEY (${s.keyHint}) to .env.local`)}catch{}}async function ai(e){let n=h(),t=rn(e),o=b(e,"--dashboard-url")??n.dashboardUrl??oe,r=Boolean(b(e,"--project")??n.project);console.log(`broods v${ae}`),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 q(b(e,"--base-url"))}catch(l){x(l instanceof Error?l.message:String(l));return}console.log(`Server: ${s.baseUrl}`);let i=new N({baseUrl:s.baseUrl,token:s.token}),a=await i.getOnboarding(),c=a.orgs.find((l)=>l.id===a.currentOrgId);if(a.user)console.log(`User: ${a.user.email}`);if(console.log(`Org: ${c?Me(c):a.currentOrgId}`),a.account)console.log(`Account: ${a.account.username} (${a.account.status})`);if(!r){x("No project set. `broods dev` picks one.");return}await ci(i,t,c?.name);let d=a.projects.map((l)=>l.name);if(!d.includes(t.project))x(`This org has no project named ${t.project}. It has: ${d.length>0?d.join(", "):"none"}.`)}async function ci(e,n,t){let o=process.env.BROODS_API_KEY,r=M("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"),x(`Could not read the runtime key: ${i}`);else if(!s?.apiKey)console.log("Runtime key: none for this scope"),x(`${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)`),x("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`),x(`BROODS_API_KEY from ${r} belongs to a different org or stage. Run \`broods stage use ${n.stage}\` to repoint it.`)}async function li(e){let[n,t]=te(e);if(!n){console.log(ve("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}
|
|
388
388
|
|
|
389
389
|
${Z("org")}`);let i=h(),a=b(e,"--dashboard-url")??i.dashboardUrl??oe,c=await Be(a,b(e,"--base-url")),d=new N({baseUrl:c.baseUrl,token:c.token}),l=await d.getOnboarding();if(o){for(let u of l.orgs){let S=u.accountStatus==="active"?"":` [${u.accountStatus} account]`;console.log(Se(`${Me(u)}${S}`,u.id===l.currentOrgId))}console.log(`
|
|
390
|
-
Only orgs where you are owner or admin can be selected from the CLI.`);return}if(r){let u=l.orgs.filter((C)=>C.accountStatus==="active"),S=t?u.find((C)=>C.slug===t||C.name===t||C.id===t):await _e("Select organization",u,Me,u.findIndex((C)=>C.id===l.currentOrgId));if(!S)throw Error(`No selectable organization matches "${t}". Run \`broods org list\`.`);await
|
|
390
|
+
Only orgs where you are owner or admin can be selected from the CLI.`);return}if(r){let u=l.orgs.filter((C)=>C.accountStatus==="active"),S=t?u.find((C)=>C.slug===t||C.name===t||C.id===t):await _e("Select organization",u,Me,u.findIndex((C)=>C.id===l.currentOrgId));if(!S)throw Error(`No selectable organization matches "${t}". Run \`broods org list\`.`);await Yt(d,c,await d.selectOnboardingOrg(S.id),e);return}let p=t??await be("Organization name",Re(process.cwd()));if(!p.trim())throw Error("Organization name is required.");await Yt(d,c,await d.createOnboardingOrg(p),e)}async function di(e){let[n,t]=te(e);if(!n){console.log(ve("project",e));return}let o=n==="list"||n==="ls";if(!o&&!(n==="delete"||n==="rm"))throw Error(`Unknown project subcommand: ${n}
|
|
391
391
|
|
|
392
|
-
${Z("project")}`);let s=h(),i=b(e,"--dashboard-url")??s.dashboardUrl??oe,a=rn(e),c=await Be(i,b(e,"--base-url")),d=new N({baseUrl:c.baseUrl,token:c.token});if(o){let C=await d.listProjects();if(C.length===0){console.log("This org has no projects yet. `broods dev` creates one.");return}console.log("Projects:");for(let A of C)console.log(
|
|
393
|
-
${k.length} empty project(s). Delete one with \`broods project delete <name>\`.`);return}let l=t??await be("Project to delete","");if(!l.trim())throw Error("Project name is required.");let p=await d.listProjects(),u=p.find((C)=>C.name===l||C.slug===l);if(!u)throw Error(`No project named "${l}". Existing: ${p.map((C)=>C.name).join(", ")}.`);if(!I(e,"--yes")){if(console.log(`Deleting ${u.name} removes ${
|
|
392
|
+
${Z("project")}`);let s=h(),i=b(e,"--dashboard-url")??s.dashboardUrl??oe,a=rn(e),c=await Be(i,b(e,"--base-url")),d=new N({baseUrl:c.baseUrl,token:c.token});if(o){let C=await d.listProjects();if(C.length===0){console.log("This org has no projects yet. `broods dev` creates one.");return}console.log("Projects:");for(let A of C)console.log(Si(A,a.project));let k=C.filter((A)=>A.empty);if(k.length>0)console.log(`
|
|
393
|
+
${k.length} empty project(s). Delete one with \`broods project delete <name>\`.`);return}let l=t??await be("Project to delete","");if(!l.trim())throw Error("Project name is required.");let p=await d.listProjects(),u=p.find((C)=>C.name===l||C.slug===l);if(!u)throw Error(`No project named "${l}". Existing: ${p.map((C)=>C.name).join(", ")}.`);if(!I(e,"--yes")){if(console.log(`Deleting ${u.name} removes ${Un(u)}.`),!await Qe(`Permanently delete project ${u.name}?`)){console.log("Left it alone. Pass --yes to skip this prompt.");return}}let S=await d.deleteProject(u.id);if(!S)throw Error(`Project ${u.name} was not found.`);if(H(`Deleted project ${S.name} (${Un(S)})`),S.name===a.project||S.slug===a.project)console.log("That was the project this directory points at. Update BROODS_PROJECT in .env.local.")}async function ui(e){let[n,t]=te(e);if(!n){console.log(ve("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}
|
|
394
394
|
|
|
395
|
-
${Z("stage")}`);let i=h(),a=b(e,"--dashboard-url")??i.dashboardUrl??oe,c=rn(e),d=await Be(a,b(e,"--base-url")),l=new N({baseUrl:d.baseUrl,token:d.token});if(o){let k=await l.listStages(c.project);if(k.length===0){console.log(`${c.project} has no stages yet. \`broods dev\` creates Development.`);return}console.log(`Stages for ${c.project}:`);for(let A of k)console.log(
|
|
395
|
+
${Z("stage")}`);let i=h(),a=b(e,"--dashboard-url")??i.dashboardUrl??oe,c=rn(e),d=await Be(a,b(e,"--base-url")),l=new N({baseUrl:d.baseUrl,token:d.token});if(o){let k=await l.listStages(c.project);if(k.length===0){console.log(`${c.project} has no stages yet. \`broods dev\` creates Development.`);return}console.log(`Stages for ${c.project}:`);for(let A of k)console.log($i(A,c.stage));return}if(r){let k=await l.listStages(c.project),A=t?k.find((re)=>Nn(re.name,t)):await _e("Select stage",k,so,k.findIndex((re)=>Nn(re.name,c.stage)));if(!A)throw Error(`${c.project} has no stage "${t}". Existing: ${k.map((re)=>re.name).join(", ")}. Create it with \`broods stage create ${t} --from ${c.stage}\`.`);let V=M("BROODS_STAGE");await $e("BROODS_STAGE",A.name),console.log(`Stage: ${A.name} (wrote BROODS_STAGE)`),Dn("BROODS_STAGE",V),await _n(l,{project:c.project,stage:A.name});return}let p=t??await be("Stage name","staging");if(!p.trim())throw Error("Stage name is required.");let u=b(e,"--from"),S=await l.createStage(c.project,p,u);if(H(`Created stage ${S.stage.name} in ${c.project}${S.clonedFrom?` from ${S.clonedFrom}`:""}`),S.clonedFrom)console.log(` ${S.stage.agentCount} agent(s), ${S.stage.variableCount} env var(s) copied`);if(!I(e,"--use")){console.log(`Switch to it with \`broods stage use ${S.stage.name}\`.`);return}let C=M("BROODS_STAGE");await $e("BROODS_STAGE",S.stage.name),console.log(`Stage: ${S.stage.name} (wrote BROODS_STAGE)`),Dn("BROODS_STAGE",C),await _n(l,{project:c.project,stage:S.stage.name})}async function gi(e){let{manifest:n,config:t}=await le({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),o=await q(b(e,"--base-url")??t.baseUrl),r=new N({baseUrl:o.baseUrl,token:o.token}),s=await r.getManifest(n.project,n.stage);Xe(yn(n,s?.manifest??null)),ji(await Mn(r,n),`${n.project}/${n.stage}`)}async function pi(e){let{manifest:n,config:t,resourceAliases:o,channels:r}=await le({project:b(e,"--project"),stage:b(e,"--stage"),command:"deploy",useRuntimeStage:!1}),s=await q(b(e,"--base-url")??t.baseUrl),a=await new N({baseUrl:s.baseUrl,token:s.token}).putManifest(n,I(e,"--prune"),I(e,"--rotate-key"));await He(n,a.ids,process.cwd(),o,a.deployment,r),await po(),H(`Synced ${a.manifest.resources.length} resources to ${n.project}/${n.stage}`),await to(a.deployment),io(r,a),oo(a)}async function to(e){if(!e)return;if(e.apiKey){await $e("BROODS_API_KEY",e.apiKey),H(`Wrote BROODS_API_KEY (${e.keyHint}) to .env.local`);return}}function oo(e){let n=e.warnings?.missingPolicies??[];if(n.length>0)x(`${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)x(`Kept on prune, a reserved sandbox instance is still live: ${t.join(", ")}. Terminate it from the dashboard, then deploy again.`)}async function fi(){let e=await Tn({maxAgeMs:0});if(e===null)throw Error("Could not reach the npm registry to check for a newer broods.");if(!Pn(e,ae)){console.log(`broods v${ae} is already the newest release.`);return}let n=Gt(),t=Ue(ae),o=Ue(e)===t,r=o?e:`the newest ${t}.x`;if(console.log(`Updating broods ${ae} → ${r} ${n.global?"globally":"in this project"}`),console.log(`$ ${[n.command,...n.args].join(" ")}`),await new Promise((s,i)=>{let a=Zt(n.command,n.args,{cwd:n.cwd,stdio:"inherit",shell:process.platform==="win32"});a.on("error",i),a.on("exit",(c)=>{if(c===0){s();return}i(Error(`${n.command} exited with code ${c??"unknown"}`))})}),console.log(`broods ${o?e:`${t}.x`} installed.`),!o)x(`broods ${e} is a new major version. Install broods@${Ue(e)} yourself to move to it.`)}async function Ht(){let e=await Tn();if(e===null||!Pn(e,ae))return;x(`broods ${e} is out, you are on ${ae}. Run \`broods update\`.`)}async function mi(e){if(await wi(e),I(e,"--once")){if(!process.env.BROODS_SUPPRESS_DEV_TARGET)await zt(e),await Ht();let u=Kt.now();await Pi(e),Pt(Kt.now()-u);return}let n=Le(Vs(),`broods-declined-${process.pid}.txt`),t={...process.env,BROODS_DECLINED_FILE:n,BROODS_SUPPRESS_DEV_TARGET:"1",BROODS_RELOAD_ENV:"1"};await zt(e),await Ht();let o,r=!1,s=!1,i,a=async()=>{let u=await Ji();if(u===i)return;await xi(e,t),i=u},c=(u)=>console.error(u instanceof Error?u.message:String(u));await a().catch(c);let d=()=>{if(r){s=!0;return}r=!0,a().catch(c).finally(()=>{if(r=!1,s)s=!1,d()})},l=Hs(P(process.cwd(),y),{recursive:!0},(u,S)=>{if(!S||qi(S))return;clearTimeout(o),o=setTimeout(d,150)}),p=new AbortController;hi(e,p.signal),process.on("SIGINT",()=>{p.abort(),l.close(),process.exit(0)})}async function hi(e,n){let t;try{t=await sn(e)}catch(r){console.log(`· live logs off. ${r instanceof Error?r.message:String(r)}`);return}let o=Bn(e);try{for await(let r of Ve(t,{backfill:0,keepReconnecting:!0,minLevel:o,signal:n,onReconnect:Gn}))console.log(Wn(r))}catch(r){if(!n.aborted)console.error(`live logs: ${r instanceof Error?r.message:String(r)}`)}}async function wi(e){await yi(),await ro(!1),await vi(e)}async function ro(e){let n=process.cwd();if(!(await Promise.all([".agent",".agents",".claude","AGENTS.md","CLAUDE.md"].map((c)=>Vt(P(n,c))))).includes(!0))return;let r=P(n,en);if(!e&&await Vt(P(r,"SKILL.md")))return;let s=Le(en,"SKILL.md"),i=Le(en,"scripts","onboard.sh");for(let c of[s,i])if(await bi(n,c)){x(`Skipped the agent skill: ${c} crosses a symlink.`);return}await Ln(P(r,"scripts"),{recursive:!0}),await ye(P(r,"SKILL.md"),Wt);let a=P(r,"scripts","onboard.sh");await ye(a,Ft),await Ns(a,493),H(`Installed the broods agent skill at ${en}/`)}async function bi(e,n){let t=e;for(let o of n.split(Ks)){t=P(t,o);try{if((await Ls(t)).isSymbolicLink())return!0}catch{return!1}}return!1}async function Vt(e){try{return await Bs(e),!0}catch{return!1}}async function yi(){let e=P(process.cwd(),y);await Ln(P(e,_),{recursive:!0});let n=[];if(await Kn(e,n),n.length>0)return;await tn(P(e,"index.ts"),mo(),!1),await tn(P(e,".gitignore"),`_generated
|
|
396
396
|
.cache
|
|
397
|
-
`,!1),H(`Created starter ${y}/`)}async function
|
|
397
|
+
`,!1),H(`Created starter ${y}/`)}async function vi(e){let n=P(process.cwd(),".env.local"),t=await Ce(n),o=fo(t),r=o.BROODS_STAGE;if(["BROODS_DASHBOARD_URL","BROODS_BASE_URL","BROODS_PROJECT","BROODS_REGION"].filter((C)=>o[C]===void 0).length===0&&r!==void 0)return;let i=o.BROODS_PROJECT===void 0,a=r===void 0,c=o.BROODS_REGION===void 0,d=h(),l=b(e,"--dashboard-url")??d.dashboardUrl??oe,p=b(e,"--project")??process.env.BROODS_PROJECT??Re(process.cwd()),u=b(e,"--stage")??v()??"development",S=b(e,"--region")??process.env.BROODS_REGION??Ne;if(process.stdin.isTTY&&i){let C=await Be(l,b(e,"--base-url")),k=new N({baseUrl:C.baseUrl,token:C.token}),A=await ki(k,C),V=await Ci(k,A);if(p=await Ai(V,p),!p.trim())throw Error("Project name is required.")}if(process.stdin.isTTY&&a){if(u=await be("Stage",u),!u.trim())throw Error("Stage is required.")}if(process.stdin.isTTY&&c){let C=[...Js];S=await _e("Select service region",C,(k)=>k.label,C.findIndex((k)=>k.region===S)).then((k)=>k.region)}await Fn({dashboardUrl:l,baseUrl:d.baseUrl??L(l),project:p,stage:u,region:S,force:!1})}async function Be(e,n){try{return await q(n)}catch(t){if(!process.stdin.isTTY)throw t;return x(`${t instanceof Error?t.message:String(t)} Starting browser login.`),await Sn(e)}}async function ki(e,n){try{return await e.getOnboarding()}catch(t){if(!(t instanceof Je)||!n.org)throw t;return x("This broods server cannot list your orgs yet; using the org from your login."),{currentOrgId:n.org.id,orgs:[{id:n.org.id,name:n.org.name,slug:n.org.slug,role:"admin",accountStatus:"active"}],projects:[]}}}async function Yt(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)x("BROODS_TOKEN is set, so the switch applies to this token only and was not stored.");else await W({...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: ${Me(r)}`),console.log(`Projects: ${t.projects.length>0?t.projects.map((s)=>s.name).join(", "):"none yet"}`),await _n(e,rn(o))}async function _n(e,n){let t;try{t=await e.getRuntimeKey(n.project,n.stage)}catch(r){x(`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){x(`${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=M("BROODS_API_KEY");if(!o&&process.env.BROODS_API_KEY===t.apiKey)return;await $e("BROODS_API_KEY",t.apiKey),H(`Wrote BROODS_API_KEY (${t.keyHint}) to .env.local`),Dn("BROODS_API_KEY",o)}function Dn(e,n){if(!n)return;x(`${e} is exported in your shell, which wins over .env.local. Run \`unset ${e}\` or the next broods command keeps the old value.`)}function Me(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 Ei(e){return e.slug===e.name?e.name:`${e.name} (${e.slug})`}function Un(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 Si(e,n){let t=e.empty?"empty":Un(e);return Se(`${e.name}: ${t}`,e.name===n||e.slug===n)}function $i(e,n){return Se(so(e),Nn(e.name,n))}function so(e){let n=e.deploymentRegion?`, ${e.deploymentRegion}`:"";return`${e.name} (${e.kind}${n}): ${e.agentCount} agent(s), ${e.variableCount} env var(s)`}function Nn(e,n){return e.trim().toLowerCase()===n.trim().toLowerCase()}function rn(e){return h(),{project:b(e,"--project")??process.env.BROODS_PROJECT??Re(process.cwd()),stage:b(e,"--stage")??v()??"development"}}async function Ci(e,n){let t=n.orgs.filter((s)=>s.accountStatus==="active"),o={kind:"create",name:"New organization"},r=await _e("Select organization",[...t,o],(s)=>("kind"in s)?"Create new organization":Me(s),t.findIndex((s)=>s.id===n.currentOrgId));if("kind"in r){let s=await be("Organization name",Re(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 Ri(e,n){return e.projects.find((o)=>o.name===n||o.slug===n)?.name??n}function Oi(e,n){return e.projects.find((t)=>t.name===n||t.slug===n)}async function Ai(e,n){let t=Ri(e,n);if(e.projects.length===0)return be("Project name",t);for(;;){let o=await Dt("Select project",e.projects,Ei,{hint:"type a new project name",defaultValue:t}),r=typeof o==="string"?o:o.name,s=Oi(e,r);if(!s)return r;if(await Qe(`Continue with the existing project ${s.name}?`))return s.name}}function xi(e,n){return new Promise((t,o)=>{let r=process.argv[1]??"",s=Zt(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 Pi(e){let n=await le({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),t=await q(b(e,"--base-url")??n.config.baseUrl),o=new N({baseUrl:t.baseUrl,token:t.token}),r=await ao(o,n.manifest,await Mn(o,n.manifest));if(r.length>0)En(r);for(let s=1;;s+=1)try{return await Ti(o,n)}catch(i){if(!(i instanceof ze)||s===zs)throw i;x("Stage changed in another session. Re-reading...")}}async function Ti(e,n){let{manifest:t,resourceAliases:o,channels:r}=n,s=await e.getManifest(t.project,t.stage),i=yn(t,s?.manifest??null);Xe(i.filter((u)=>u.operation!=="delete"));let a=await e.putManifest(t,!1,!1,s===null?0:s.revision);await He(t,a.ids,process.cwd(),o,a.deployment,r),await po();let c=await Di(),d=i.filter((u)=>u.operation==="delete"),l=d.filter((u)=>!c.has(`${u.kind}:${u.name}`)),p=!1;if(l.length>0)if(x("These remote resources are no longer declared locally:"),Xe(l),await Qe(`Delete ${l.length} resource(s) from ${t.project}/${t.stage}?`))a=await e.putManifest(t,!0,!1,a.revision),await He(t,a.ids,process.cwd(),o,a.deployment,r),await Ni(),p=!0;else await Ui(l.map((u)=>`${u.kind}:${u.name}`));if(!p&&d.length>0){let u=d.map((S)=>`${S.kind}:${S.name}`).join(", ");x(`${d.length} undeclared resource(s) kept remotely: ${u}. Re-declare in code or run \`deploy --prune\` to remove.`)}return await to(a.deployment),io(r,a),oo(a),a}function io(e,n){let t=n.deployment;if(!t||e.length===0)return;let o=new B,r=new Map;for(let i of e){if(!n.ids.agents[i.agentName])continue;let a=r.get(i.type)??[];a.push(i.alias),r.set(i.type,a)}let s=t.stageKind===void 0||t.stageKind==="production";for(let[i,a]of r){let c=s?o.accountWebhookUrl(t.accountId,i):o.stageWebhookUrl(t.accountId,t.endpointId,i);console.log(`Channel ${a.join(", ")} (${i}): ${c}${i==="pancake"?"?secret=<PANCAKE_WEBHOOK_SECRET>":""}`)}}async function Mn(e,n){let t=gt(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:Ii(r,o)}))}async function ao(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 ji(e,n){let t=nn(e,"drifted");if(t.length>0)x(`.env.local and ${n} disagree on ${t.length} variable(s): ${t.join(", ")}. Run \`broods env sync\` to push the local values.`)}function Ii(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===_i(t)?"synced":"drifted"}function _i(e){return qt("sha256").update(e).digest("hex")}function nn(e,n){return e.filter((t)=>t.state===n).map((t)=>t.name)}async function zt(e){let n=h(),{manifest:t,config:o}=await le({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),r=await q(b(e,"--base-url")??o.baseUrl);At({project:t.project,stage:t.stage,dashboardUrl:b(e,"--dashboard-url")??n.dashboardUrl??r.dashboardUrl??o.dashboardUrl??oe})}async function Di(){let e=process.env.BROODS_DECLINED_FILE;if(!e)return new Set;let n=await Ce(e);return new Set(n.split(/\r?\n/).map((t)=>t.trim()).filter(Boolean))}async function Ui(e){let n=process.env.BROODS_DECLINED_FILE;if(!n||e.length===0)return;await ye(n,`${e.join(`
|
|
398
398
|
`)}
|
|
399
|
-
`,{flag:"a"})}async function
|
|
399
|
+
`,{flag:"a"})}async function Ni(){let e=process.env.BROODS_DECLINED_FILE;if(!e)return;await ye(e,"","utf8")}async function Li(e){let[n,t]=te(e);if(!n){console.log(ve("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}
|
|
400
400
|
|
|
401
401
|
${Z("env")}`);if(a&&!t)throw Error(`broods env ${n} needs a variable name.
|
|
402
402
|
|
|
403
|
-
${Z("env")}`);let{manifest:c,config:d}=await le({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),l=await q(b(e,"--base-url")??d.baseUrl),p=new N({baseUrl:l.baseUrl,token:l.token}),u=`${c.project}/${c.stage}`;if(i){await
|
|
403
|
+
${Z("env")}`);let{manifest:c,config:d}=await le({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),l=await q(b(e,"--base-url")??d.baseUrl),p=new N({baseUrl:l.baseUrl,token:l.token}),u=`${c.project}/${c.stage}`;if(i){await Mi(p,c,u);return}if(o){let C=await p.listEnv(c.project,c.stage);if(C.length===0){console.log(`No environment variables set for ${u}.`);return}console.log(`Environment variables for ${u} (values hidden):`);for(let k of C)console.log(` ${k.name}`);return}if(s){let C=await p.getEnv(c.project,c.stage,t);if(C===null){console.error(`${t} is not set for ${u}`),process.exitCode=1;return}console.log(C);return}if(r){await p.removeEnv(c.project,c.stage,t),H(`Removed ${t} from ${u}`);return}let S=await _t(t);await p.setEnv(c.project,c.stage,t,S),H(`Stored ${t} for ${u}`)}async function Mi(e,n,t){let o=await Mn(e,n);if(o.length===0){console.log('No env("NAME") references in this project.');return}let r=await ao(e,n,o);if(r.length>0)En(r);let s=nn(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=nn(o,"stage-only");if(i.length>0)console.log(`${i.length} referenced variable(s) live only on ${t}: ${i.join(", ")}`);let a=nn(o,"unresolved");if(a.length>0)x(`${a.length} referenced variable(s) with no value here or on ${t}: ${a.join(", ")}. Put them in .env.local, or run \`broods env set <NAME> --stage ${n.stage}\`.`)}function Bn(e){if(I(e,"--all"))return"DEBUG";let n=b(e,"--level");if(n===void 0&&I(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 Bi(e){h();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 sn(e){let n=await Bi(e),t=h(),o=await Be(b(e,"--dashboard-url")??t.dashboardUrl??oe,b(e,"--base-url")),r=new N({baseUrl:o.baseUrl,token:o.token}),s=await r.mintStageSession(n.project,n.stage),i=s,a=async()=>{let c=i??await r.mintStageSession(n.project,n.stage);return i=void 0,c.token};return{baseUrl:o.baseUrl,credential:a,project:s.projectSlug,stage:s.stageSlug}}function co(e){return e==="WARN"?" (--all for INFO too)":""}function Gn(e,n){console.error(je(`Reconnecting to live logs (attempt ${e}): ${n}`,{stream:"stderr"}))}function Wn(e){let n=new Date(e.ts).toISOString().slice(11,23),t=e.level.padEnd(5),o=Ys(e.message);return`${n} ${t} ${e.eventType} ${o}`}async function Gi(e){let n=await sn(e),{project:t,stage:o}=n,r=Bn(e),s=new AbortController,i=()=>s.abort();process.on("SIGINT",i),console.log(`Streaming live logs for ${t}/${o} [${r}+]`+co(r)+", Ctrl+C to stop");try{for await(let a of Ve(n,{backfill:0,minLevel:r,signal:s.signal,onReconnect:Gn}))console.log(Wn(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 Wi(e){if(I(e,"--doctor")){await Fi(I(e,"--request"));return}let n=te(e)[0];if(!n){console.log(ve("machine",e));return}let{runMachineDaemon:t}=await import("../chunk-17zpcz3t.js"),{baseUrl:o,credential:r}=await sn(e),s=P(b(e,"--cwd")??process.cwd()),i=I(e,"--computer"),a=b(e,"--mcp"),c=I(e,"--force"),d=new AbortController,l=()=>d.abort();process.on("SIGINT",l),console.log(`Connecting ${n} to ${o} (cwd ${s}${i?", computer use on":""}), Ctrl+C to stop`);try{await t({baseUrl:o,computer:i,credential:r,cwd:s,force:c,log:(p)=>console.log(p),mcpFile:a?P(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",l)}}async function Fi(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 Ki(e){let n=await sn(e),{project:t,stage:o}=n,r=b(e,"--sandbox");if(I(e,"--sandbox")&&!G(r))throw Error("--sandbox needs the instance log id, the UUID shown in the dashboard Instances sheet.");let s=r?"DEBUG":Bn(e),i=Number(b(e,"--limit")??b(e,"-n")??100),a=I(e,"--json"),c=new AbortController,d=()=>c.abort();process.on("SIGINT",d),console.log(`Logs for ${t}/${o}`+(r?` sandbox ${r}`:"")+` [${s}+]`+co(s)+` (backfill ${i}), Ctrl+C to stop`);try{for await(let l of Ve(n,{backfill:i,minLevel:s,...r?{sandboxId:r}:{},signal:c.signal,onReconnect:Gn}))if(a)console.log(JSON.stringify(l));else console.log(Wn(l))}catch(l){if(!c.signal.aborted)console.error(l instanceof Error?l.message:String(l)),process.exitCode=1}finally{process.off("SIGINT",d)}}async function Hi(e){let[n,t]=te(e);if(!n){console.log(ve("agent",e));return}if(n==="list"||n==="ls"){await Vi(e);return}if(n==="get"){await Yi(t,e);return}throw Error(`Unknown agent subcommand: ${n}
|
|
404
404
|
|
|
405
|
-
${Z("agent")}`)}async function
|
|
405
|
+
${Z("agent")}`)}async function lo(e){let{manifest:n,config:t}=await le({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),o=await q(b(e,"--base-url")??t.baseUrl),r=await new N({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 Vi(e){let{manifest:n,agents:t}=await lo(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=uo(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 Yi(e,n){if(!e)throw Error(`Missing agent name.
|
|
406
406
|
|
|
407
|
-
${Z("agent")}`);let{manifest:t,agents:o}=await
|
|
407
|
+
${Z("agent")}`);let{manifest:t,agents:o}=await lo(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,S)=>S===0?`${u} (default)`:u),a=Array.isArray(s.workspaces)?s.workspaces.map((u)=>typeof u==="string"?u:u.name).filter(Boolean):[],c=we(s.tools)?Object.keys(s.tools):[],d=we(s.channels)?Object.keys(s.channels):[],l=we(s.subagent)&&Array.isArray(s.subagent.allowed)?s.subagent.allowed.map((u)=>typeof u==="string"?u:u.name).filter(Boolean):[],p=we(s.hooks)&&Array.isArray(s.hooks.webhooks)?s.hooks.webhooks.filter(we):[];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: ${uo(s)}`),console.log(` Sandboxes: ${i.length>0?i.join(", "):"none"}`),console.log(` Workspaces: ${a.length>0?a.join(", "):"none"}`),console.log(` Tools: ${c.length>0?c.join(", "):"none"}`),console.log(` Subagents: ${l.length>0?l.join(", "):"none"}`),console.log(` Channels: ${d.length>0?d.join(", "):"none"}`),p.length>0)console.log(" Webhooks:"),p.forEach((u,S)=>{let C=Array.isArray(u.events)&&u.events.length>0?u.events.join(", "):"all events",k=u.enabled===!1?"disabled":"enabled",A=typeof u.url==="string"?u.url:"none";console.log(` [${S}] ${k} → ${A} (${C})`)})}function uo(e){let n=we(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 zi(e){let[n,...t]=te(e);if(!n)throw Error(`Missing agent name.
|
|
408
408
|
|
|
409
|
-
${Z("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 le({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),a=await q(b(e,"--base-url")??i.baseUrl),c=s.resources.find((A)=>A.kind==="agent"&&A.name===n);if(!c)throw Error(`Unknown local agent: ${n}`);let l=(await new N({baseUrl:a.baseUrl,token:a.token}).getManifest(s.project,s.stage))?.ids.agents[n];if(!l)throw Error(`Agent ${n} is not synced yet. Run broods dev --once or broods deploy first.`);let p=await new N({baseUrl:a.baseUrl,token:a.token}).getRuntimeKey(s.project,s.stage).catch(()=>null);if(p?.apiKey)await $e("BROODS_API_KEY",p.apiKey);if(c.config.publicAccess!==!0)x(`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
|
|
409
|
+
${Z("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 le({project:b(e,"--project"),stage:b(e,"--stage"),command:"dev"}),a=await q(b(e,"--base-url")??i.baseUrl),c=s.resources.find((A)=>A.kind==="agent"&&A.name===n);if(!c)throw Error(`Unknown local agent: ${n}`);let l=(await new N({baseUrl:a.baseUrl,token:a.token}).getManifest(s.project,s.stage))?.ids.agents[n];if(!l)throw Error(`Agent ${n} is not synced yet. Run broods dev --once or broods deploy first.`);let p=await new N({baseUrl:a.baseUrl,token:a.token}).getRuntimeKey(s.project,s.stage).catch(()=>null);if(p?.apiKey)await $e("BROODS_API_KEY",p.apiKey);if(c.config.publicAccess!==!0)x(`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 B({baseUrl:b(e,"--base-url")??process.env.BROODS_BASE_URL??process.env.BROODS_HOST??a.baseUrl,...p?.apiKey?{apiKey:p.apiKey}:{}}),S={kind:"agent",name:n,id:l,project:s.project,stage:s.stage,...p?.endpointId?{endpointId:p.endpointId}:{},...p?.projectSlug?{projectSlug:p.projectSlug}:{},...p?.stageSlug?{stageSlug:p.stageSlug}:{}},{runAgentTui:C,streamAgentText:k}=await import("../chunk-5esx8msr.js");try{if(r){await C({client:u,agent:S,...o?{prompt:o}:{}});return}await k({client:u,agent:S,prompt:o})}catch(A){if((A instanceof Error?A.message:String(A)).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 A}}async function tn(e,n,t){try{await ye(e,n,{flag:t?"w":"wx"})}catch(o){if(o.code==="EEXIST")return;throw o}}async function go(){let e=P(process.cwd(),".gitignore"),n=await Ce(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()}
|
|
410
410
|
.env*.local
|
|
411
411
|
`:`.env*.local
|
|
412
|
-
`;await ye(e,o,"utf8")}async function
|
|
412
|
+
`;await ye(e,o,"utf8")}async function po(){let e=P(process.cwd(),y,".gitignore"),n=await Ce(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()+`
|
|
413
413
|
`+o.join(`
|
|
414
414
|
`)+`
|
|
415
415
|
`:o.join(`
|
|
416
416
|
`)+`
|
|
417
|
-
`;await ye(e,r,"utf8")}async function
|
|
417
|
+
`;await ye(e,r,"utf8")}async function Fn(e){let n=P(process.cwd(),".env.local"),t=await Ce(n),o=fo(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?$/,`
|
|
418
418
|
`).split(/\n/):["# Local broods CLI settings. Tokens are stored outside the repo."],i=!1;for(let[c,d]of Object.entries(r)){if(!d)continue;if(o[c]!==void 0&&!e.force)continue;let l=s.findIndex((p)=>p.trim().startsWith(`${c}=`));if(l>=0)s[l]=`${c}=${on(d)}`;else s.push(`${c}=${on(d)}`);if(process.env[c]===void 0)process.env[c]=d;i=!0}if(!i&&t)return;let a=`${s.filter((c,d,l)=>!(c===""&&d===l.length-1)).join(`
|
|
419
419
|
`)}
|
|
420
|
-
`;await K(n,a),await
|
|
420
|
+
`;await K(n,a),await go()}async function $e(e,n){let t=P(process.cwd(),".env.local"),o=await Ce(t),r=o?o.replace(/\n?$/,`
|
|
421
421
|
`).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}=${on(n)}`;else r.push(`${e}=${on(n)}`);process.env[e]=n;let i=`${r.filter((a,c,d)=>!(a===""&&c===d.length-1)).join(`
|
|
422
422
|
`)}
|
|
423
|
-
`;await K(t,i),await
|
|
423
|
+
`;await K(t,i),await go()}async function Ce(e){try{return await Jt(e,"utf8")}catch(n){if(n.code==="ENOENT")return"";throw n}}function fo(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 on(e){return JSON.stringify(e)}function Re(e){return Ws(P(e)).replace(/^@/,"").replace(/\//g,"-").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"broods-app"}async function Ji(){let e=P(process.cwd(),y),n=[];await Kn(e,n);let t=qt("sha256");for(let o of n.sort())t.update(Fs(e,o)),t.update("\x00"),t.update(await Jt(o)),t.update("\x00");return t.digest("hex")}async function Kn(e,n){let t=await Ms(e,{withFileTypes:!0});for(let o of t){let r=Le(e,o.name);if(o.isDirectory()){if(o.name===_||o.name==="generated"||o.name===".cache")continue;await Kn(r,n);continue}if(o.isFile()&&(o.name.endsWith(".ts")||o.name.endsWith(".md")))n.push(r)}}function qi(e){return e.split(/[\\/]/).some((n)=>n===_||n==="generated"||n===".cache")}function mo(){return`import { defineAgent, defineSandbox, env } from "broods";
|
|
424
424
|
|
|
425
425
|
// A Lambda sandbox: a fresh, ephemeral bash environment created per run.
|
|
426
426
|
export const lambdaSandbox = defineSandbox({
|
|
@@ -449,4 +449,4 @@ export const myAgent = defineAgent({
|
|
|
449
449
|
// only reachable via internal endpoints or channel webhooks.
|
|
450
450
|
publicAccess: true,
|
|
451
451
|
});
|
|
452
|
-
`}function
|
|
452
|
+
`}function Zi(){if("bun"in process.versions)return;if(typeof Gs.registerHooks==="function")return;throw Error(`broods needs Node ${De.engines.node.replace(">=","")} or newer, or Bun. This is Node ${process.version}.`)}function Xi(e,n){if(e==="status")throw Error("status was renamed to whoami. Run `broods whoami`.");if(I(n,"--env")||b(n,"--env")!==void 0)throw Error("--env was renamed to --stage. Pass --stage <name> instead.");h();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 Qi(){let e=h(),n=z(),[{createBroodsMcpServer:t},{serveStdio:o}]=await Promise.all([import("../chunk-m96g7766.js"),import("../chunk-0057x2fk.js")]),r=n?new N({baseUrl:n.baseUrl,token:n.token}):null,s=t({allowDestructive:process.env.BROODS_MCP_ALLOW_DESTRUCTIVE==="1"&&M("BROODS_MCP_ALLOW_DESTRUCTIVE"),cli:r,scope:{project:e.project,stage:e.stage}});o(()=>s),await new Promise((i)=>{process.stdin.on("close",i)})}Xs().catch((e)=>{xt(e instanceof Error?e.message:String(e)),process.exit(1)});export{se,fe,D};
|