broods 0.52.1 → 0.52.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- import{S,ne,re,ue}from"./chunk-9th6spww.js";var c=()=>{let a={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function n(t){return a[t]??null}let d={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(t)=>{switch(t.code){case"invalid_type":{let e=o[t.expected]??t.expected,r=ue(t.input),l=o[r]??r;return`Invalid input: expected ${e}, received ${l}`}case"invalid_value":if(t.values.length===1)return`Invalid input: expected ${re(t.values[0])}`;return`Invalid option: expected one of ${ne(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=n(t.origin);if(r)return`Too big: expected ${t.origin??"value"} to have ${e}${t.maximum.toString()} ${r.unit??"elements"}`;return`Too big: expected ${t.origin??"value"} to be ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=n(t.origin);if(r)return`Too small: expected ${t.origin} to have ${e}${t.minimum.toString()} ${r.unit}`;return`Too small: expected ${t.origin} to be ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;if(e.format==="starts_with")return`Invalid string: must start with "${e.prefix}"`;if(e.format==="ends_with")return`Invalid string: must end with "${e.suffix}"`;if(e.format==="includes")return`Invalid string: must include "${e.includes}"`;if(e.format==="regex")return`Invalid string: must match pattern ${e.pattern}`;return`Invalid ${d[e.format]??t.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${t.divisor}`;case"unrecognized_keys":return`Unrecognized key${t.keys.length>1?"s":""}: ${ne(t.keys,", ")}`;case"invalid_key":return`Invalid key in ${t.origin}`;case"invalid_union":if(t.options&&Array.isArray(t.options)&&t.options.length>0)return`Invalid discriminator value. Expected ${t.options.map((r)=>`'${r}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${t.origin}`;default:return"Invalid input"}}};function i(){return{localeError:c()}}S(i());
@@ -1,5 +0,0 @@
1
- function L(e){if(e.events&&e.input!==void 0)throw Error("Run input accepts either `input` or `events`, not both");if(e.events&&e.events.length>0)return e.events;if(typeof e.input==="string")return[{role:"user",content:[{type:"text",text:e.input}]}];throw Error("Run input requires `input` (string) or a non-empty `events` array")}async function*ae(e){let n=e.getReader(),t=new TextDecoder,o="";try{while(!0){let{done:r,value:i}=await n.read();if(r)break;o+=t.decode(i,{stream:!0});let s=o.split(`
2
- `);o=s.pop()??"";for(let a of s)if(a.startsWith("data: "))yield a.slice(6)}}finally{await n.cancel().catch(()=>{return}),n.releaseLock()}}var Se=500,mn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Cn=/^(?!0{32}$)[0-9a-f]{32}$/;function he(e){return e==="DEBUG"||e==="INFO"||e==="WARN"||e==="ERROR"}function be(e){if(typeof e!=="object"||e===null)return!1;let n=e;if(n.type==="subscribe")return hn(n);if(n.type==="unsubscribe")return q(n.stream);if(n.type==="fetchTrace")return F(n.traceId);return!1}function ve(e){return e==="task"||e==="cron"||e==="subtask"}function U(e){return typeof e==="string"&&mn.test(e)}function F(e){return typeof e==="string"&&Cn.test(e)}function q(e){return e==="logs"||e==="traces"}function hn(e){let n=e.stream;if(!q(n))return!1;let t=e.backfill;if(t!==void 0&&(typeof t!=="number"||!Number.isSafeInteger(t)||t<0||t>500))return!1;if(e.liveOnly!==void 0&&typeof e.liveOnly!=="boolean")return!1;let o=e.minLevel;if(o!==void 0&&!he(o))return!1;let r=e.sandboxId;return r===void 0||n==="logs"&&U(r)}import{readFileSync as Sn}from"node:fs";import{chmod as Q,mkdir as Rn,writeFile as bn}from"node:fs/promises";import{homedir as In}from"node:os";import{dirname as J,join as xn}from"node:path";var y="broods",v="_generated",x=xn(In(),".broods","config.json"),X="broods.app",Y="dashboard",kn="gateway";function T(e){let n=process.env.BROODS_TOKEN,t=e??process.env.BROODS_BASE_URL;if(n&&t)return{baseUrl:h(t),token:n,createdAt:new Date().toISOString()};let o=ne();if(!o)return null;if(t)return o.logins[h(t)]??null;let r=process.env.BROODS_DASHBOARD_URL;if(r){let i=h(r);return Object.values(o.logins).find((s)=>s.dashboardUrl===i)??null}return o.logins[o.current]??null}async function B(e){let n=ne()?.logins??{},t={current:e.baseUrl,logins:{...n,[e.baseUrl]:e}};await Rn(J(x),{recursive:!0,mode:448}),await Q(J(x),448),await H(x,`${JSON.stringify(t,null,2)}
3
- `)}async function H(e,n){await bn(e,n,{encoding:"utf8",mode:384}),await Q(e,384)}function b(){return process.env.BROODS_STAGE}function h(e){let n=e.length;while(n>0&&e.charCodeAt(n-1)===47)n-=1;return e.slice(0,n)}function M(e){try{let n=new URL(e);if(!n.hostname.startsWith(`${Y}.`))return;let t=n.hostname.slice(Y.length+1);if(t!==X&&!t.endsWith(`.${X}`))return;return n.hostname=`${kn}.${t}`,h(n.origin)}catch{return}}function ne(){try{let e=JSON.parse(Sn(x,"utf8"));if(typeof e.current!=="string"||!e.logins)return null;return{current:e.current,logins:e.logins}}catch{return null}}import{existsSync as re,readFileSync as ie,statSync as An}from"node:fs";import{join as se,resolve as ue}from"node:path";var O=new Map,vn=new Set(Object.keys(process.env)),oe=new Set;function m(e=process.cwd()){wn(e);let n=T();return{dashboardUrl:process.env.BROODS_DASHBOARD_URL??n?.dashboardUrl,baseUrl:process.env.BROODS_BASE_URL??n?.baseUrl,token:n?.token,project:process.env.BROODS_PROJECT,stage:b()}}function N(){let e={};for(let[n,t]of Object.entries(process.env))if(typeof t==="string"&&!n.startsWith("BROODS_"))e[n]=t;return e}function E(e,n=process.cwd()){let t=process.env[e];if(t===void 0)return!1;let o=ue(n);for(let r of[".env.local",".env"]){let i=se(o,r);if(!re(i))continue;let s=Z(ie(i,"utf8"));if(s[e]!==void 0)return s[e]!==t}return!0}function wn(e){let n=ue(e),t=process.env.BROODS_RELOAD_ENV==="1";for(let o of[".env",".env.local"]){let r=se(n,o);if(!re(r)){O.delete(r);continue}let i=An(r).mtimeMs,s=O.get(r);if(s&&s.mtimeMs===i)continue;O.set(r,{mtimeMs:i});for(let[a,c]of Object.entries(Z(ie(r,"utf8"))))if(t||!vn.has(a)||oe.has(a))process.env[a]=c,oe.add(a)}}function Z(e){let n={};for(let t of e.split(/\r?\n/)){let o=t.trim();if(!o||o.startsWith("#"))continue;let r=o.startsWith("export ")?o.slice(7).trim():o,i=r.indexOf("=");if(i<=0)continue;let s=r.slice(0,i).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))continue;n[s]=Tn(r.slice(i+1).trim())}return n}function Tn(e){if(e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1).replace(/\\n/g,`
4
- `).replace(/\\"/g,'"');if(e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);let n=e.indexOf(" #");return n>=0?e.slice(0,n).trimEnd():e}var P=new TextEncoder,le={name:"HMAC",hash:"SHA-256"};async function pe(e,n,t,o){let r=ge(P.encode(JSON.stringify(t))),i=await crypto.subtle.sign(le,await En(n,o),P.encode(r));return`${e}${r}.${ge(new Uint8Array(i))}`}function ge(e){let n="";for(let t of e)n+=String.fromCharCode(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function En(e,n){let t=await crypto.subtle.digest("SHA-256",P.encode(`${e}${n}`));return crypto.subtle.importKey("raw",t,le,!1,["sign","verify"])}var Nn="buat_",V="bsig_",ee="x-broods-user-token",de="broods.user.";var ye=600000,G=3600000,Dn="broods-user-token:",me=/^[A-Za-z0-9._@+=-]{1,128}$/,en=100,On=256,Mn=60000;async function nn(e,n,t=Date.now()){if(!n.startsWith(V))throw Error(`The user token signing secret must start with ${V}. It is not the bsk_ runtime key.`);let o=_n(e,t);if(!o||e.expiresAt>t+G)throw Error(`Invalid user token: userId must match ${me.source}, conversations must be at most ${en} non-empty keys, and expiresAt must be in the next ${G/60000} minutes.`);return await pe(Nn,Dn,o,n)}function _n(e,n){if(!e||typeof e!=="object")return null;let{userId:t,conversations:o,expiresAt:r}=e;if(typeof t!=="string"||!me.test(t)||typeof r!=="number"||!Number.isFinite(r)||r<=n||r>n+G+Mn)return null;if(o===void 0)return{userId:t,expiresAt:r};if(!Array.isArray(o)||o.length>en||!o.every((i)=>typeof i==="string"&&i.trim()===i&&i.length>0&&i.length<=On))return null;return{userId:t,conversations:o,expiresAt:r}}var g="BROODS_USER_TOKEN_SECRET";async function _e(e){let n=e.secret??process.env[g];if(!n)throw Error(`signUserToken needs the stage's signing secret: pass secret or set ${g}. \`broods dev\` and \`broods deploy\` write it to .env.local; the dashboard's Runtime key tab rotates it.`);return await nn({userId:e.userId,...e.conversations?{conversations:e.conversations}:{},expiresAt:Date.now()+(e.ttlMs??ye)},n)}var z="https://gateway.broods.app";class ce extends Error{accepted;constructor(e){super(`Ingress ${e.eventId} was accepted asynchronously with status ${e.status??"queued"}`);this.accepted=e;this.name="IngressAcceptedError"}}class j{baseUrl;apiKey;userToken;fetchImpl;constructor(e={}){m(),this.baseUrl=K(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||z),this.apiKey=e.apiKey||process.env.BROODS_API_KEY||void 0,this.userToken=e.userToken,this.fetchImpl=e.fetch??fetch}channelWebhookUrl(e){return`${this.baseUrl}${e.webhookPath.startsWith("/")?"":"/"}${e.webhookPath}`}accountWebhookUrl(e,n){let t=[e,n].map(encodeURIComponent);return`${this.baseUrl}/v1/webhooks/${t.join("/")}`}stageWebhookUrl(e,n,t){let o=[e,"dev",n,t].map(encodeURIComponent);return`${this.baseUrl}/v1/webhooks/${o.join("/")}`}agent(e,n){if(typeof e==="string"){let o=e,r=n??"";if(!r)throw Error(`Agent ${o} is missing a generated id. Run broods dev --once or broods deploy to sync it first.`);return{id:r,run:(i)=>this.run({...i,agentName:o,agentId:r}),runAsync:(i)=>this.runAsync({...i,agentName:o,agentId:r}),continue:(i)=>this.continue({...i,agentId:r}),stream:(i)=>this.stream({...i,agentName:o,agentId:r})}}let t=e;if(!t.id)throw Error(`Agent ${t.name} is missing a generated id. Run broods dev --once or broods deploy to sync it first.`);return{id:t.id,run:(o)=>this.run(t,o),runAsync:(o)=>this.runAsync(t,o),continue:(o)=>this.continue(t,o),stream:(o)=>this.stream(t,o)}}async run(e,n){let t=[],o="",r=n?this.stream(e,n):this.stream(e);for await(let i of r)if(t.push(i),i.type==="text-delta")o+=i.text;return{text:o,events:t}}async*stream(e,n){let t=n?{...n,agentId:e.id,agentName:e.name}:e,o=tn(t,"cli"),r=n?this.scopedUrl(e):`${this.baseUrl}/v1/runs`,i=await this.openStream(o,r);if(!i.ok)throw Error(`Run failed: ${i.status} ${await i.text()}`);if(i.status===202)throw new ce(on(await i.json(),o));if(!i.body)throw Error("Run response has no body");for await(let s of ae(i.body)){let a;try{a=JSON.parse(s)}catch{continue}if(a.type==="error")throw Error(`Agent run failed: ${Un(a.error)}`);yield a}}async runAsync(e,n){let t=n?{...n,agentId:e.id,agentName:e.name}:e,o={...tn(t,"async"),background:!0},r=n?this.scopedUrl(e):`${this.baseUrl}/v1/runs`;return this.postAcceptedRun(r,o,"Async run")}async continue(e,n){let t=n?e:null,o=n??e,r={agentId:t?t.id:e.agentId,eventId:o.eventId??`continue-${crypto.randomUUID()}`,conversationKey:o.conversationKey,continue:!0},i=t?this.scopedUrl(t):`${this.baseUrl}/v1/runs`;return this.postAcceptedRun(i,r,"Continue")}async getAsyncStatus(e){let n=this.resolveStatusUrl(e),t=await this.fetchJson(n,{method:"GET",headers:await this.apiKeyHeaders()});if(t.status===404)return{status:"not_found"};if(!t.ok)throw Error(`Status check failed: ${t.status} ${await t.text()}`);return await t.json()}async waitForAsyncStatus(e,n={}){let t=Date.now()+(n.timeoutMs??180000),o=n.intervalMs??2000;while(Date.now()<t){if(n.signal?.aborted)throw Error("Async status polling aborted.");let r=await this.getAsyncStatus(e);if(r.status==="awaiting_approval"||r.status==="awaiting_input"||r.status==="completed"||r.status==="failed"||r.status==="expired"||r.status==="not_found")return r;await Wn(o,n.signal)}throw Error("Polling timeout")}scopedUrl(e){if(e.projectSlug&&e.stageSlug&&e.endpointId)return`${this.baseUrl}/v1/projects/${encodeURIComponent(e.projectSlug)}/stages/${encodeURIComponent(e.stageSlug)}/agents/${encodeURIComponent(e.endpointId)}`;return`${this.baseUrl}/v1/runs`}asyncAgentRun(e,n){return{...e,conversationKey:n,poll:()=>this.getAsyncStatus(e),wait:(t)=>this.waitForAsyncStatus(e,t)}}async postAcceptedRun(e,n,t){let o=await this.fetchJson(e,{method:"POST",headers:await this.apiKeyHeaders(),body:JSON.stringify(n)});if(o.status!==202)throw Error(`${t} failed: ${o.status} ${await Pn(o,"202 JSON")}`);return this.asyncAgentRun(on(await o.json(),n),n.conversationKey)}async openStream(e,n){if(this.apiKey)return await this.fetchCore(e,n,{Authorization:`Bearer ${this.apiKey}`,...await this.userTokenHeaders()});throw Error(`BroodsClient streams directly from the core service at ${this.baseUrl}. Provide apiKey. For a self-hosted core service, set host/baseUrl or BROODS_HOST/BROODS_BASE_URL.`)}async fetchCore(e,n,t){try{return await this.fetchImpl(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t},body:JSON.stringify(e)})}catch(o){throw Error(`Cannot access the broods core service at ${n}. The SDK uses ${z} by default; set host/baseUrl or BROODS_HOST/BROODS_BASE_URL to your own core service URL if your account uses a custom deployment. Cause: ${o instanceof Error?o.message:String(o)}`)}}async apiKeyHeaders(){if(!this.apiKey)throw Error("BroodsClient requires apiKey or BROODS_API_KEY.");return{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...await this.userTokenHeaders()}}async userTokenHeaders(){let e=typeof this.userToken==="function"?await this.userToken():this.userToken;return e?{[ee]:e}:{}}async fetchJson(e,n){try{return await this.fetchImpl(e,n)}catch(t){throw Error(`Cannot access the broods core service at ${e}. Cause: ${t instanceof Error?t.message:String(t)}`)}}resolveStatusUrl(e){if(typeof e!=="string")return e.statusUrl;if(/^https?:\/\//.test(e))return e;return Kn(this.baseUrl,e)}}function K(e){let n=e.trim(),t=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(n)?n:`https://${n}`;return h(t)}function tn(e,n){let t=e.eventId??`${n}-${crypto.randomUUID()}`;return{agentId:e.agentId,eventId:t,conversationKey:e.conversationKey??t,events:L(e),...e.mode!==void 0?{mode:e.mode}:{},...e.idempotencyKey!==void 0?{idempotencyKey:e.idempotencyKey}:{},...e.system!==void 0?{system:e.system}:{},...e.model!==void 0?{model:e.model}:{}}}function Un(e){if(typeof e==="string")return e;if(!e||typeof e!=="object")return String(e);let n=e,t=n.data?.error?.message??n.message??n.responseBody??JSON.stringify(e),o=n.name?`${n.name}: `:"",r=n.statusCode?` (HTTP ${n.statusCode})`:"";return`${o}${t}${r}`}function on(e,n){if(!e||typeof e!=="object")throw Error("Async response must be an object");let t=e.statusUrl;if(typeof t!=="string"||t.length===0)throw Error("Async response missing statusUrl");let o=e.runId;if(typeof o!=="string"||o.length===0)throw Error("Async response missing runId");let r=typeof e.eventId==="string"?e.eventId:o,{status:i,requestedMode:s}=e;return{statusUrl:t,runId:o,eventId:r,agentId:n.agentId,...i==="accepted"||i==="queued"||i==="applied"||i==="processing"?{status:i}:{},...s==="reject"||s==="followup"||s==="collect"||s==="steer"?{requestedMode:s}:{}}}async function Pn(e,n){if((e.headers.get("content-type")??"").toLowerCase().includes("text/event-stream"))return await e.body?.cancel().catch(()=>{}),`expected ${n}, but the server returned an SSE stream. This usually means the core deployment ignored the background flag and ran the request on the direct streaming runner.`;let o=await e.text();if(o.length<=2000)return o;return`${o.slice(0,2000)}... [truncated ${o.length-2000} chars]`}function Wn(e,n){return new Promise((t,o)=>{if(n?.aborted){o(Error("Async status polling aborted."));return}let r=setTimeout(t,e);n?.addEventListener("abort",()=>{clearTimeout(r),o(Error("Async status polling aborted."))},{once:!0})})}function Kn(e,n){return`${K(e)}/v1/runs/${encodeURIComponent(n)}`}var Ln=2000,rn=0,I=1;class fe{baseUrl;apiKey;userToken;WebSocketImpl;connectTimeoutMs;constructor(e={}){if(m(),this.baseUrl=gn(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||z),this.apiKey=e.apiKey||process.env.BROODS_API_KEY||"",!this.apiKey)throw Error("BroodsWebSocketClient requires apiKey or BROODS_API_KEY.");this.userToken=e.userToken,this.WebSocketImpl=e.WebSocket,this.connectTimeoutMs=e.connectTimeoutMs??Ln}subscribe(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=$n(e),i=un(this.baseUrl),s=new t(o,k(this.apiKey,e.userToken??this.userToken)),a=!1,c=!1,d=setTimeout(()=>{if(!a)R(i)},this.connectTimeoutMs),C=(p=1000,w="client closed")=>{if(c)return;if(c=!0,clearTimeout(d),e.signal?.removeEventListener("abort",A),s.readyState===I||s.readyState===rn)s.close(p,w)},R=(p)=>{n.onError?.(p),C(1000,"websocket error")},yn=()=>{n.onDone?.(),C(1000,"done")},A=()=>{if(s.readyState===I)s.send(JSON.stringify({type:"cancel"}));R(Error("WebSocket run aborted."))};return e.signal?.addEventListener("abort",A,{once:!0}),s.onopen=()=>{if(a=!0,clearTimeout(d),e.signal?.aborted){A();return}s.send(JSON.stringify({type:"execute",agentId:r,...e.answers?{answers:e.answers}:{events:L(e)},sessionId:e.sessionId,...e.eventId!==void 0?{eventId:e.eventId}:{},...e.mode!==void 0?{mode:e.mode}:{},...e.idempotencyKey!==void 0?{idempotencyKey:e.idempotencyKey}:{},...e.system!==void 0?{system:e.system}:{},...e.model!==void 0?{model:e.model}:{}}))},s.onmessage=(p)=>{if(typeof p.data!=="string")return;let w=an(p.data);if(!w)return;let D=cn(w,n);switch(n.onMessage?.(D),D.type){case"meta":n.onMeta?.(D);break;case"done":yn();break;case"error":R(Error(sn(D.error)));break}},s.onerror=()=>{R(i)},s.onclose=(p)=>{if(clearTimeout(d),e.signal?.removeEventListener("abort",A),c||p.code===1000)return;R(Error(p.reason||"WebSocket connection closed."))},{url:o,sendControl:function(p){if(s.readyState!==I)throw Error("WebSocket is not open");s.send(JSON.stringify({type:"control",...p}))},close:C}}attach(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=new t(o,k(this.apiKey,e.userToken??this.userToken)),i=!1,s=(c=1000,d="client closed")=>{if(i)return;if(i=!0,e.signal?.removeEventListener("abort",a),r.readyState===I||r.readyState===rn)r.close(c,d)},a=()=>{s(1000,"aborted"),n.onError?.(Error("WebSocket attach aborted."))};if(e.signal?.aborted)a();else e.signal?.addEventListener("abort",a,{once:!0});return r.onopen=()=>{if(i)return;r.send(JSON.stringify({type:"attach",...e,signal:void 0,agent:void 0,userToken:void 0}))},r.onmessage=(c)=>{if(i||typeof c.data!=="string")return;let d=an(c.data);if(!d)return;let C=cn(d,n);if(i)return;if(n.onMessage?.(C),i)return;if(C.type==="done")n.onDone?.();if(C.type==="error")n.onError?.(Error(sn(C.error)))},r.onerror=()=>{if(i)return;s(1000,"websocket error"),n.onError?.(un(this.baseUrl))},r.onclose=(c)=>{if(e.signal?.removeEventListener("abort",a),!i&&c.code!==1000)n.onError?.(Error(c.reason||"WebSocket connection closed."))},{url:o,sendControl:function(c){if(r.readyState!==I)throw Error("WebSocket is not open");r.send(JSON.stringify({type:"control",...c}))},close:s}}async*stream(e){let n=[],t=!1,o=null,r=null,i=()=>{r?.(),r=null},s=this.subscribe(e,{onMessage:function(a){n.push(a),i()},onDone:function(){t=!0,i()},onError:function(a){o=a,i()}});try{while(!0){if(n.length>0){yield n.shift();continue}if(o)throw o;if(t)return;await new Promise((a)=>{r=a})}}finally{s.close()}}buildUrl(e){let n=Bn(e),t=e.projectSlug??e.agent?.projectSlug,o=e.stageSlug??e.agent?.stageSlug,r=t&&o?`/projects/${encodeURIComponent(t)}/stages/${encodeURIComponent(o)}`:"";return`${W(this.baseUrl)}/v1${r}/agents/${encodeURIComponent(n)}/ws`}resolveWebSocket(){let e=this.WebSocketImpl??globalThis.WebSocket;if(!e)throw Error("WebSocket is not available. Pass a WebSocket implementation in BroodsWebSocketClient options.");return e}}function W(e){let n=new URL(gn(e));if(n.protocol==="https:")n.protocol="wss:";if(n.protocol==="http:")n.protocol="ws:";return h(n.toString())}function k(e,n){return["broods.v1",`broods.token.${e}`,...n?[`${de}${n}`]:[]]}function sn(e){if(typeof e==="string")return e;if(e&&typeof e==="object"&&typeof e.message==="string")return e.message;return e===void 0?"WebSocket stream error.":JSON.stringify(e)}function gn(e){let n=e.trim();if(/^wss?:\/\//.test(n))return h(n);return K(n)}function an(e){try{let n=JSON.parse(e);return typeof n==="object"&&n!==null&&typeof n.type==="string"?n:null}catch{return null}}function $n(e){let n=e.agentId??e.agent?.id??e.endpointId;if(!n)throw Error("WebSocket run requires agent, agentId, or endpointId.");return n}function Bn(e){let n=e.endpointId??e.agent?.endpointId??e.agent?.id;if(!n)throw Error("WebSocket run requires agent or endpointId.");return n}function cn(e,n){if(e.type!=="output")return e;let t=e;return n.onOutput?.(t),t.data}function un(e){return Error(`Cannot access the WebSocket service at ${e}.`)}var pn=Symbol.for("broods.resource"),dn=Symbol.for("broods.config"),fn=Symbol.for("broods.connection"),ln=/^[A-Z][A-Z0-9_]{0,63}$/,we=new Proxy((e)=>{if(!ln.test(e))throw Error("env name must match /^[A-Z][A-Z0-9_]*$/ and be at most 64 characters.");return{__beeblastEnv:!0,name:e}},{get:function(e,n,t){if(typeof n==="string"&&ln.test(n))throw Error(`env.${n} is not supported; use env("${n}")`);return Reflect.get(e,n,t)}});function Re(e){let{name:n,description:t,...o}=e;return S("agent",n,t,o)}function $e(e){return{[dn]:!0,config:e}}function Ce(e){let{name:n,description:t,...o}=e;return S("cron",n,t,o)}function Ee(e){return e}function ke(e){let{name:n,description:t,...o}=e;return S("mcp",n,t,o)}function Te(e){let{name:n,description:t,...o}=e;return S("policy",n,t,o)}function ze(e){let{name:n,description:t,...o}=e;return S("sandbox",n,t,o)}function Pe(e){let{name:n,description:t,...o}=e;return S("skill",n,t,o)}function Ie(e){let{name:n,description:t,...o}=e;return S("workspace",n,t,o)}function xe(e){return l("discord",e)}function Ae(e){return l("github",e)}function Oe(e){return l("gchat",e)}function Me(e){return l("instagram",e)}function Ne(e){return l("linear",e)}function je(e){return l("matrix",e)}function qe(e){return l("messenger",e)}function De(e){return l("pancake",e)}function Le(e){return l("slack",e)}function Ue(e){return l("teams",e)}function Fe(e){return l("telegram",e)}function Be(e){return l("twilio",e)}function He(e){return l("whatsapp",e)}function Ze(e){return l("zalo",e)}function Ve(e){let{name:n,description:t,channelId:o,guildId:r,...i}=e;return u(n,t,o,r,i)}function Ge(e){let{name:n,description:t,repo:o,...r}=e,[i,...s]=o.split("/");if(!i||s.length!==1||!s[0])throw Error(`Channel "${n}" repo must be "owner/name", not "${o}"`);return u(n,t,o,i,r)}function Ke(e){let{name:n,description:t,spaceName:o,...r}=e;return u(n,t,o,void 0,r)}function We(e){let{name:n,description:t,igsid:o,...r}=e;return u(n,t,o,void 0,r)}function Je(e){let{name:n,description:t,team:o,...r}=e;return u(n,t,o,void 0,r)}function Ye(e){let{name:n,description:t,channelId:o,...r}=e;return u(n,t,o,void 0,r)}function Xe(e){let{name:n,description:t,psid:o,...r}=e;return u(n,t,o,void 0,r)}function Qe(e){let{name:n,description:t,conversationId:o,...r}=e;return u(n,t,o,void 0,r)}function et(e){let{name:n,description:t,channelId:o,teamId:r,...i}=e;return u(n,t,o,r,i)}function tt(e){let{name:n,description:t,channelId:o,teamId:r,...i}=e;return u(n,t,o,r,i)}function nt(e){let{name:n,description:t,chatId:o,...r}=e;return u(n,t,o,void 0,r)}function rt(e){let{name:n,description:t,from:o,...r}=e;return u(n,t,o,void 0,r)}function ot(e){let{name:n,description:t,waId:o,...r}=e;return u(n,t,o,void 0,r)}function st(e){let{name:n,description:t,chatId:o,...r}=e;return u(n,t,o,void 0,r)}function te(e){return Boolean(e&&typeof e==="object"&&e[dn])}function _(e){return Boolean(e&&typeof e==="object"&&e[fn])}function f(e){return Boolean(e&&typeof e==="object"&&e[pn])}function u(e,n,t,o,r){return S("channelRecord",e,n,{...r,externalId:t,...o?{workspaceRef:o}:{}})}function l(e,n){let{partition:t,...o}=n;return{[fn]:!0,kind:"connection",type:e,...t?{partition:t}:{},config:o}}function S(e,n,t,o){return{[pn]:!0,kind:e,name:n,...t?{description:t}:{},config:o}}
5
- export{L,ae,Se,he,be,ve,U,F,y,v,x,T,B,H,b,h,M,m,N,E,Z,V,ee,G,g,_e,z,ce,j,K,fe,W,k,we,Re,$e,Ce,Ee,ke,Te,ze,Pe,Ie,xe,Ae,Oe,Me,Ne,je,qe,De,Le,Ue,Fe,Be,He,Ze,Ve,Ge,Ke,We,Je,Ye,Xe,Qe,et,tt,nt,rt,ot,st,te,_,f};
File without changes