broods 0.36.2 → 0.37.1

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,5 +1,5 @@
1
- function W(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*Se(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()}}var Me=500,ge=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,le=/^(?!0{32}$)[0-9a-f]{32}$/;function xe(e){return e==="DEBUG"||e==="INFO"||e==="WARN"||e==="ERROR"}function Ae(e){if(typeof e!=="object"||e===null)return!1;let n=e;if(n.type==="subscribe")return de(n);if(n.type==="unsubscribe")return D(n.stream);if(n.type==="fetchTrace")return $e(n.traceId);return!1}function ze(e){return e==="task"||e==="cron"||e==="subtask"}function G(e){return typeof e==="string"&&ge.test(e)}function $e(e){return typeof e==="string"&&le.test(e)}function D(e){return e==="logs"||e==="traces"}function de(e){let n=e.stream;if(!D(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&&!xe(o))return!1;let r=e.sandboxId;return r===void 0||n==="logs"&&G(r)}import{mkdir as pe,readFile as fe,writeFile as ye}from"node:fs/promises";import{homedir as me}from"node:os";import{dirname as be,join as Re}from"node:path";var v="broods",w="_generated",k=Re(me(),".broods","config.json"),T="broods.app",M="dashboard",he="gateway";async function K(){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 fe(k,"utf8"));if(typeof t.baseUrl!=="string"||!t.baseUrl)return null;return t}catch{return null}}async function J(e){await pe(be(k),{recursive:!0}),await ye(k,`${JSON.stringify(e,null,2)}
3
- `,"utf8")}function _(){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 ae(e){try{let n=new URL(e);if(!n.hostname.startsWith(`${M}.`))return;let t=n.hostname.slice(M.length+1);if(t!==T&&!t.endsWith(`.${T}`))return;return n.hostname=`${he}.${t}`,g(n.origin)}catch{return}}import{existsSync as B,readFileSync as O,statSync as Ce}from"node:fs";import{join as H,resolve as L}from"node:path";var E=new Map,Ie=new Set(Object.keys(process.env)),U=new Set;function f(e=process.cwd()){ve(e);let n=Te();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:_()}}function N(e,n=process.cwd()){let t=process.env[e];if(t===void 0)return!1;let o=L(n);for(let r of[".env.local",".env"]){let s=H(o,r);if(!B(s))continue;let i=j(O(s,"utf8"));if(i[e]!==void 0)return i[e]!==t}return!0}function ve(e){let n=L(e),t=process.env.BROODS_RELOAD_ENV==="1";for(let o of[".env",".env.local"]){let r=H(n,o);if(!B(r)){E.delete(r);continue}let s=Ce(r).mtimeMs,i=E.get(r);if(i&&i.mtimeMs===s)continue;E.set(r,{mtimeMs:s});for(let[a,u]of Object.entries(j(O(r,"utf8"))))if(t||!Ie.has(a)||U.has(a))process.env[a]=u,U.add(a)}}function j(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]=Ee(r.slice(s+1).trim())}return n}function Ee(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 Te(){try{let e=JSON.parse(O(k,"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 P="https://gateway.broods.app";class we extends Error{accepted;constructor(e){super(`Ingress ${e.eventId} was accepted asynchronously with status ${e.status??"queued"}`);this.accepted=e;this.name="IngressAcceptedError"}}class F{baseUrl;apiKey;fetchImpl;constructor(e={}){f(),this.baseUrl=Y(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||P),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}/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:(s)=>this.run({...s,agentName:o,agentId:r}),runAsync:(s)=>this.runAsync({...s,agentName:o,agentId:r}),continue:(s)=>this.continue({...s,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),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 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=q(t,"cli"),r=n?this.scopedUrl(e):`${this.baseUrl}/v1/runs`,s=await this.openStream(o,r);if(!s.ok)throw Error(`Run failed: ${s.status} ${await s.text()}`);if(s.status===202)throw new we(Z(await s.json(),o));if(!s.body)throw Error("Run response has no body");for await(let i of Se(s.body)){let a;try{a=JSON.parse(i)}catch{continue}if(a.type==="error")throw Error(`Agent run failed: ${Pe(a.error)}`);yield a}}async runAsync(e,n){let t=n?{...n,agentId:e.id,agentName:e.name}:e,o={...q(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},s=t?this.scopedUrl(t):`${this.baseUrl}/v1/runs`;return this.postAcceptedRun(s,r,"Continue")}async getAsyncStatus(e){let n=this.resolveStatusUrl(e),t=await this.fetchJson(n,{method:"GET",headers: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 tn(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(en(e))});if(n.status!==201)throw Error(`Create cron job failed: ${n.status} ${await n.text()}`);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 e.text()}`);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 n.text()}`);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 r.text()}`);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 t.text()}`);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 n.text()}`);return(await n.json()).deleted}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:this.apiKeyHeaders(),body:JSON.stringify(n)});if(o.status!==202)throw Error(`${t} failed: ${o.status} ${await nn(o,"202 JSON")}`);return this.asyncAgentRun(Z(await o.json(),n),n.conversationKey)}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 ${P} 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){if(typeof e!=="string")return e.statusUrl;if(/^https?:\/\//.test(e))return e;return on(this.baseUrl,e)}}function Y(e){let n=e.trim(),t=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(n)?n:`https://${n}`;return g(t)}function q(e,n){let t=e.eventId??`${n}-${Date.now()}`;return{agentId:e.agentId,eventId:t,conversationKey:e.conversationKey??t,events:W(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 Pe(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 Z(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=typeof e.runId==="string"?e.runId:_e(t);if(!o)throw Error("Async response missing runId");let r=typeof e.eventId==="string"?e.eventId:o,{status:s,requestedMode:i}=e;return{statusUrl:t,runId:o,eventId:r,agentId:n.agentId,...s==="accepted"||s==="queued"||s==="applied"||s==="processing"?{status:s}:{},...i==="reject"||i==="followup"||i==="collect"||i==="steer"?{requestedMode:i}:{}}}function _e(e){let n=new URL(e).pathname.match(/\/v1\/runs\/([^/]+)$/);return n?.[1]?decodeURIComponent(n[1]):void 0}function en(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}}async function nn(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 tn(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 on(e,n){return`${Y(e)}/v1/runs/${encodeURIComponent(n)}`}var rn=2000,z=0,b=1;class ke{baseUrl;apiKey;WebSocketImpl;connectTimeoutMs;constructor(e={}){if(f(),this.baseUrl=te(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||P),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??rn}subscribe(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=sn(e),s=ne(this.baseUrl),i=new t(o,I(this.apiKey)),a=!1,u=!1,l=setTimeout(()=>{if(!a)m(s)},this.connectTimeoutMs),x=(c=1000,S="client closed")=>{if(u)return;if(u=!0,clearTimeout(l),e.signal?.removeEventListener("abort",C),i.readyState===b||i.readyState===z)i.close(c,S)},m=(c)=>{n.onError?.(c),x(1011,"websocket error")},ue=()=>{n.onDone?.(),x(1000,"done")},C=()=>{if(i.readyState===b)i.send(JSON.stringify({type:"cancel"}));m(Error("WebSocket run aborted."))};return e.signal?.addEventListener("abort",C,{once:!0}),i.onopen=()=>{if(a=!0,clearTimeout(l),e.signal?.aborted){C();return}i.send(JSON.stringify({type:"execute",agentId:r,...e.answers?{answers:e.answers}:{events:W(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 S=Q(c.data);if(!S)return;let A=ee(S,n);switch(n.onMessage?.(A),A.type){case"meta":n.onMeta?.(A);break;case"done":ue();break;case"error":m(Error(V(A.error)));break}},i.onerror=()=>{m(s)},i.onclose=(c)=>{if(clearTimeout(l),e.signal?.removeEventListener("abort",C),u||c.code===1000)return;m(Error(c.reason||"WebSocket connection closed."))},{url:o,sendControl:function(c){if(i.readyState!==b)throw Error("WebSocket is not open");i.send(JSON.stringify({type:"control",...c}))},close:x}}attach(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=new t(o,I(this.apiKey)),s=!1,i=(a=1000,u="client closed")=>{if(s)return;if(s=!0,r.readyState===b||r.readyState===z)r.close(a,u)};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 u=Q(a.data);if(!u)return;let l=ee(u,n);if(n.onMessage?.(l),l.type==="done")n.onDone?.();if(l.type==="error")n.onError?.(Error(V(l.error)))},r.onerror=()=>n.onError?.(ne(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!==b)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=an(e),t=e.projectSlug??e.agent?.projectSlug,o=e.stageSlug??e.agent?.stageSlug,r=t&&o?`/projects/${encodeURIComponent(t)}/stages/${encodeURIComponent(o)}`:"";return`${X(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 X(e){let n=new URL(te(e));if(n.protocol==="https:")n.protocol="wss:";if(n.protocol==="http:")n.protocol="ws:";return g(n.toString())}function I(e){return["broods.v1",`broods.token.${e}`]}function V(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 te(e){let n=e.trim();if(/^wss?:\/\//.test(n))return g(n);return Y(n)}function Q(e){try{let n=JSON.parse(e);return typeof n==="object"&&n!==null&&typeof n.type==="string"?n:null}catch{return null}}function sn(e){let n=e.agentId??e.agent?.id??e.endpointId;if(!n)throw Error("WebSocket run requires agent, agentId, or endpointId.");return n}function an(e){let n=e.endpointId??e.agent?.endpointId??e.agent?.id;if(!n)throw Error("WebSocket run requires agent or endpointId.");return n}function ee(e,n){if(e.type!=="output")return e;let t=e;return n.onOutput?.(t),t.data}function ne(e){return Error(`Cannot access the WebSocket service at ${e}.`)}var re=Symbol.for("broods.resource"),se=Symbol.for("broods.config"),ce=Symbol.for("broods.connection"),oe=/^[A-Z][A-Z0-9_]{0,63}$/,Oe=new Proxy((e)=>{if(!oe.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"&&oe.test(n))throw Error(`env.${n} is not supported; use env("${n}")`);return Reflect.get(e,n,t)}});function Ne(e){let{name:n,description:t,...o}=e;return d("agent",n,t,o)}function je(e){return{[se]:!0,config:e}}function qe(e){let{name:n,description:t,...o}=e;return d("cron",n,t,o)}function De(e){return e}function Le(e){let{name:n,description:t,...o}=e;return d("mcp",n,t,o)}function Ue(e){let{name:n,description:t,...o}=e;return d("policy",n,t,o)}function Fe(e){let{name:n,description:t,...o}=e;return d("sandbox",n,t,o)}function Be(e){let{name:n,description:t,...o}=e;return d("skill",n,t,o)}function Ve(e){let{name:n,description:t,...o}=e;return d("workspace",n,t,o)}function Ze(e){return y("discord",e)}function He(e){return y("github",e)}function We(e){return y("pancake",e)}function Ge(e){return y("slack",e)}function Ke(e){return y("telegram",e)}function Je(e){return y("zalo",e)}function Ye(e){let{name:n,description:t,channelId:o,guildId:r,...s}=e;return p(n,t,o,r,s)}function Xe(e){let{name:n,description:t,repo:o,...r}=e,[s,...i]=o.split("/");if(!s||i.length!==1||!i[0])throw Error(`Channel "${n}" repo must be "owner/name", not "${o}"`);return p(n,t,o,s,r)}function Qe(e){let{name:n,description:t,conversationId:o,...r}=e;return p(n,t,o,void 0,r)}function et(e){let{name:n,description:t,channelId:o,teamId:r,...s}=e;return p(n,t,o,r,s)}function tt(e){let{name:n,description:t,chatId:o,...r}=e;return p(n,t,o,void 0,r)}function rt(e){let{name:n,description:t,chatId:o,...r}=e;return p(n,t,o,void 0,r)}function ie(e){return Boolean(e&&typeof e==="object"&&e[se])}function R(e){return Boolean(e&&typeof e==="object"&&e[ce])}function h(e){return Boolean(e&&typeof e==="object"&&e[re])}function p(e,n,t,o,r){return d("channelRecord",e,n,{...r,externalId:t,...o?{workspaceRef:o}:{}})}function y(e,n){let{partition:t,...o}=n;return{[ce]:!0,kind:"connection",type:e,...t?{partition:t}:{},config:o}}function d(e,n,t,o){return{[re]:!0,kind:e,name:n,...t?{description:t}:{},config:o}}
5
- export{W,Se,Me,xe,Ae,ze,G,$e,v,w,k,K,J,_,g,ae,f,N,P,we,F,Y,ke,X,I,Oe,Ne,je,qe,De,Le,Ue,Fe,Be,Ve,Ze,He,We,Ge,Ke,Je,Ye,Xe,Qe,et,tt,rt,ie,R,h};
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*me(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()}}var xe=500,ge=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,le=/^(?!0{32}$)[0-9a-f]{32}$/;function Ce(e){return e==="DEBUG"||e==="INFO"||e==="WARN"||e==="ERROR"}function Oe(e){if(typeof e!=="object"||e===null)return!1;let n=e;if(n.type==="subscribe")return de(n);if(n.type==="unsubscribe")return N(n.stream);if(n.type==="fetchTrace")return ze(n.traceId);return!1}function Ae(e){return e==="task"||e==="cron"||e==="subtask"}function F(e){return typeof e==="string"&&ge.test(e)}function ze(e){return typeof e==="string"&&le.test(e)}function N(e){return e==="logs"||e==="traces"}function de(e){let n=e.stream;if(!N(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&&!Ce(o))return!1;let r=e.sandboxId;return r===void 0||n==="logs"&&F(r)}import{mkdir as pe,readFile as fe,writeFile as ye}from"node:fs/promises";import{homedir as be}from"node:os";import{dirname as Re,join as Se}from"node:path";var S="broods",v="_generated",C=Se(be(),".broods","config.json"),T="broods.app",M="dashboard",Ie="gateway";async function Z(){let e=process.env.BROODS_TOKEN,n=process.env.BROODS_BASE_URL;if(e&&n)return{baseUrl:f(n),token:e,createdAt:new Date().toISOString()};try{let t=JSON.parse(await fe(C,"utf8"));if(typeof t.baseUrl!=="string"||!t.baseUrl)return null;return t}catch{return null}}async function H(e){await pe(Re(C),{recursive:!0}),await ye(C,`${JSON.stringify(e,null,2)}
3
+ `,"utf8")}function _(){return process.env.BROODS_STAGE}function f(e){let n=e.length;while(n>0&&e.charCodeAt(n-1)===47)n-=1;return e.slice(0,n)}function te(e){try{let n=new URL(e);if(!n.hostname.startsWith(`${M}.`))return;let t=n.hostname.slice(M.length+1);if(t!==T&&!t.endsWith(`.${T}`))return;return n.hostname=`${Ie}.${t}`,f(n.origin)}catch{return}}import{existsSync as P,readFileSync as D,statSync as ke}from"node:fs";import{join as W,resolve as L}from"node:path";var x=new Map,ve=new Set(Object.keys(process.env)),U=new Set;function h(e=process.cwd()){we(e);let n=Te();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:_()}}function O(e,n=process.cwd()){let t=process.env[e];if(t===void 0)return!1;let o=L(n);for(let r of[".env.local",".env"]){let s=W(o,r);if(!P(s))continue;let i=G(D(s,"utf8"));if(i[e]!==void 0)return i[e]!==t}return!0}function we(e){let n=L(e),t=process.env.BROODS_RELOAD_ENV==="1";for(let o of[".env",".env.local"]){let r=W(n,o);if(!P(r)){x.delete(r);continue}let s=ke(r).mtimeMs,i=x.get(r);if(i&&i.mtimeMs===s)continue;x.set(r,{mtimeMs:s});for(let[a,u]of Object.entries(G(D(r,"utf8"))))if(t||!ve.has(a)||U.has(a))process.env[a]=u,U.add(a)}}function G(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]=Ee(r.slice(s+1).trim())}return n}function Ee(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 Te(){try{let e=JSON.parse(D(C,"utf8"));if(typeof e.baseUrl!=="string"||typeof e.token!=="string")return null;return{baseUrl:f(e.baseUrl),...typeof e.dashboardUrl==="string"?{dashboardUrl:f(e.dashboardUrl)}:{},token:e.token}}catch{return null}}var z="https://gateway.broods.app";class he 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;fetchImpl;constructor(e={}){h(),this.baseUrl=V(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.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:(s)=>this.run({...s,agentName:o,agentId:r}),runAsync:(s)=>this.runAsync({...s,agentName:o,agentId:r}),continue:(s)=>this.continue({...s,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),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 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=q(t,"cli"),r=n?this.scopedUrl(e):`${this.baseUrl}/v1/runs`,s=await this.openStream(o,r);if(!s.ok)throw Error(`Run failed: ${s.status} ${await s.text()}`);if(s.status===202)throw new he(J(await s.json(),o));if(!s.body)throw Error("Run response has no body");for await(let i of me(s.body)){let a;try{a=JSON.parse(i)}catch{continue}if(a.type==="error")throw Error(`Agent run failed: ${$e(a.error)}`);yield a}}async runAsync(e,n){let t=n?{...n,agentId:e.id,agentName:e.name}:e,o={...q(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},s=t?this.scopedUrl(t):`${this.baseUrl}/v1/runs`;return this.postAcceptedRun(s,r,"Continue")}async getAsyncStatus(e){let n=this.resolveStatusUrl(e),t=await this.fetchJson(n,{method:"GET",headers: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 tn(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(en(e))});if(n.status!==201)throw Error(`Create cron job failed: ${n.status} ${await n.text()}`);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 e.text()}`);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 n.text()}`);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 r.text()}`);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 t.text()}`);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 n.text()}`);return(await n.json()).deleted}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:this.apiKeyHeaders(),body:JSON.stringify(n)});if(o.status!==202)throw Error(`${t} failed: ${o.status} ${await nn(o,"202 JSON")}`);return this.asyncAgentRun(J(await o.json(),n),n.conversationKey)}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 ${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)}`)}}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){if(typeof e!=="string")return e.statusUrl;if(/^https?:\/\//.test(e))return e;return on(this.baseUrl,e)}}function V(e){let n=e.trim(),t=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(n)?n:`https://${n}`;return f(t)}function q(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 $e(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 J(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=typeof e.runId==="string"?e.runId:_e(t);if(!o)throw Error("Async response missing runId");let r=typeof e.eventId==="string"?e.eventId:o,{status:s,requestedMode:i}=e;return{statusUrl:t,runId:o,eventId:r,agentId:n.agentId,...s==="accepted"||s==="queued"||s==="applied"||s==="processing"?{status:s}:{},...i==="reject"||i==="followup"||i==="collect"||i==="steer"?{requestedMode:i}:{}}}function _e(e){let n=new URL(e).pathname.match(/\/v1\/runs\/([^/]+)$/);return n?.[1]?decodeURIComponent(n[1]):void 0}function en(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}}async function nn(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 tn(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 on(e,n){return`${V(e)}/v1/runs/${encodeURIComponent(n)}`}var rn=2000,Y=0,b=1;class Pe{baseUrl;apiKey;WebSocketImpl;connectTimeoutMs;constructor(e={}){if(h(),this.baseUrl=re(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.WebSocketImpl=e.WebSocket,this.connectTimeoutMs=e.connectTimeoutMs??rn}subscribe(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=sn(e),s=oe(this.baseUrl),i=new t(o,E(this.apiKey)),a=!1,u=!1,l=setTimeout(()=>{if(!a)m(s)},this.connectTimeoutMs),A=(c=1000,I="client closed")=>{if(u)return;if(u=!0,clearTimeout(l),e.signal?.removeEventListener("abort",R),i.readyState===b||i.readyState===Y)i.close(c,I)},m=(c)=>{n.onError?.(c),A(1011,"websocket error")},ue=()=>{n.onDone?.(),A(1000,"done")},R=()=>{if(i.readyState===b)i.send(JSON.stringify({type:"cancel"}));m(Error("WebSocket run aborted."))};return e.signal?.addEventListener("abort",R,{once:!0}),i.onopen=()=>{if(a=!0,clearTimeout(l),e.signal?.aborted){R();return}i.send(JSON.stringify({type:"execute",agentId:r,...e.answers?{answers:e.answers}:{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 I=Q(c.data);if(!I)return;let k=ee(I,n);switch(n.onMessage?.(k),k.type){case"meta":n.onMeta?.(k);break;case"done":ue();break;case"error":m(Error(X(k.error)));break}},i.onerror=()=>{m(s)},i.onclose=(c)=>{if(clearTimeout(l),e.signal?.removeEventListener("abort",R),u||c.code===1000)return;m(Error(c.reason||"WebSocket connection closed."))},{url:o,sendControl:function(c){if(i.readyState!==b)throw Error("WebSocket is not open");i.send(JSON.stringify({type:"control",...c}))},close:A}}attach(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=new t(o,E(this.apiKey)),s=!1,i=(a=1000,u="client closed")=>{if(s)return;if(s=!0,r.readyState===b||r.readyState===Y)r.close(a,u)};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 u=Q(a.data);if(!u)return;let l=ee(u,n);if(n.onMessage?.(l),l.type==="done")n.onDone?.();if(l.type==="error")n.onError?.(Error(X(l.error)))},r.onerror=()=>n.onError?.(oe(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!==b)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=an(e),t=e.projectSlug??e.agent?.projectSlug,o=e.stageSlug??e.agent?.stageSlug,r=t&&o?`/projects/${encodeURIComponent(t)}/stages/${encodeURIComponent(o)}`:"";return`${K(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 K(e){let n=new URL(re(e));if(n.protocol==="https:")n.protocol="wss:";if(n.protocol==="http:")n.protocol="ws:";return f(n.toString())}function E(e){return["broods.v1",`broods.token.${e}`]}function X(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 re(e){let n=e.trim();if(/^wss?:\/\//.test(n))return f(n);return V(n)}function Q(e){try{let n=JSON.parse(e);return typeof n==="object"&&n!==null&&typeof n.type==="string"?n:null}catch{return null}}function sn(e){let n=e.agentId??e.agent?.id??e.endpointId;if(!n)throw Error("WebSocket run requires agent, agentId, or endpointId.");return n}function an(e){let n=e.endpointId??e.agent?.endpointId??e.agent?.id;if(!n)throw Error("WebSocket run requires agent or endpointId.");return n}function ee(e,n){if(e.type!=="output")return e;let t=e;return n.onOutput?.(t),t.data}function oe(e){return Error(`Cannot access the WebSocket service at ${e}.`)}var ie=Symbol.for("broods.resource"),ae=Symbol.for("broods.config"),ce=Symbol.for("broods.connection"),se=/^[A-Z][A-Z0-9_]{0,63}$/,Me=new Proxy((e)=>{if(!se.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"&&se.test(n))throw Error(`env.${n} is not supported; use env("${n}")`);return Reflect.get(e,n,t)}});function Ne(e){let{name:n,description:t,...o}=e;return d("agent",n,t,o)}function je(e){return{[ae]:!0,config:e}}function qe(e){let{name:n,description:t,...o}=e;return d("cron",n,t,o)}function Le(e){return e}function De(e){let{name:n,description:t,...o}=e;return d("mcp",n,t,o)}function Ue(e){let{name:n,description:t,...o}=e;return d("policy",n,t,o)}function Be(e){let{name:n,description:t,...o}=e;return d("sandbox",n,t,o)}function Fe(e){let{name:n,description:t,...o}=e;return d("skill",n,t,o)}function Ze(e){let{name:n,description:t,...o}=e;return d("workspace",n,t,o)}function He(e){return y("discord",e)}function Ve(e){return y("github",e)}function Ke(e){return y("pancake",e)}function We(e){return y("slack",e)}function Ge(e){return y("telegram",e)}function Je(e){return y("zalo",e)}function Ye(e){let{name:n,description:t,channelId:o,guildId:r,...s}=e;return p(n,t,o,r,s)}function Xe(e){let{name:n,description:t,repo:o,...r}=e,[s,...i]=o.split("/");if(!s||i.length!==1||!i[0])throw Error(`Channel "${n}" repo must be "owner/name", not "${o}"`);return p(n,t,o,s,r)}function Qe(e){let{name:n,description:t,conversationId:o,...r}=e;return p(n,t,o,void 0,r)}function et(e){let{name:n,description:t,channelId:o,teamId:r,...s}=e;return p(n,t,o,r,s)}function tt(e){let{name:n,description:t,chatId:o,...r}=e;return p(n,t,o,void 0,r)}function nt(e){let{name:n,description:t,chatId:o,...r}=e;return p(n,t,o,void 0,r)}function ne(e){return Boolean(e&&typeof e==="object"&&e[ae])}function w(e){return Boolean(e&&typeof e==="object"&&e[ce])}function g(e){return Boolean(e&&typeof e==="object"&&e[ie])}function p(e,n,t,o,r){return d("channelRecord",e,n,{...r,externalId:t,...o?{workspaceRef:o}:{}})}function y(e,n){let{partition:t,...o}=n;return{[ce]:!0,kind:"connection",type:e,...t?{partition:t}:{},config:o}}function d(e,n,t,o){return{[ie]:!0,kind:e,name:n,...t?{description:t}:{},config:o}}
5
+ export{B,me,xe,Ce,Oe,Ae,F,ze,S,v,C,Z,H,_,f,te,h,O,z,he,j,V,Pe,K,E,Me,Ne,je,qe,Le,De,Ue,Be,Fe,Ze,He,Ve,Ke,We,Ge,Je,Ye,Xe,Qe,et,tt,nt,ne,w,g};
@@ -0,0 +1,17 @@
1
+ import{getToolName as Re,isToolUIPart as Zt,readUIMessageStream as Ae}from"ai";import{convertToModelMessages as oa,generateId as ua,getToolName as ca,isToolUIPart as le}from"ai";var Ht=(t)=>{throw TypeError(t)},St=(t,e,a)=>e.has(t)||Ht("Cannot "+a),u=(t,e,a)=>(St(t,e,"read from private field"),a?a.call(t):e.get(t)),v=(t,e,a)=>e.has(t)?Ht("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,a),c=(t,e,a,r)=>(St(t,e,"write to private field"),r?r.call(t,a):e.set(t,a),a),o=(t,e,a)=>(St(t,e,"access private method"),a),Kt=String.fromCharCode(27),Sa=new RegExp(`${Kt}\\[[0-?]*[ -/]*[@-~]`,"g"),bt=new RegExp(`^${Kt}\\[[0-?]*[ -/]*[@-~]`);function B(t){let e=0,a=0;while(a<t.length){let r=t.slice(a).match(bt);if(r){a+=r[0].length;continue}let n=t.codePointAt(a);if(n==null)break;let i=String.fromCodePoint(n);e+=Jt(n),a+=i.length}return e}function H(t,e){if(e<=0)return"";let a="",r=0,n=0;while(n<t.length&&r<e){let i=t.slice(n).match(bt);if(i){a+=i[0],n+=i[0].length;continue}let d=t.codePointAt(n);if(d==null)break;let p=String.fromCodePoint(d),h=Jt(d);if(h>0&&r+h>e)break;a+=p,n+=p.length,r+=h}while(n<t.length){let i=t.slice(n).match(bt);if(!i)break;a+=i[0],n+=i[0].length}return a}function Jt(t){if(t===9)return 4;if(t<32||t>=127&&t<160)return 0;if(fe(t))return 0;return ve(t)?2:1}function fe(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t===1471||t>=1473&&t<=1474||t>=1476&&t<=1477||t===1479||t>=1552&&t<=1562||t>=1611&&t<=1631||t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t===1809||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2027&&t<=2035||t>=2070&&t<=2073||t>=2075&&t<=2083||t>=2085&&t<=2087||t>=2089&&t<=2093||t>=2137&&t<=2139||t>=2259&&t<=2306||t===2362||t===2364||t>=2369&&t<=2376||t===2381||t>=2385&&t<=2391||t===8205||t>=65024&&t<=65039||t>=917760&&t<=917999}function ve(t){return t>=4352&&(t<=4447||t===9001||t===9002||t>=11904&&t<=42191&&t!==12351||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65135||t>=65280&&t<=65376||t>=65504&&t<=65510||t>=127744&&t<=128591||t>=129280&&t<=129535||t>=131072&&t<=262141)}var M={bold:"\x1B[1m",boldOff:"\x1B[22m",italic:"\x1B[3m",italicOff:"\x1B[23m"},me="─";function ge(t){var e;let a=t.split(`
2
+ `),r=[];for(let n=0;n<a.length;n+=1){let i=be(a,n);if(i!=null){r.push(...Te(i)),n=i.endIndex-1;continue}r.push(ye((e=a[n])!=null?e:""))}return r.join(`
3
+ `)}function ye(t){if(t.startsWith("### "))return C(`▶ ${t.slice(4)}`);if(t.startsWith("## "))return C(`■ ${t.slice(3)}`);if(t.startsWith("# "))return C(`█ ${t.slice(2)}`);let e=t.match(/^(\s*)[-+*]\s+(.*)$/);if(e){let[,a,r=""]=e;return C(`${a}•${r.length>0?` ${r}`:""}`)}if(/^\d+\. /.test(t))return C(t.replace(/^(\d+)\. /,"$1. "));if(t.startsWith("> "))return C(`│ ${t.slice(2)}`);return C(t)}function C(t){return t.replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*\n]+)\*\*/g,`${M.bold}$1${M.boldOff}`).replace(/__([^_\n]+)__/g,`${M.bold}$1${M.boldOff}`).replace(/\*([^*\n]+)\*/g,`${M.italic}$1${M.italicOff}`).replace(/_([^_\n]+)_/g,`${M.italic}$1${M.italicOff}`)}function be(t,e){var a,r,n;let i=gt((a=t[e])!=null?a:"");if(i==null||i.length<2)return;let d=gt((r=t[e+1])!=null?r:"");if(d==null||d.length!==i.length)return;let p=ke(d);if(p==null)return;let h=[],m=e+2;while(m<t.length){let f=gt((n=t[m])!=null?n:"");if(f==null)break;h.push(xe(f,i.length)),m+=1}return{alignments:p,endIndex:m,header:i,rows:h}}function gt(t){if(!t.includes("|"))return;let e=t.trim();if(e.startsWith("|"))e=e.slice(1);if(e.endsWith("|")&&!e.endsWith("\\|"))e=e.slice(0,-1);let a=[],r="";for(let n=0;n<e.length;n+=1){let i=e[n],d=e[n+1];if(i==="\\"&&d==="|"){r+="|",n+=1;continue}if(i==="|"){a.push(r.trim()),r="";continue}r+=i}return a.push(r.trim()),a}function ke(t){let e=[];for(let a of t){let r=a.match(/^(:)?-{3,}(:)?$/);if(r==null)return;let[,n,i]=r;e.push(n!=null&&i!=null?"center":i!=null?"right":"left")}return e}function xe(t,e){return Array.from({length:e},(a,r)=>{var n;return(n=t[r])!=null?n:""})}function Te(t){let e=t.header.map((i)=>`${M.bold}${C(i)}${M.boldOff}`),a=t.rows.map((i)=>i.map(C)),r=[e,...a],n=t.alignments.map((i,d)=>Math.max(3,...r.map((p)=>{var h;return B((h=p[d])!=null?h:"")})));return[Et(e,n,t.alignments),n.map((i)=>me.repeat(i)).join(" "),...a.map((i)=>Et(i,n,t.alignments))]}function Et(t,e,a){return t.map((r,n)=>{var i,d;return we(r,(i=e[n])!=null?i:0,(d=a[n])!=null?d:"left")}).join(" ")}function we(t,e,a){let r=Math.max(0,e-B(t));if(a==="right")return`${" ".repeat(r)}${t}`;if(a==="center"){let n=Math.floor(r/2),i=r-n;return`${" ".repeat(n)}${t}${" ".repeat(i)}`}return`${t}${" ".repeat(r)}`}var Yt="─";function Me(t){var e;let a=Math.max(20,t.width),r=Math.max(8,t.height),n=3,d=r-3-2,p=t.visibleBodyLines.slice(0,d);while(p.length<d)p.push("");return[Wt(a,t.title,t.rightTitle),...p.map((m)=>At(m,a)),Rt(a),Wt(a,t.inputActive?"Input":"Status"),At(t.inputActive?`> ${t.input}${t.inputCursorVisible===!1?" ":"█"}`:(e=t.status)!=null?e:"Streaming... ↑/↓ scroll · Ctrl+C quit",a),Rt(a)].join(`
4
+ `)}function Wt(t,e,a){let r=Math.max(0,t-2),n=e?H(` ${e} `,r):"",i=a?H(` ${a} `,Math.max(0,r-B(n))):"",d=Math.max(0,r-B(n)-B(i));return`┌${n}${Yt.repeat(d)}${i}┐`}function Rt(t){return`└${Yt.repeat(t-2)}┘`}function At(t,e){let a=e-4,r=H(t,a),n=" ".repeat(Math.max(0,a-B(r)));return`│ ${r}${n} │`}var G="\x1B",Se=`${G}[H`,_e=`${G}[2J`,$e=`${G}[2K`,Ce=`${G}[?2026h`,Ie=`${G}[?2026l`,ct,V,q,P,Z,kt,Gt,Be=class{constructor(t,e){v(this,kt),v(this,ct),v(this,V),v(this,q),v(this,P,!1),v(this,Z,!1);var a;c(this,V,t.write.bind(t)),c(this,ct,(a=e==null?void 0:e.useSynchronizedUpdates)!=null?a:!0),t.write=(r,n,i)=>{if(!u(this,P))c(this,Z,!0);return u(this,V).call(this,r,n,i)}}present(t){let e=Ee(t),a=u(this,q)&&!u(this,Z)?We(u(this,q),e):`${Se}${_e}${t}`;if(c(this,q,e),c(this,Z,!1),a.length===0)return;o(this,kt,Gt).call(this,a)}reset(){c(this,q,void 0)}};ct=new WeakMap;V=new WeakMap;q=new WeakMap;P=new WeakMap;Z=new WeakMap;kt=new WeakSet;Gt=function(t){c(this,P,!0);try{if(!u(this,ct)){u(this,V).call(this,t);return}u(this,V).call(this,`${Ce}${t}${Ie}`)}finally{c(this,P,!1)}};function Ee(t){return{lines:t.split(`
5
+ `)}}function We(t,e){let a="",r=Math.max(t.lines.length,e.lines.length);for(let n=0;n<r;n++){let i=e.lines[n];if(t.lines[n]===i)continue;a+=`${G}[${n+1};1H${$e}${i!=null?i:""}`}return a}var Ue="outputTokensPerSecond",k={reset:"\x1B[0m",dim:"\x1B[2m",user:"\x1B[96m",assistant:"\x1B[92m",reasoning:"\x1B[94m",tool:"\x1B[95m",error:"\x1B[91m"},Le={user:{color:k.user,border:"─"},assistant:{color:k.assistant,border:"─"},reasoning:{color:k.reasoning,border:"·"},tool:{color:k.tool,border:"─"},error:{color:k.error,border:"─"}},Oe=500,U="↑/↓ · PgUp/PgDn · Esc/Ctrl+C",Fe="↑/↓ · PgUp/PgDn · q/Esc/Ctrl+C",Q=`Processing input... ${U}`,Ut=`Processing tool results... ${U}`,xt=`Streaming... ${U}`,Lt=`Executing tools... ${U}`,T,_,z,nt,st,it,dt,x,S,A,E,tt,y,K,b,W,et,R,L,N,O,w,F,X,l,lt,ot,j,I,Qt,J,at,Xt,rt,ht,jt,_t,Tt,ut,Pt,te,$t,ft,g,Y,ee,Ct,D,vt,mt,It,ae,wt=class{constructor(t){v(this,l),v(this,T),v(this,_),v(this,z),v(this,nt),v(this,st),v(this,it),v(this,dt),v(this,x,[]),v(this,S,""),v(this,A,!1),v(this,E,0),v(this,tt,""),v(this,y,xt),v(this,K,!1),v(this,b,!1),v(this,W),v(this,et),v(this,R),v(this,L),v(this,N,!0),v(this,O),v(this,w),v(this,F),v(this,X);var e,a,r,n,i,d;c(this,T,(e=t==null?void 0:t.input)!=null?e:process.stdin),c(this,_,(a=t==null?void 0:t.output)!=null?a:process.stdout),c(this,z,(r=t==null?void 0:t.frameBuffer)!=null?r:new Be(u(this,_))),c(this,nt,(n=t==null?void 0:t.tools)!=null?n:"auto-collapsed"),c(this,st,(i=t==null?void 0:t.reasoning)!=null?i:"auto-collapsed"),c(this,it,(d=t==null?void 0:t.responseStatistics)!=null?d:Ue),c(this,dt,t==null?void 0:t.contextSize),c(this,et,t==null?void 0:t.contextSize)}async readPrompt(t){var e;return o(this,l,lt).call(this,t),c(this,A,!0),c(this,S,(e=t==null?void 0:t.initialPrompt)!=null?e:""),c(this,y,`Type a prompt and press Enter · ${U}`),o(this,l,Xt).call(this),o(this,l,g).call(this),await new Promise((a,r)=>{c(this,w,(n)=>{let i=pt(n);switch(i.type){case"character":c(this,S,u(this,S)+i.value),o(this,l,ht).call(this),o(this,l,g).call(this);break;case"backspace":c(this,S,u(this,S).slice(0,-1)),o(this,l,ht).call(this),o(this,l,g).call(this);break;case"enter":{let d=u(this,S);c(this,A,!1),o(this,l,rt).call(this),c(this,y,Q),o(this,l,_t).call(this,d),c(this,S,""),o(this,l,g).call(this),o(this,l,I).call(this),a(d);break}case"up":case"down":o(this,l,J).call(this,i.type);break;case"page-up":case"page-down":o(this,l,at).call(this,i.type);break;case"ctrl-l":o(this,l,Y).call(this);break;case"escape":case"ctrl-c":o(this,l,rt).call(this),o(this,l,ot).call(this),r(yt());break;case"ignore":break}}),o(this,l,j).call(this)})}async renderStream(t,e){var a,r,n,i;o(this,l,lt).call(this,e),c(this,A,!1),c(this,y,Q),o(this,l,jt).call(this,e==null?void 0:e.submittedPrompt),c(this,b,!1),c(this,W,void 0),c(this,R,void 0),c(this,L,void 0);let d={tools:(a=e==null?void 0:e.tools)!=null?a:u(this,nt),reasoning:(r=e==null?void 0:e.reasoning)!=null?r:u(this,st),responseStatistics:(n=e==null?void 0:e.responseStatistics)!=null?n:u(this,it)};o(this,l,g).call(this);let p=new Promise((f)=>{c(this,X,f)});c(this,w,(f)=>o(this,l,Qt).call(this,f)),o(this,l,j).call(this);let h,m=Ze(o(this,l,te).call(this,t.uiMessageStream));try{let f=Ae({message:t.message,stream:m,onError:(s)=>o(this,l,$t).call(this,"Error",Ne(s))});for await(let s of ze(f,p)){if(u(this,b))break;h=s,o(this,l,Tt).call(this,s,d)}if(!u(this,b)&&h&&u(this,R)!=null)o(this,l,Tt).call(this,h,d)}finally{if(c(this,X,void 0),u(this,b))(i=t.abort)==null||i.call(t);if(o(this,l,I).call(this),c(this,y,u(this,b)?"Interrupted":(e==null?void 0:e.continueSession)?`Done · Enter another prompt · ${U}`:`Done · ${Fe}`),o(this,l,g).call(this),await o(this,l,ae).call(this,e),u(this,b)||!(e==null?void 0:e.continueSession))o(this,l,ot).call(this)}if(u(this,b))throw yt();return h}async readToolApproval(t,e){return o(this,l,lt).call(this,e),c(this,A,!1),c(this,y,`Approve ${Ye(t)}? y/n · ${U}`),c(this,b,!1),o(this,l,g).call(this),await new Promise((a,r)=>{c(this,w,(n)=>{let i=pt(n);switch(i.type){case"character":{let d=i.value.toLowerCase();if(d==="y")c(this,y,`Approved · ${Q}`),o(this,l,I).call(this),o(this,l,g).call(this),a({approved:!0});else if(d==="n")c(this,y,`Denied · ${Q}`),o(this,l,I).call(this),o(this,l,g).call(this),a({approved:!1,reason:"Denied by user."});break}case"up":case"down":o(this,l,J).call(this,i.type);break;case"page-up":case"page-down":o(this,l,at).call(this,i.type);break;case"ctrl-l":o(this,l,Y).call(this);break;case"escape":case"ctrl-c":c(this,b,!0),o(this,l,ot).call(this),r(yt());break;default:break}}),o(this,l,j).call(this)})}};T=new WeakMap;_=new WeakMap;z=new WeakMap;nt=new WeakMap;st=new WeakMap;it=new WeakMap;dt=new WeakMap;x=new WeakMap;S=new WeakMap;A=new WeakMap;E=new WeakMap;tt=new WeakMap;y=new WeakMap;K=new WeakMap;b=new WeakMap;W=new WeakMap;et=new WeakMap;R=new WeakMap;L=new WeakMap;N=new WeakMap;O=new WeakMap;w=new WeakMap;F=new WeakMap;X=new WeakMap;l=new WeakSet;lt=function(t){var e,a,r,n;if(c(this,tt,(e=t==null?void 0:t.title)!=null?e:u(this,tt)),c(this,et,(a=t==null?void 0:t.contextSize)!=null?a:u(this,dt)),u(this,K))return;if(c(this,K,!0),u(this,z).reset(),u(this,_).write("\x1B[?1049h\x1B[?25l"),u(this,T).isTTY)(n=(r=u(this,T)).setRawMode)==null||n.call(r,!0),u(this,T).resume();c(this,F,()=>o(this,l,Y).call(this)),u(this,_).on("resize",u(this,F))};ot=function(){var t,e;if(o(this,l,I).call(this),o(this,l,rt).call(this),!u(this,K))return;if(u(this,T).isTTY)(e=(t=u(this,T)).setRawMode)==null||e.call(t,!1),u(this,T).pause();if(u(this,F))u(this,_).off("resize",u(this,F)),c(this,F,void 0);u(this,_).write("\x1B[?25h\x1B[?1049l"),u(this,z).reset(),c(this,K,!1)};j=function(){if(u(this,w))u(this,T).on("data",u(this,w))};I=function(){if(u(this,w))u(this,T).off("data",u(this,w)),c(this,w,void 0)};Qt=function(t){var e;let a=pt(t);switch(a.type){case"up":case"down":o(this,l,J).call(this,a.type);break;case"page-up":case"page-down":o(this,l,at).call(this,a.type);break;case"ctrl-l":o(this,l,Y).call(this);break;case"escape":case"ctrl-c":c(this,b,!0),(e=u(this,X))==null||e.call(this);break;default:break}};J=function(t,e=1){let a=t==="up"?e:-e;c(this,E,o(this,l,Ct).call(this,u(this,E)+a)),o(this,l,g).call(this)};at=function(t){o(this,l,J).call(this,t==="page-up"?"up":"down",o(this,l,vt).call(this))};Xt=function(){var t,e;o(this,l,rt).call(this),o(this,l,ht).call(this),c(this,O,setInterval(()=>{c(this,N,!u(this,N)),o(this,l,g).call(this)},Oe)),(e=(t=u(this,O)).unref)==null||e.call(t)};rt=function(){if(u(this,O))clearInterval(u(this,O)),c(this,O,void 0);c(this,N,!0)};ht=function(){c(this,N,!0)};jt=function(t){if(t==null)return;let e=u(this,x).at(-1);if((e==null?void 0:e.kind)==="user"&&e.content===t)return;o(this,l,_t).call(this,t)};_t=function(t){let e=o(this,l,D).call(this);u(this,x).push({kind:"user",title:"User",content:t}),o(this,l,ft).call(this,e)};Tt=function(t,e){var a,r,n;let i=o(this,l,D).call(this),d=new Set,p=aa(t.metadata);c(this,W,(a=p.totalTokens)!=null?a:u(this,W)),c(this,R,(r=p.outputTokens)!=null?r:u(this,R)),c(this,L,(n=p.outputTokensPerSecond)!=null?n:u(this,L));for(let[h,m]of t.parts.entries()){let f=Ge(t.id,h);switch(m.type){case"text":{let s=m.text.trim();if(s.length===0)break;d.add(f),o(this,l,ut).call(this,{id:f,kind:"assistant",title:"Assistant",rightTitle:sa({totalTokens:u(this,W),outputTokens:u(this,R),outputTokensPerSecond:u(this,L)},e.responseStatistics),content:s});break}case"reasoning":{let s=m.text.trim();if(e.reasoning==="hidden"||s.length===0)break;d.add(f),o(this,l,ut).call(this,{id:f,kind:"reasoning",title:"Reasoning",content:s,collapsed:Ot(t,h,e.reasoning,e)});break}default:if(Zt(m)){if(e.tools==="hidden")break;d.add(f),o(this,l,ut).call(this,{id:f,...De(m,{mode:e.tools,collapsed:Ot(t,h,e.tools,e)})})}break}}o(this,l,Pt).call(this,t.id,d),o(this,l,ft).call(this,i)};ut=function(t){let e=t.id?u(this,x).find((a)=>a.id===t.id):void 0;if(e){let a=e.cache;e.kind=t.kind,e.title=t.title,e.rightTitle=t.rightTitle,e.content=t.content,e.collapsed=t.collapsed,e.cache=a&&ne(t,a)?a:void 0;return}u(this,x).push(t)};Pt=function(t,e){let a=`${t}:`;c(this,x,u(this,x).filter((r)=>r.id==null||!r.id.startsWith(a)||e.has(r.id)))};te=async function*(t){let e=!1;for await(let a of Qe(t)){let r=He(a,{hasPendingToolResults:e});if(a.type==="start-step")e=!1;else if(Ke(a))e=!0;if(r&&u(this,y)!==r)c(this,y,r),o(this,l,g).call(this);else if(Ve(a)&&u(this,y)!==xt)c(this,y,xt),o(this,l,g).call(this);if(a.type==="error")o(this,l,$t).call(this,"Error",a.errorText);if(a.type==="finish"){let n=ea(a);c(this,W,n.totalTokens),c(this,R,n.outputTokens),c(this,L,n.outputTokensPerSecond)}yield a}};$t=function(t,e){let a=o(this,l,D).call(this);u(this,x).push({kind:"error",title:t,content:e}),o(this,l,ft).call(this,a)};ft=function(t){if(u(this,E)!==0){let e=o(this,l,D).call(this)-t;c(this,E,o(this,l,Ct).call(this,u(this,E)+e))}o(this,l,g).call(this)};g=function(){let t=Me({width:o(this,l,mt).call(this),height:o(this,l,It).call(this),title:u(this,tt),rightTitle:ie(u(this,W),u(this,et)),visibleBodyLines:o(this,l,ee).call(this),input:u(this,S),inputActive:u(this,A),inputCursorVisible:u(this,N),status:u(this,y)});u(this,z).present(t)};Y=function(){u(this,z).reset(),o(this,l,g).call(this)};ee=function(){if(u(this,x).length===0)return["Waiting for input..."];let t=o(this,l,vt).call(this),e=o(this,l,D).call(this),a=Math.max(0,e-t-u(this,E)),r=a+t,n=[],i=0;for(let d of u(this,x)){let p=re(d,o(this,l,mt).call(this)-4),h=i+p.length;if(h>a&&i<r)n.push(...p.slice(Math.max(0,a-i),r-i));if(n.length>=t)break;i=h}return n};Ct=function(t){let e=Math.max(0,o(this,l,D).call(this)-o(this,l,vt).call(this));return Math.min(Math.max(0,t),e)};D=function(){if(u(this,x).length===0)return 1;let t=0;for(let e of u(this,x))t+=re(e,o(this,l,mt).call(this)-4).length;return t};vt=function(){return Math.max(1,o(this,l,It).call(this)-5)};mt=function(){var t;return Math.max(20,(t=u(this,_).columns)!=null?t:80)};It=function(){var t;return Math.max(8,(t=u(this,_).rows)!=null?t:24)};ae=async function(t){if((t==null?void 0:t.waitForExit)===!1||!u(this,T).isTTY||u(this,b))return;await new Promise((e)=>{c(this,w,(a)=>{let r=pt(a);switch(r.type){case"up":case"down":o(this,l,J).call(this,r.type);break;case"page-up":case"page-down":o(this,l,at).call(this,r.type);break;case"ctrl-l":o(this,l,Y).call(this);break;case"escape":o(this,l,I).call(this),e();break;case"character":if(r.value==="q")o(this,l,I).call(this),e();break;case"ctrl-c":o(this,l,I).call(this),process.exitCode=130,e();break;default:break}}),o(this,l,j).call(this)})};function yt(){return Error("Interrupted")}async function*ze(t,e){let a=t[Symbol.asyncIterator](),r=e.then(()=>({done:!0,value:void 0}));while(!0){let n=await Promise.race([a.next(),r]);if(n.done)break;yield n.value}}function Ne(t){if(t instanceof Error)return t.message;if(typeof t==="string")return t;return JSON.stringify(t)}function De(t,e){var a,r,n,i;let d=Re(t),p=`Tool · ${(a=t.title)!=null?a:d}`,h="input"in t?t.input:void 0,m=h===void 0?"Input: (streaming...)":`Input:
6
+ ${Ft(h)}`,f=Je(t);if(e.collapsed)return{kind:"tool",title:p,rightTitle:f,content:"",collapsed:!0};switch(t.state){case"input-streaming":return{kind:"tool",title:p,rightTitle:f,content:m};case"input-available":return{kind:"tool",title:p,rightTitle:f,content:m};case"approval-requested":return{kind:"tool",title:p,rightTitle:f,content:m};case"approval-responded":return{kind:"tool",title:p,rightTitle:f,content:m};case"output-available":return{kind:"tool",title:p,rightTitle:f,content:`${m}
7
+
8
+ Output:
9
+ ${Ft(t.output)}`};case"output-error":return{kind:"error",title:`Tool Error · ${(r=t.title)!=null?r:d}`,rightTitle:f,content:`${m}
10
+
11
+ Error:
12
+ ${t.errorText}`};case"output-denied":return{kind:"error",title:`Tool Denied · ${(n=t.title)!=null?n:d}`,rightTitle:f,content:`${m}
13
+
14
+ Reason: ${(i=t.approval.reason)!=null?i:"denied"}`}}}function Ot(t,e,a,r){switch(a){case"collapsed":return!0;case"auto-collapsed":return t.parts.slice(e+1).some((n)=>qe(n,r));case"full":case"hidden":return!1}}function qe(t,e){switch(t.type){case"text":return t.text.trim().length>0;case"reasoning":return e.reasoning!=="hidden"&&t.text.trim().length>0;default:return Zt(t)&&e.tools!=="hidden"}}function Ve(t){switch(t.type){case"text-start":case"text-delta":case"reasoning-start":case"reasoning-delta":case"tool-input-start":case"tool-input-delta":return!0;default:return!1}}function He(t,{hasPendingToolResults:e}){switch(t.type){case"start-step":return e?Ut:Q;case"tool-output-available":case"tool-output-error":case"tool-output-denied":return Ut;case"tool-input-available":return Lt;case"tool-approval-response":return t.approved?Lt:void 0;default:return}}function Ke(t){switch(t.type){case"tool-output-available":case"tool-output-error":case"tool-output-denied":return!0;default:return!1}}function Je(t){switch(t.state){case"input-streaming":return"waiting";case"approval-requested":return"approval requested";case"input-available":return"executing";case"approval-responded":return t.approval.approved?"executing":"denied";case"output-available":case"output-error":return"done";case"output-denied":return"denied"}}function Ft(t){if(typeof t==="string")return t;return JSON.stringify(t,null,2)}function Ye(t){var e;return`tool ${(e=t.title)!=null?e:t.toolName}`}function Ge(t,e){return`${t}:${e}`}function Ze(t){if(t instanceof ReadableStream)return t;return new ReadableStream({async start(e){try{for await(let a of t)e.enqueue(a);e.close()}catch(a){e.error(a)}}})}async function*Qe(t){if(t instanceof ReadableStream){let e=t.getReader();try{while(!0){let{done:a,value:r}=await e.read();if(a)return;yield r}}finally{e.releaseLock()}return}yield*t}function re(t,e){if(t.cache&&ne(t,t.cache,e))return t.cache.lines;let a=Xe(t,e);return t.cache={width:e,kind:t.kind,title:t.title,rightTitle:t.rightTitle,content:t.content,collapsed:t.collapsed===!0,lines:a},a}function ne(t,e,a=e.width){return e.width===a&&e.kind===t.kind&&e.title===t.title&&e.rightTitle===t.rightTitle&&e.content===t.content&&e.collapsed===(t.collapsed===!0)}function Xe(t,e){let a=Le[t.kind],r=Math.max(1,e-4),n=` ${t.title} `,i=t.rightTitle?` ${t.rightTitle} `:"";if(t.collapsed){let s=Math.max(0,e-2-n.length-i.length),he=`${a.color}╭${n}${a.border.repeat(s)}${i}╮${k.reset}`,pe=`${a.color}╰${a.border.repeat(Math.max(0,e-2))}╯${k.reset}`;return[he,pe]}let d=Math.max(0,e-2-n.length-i.length),p=`${a.color}╭${n}${a.border.repeat(d)}${i}╮${k.reset}`,h=`${a.color}╰${a.border.repeat(Math.max(0,e-2))}╯${k.reset}`,f=(t.content.length>0?ge(t.content):k.dim+"(streaming...)"+k.reset).split(`
15
+ `).flatMap((s)=>Pe(s,r));return[p,...f.map((s)=>je(s,r,a.color)),h]}function je(t,e,a){let r=H(t,e),n=" ".repeat(Math.max(0,e-B(r)));return`${a}│${k.reset} ${r}${n} ${a}│${k.reset}`}function Pe(t,e){if(t.length===0)return[""];let a=[],r=t;while(B(r)>e){let n=ta(r,e);a.push(r.slice(0,n).trimEnd()),r=r.slice(n).trimStart()}return a.push(r),a}function ta(t,e){let r=H(t,e+1).lastIndexOf(" ");if(r>0)return r;return H(t,e).length}function ea(t){var e,a;let r="usage"in t?t.usage:void 0,n="messageMetadata"in t?(e=t.messageMetadata)==null?void 0:e.usage:void 0,i="messageMetadata"in t?(a=t.messageMetadata)==null?void 0:a.performance:void 0;return{totalTokens:se(r!=null?r:n),outputTokens:Bt(r!=null?r:n),outputTokensPerSecond:i==null?void 0:i.outputTokensPerSecond}}function aa(t){var e;let a=t;return{totalTokens:se(a==null?void 0:a.usage),outputTokens:Bt(a==null?void 0:a.usage),outputTokensPerSecond:(e=a==null?void 0:a.performance)==null?void 0:e.outputTokensPerSecond}}function se(t){let e=t==null?void 0:t.totalTokens;if(typeof e==="number")return e;if(typeof(e==null?void 0:e.total)==="number")return e.total;let a=ra(t),r=Bt(t);if(a!=null&&r!=null)return a+r;return}function ra(t){let e=t==null?void 0:t.inputTokens;if(typeof e==="number")return e;if(typeof(e==null?void 0:e.total)==="number")return e.total;return t==null?void 0:t.promptTokens}function Bt(t){let e=t==null?void 0:t.outputTokens;if(typeof e==="number")return e;if(typeof(e==null?void 0:e.total)==="number")return e.total;return t==null?void 0:t.completionTokens}function ie(t,e){if(t==null)return;let a=`${t.toLocaleString()} ${t===1?"token":"tokens"}`,r=na(t,e);return r==null?a:`${a} ${r}`}function na(t,e){if(e==null||e<=0||!Number.isFinite(e))return;return`${Math.round(t/e*100).toLocaleString()}%`}function sa(t,e){if(e==="outputTokensPerSecond")return ia(t.outputTokensPerSecond);return ie(t.outputTokens)}function ia(t){if(t==null)return;return`${la(t)} tok/s`}function la(t){return Number.isInteger(t)?t.toLocaleString():t.toLocaleString(void 0,{maximumFractionDigits:1})}function pt(t){let e=t.toString("utf8");switch(e){case"\f":return{type:"ctrl-l"};case"\x03":return{type:"ctrl-c"};case"\x1B":return{type:"escape"};case"\r":case`
16
+ `:return{type:"enter"};case"":case"\b":return{type:"backspace"};case"\x1B[A":return{type:"up"};case"\x1B[B":return{type:"down"};case"\x1B[5~":return{type:"page-up"};case"\x1B[6~":return{type:"page-down"};default:if(e>=" "&&e!=="")return{type:"character",value:e};return{type:"ignore"}}}var da="outputTokensPerSecond",ha=class{constructor(t){this.chatId=ua();var e,a,r,n;this.agent=t.agent,this.transport=t.transport,this.renderer=(e=fa(t))!=null?e:pa(t),this.title=t.title,this.tools=(a=t.tools)!=null?a:"auto-collapsed",this.reasoning=(r=t.reasoning)!=null?r:"auto-collapsed",this.responseStatistics=(n=t.responseStatistics)!=null?n:da,this.contextSize=t.contextSize,this.sandbox=t.sandbox}async run(){let t=this.title,e=[],a=0,r=()=>`message-${++a}`,n,i=!1,d=!1;while(!0){if(!d){if(n==null){if(!this.renderer.readPrompt){if(i)return;throw Error("No prompt was provided and the renderer does not support prompt input.")}try{n=await this.renderer.readPrompt({title:t})}catch(h){if(Vt(h))return;throw h}if(n==null)return}e.push(ga(r(),n)),i=!0}let p=await this.streamMessages([...e],r);try{let h=await this.renderer.renderStream(p,{title:t,submittedPrompt:n,continueSession:Boolean(this.renderer.readPrompt),tools:this.tools,reasoning:this.reasoning,responseStatistics:this.responseStatistics,contextSize:this.contextSize,waitForExit:!1});if(h&&h.parts.length>0){let m=ya(h);if(m.length>0){if(!this.renderer.readToolApproval)throw Error("Tool approval was requested, but the renderer does not support tool approval input.");for(let f of m){let s=await this.renderer.readToolApproval(f,{title:t});ba(h,f,s)}Nt(e,h,d),d=!0,n=void 0;continue}Nt(e,h,d)}}catch(h){if(Vt(h))return;throw h}d=!1,n=void 0}}async streamMessages(t,e){let a=new AbortController,r=()=>a.abort();if(this.transport)return{uiMessageStream:await this.transport.sendMessages({trigger:"submit-message",chatId:this.chatId,messageId:void 0,messages:t,abortSignal:a.signal}),message:Mt(t),abort:r};let n=this.agent,i=await n.stream({prompt:await oa(t,{tools:n.tools}),abortSignal:a.signal,options:void 0,experimental_sandbox:this.sandbox});return{uiMessageStream:va(i.fullStream,e,t),message:Mt(t),abort:r}}};function pa(t){return t.tools===void 0&&t.reasoning===void 0&&t.responseStatistics===void 0&&t.contextSize===void 0?new wt:new wt({tools:t.tools,reasoning:t.reasoning,responseStatistics:t.responseStatistics,contextSize:t.contextSize})}function fa(t){if(t.renderer)return t.renderer;if(!t.screen&&!t.userInput)return;return new wt({tools:t.tools,reasoning:t.reasoning,responseStatistics:t.responseStatistics,contextSize:t.contextSize,input:t.userInput,output:t.screen})}async function*va(t,e,a=[]){var r,n;let i=new Set,d=new Set,p=new Set,h,m,f=!1;yield{type:"start",messageId:(n=(r=Mt(a))==null?void 0:r.id)!=null?n:e()};for await(let s of t)switch(s.type){case"text-start":i.add(s.id),yield{type:"text-start",id:s.id,providerMetadata:s.providerMetadata};break;case"text-delta":if(!i.has(s.id))i.add(s.id),yield{type:"text-start",id:s.id,providerMetadata:s.providerMetadata};yield{type:"text-delta",id:s.id,delta:s.text,providerMetadata:s.providerMetadata};break;case"text-end":i.delete(s.id),yield{type:"text-end",id:s.id,providerMetadata:s.providerMetadata};break;case"reasoning-start":d.add(s.id),yield{type:"reasoning-start",id:s.id,providerMetadata:s.providerMetadata};break;case"reasoning-delta":if(!d.has(s.id))d.add(s.id),yield{type:"reasoning-start",id:s.id,providerMetadata:s.providerMetadata};yield{type:"reasoning-delta",id:s.id,delta:s.text,providerMetadata:s.providerMetadata};break;case"reasoning-end":d.delete(s.id),yield{type:"reasoning-end",id:s.id,providerMetadata:s.providerMetadata};break;case"tool-input-start":yield{type:"tool-input-start",toolCallId:s.id,toolName:s.toolName,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata,dynamic:s.dynamic,title:s.title};break;case"tool-input-delta":yield{type:"tool-input-delta",toolCallId:s.id,inputTextDelta:s.delta};break;case"tool-call":p.add(s.toolCallId),yield{type:"tool-input-available",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata,dynamic:s.dynamic,title:s.title};break;case"tool-approval-request":if(!p.has(s.toolCall.toolCallId))p.add(s.toolCall.toolCallId),yield{type:"tool-input-available",toolCallId:s.toolCall.toolCallId,toolName:s.toolCall.toolName,input:s.toolCall.input,providerExecuted:s.toolCall.providerExecuted,providerMetadata:s.toolCall.providerMetadata,toolMetadata:s.toolCall.toolMetadata,dynamic:s.toolCall.dynamic,title:s.toolCall.title};yield{type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId,isAutomatic:s.isAutomatic};break;case"tool-approval-response":yield{type:"tool-approval-response",approvalId:s.approvalId,approved:s.approved,reason:s.reason,providerExecuted:s.providerExecuted};break;case"tool-result":yield{type:"tool-output-available",toolCallId:s.toolCallId,output:s.output,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata,dynamic:s.dynamic,preliminary:s.preliminary};break;case"tool-error":yield{type:"tool-output-error",toolCallId:s.toolCallId,errorText:Dt(s.error),providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata,dynamic:s.dynamic};break;case"tool-output-denied":yield{type:"tool-output-denied",toolCallId:s.toolCallId};break;case"source":if(s.sourceType==="url")yield{type:"source-url",sourceId:s.id,url:s.url,title:s.title,providerMetadata:s.providerMetadata};else yield{type:"source-document",sourceId:s.id,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata};break;case"file":yield{type:"file",url:qt(s.file.mediaType,s.file.base64),mediaType:s.file.mediaType,providerMetadata:s.providerMetadata};break;case"reasoning-file":yield{type:"reasoning-file",url:qt(s.file.mediaType,s.file.base64),mediaType:s.file.mediaType,providerMetadata:s.providerMetadata};break;case"start-step":yield{type:"start-step"};break;case"finish-step":h=s.usage,m=s.performance,yield{type:"finish-step"};break;case"finish":yield*zt(i,d),f=!0,yield{type:"finish",finishReason:s.finishReason,messageMetadata:ma(h!=null?h:s.totalUsage,m)};break;case"abort":yield{type:"abort",reason:s.reason};break;case"error":yield{type:"error",errorText:Dt(s.error)};break}if(!f)yield*zt(i,d),yield{type:"finish"}}function ma(t,e){if((t==null?void 0:t.totalTokens)==null&&(t==null?void 0:t.outputTokens)==null&&(e==null?void 0:e.outputTokensPerSecond)==null)return;return{...(t==null?void 0:t.totalTokens)==null&&(t==null?void 0:t.outputTokens)==null?{}:{usage:{...t.totalTokens==null?{}:{totalTokens:t.totalTokens},...t.outputTokens==null?{}:{outputTokens:t.outputTokens}}},...(e==null?void 0:e.outputTokensPerSecond)==null?{}:{performance:{outputTokensPerSecond:e.outputTokensPerSecond}}}}function*zt(t,e){for(let a of t)yield{type:"text-end",id:a};t.clear();for(let a of e)yield{type:"reasoning-end",id:a};e.clear()}function ga(t,e){return{id:t,role:"user",parts:[{type:"text",text:e}]}}function Nt(t,e,a){var r;if(a&&((r=t.at(-1))==null?void 0:r.role)==="assistant"){t[t.length-1]=e;return}t.push(e)}function Mt(t){let e=t.at(-1);return(e==null?void 0:e.role)==="assistant"?e:void 0}function ya(t){let e=[];for(let[a,r]of t.parts.entries()){if(!le(r)||r.state!=="approval-requested"||r.approval.isAutomatic===!0)continue;e.push({approvalId:r.approval.id,toolCallId:r.toolCallId,toolName:ca(r),title:r.title,input:r.input,providerExecuted:r.providerExecuted,messageId:t.id,partIndex:a})}return e}function ba(t,e,a){let r=t.parts[e.partIndex];if(!r||!le(r)||r.toolCallId!==e.toolCallId)throw Error(`Could not find tool approval request ${e.approvalId}.`);r.state="approval-responded",r.approval={id:e.approvalId,approved:a.approved,...a.reason?{reason:a.reason}:{}}}function Dt(t){if(t instanceof Error)return t.message;if(typeof t==="string")return t;return JSON.stringify(t)}function qt(t,e){return`data:${t};base64,${e}`}function Vt(t){return t instanceof Error&&t.message==="Interrupted"}async function oe(t){await new ha(t).run()}import{convertToModelMessages as ka,generateId as ue,toTextStream as xa,toUIMessageStream as Ta}from"ai";async function Aa(t){if(t.prompt!==void 0)wa(t.prompt);await oe({title:`broods · ${t.agent.name}`,tools:"full",transport:new ce(t.client,t.agent)})}async function Ua(t){let e=xa({stream:de(t.client.stream(t.agent,{input:t.prompt}),void 0,()=>{})});for await(let a of e)process.stdout.write(a);process.stdout.write(`
17
+ `)}async function wa(t){let e=process.stdin.listenerCount("data"),a=Date.now()+1e4;while(process.stdin.listenerCount("data")<=e){if(Date.now()>a)return;await new Promise((r)=>setTimeout(r,20))}process.stdin.emit("data",Buffer.from(t)),process.stdin.emit("data",Buffer.from("\r"))}class ce{client;agent;conversationKey=`tui-${ue()}`;sentApprovals=new Set;sentUserTurns=0;constructor(t,e){this.client=t;this.agent=e}async reconnectToStream(){return null}async sendMessages(t){let e=this.pendingEvents(await ka(t.messages));if(e.events.length===0)throw Error("Nothing new to send: the agent already saw this turn.");let a=this.client.stream(this.agent,{conversationKey:this.conversationKey,events:e.events});return Ta({stream:de(a,t.abortSignal,e.commit),originalMessages:t.messages,generateMessageId:ue,sendSources:!0})}pendingEvents(t){let e=[],a=[],r=0;for(let n of t){if(n.role==="user"){if(r+=1,r>this.sentUserTurns)e.push(n);continue}if(n.role!=="tool")continue;for(let i of n.content)if(i.type==="tool-approval-response"&&!this.sentApprovals.has(i.approvalId))a.push(i)}if(a.length>0)e.push({role:"tool",content:a});return{events:e,commit:()=>{this.sentUserTurns=r;for(let n of a)this.sentApprovals.add(n.approvalId)}}}}function Ma(t){return new Promise((e)=>{if(!t)return;let a=()=>e({done:!0,value:void 0});if(t.aborted)a();else t.addEventListener("abort",a,{once:!0})})}function de(t,e,a){let r=!1,n=()=>void t.return(void 0);return new ReadableStream({pull:async function(i){let d=await Promise.race([t.next(),Ma(e)]);if(e?.aborted){n(),i.close();return}if(!r)r=!0,a();if(d.done)i.close();else i.enqueue(d.value)},cancel:n})}export{Aa as runAgentTui,Ua as streamAgentText};