broods 0.14.0 → 0.17.4

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{Q as a}from"./chunk-4gvdgqrg.js";import"./chunk-pfhy5049.js";export default a();
@@ -1,2 +0,0 @@
1
- import{R as c,T as s}from"./chunk-pfhy5049.js";var g=c(function(pr,A){var{defineProperty:w,getOwnPropertyDescriptor:ne,getOwnPropertyNames:se}=Object,ie=Object.prototype.hasOwnProperty,ae=(e,r)=>{for(var t in r)w(e,t,{get:r[t],enumerable:!0})},ce=(e,r,t,n)=>{if(r&&typeof r==="object"||typeof r==="function"){for(let o of se(r))if(!ie.call(e,o)&&o!==t)w(e,o,{get:()=>r[o],enumerable:!(n=ne(r,o))||n.enumerable})}return e},ue=(e)=>ce(w({},"__esModule",{value:!0}),e),D={};ae(D,{VercelOidcTokenError:()=>x});A.exports=ue(D);class x extends Error{constructor(e,r){super(e);this.name="VercelOidcTokenError",this.cause=r}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var R=c(function(lr,C){var{create:pe,defineProperty:h,getOwnPropertyDescriptor:le,getOwnPropertyNames:fe,getPrototypeOf:_e}=Object,de=Object.prototype.hasOwnProperty,he=(e,r)=>{for(var t in r)h(e,t,{get:r[t],enumerable:!0})},S=(e,r,t,n)=>{if(r&&typeof r==="object"||typeof r==="function"){for(let o of fe(r))if(!de.call(e,o)&&o!==t)h(e,o,{get:()=>r[o],enumerable:!(n=le(r,o))||n.enumerable})}return e},P=(e,r,t)=>(t=e!=null?pe(_e(e)):{},S(r||!e||!e.__esModule?h(t,"default",{value:e,enumerable:!0}):t,e)),ve=(e)=>S(h({},"__esModule",{value:!0}),e),V={};he(V,{findRootDir:()=>we,getUserDataDir:()=>ge});C.exports=ve(V);var f=P(s("path")),ke=P(s("fs")),O=P(s("os")),ye=g();function we(){try{let e=process.cwd();while(e!==f.default.dirname(e)){let r=f.default.join(e,".vercel");if(ke.default.existsSync(r))return e;e=f.default.dirname(e)}}catch(e){throw new ye.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function ge(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(O.default.platform()){case"darwin":return f.default.join(O.default.homedir(),"Library/Application Support");case"linux":return f.default.join(O.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var J=c(function(fr,U){var{create:Oe,defineProperty:v,getOwnPropertyDescriptor:Pe,getOwnPropertyNames:be,getPrototypeOf:je}=Object,Te=Object.prototype.hasOwnProperty,Ee=(e,r)=>{for(var t in r)v(e,t,{get:r[t],enumerable:!0})},M=(e,r,t,n)=>{if(r&&typeof r==="object"||typeof r==="function"){for(let o of be(r))if(!Te.call(e,o)&&o!==t)v(e,o,{get:()=>r[o],enumerable:!(n=Pe(r,o))||n.enumerable})}return e},I=(e,r,t)=>(t=e!=null?Oe(je(e)):{},M(r||!e||!e.__esModule?v(t,"default",{value:e,enumerable:!0}):t,e)),me=(e)=>M(v({},"__esModule",{value:!0}),e),N={};Ee(N,{isValidAccessToken:()=>Se,readAuthConfig:()=>xe,writeAuthConfig:()=>Ae});U.exports=me(N);var _=I(s("fs")),q=I(s("path")),De=L();function F(){let e=(0,De.getVercelDataDir)();if(!e)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return q.join(e,"auth.json")}function xe(){try{let e=F();if(!_.existsSync(e))return null;let r=_.readFileSync(e,"utf8");if(!r)return null;return JSON.parse(r)}catch(e){return null}}function Ae(e){let r=F(),t=q.dirname(r);if(!_.existsSync(t))_.mkdirSync(t,{mode:504,recursive:!0});_.writeFileSync(r,JSON.stringify(e,null,2),{mode:384})}function Se(e,r=0){if(!e.token)return!1;if(typeof e.expiresAt!=="number")return!0;let t=Math.floor(Date.now()/1000),n=r/1000;return e.expiresAt>=t+n}});var G=c(function(_r,z){var{defineProperty:T,getOwnPropertyDescriptor:Ve,getOwnPropertyNames:Ce}=Object,Re=Object.prototype.hasOwnProperty,Me=(e,r)=>{for(var t in r)T(e,t,{get:r[t],enumerable:!0})},Ie=(e,r,t,n)=>{if(r&&typeof r==="object"||typeof r==="function"){for(let o of Ce(r))if(!Re.call(e,o)&&o!==t)T(e,o,{get:()=>r[o],enumerable:!(n=Ve(r,o))||n.enumerable})}return e},Ne=(e)=>Ie(T({},"__esModule",{value:!0}),e),B={};Me(B,{processTokenResponse:()=>Je,refreshTokenRequest:()=>Ue});z.exports=Ne(B);var b=s("os"),qe="https://vercel.com",Fe="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",H=`@vercel/oidc node-${process.version} ${(0,b.platform)()} (${(0,b.arch)()}) ${(0,b.hostname)()}`,j=null;async function $e(){if(j)return j;let e=`${qe}/.well-known/openid-configuration`,r=await fetch(e,{headers:{"user-agent":H}});if(!r.ok)throw Error("Failed to discover OAuth endpoints");let t=await r.json();if(!t||typeof t.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let n=t.token_endpoint;return j=n,n}async function Ue(e){let r=await $e();return await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":H},body:new URLSearchParams({client_id:Fe,grant_type:"refresh_token",...e})})}async function Je(e){let r=await e.json();if(!e.ok){let t=typeof r==="object"&&r&&"error"in r?String(r.error):"Token refresh failed";return[Error(t)]}if(typeof r!=="object"||r===null)return[Error("Invalid token response")];if(typeof r.access_token!=="string")return[Error("Missing access_token in response")];if(r.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof r.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,r]}});var K=c(function(dr,Z){var{defineProperty:E,getOwnPropertyDescriptor:Le,getOwnPropertyNames:Be}=Object,He=Object.prototype.hasOwnProperty,ze=(e,r)=>{for(var t in r)E(e,t,{get:r[t],enumerable:!0})},Ge=(e,r,t,n)=>{if(r&&typeof r==="object"||typeof r==="function"){for(let o of Be(r))if(!He.call(e,o)&&o!==t)E(e,o,{get:()=>r[o],enumerable:!(n=Le(r,o))||n.enumerable})}return e},Xe=(e)=>Ge(E({},"__esModule",{value:!0}),e),X={};ze(X,{AccessTokenMissingError:()=>Y,RefreshAccessTokenFailedError:()=>Q});Z.exports=Xe(X);class Y extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login).");this.name="AccessTokenMissingError"}}class Q extends Error{constructor(e){super("Failed to refresh authentication token.",{cause:e});this.name="RefreshAccessTokenFailedError"}}});var L=c(function(hr,oe){var{create:Ye,defineProperty:k,getOwnPropertyDescriptor:Qe,getOwnPropertyNames:Ze,getPrototypeOf:Ke}=Object,We=Object.prototype.hasOwnProperty,er=(e,r)=>{for(var t in r)k(e,t,{get:r[t],enumerable:!0})},ee=(e,r,t,n)=>{if(r&&typeof r==="object"||typeof r==="function"){for(let o of Ze(r))if(!We.call(e,o)&&o!==t)k(e,o,{get:()=>r[o],enumerable:!(n=Qe(r,o))||n.enumerable})}return e},re=(e,r,t)=>(t=e!=null?Ye(Ke(e)):{},ee(r||!e||!e.__esModule?k(t,"default",{value:e,enumerable:!0}):t,e)),rr=(e)=>ee(k({},"__esModule",{value:!0}),e),te={};er(te,{assertVercelOidcTokenResponse:()=>m,findProjectInfo:()=>sr,getTokenPayload:()=>cr,getVercelDataDir:()=>tr,getVercelOidcToken:()=>nr,getVercelToken:()=>or,isExpired:()=>ur,loadToken:()=>ar,saveToken:()=>ir});oe.exports=rr(te);var d=re(s("path")),i=re(s("fs")),l=g(),y=R(),u=J(),W=G(),p=K();function tr(){let r=(0,y.getUserDataDir)();if(!r)return null;return d.join(r,"com.vercel.cli")}async function or(e){let r=(0,u.readAuthConfig)();if(!r?.token)throw new p.AccessTokenMissingError;if((0,u.isValidAccessToken)(r,e?.expirationBufferMs))return r.token;if(!r.refreshToken)throw(0,u.writeAuthConfig)({}),new p.RefreshAccessTokenFailedError("No refresh token available");try{let t=await(0,W.refreshTokenRequest)({refresh_token:r.refreshToken}),[n,o]=await(0,W.processTokenResponse)(t);if(n||!o)throw(0,u.writeAuthConfig)({}),new p.RefreshAccessTokenFailedError(n);let a={token:o.access_token,expiresAt:Math.floor(Date.now()/1000)+o.expires_in};if(o.refresh_token)a.refreshToken=o.refresh_token;return(0,u.writeAuthConfig)(a),a.token}catch(t){if((0,u.writeAuthConfig)({}),t instanceof p.AccessTokenMissingError||t instanceof p.RefreshAccessTokenFailedError)throw t;throw new p.RefreshAccessTokenFailedError(t)}}async function nr(e,r,t){let n=`https://api.vercel.com/v1/projects/${r}/token?source=vercel-oidc-refresh${t?`&teamId=${t}`:""}`,o=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new l.VercelOidcTokenError(`Failed to refresh OIDC token: ${o.statusText}`);let a=await o.json();return m(a),a}function m(e){if(!e||typeof e!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in e)||typeof e.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function sr(){let e=(0,y.findRootDir)();if(!e)throw new l.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let r=d.join(e,".vercel","project.json");if(!i.existsSync(r))throw new l.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let t=JSON.parse(i.readFileSync(r,"utf8"));if(typeof t.projectId!=="string"&&typeof t.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:t.projectId,teamId:t.orgId}}function ir(e,r){let t=(0,y.getUserDataDir)();if(!t)throw new l.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let n=d.join(t,"com.vercel.token",`${r}.json`),o=JSON.stringify(e);i.mkdirSync(d.dirname(n),{mode:504,recursive:!0}),i.writeFileSync(n,o),i.chmodSync(n,432);return}function ar(e){let r=(0,y.getUserDataDir)();if(!r)throw new l.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let t=d.join(r,"com.vercel.token",`${e}.json`);if(!i.existsSync(t))return null;let n=JSON.parse(i.readFileSync(t,"utf8"));return m(n),n}function cr(e){let r=e.split(".");if(r.length!==3)throw new l.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let t=r[1].replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(t.length+(4-t.length%4)%4,"=");return JSON.parse(Buffer.from(n,"base64").toString("utf8"))}function ur(e,r=0){return e.exp*1000<Date.now()+r}});
2
- export{g as P,L as Q};
@@ -1,5 +0,0 @@
1
- function b(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*E(e){let n=e.getReader(),t=new TextDecoder,o="";try{while(!0){let{done:r,value:s}=await n.read();if(r)break;o+=t.decode(s,{stream:!0});let i=o.split(`
2
- `);o=i.pop()??"";for(let a of i)if(a.startsWith("data: "))yield a.slice(6)}}finally{n.releaseLock()}}import{mkdir as X,readFile as Q,writeFile as ee}from"node:fs/promises";import{homedir as ne}from"node:os";import{dirname as te,join as oe}from"node:path";var ve="broods",Ee="_generated",m=oe(ne(),".broods","config.json"),D="broods.app",T="dashboard",re="gateway";async function De(){let e=process.env.BROODS_TOKEN,n=process.env.BROODS_BASE_URL;if(e&&n)return{baseUrl:g(n),token:e,createdAt:new Date().toISOString()};try{let t=JSON.parse(await Q(m,"utf8"));if(typeof t.baseUrl!=="string"||!t.baseUrl)return null;return t}catch{return null}}async function Te(e){await X(te(m),{recursive:!0}),await ee(m,`${JSON.stringify(e,null,2)}
3
- `,"utf8")}function O(){return process.env.BROODS_STAGE}function g(e){let n=e.length;while(n>0&&e.charCodeAt(n-1)===47)n-=1;return e.slice(0,n)}function Oe(e){try{let n=new URL(e);if(!n.hostname.startsWith(`${T}.`))return;let t=n.hostname.slice(T.length+1);if(t!==D&&!t.endsWith(`.${D}`))return;return n.hostname=`${re}.${t}`,g(n.origin)}catch{return}}import{existsSync as P,readFileSync as v,statSync as se}from"node:fs";import{join as U,resolve as W}from"node:path";var x=new Map,ie=new Set(Object.keys(process.env)),N=new Set;function k(e=process.cwd()){ae(e);let n=le();return{dashboardUrl:process.env.BROODS_DASHBOARD_URL??n?.dashboardUrl,baseUrl:process.env.BROODS_BASE_URL??n?.baseUrl,token:process.env.BROODS_TOKEN??n?.token,project:process.env.BROODS_PROJECT,stage:O()}}function Me(e,n=process.cwd()){let t=process.env[e];if(t===void 0)return!1;let o=W(n);for(let r of[".env.local",".env"]){let s=U(o,r);if(!P(s))continue;let i=M(v(s,"utf8"));if(i[e]!==void 0)return i[e]!==t}return!0}function ae(e){let n=W(e),t=process.env.BROODS_RELOAD_ENV==="1";for(let o of[".env",".env.local"]){let r=U(n,o);if(!P(r)){x.delete(r);continue}let s=se(r).mtimeMs,i=x.get(r);if(i&&i.mtimeMs===s)continue;x.set(r,{mtimeMs:s});for(let[a,l]of Object.entries(M(v(r,"utf8"))))if(t||!ie.has(a)||N.has(a))process.env[a]=l,N.add(a)}}function M(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,s=r.indexOf("=");if(s<=0)continue;let i=r.slice(0,s).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))continue;n[i]=ce(r.slice(s+1).trim())}return n}function ce(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}function le(){try{let e=JSON.parse(v(m,"utf8"));if(typeof e.baseUrl!=="string"||typeof e.token!=="string")return null;return{baseUrl:g(e.baseUrl),...typeof e.dashboardUrl==="string"?{dashboardUrl:g(e.dashboardUrl)}:{},token:e.token}}catch{return null}}var A="https://gateway.broods.app";class H extends Error{accepted;constructor(e){super(`Ingress ${e.eventId} was accepted asynchronously with status ${e.status??"queued"}`);this.accepted=e;this.name="IngressAcceptedError"}}class ge{baseUrl;apiKey;fetchImpl;constructor(e={}){k(),this.baseUrl=w(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||A),this.apiKey=e.apiKey||process.env.BROODS_API_KEY||void 0,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}/webhooks/${t.join("/")}`}stageWebhookUrl(e,n,t){let o=[e,"dev",n,t].map(encodeURIComponent);return`${this.baseUrl}/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:(s)=>this.run({...s,agentName:o,agentId:r}),runAsync:(s)=>this.runAsync({...s,agentName:o,agentId:r}),stream:(s)=>this.stream({...s,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),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 s of r)if(t.push(s),s.type==="text-delta")o+=s.text;return{text:o,events:t}}async*stream(e,n){let t=n?{...n,agentId:e.id,agentName:e.name}:e,o=_(t,"cli"),r=n?this.scopedUrl(e):this.baseUrl,s=await this.openStream(o,r);if(!s.ok)throw Error(`Run failed: ${s.status} ${await s.text()}`);if(s.status===202)throw new H(K(await s.json(),o));if(!s.body)throw Error("Run response has no body");for await(let i of E(s.body)){let a;try{a=JSON.parse(i)}catch{continue}if(a.type==="error")throw Error(`Agent run failed: ${me(a.error)}`);yield a}}async runAsync(e,n){let t=n?{...n,agentId:e.id,agentName:e.name}:e,o=_(t,"async"),r=n?this.scopedUrl(e,"/async"):`${this.baseUrl}/async`,s=await this.fetchJson(r,{method:"POST",headers:this.apiKeyHeaders(),body:JSON.stringify(o)});if(s.status!==202)throw Error(`Async run failed: ${s.status} ${await pe(s,"202 JSON")}`);let i=K(await s.json(),o);return{...i,conversationKey:o.conversationKey,poll:()=>this.getAsyncStatus(i),wait:(a)=>this.waitForAsyncStatus(i,a)}}async getAsyncStatus(e,n={}){let t=this.resolveStatusUrl(e,n),o=await this.fetchJson(t,{method:"GET",headers:this.apiKeyHeaders()});if(o.status===404)return{status:"not_found"};if(!o.ok)throw Error(`Status check failed: ${o.status} ${await o.text()}`);return await o.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,n);if(r.status==="awaiting_approval"||r.status==="completed"||r.status==="failed"||r.status==="expired"||r.status==="not_found")return r;await ye(o,n.signal)}throw Error("Polling timeout")}async createCron(e){let n=await this.fetchJson(`${this.baseUrl}/v1/crons`,{method:"POST",headers:this.apiKeyHeaders(),body:JSON.stringify(fe(e))});if(n.status!==201)throw Error(`Create cron job failed: ${n.status} ${await p(n)}`);return await n.json()}async listCrons(){let e=await this.fetchJson(`${this.baseUrl}/v1/crons`,{method:"GET",headers:this.apiKeyHeaders()});if(!e.ok)throw Error(`List cron jobs failed: ${e.status} ${await p(e)}`);return(await e.json()).crons}async getCron(e){let n=await this.fetchJson(`${this.baseUrl}/v1/crons/${encodeURIComponent(e)}`,{method:"GET",headers:this.apiKeyHeaders()});if(n.status===404)return null;if(!n.ok)throw Error(`Get cron job failed: ${n.status} ${await p(n)}`);return await n.json()}async listCronRuns(e,n={}){let t=new URLSearchParams;if(n.limit!==void 0)t.set("limit",String(n.limit));let o=t.size>0?`?${t}`:"",r=await this.fetchJson(`${this.baseUrl}/v1/crons/${encodeURIComponent(e)}/runs${o}`,{method:"GET",headers:this.apiKeyHeaders()});if(!r.ok)throw Error(`List cron job runs failed: ${r.status} ${await p(r)}`);return(await r.json()).runs}async updateCron(e,n){let t=await this.fetchJson(`${this.baseUrl}/v1/crons/${encodeURIComponent(e)}`,{method:"PATCH",headers:this.apiKeyHeaders(),body:JSON.stringify(n)});if(!t.ok)throw Error(`Update cron job failed: ${t.status} ${await p(t)}`);return await t.json()}async deleteCron(e){let n=await this.fetchJson(`${this.baseUrl}/v1/crons/${encodeURIComponent(e)}`,{method:"DELETE",headers:this.apiKeyHeaders()});if(n.status===404)return!1;if(!n.ok)throw Error(`Delete cron job failed: ${n.status} ${await p(n)}`);return(await n.json()).deleted}scopedUrl(e,n=""){if(e.projectSlug&&e.stageSlug&&e.endpointId)return`${this.baseUrl}/v1/${encodeURIComponent(e.projectSlug)}/agents/${encodeURIComponent(e.stageSlug)}/${encodeURIComponent(e.endpointId)}${n}`;return`${this.baseUrl}${n}`}async openStream(e,n){if(this.apiKey)return await this.fetchCore(e,n,{Authorization:`Bearer ${this.apiKey}`});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 ${A} 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)}`)}}apiKeyHeaders(){if(!this.apiKey)throw Error("BroodsClient requires apiKey or BROODS_API_KEY.");return{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}}async fetchJson(e,n){try{return await this.fetchImpl(e,{...n,headers:{"Content-Type":"application/json",...n.headers??{}}})}catch(t){throw Error(`Cannot access the broods core service at ${e}. Cause: ${t instanceof Error?t.message:String(t)}`)}}resolveStatusUrl(e,n){if(typeof e!=="string")return e.statusUrl;if(/^https?:\/\//.test(e))return e;if(!n.agentId)throw Error("Polling by status id requires agentId.");return de(this.baseUrl,e,n.agentId)}}function w(e){let n=e.trim(),t=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(n)?n:`https://${n}`;return g(t)}function _(e,n){let t=e.eventId??`${n}-${Date.now()}`;return{agentId:e.agentId,eventId:t,conversationKey:e.conversationKey??t,events:b(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 K(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=ue(t);if(!o.statusId)throw Error("Async response statusUrl missing status id");let r=typeof e.eventId==="string"?e.eventId:o.statusId,s=e.status,i=e.requestedMode;return{statusUrl:t,statusId:o.statusId,eventId:r,agentId:o.agentId??n.agentId,...s==="accepted"||s==="queued"||s==="applied"||s==="processing"?{status:s}:{},...i==="reject"||i==="followup"||i==="collect"||i==="steer"?{requestedMode:i}:{}}}function ue(e){let n=new URL(e),t=n.pathname.match(/\/status\/([^/]+)$/);return{statusId:t?.[1]?decodeURIComponent(t[1]):void 0,agentId:n.searchParams.get("agentId")??void 0}}function de(e,n,t){return`${w(e)}/status/${encodeURIComponent(n)}?agentId=${encodeURIComponent(t)}`}async function pe(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 routed /async to the direct streaming runner instead of the async handler.`;let o=await e.text();if(o.length<=2000)return o;return`${o.slice(0,2000)}... [truncated ${o.length-2000} chars]`}async function p(e){let n=await e.text();if(n.includes("Request body must include eventId and conversationKey"))return`${n}. Cron job APIs must be served by the configured baseUrl. Prefer defining stable cron jobs with defineCron(...) in broods/ and syncing with \`broods dev\` or \`broods deploy\`.`;return n}function fe(e){if("agentId"in e)return e;let n=e.agent,t=typeof n==="string"?n:n.id,{agent:o,...r}=e;return{...r,agentId:t}}function ye(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 me(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}`}var he=2000,B=0,h=1;class Se{baseUrl;apiKey;WebSocketImpl;connectTimeoutMs;constructor(e={}){if(k(),this.baseUrl=J(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||A),this.apiKey=e.apiKey||process.env.BROODS_API_KEY||"",!this.apiKey)throw Error("BroodsWebSocketClient requires apiKey or BROODS_API_KEY.");this.WebSocketImpl=e.WebSocket,this.connectTimeoutMs=e.connectTimeoutMs??he}subscribe(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=Re(e),s=j(this.baseUrl),i=new t(o),a=!1,l=!1,u=setTimeout(()=>{if(!a)y(s)},this.connectTimeoutMs),I=(c=1000,R="client closed")=>{if(l)return;if(l=!0,clearTimeout(u),e.signal?.removeEventListener("abort",S),i.readyState===h||i.readyState===B)i.close(c,R)},y=(c)=>{n.onError?.(c),I(1011,"websocket error")},Y=()=>{n.onDone?.(),I(1000,"done")},S=()=>{if(i.readyState===h)i.send(JSON.stringify({type:"cancel"}));y(Error("WebSocket run aborted."))};return e.signal?.addEventListener("abort",S,{once:!0}),i.onopen=()=>{if(a=!0,clearTimeout(u),e.signal?.aborted){S();return}i.send(JSON.stringify({type:"execute",agentId:r,events:b(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}:{}}))},i.onmessage=(c)=>{if(typeof c.data!=="string")return;let R=G(c.data);if(!R)return;let C=L(R,n);switch(n.onMessage?.(C),C.type){case"meta":n.onMeta?.(C);break;case"done":Y();break;case"error":y(Error(q(C.error)));break}},i.onerror=()=>{y(s)},i.onclose=(c)=>{if(clearTimeout(u),e.signal?.removeEventListener("abort",S),l||c.code===1000)return;y(Error(c.reason||"WebSocket connection closed."))},{url:o,sendControl:function(c){if(i.readyState!==h)throw Error("WebSocket is not open");i.send(JSON.stringify({type:"control",...c}))},close:I}}attach(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=new t(o),s=!1,i=(a=1000,l="client closed")=>{if(s)return;if(s=!0,r.readyState===h||r.readyState===B)r.close(a,l)};return r.onopen=()=>r.send(JSON.stringify({type:"attach",...e,signal:void 0,agent:void 0})),r.onmessage=(a)=>{if(typeof a.data!=="string")return;let l=G(a.data);if(!l)return;let u=L(l,n);if(n.onMessage?.(u),u.type==="done")n.onDone?.();if(u.type==="error")n.onError?.(Error(q(u.error)))},r.onerror=()=>n.onError?.(j(this.baseUrl)),r.onclose=(a)=>{if(!s&&a.code!==1000)n.onError?.(Error(a.reason||"WebSocket connection closed."))},{url:o,sendControl:function(a){if(r.readyState!==h)throw Error("WebSocket is not open");r.send(JSON.stringify({type:"control",...a}))},close:i}}async*stream(e){let n=[],t=!1,o=null,r=null,s=()=>{r?.(),r=null},i=this.subscribe(e,{onMessage:function(a){n.push(a),s()},onDone:function(){t=!0,s()},onError:function(a){o=a,s()}});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{i.close()}}buildUrl(e){let n=Ce(e),t=e.projectSlug??e.agent?.projectSlug,o=e.stageSlug??e.agent?.stageSlug,r=t?`/${t}`:"",s=o?`/${o}`:"";return`${be(this.baseUrl)}/v1${r}/agents${s}/${encodeURIComponent(n)}/ws?token=${encodeURIComponent(this.apiKey)}`}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 Re(e){let n=e.agentId??e.agent?.id??e.endpointId;if(!n)throw Error("WebSocket run requires agent, agentId, or endpointId.");return n}function Ce(e){let n=e.endpointId??e.agent?.endpointId??e.agent?.id;if(!n)throw Error("WebSocket run requires agent or endpointId.");return n}function be(e){let n=new URL(J(e));if(n.protocol==="https:")n.protocol="wss:";if(n.protocol==="http:")n.protocol="ws:";return g(n.toString())}function J(e){let n=e.trim();if(/^wss?:\/\//.test(n))return g(n);return w(n)}function j(e){return Error(`Cannot access the WebSocket service at ${e}.`)}function L(e,n){if(e.type!=="output")return e;let t=e;return n.onOutput?.(t),t.data}function G(e){try{let n=JSON.parse(e);return typeof n==="object"&&n!==null&&typeof n.type==="string"?n:null}catch{return null}}function q(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)}var Z=Symbol.for("broods.resource"),z=Symbol.for("broods.config"),V=Symbol.for("broods.channel"),F=/^[A-Z][A-Z0-9_]{0,63}$/,Ze=new Proxy((e)=>{if(!F.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"&&F.test(n))throw Error(`env.${n} is not supported; use env("${n}")`);return Reflect.get(e,n,t)}});function d(e,n,t,o){return{[Z]:!0,kind:e,name:n,...t?{description:t}:{},config:o}}function f(e,n){let{workspaceScope:t,...o}=n;return{[V]:!0,kind:"channel",type:e,...t?{workspaceScope:t}:{},config:{...o,...t?{workspaceScope:t}:{}}}}function ze(e){return f("telegram",e)}function Ve(e){return f("github",e)}function Ye(e){return f("slack",e)}function Xe(e){return f("discord",e)}function Qe(e){return f("pancake",e)}function en(e){return f("zalo",e)}function nn(e){return{[z]:!0,config:e}}function tn(e){let{name:n,description:t,...o}=e;return d("agent",n,t,o)}function on(e){return e}function rn(e){let{name:n,description:t,...o}=e;return d("workspace",n,t,o)}function sn(e){let{name:n,description:t,...o}=e;return d("sandbox",n,t,o)}function an(e){let{name:n,description:t,...o}=e;return d("skill",n,t,o)}function cn(e){let{name:n,...t}=e;return d("tool",n,void 0,t)}function ln(e){let{name:n,description:t,...o}=e;return d("policy",n,t,o)}function gn(e){let{name:n,description:t,...o}=e;return d("channelRecord",n,t,o)}function un(e){let{name:n,description:t,...o}=e;return d("cron",n,t,o)}function dn(e){return Boolean(e&&typeof e==="object"&&e[Z])}function pn(e){return Boolean(e&&typeof e==="object"&&e[V])}function fn(e){return Boolean(e&&typeof e==="object"&&e[z])}
5
- export{b as d,E as e,ve as f,Ee as g,m as h,De as i,Te as j,O as k,g as l,Oe as m,k as n,Me as o,A as p,H as q,ge as r,w as s,Se as t,be as u,Ze as v,ze as w,Ve as x,Ye as y,Xe as z,Qe as A,en as B,nn as C,tn as D,on as E,rn as F,sn as G,an as H,cn as I,ln as J,gn as K,un as L,dn as M,pn as N,fn as O};
@@ -1,2 +0,0 @@
1
- import{createRequire as g}from"node:module";var d=Object.defineProperty;var h=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports);var e=(b)=>b;function f(b,a){this[b]=e.bind(null,a)}var i=(b,a)=>{for(var c in a)d(b,c,{get:a[c],enumerable:!0,configurable:!0,set:f.bind(a,c)})};var k=g(import.meta.url);
2
- export{h as R,i as S,k as T};
@@ -1 +0,0 @@
1
- import{P as _,Q as k}from"./chunk-4gvdgqrg.js";import{R as s}from"./chunk-pfhy5049.js";var T=s(function(w,f){var{defineProperty:i,getOwnPropertyDescriptor:l,getOwnPropertyNames:u}=Object,d=Object.prototype.hasOwnProperty,O=(t,e)=>{for(var o in e)i(t,o,{get:e[o],enumerable:!0})},j=(t,e,o,n)=>{if(e&&typeof e==="object"||typeof e==="function"){for(let r of u(e))if(!d.call(t,r)&&r!==o)i(t,r,{get:()=>e[r],enumerable:!(n=l(e,r))||n.enumerable})}return t},v=(t)=>j(i({},"__esModule",{value:!0}),t),p={};O(p,{refreshToken:()=>y});f.exports=v(p);var c=_(),a=k();async function y(t){let e=t?.project,o=t?.team;if(!e&&!o){let r=(0,a.findProjectInfo)();e=r.projectId,o=r.teamId}else if(!e||!o){let r=(0,a.findProjectInfo)();e=e??r.projectId,o=o??r.teamId}if(!e)throw new c.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let n=(0,a.loadToken)(e);if(!n||(0,a.isExpired)((0,a.getTokenPayload)(n.token),t?.expirationBufferMs)){let r=await(0,a.getVercelToken)({expirationBufferMs:t?.expirationBufferMs});if(n=await(0,a.getVercelOidcToken)(r,e,o),!n)throw new c.VercelOidcTokenError("Failed to refresh OIDC token");(0,a.saveToken)(n,e)}process.env.VERCEL_OIDC_TOKEN=n.token;return}});export default T();