broods 0.43.1 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{L,E}from"./chunk-8h6ctjyq.js";import{e,o,a,l,n,t,d,R,s,p,r}from"./chunk-44z8fx25.js";import{se,fe,q}from"./cli/index.js";import{spawn as te}from"node:child_process";import{hostname as oe}from"node:os";import{performance as A}from"node:perf_hooks";var N=["cursor_position","double_click","hold_key","key","left_click","left_click_drag","left_mouse_down","left_mouse_up","middle_click","mouse_move","right_click","screenshot","scroll","triple_click","type","wait","zoom"];var _={badFrame:{code:4400,reason:"Malformed frame"},occupied:{code:4423,reason:"Already connected from another daemon"},replaced:{code:4409,reason:"Replaced by a newer connection"},unauthorized:{code:4401,reason:"Unauthorized; run broods login"},unknownSandbox:{code:4404,reason:"No machine sandbox with that name in this account"}};var H="/v1/machines/ws",P=t({action:p(N),coordinate:n(o().int()).length(2).optional().describe("[x, y] in screenshot pixels for mouse actions."),start_coordinate:n(o().int()).length(2).optional().describe("[x, y] where a left_click_drag starts."),text:e().optional().describe("Text for type, the key chord for key and hold_key, or modifiers to hold during a click, drag or scroll."),scroll_direction:p(["down","left","right","up"]).optional(),scroll_amount:o().int().min(1).optional().describe("Scroll clicks, default 3."),duration:o().min(0).max(300).optional().describe("Seconds for wait and hold_key."),region:n(o().int()).length(4).optional().describe("[x0, y0, x1, y1] of the screenshot to zoom into."),repeat:o().int().min(1).max(100).optional().describe("How many times to press the key.")}),U=P.extend({type:r("computer"),id:e()}),B=t({type:r("computer-result"),id:e(),text:e().optional(),image:t({data:e(),mediaType:e()}).optional(),app:e().optional(),error:e().optional()}),W=t({type:r("exec"),id:e(),code:e(),cwd:e().optional(),env:s(e(),e()).optional(),timeoutSeconds:o().positive(),outputLimitBytes:o().positive()}),G=t({type:r("hello"),sandbox:e().min(1),hostname:e().optional(),platform:e().optional(),computer:a().optional(),mcp:n(e()).optional(),instance:e().optional(),force:a().optional()}),J=t({type:r("mcp-call"),id:e(),server:e(),tool:e(),args:s(e(),l())}),K=t({type:r("mcp-list"),id:e(),server:e()}),X=t({type:r("mcp-result"),id:e(),result:d({content:n(l())}).optional(),error:e().optional()}),Y=t({type:r("mcp-tools"),id:e(),tools:n(d({name:e(),inputSchema:s(e(),l())})).optional(),error:e().optional()}),Z=t({type:r("ready"),sandboxId:e()}),Q=t({type:r("result"),id:e(),exitCode:o().nullable(),stdout:e(),stderr:e(),durationMs:o(),timedOut:a(),truncated:a()}),V=R("type",[U,W,J,K,Z]),ue=R("type",[B,G,X,Y,Q]);function T(i){let c=new URL(H,i);return c.protocol=c.protocol==="https:"?"wss:":"ws:",c.toString()}function D(i){return ee(V,i)}function ee(i,c){if(typeof c!=="string")return null;try{let u=i.safeParse(JSON.parse(c));return u.success?u.data:null}catch{return null}}var re=new Set([_.occupied.code,_.replaced.code,_.unauthorized.code,_.unknownSandbox.code]),z=72,k=30000,I=1000;function ne(i,c,u){return new Promise((f)=>{let m=A.now(),h=new C(i.outputLimitBytes),w=new C(i.outputLimitBytes),b=!1,x=!1,M=(y,O)=>{if(x)return;if(x=!0,clearTimeout(v),u?.removeEventListener("abort",g),O)w.append(Buffer.from(`${O}
2
- `));f({type:"result",id:i.id,exitCode:y,stdout:h.text(),stderr:w.text(),durationMs:Math.round(A.now()-m),timedOut:b,truncated:h.truncated||w.truncated})},F=te("bash",["-lc",i.code],{cwd:i.cwd??c,env:{...L(),...i.env},detached:!0,stdio:["ignore","pipe","pipe"]}),S=()=>{if(!F.pid)return;try{process.kill(-F.pid,"SIGKILL")}catch{F.kill("SIGKILL")}},v=setTimeout(()=>{b=!0,S()},i.timeoutSeconds*1000),g=()=>{S(),M(null,"stopped: the daemon closed its socket")};if(u?.addEventListener("abort",g,{once:!0}),F.stdout.on("data",(y)=>h.append(y)),F.stderr.on("data",(y)=>w.append(y)),F.on("error",(y)=>M(null,y.message)),F.on("close",(y)=>M(y)),u?.aborted)g()})}async function we(i){let c=fe(),u=crypto.randomUUID(),f=i.mcpFile?await ce(i.mcpFile,i.log):null,m=i.computer?await ae(i.log):null,h=I;try{while(!i.signal.aborted){let w=Date.now(),b;try{b=await i.credential()}catch(M){if(M instanceof q)throw M;i.log(`stage session unavailable (${M instanceof Error?M.message:String(M)}), retrying in ${Math.round(h/1000)}s`),await se(h,i.signal),h=Math.min(h*2,k);continue}let x=await pe(i,b,u,c,m,f);if(i.signal.aborted)return;if(re.has(x.code))throw Error(x.reason||`core closed the socket (${x.code})`);if(Date.now()-w>k)h=I;i.log(`disconnected (${x.reason||x.code}), reconnecting in ${Math.round(h/1000)}s`),await se(h,i.signal),h=Math.min(h*2,k)}}finally{m?.stop(),await f?.stop()}}class C{#o=[];#e;#t=0;truncated=!1;constructor(i){this.#e=i}append(i){if(this.#t>=this.#e){this.truncated=!0;return}let c=this.#e-this.#t;if(i.byteLength>c){this.#o.push(i.subarray(0,c)),this.#t=this.#e,this.truncated=!0;return}this.#o.push(i),this.#t+=i.byteLength}text(){let i=Buffer.concat(this.#o).toString("utf8");return this.truncated?`${i}
1
+ import{U,z}from"./chunk-t0fvmbkd.js";import{e,o,a,l,n,t,d,C,s,p,r}from"./chunk-naxtmb6t.js";import{se,fe,D}from"./cli/index.js";import{spawn as te}from"node:child_process";import{hostname as oe}from"node:os";import{performance as L}from"node:perf_hooks";var N=["cursor_position","double_click","hold_key","key","left_click","left_click_drag","left_mouse_down","left_mouse_up","middle_click","mouse_move","right_click","screenshot","scroll","triple_click","type","wait","zoom"];var _={badFrame:{code:4400,reason:"Malformed frame"},occupied:{code:4423,reason:"Already connected from another daemon"},replaced:{code:4409,reason:"Replaced by a newer connection"},unauthorized:{code:4401,reason:"Unauthorized; run broods login"},unknownSandbox:{code:4404,reason:"No machine sandbox with that name in this account"}};var H="/v1/machines/ws",P=t({action:p(N),coordinate:n(o().int()).length(2).optional().describe("[x, y] in screenshot pixels for mouse actions."),start_coordinate:n(o().int()).length(2).optional().describe("[x, y] where a left_click_drag starts."),text:e().optional().describe("Text for type, the key chord for key and hold_key, or modifiers to hold during a click, drag or scroll."),scroll_direction:p(["down","left","right","up"]).optional(),scroll_amount:o().int().min(1).optional().describe("Scroll clicks, default 3."),duration:o().min(0).max(300).optional().describe("Seconds for wait and hold_key."),region:n(o().int()).length(4).optional().describe("[x0, y0, x1, y1] of the screenshot to zoom into."),repeat:o().int().min(1).max(100).optional().describe("How many times to press the key.")}),B=P.extend({type:r("computer"),id:e()}),W=t({type:r("computer-result"),id:e(),text:e().optional(),image:t({data:e(),mediaType:e()}).optional(),app:e().optional(),error:e().optional()}),G=t({type:r("exec"),id:e(),code:e(),cwd:e().optional(),env:s(e(),e()).optional(),timeoutSeconds:o().positive(),outputLimitBytes:o().positive()}),J=t({type:r("hello"),sandbox:e().min(1),hostname:e().optional(),platform:e().optional(),computer:a().optional(),mcp:n(e()).optional(),instance:e().optional(),force:a().optional()}),K=t({type:r("mcp-call"),id:e(),server:e(),tool:e(),args:s(e(),l())}),X=t({type:r("mcp-list"),id:e(),server:e()}),Y=t({type:r("mcp-result"),id:e(),result:d({content:n(l())}).optional(),error:e().optional()}),q=t({type:r("mcp-tools"),id:e(),tools:n(d({name:e(),inputSchema:s(e(),l())})).optional(),error:e().optional()}),Z=t({type:r("ready"),sandboxId:e()}),Q=t({type:r("result"),id:e(),exitCode:o().nullable(),stdout:e(),stderr:e(),durationMs:o(),timedOut:a(),truncated:a()}),V=C("type",[B,G,K,X,Z]),ue=C("type",[W,J,Y,q,Q]);function T(i){let c=new URL(H,i);return c.protocol=c.protocol==="https:"?"wss:":"ws:",c.toString()}function R(i){return ee(V,i)}function ee(i,c){if(typeof c!=="string")return null;try{let u=i.safeParse(JSON.parse(c));return u.success?u.data:null}catch{return null}}var re=new Set([_.occupied.code,_.replaced.code,_.unauthorized.code,_.unknownSandbox.code]),A=72,k=30000,I=1000;function ne(i,c,u){return new Promise((f)=>{let m=L.now(),h=new E(i.outputLimitBytes),w=new E(i.outputLimitBytes),b=!1,x=!1,M=(y,O)=>{if(x)return;if(x=!0,clearTimeout(v),u?.removeEventListener("abort",g),O)w.append(Buffer.from(`${O}
2
+ `));f({type:"result",id:i.id,exitCode:y,stdout:h.text(),stderr:w.text(),durationMs:Math.round(L.now()-m),timedOut:b,truncated:h.truncated||w.truncated})},F=te("bash",["-lc",i.code],{cwd:i.cwd??c,env:{...U(),...i.env},detached:!0,stdio:["ignore","pipe","pipe"]}),S=()=>{if(!F.pid)return;try{process.kill(-F.pid,"SIGKILL")}catch{F.kill("SIGKILL")}},v=setTimeout(()=>{b=!0,S()},i.timeoutSeconds*1000),g=()=>{S(),M(null,"stopped: the daemon closed its socket")};if(u?.addEventListener("abort",g,{once:!0}),F.stdout.on("data",(y)=>h.append(y)),F.stderr.on("data",(y)=>w.append(y)),F.on("error",(y)=>M(null,y.message)),F.on("close",(y)=>M(y)),u?.aborted)g()})}async function we(i){let c=fe(),u=crypto.randomUUID(),f=i.mcpFile?await ce(i.mcpFile,i.log):null,m=i.computer?await ae(i.log):null,h=I;try{while(!i.signal.aborted){let w=Date.now(),b;try{b=await i.credential()}catch(M){if(M instanceof D)throw M;i.log(`stage session unavailable (${M instanceof Error?M.message:String(M)}), retrying in ${Math.round(h/1000)}s`),await se(h,i.signal),h=Math.min(h*2,k);continue}let x=await pe(i,b,u,c,m,f);if(i.signal.aborted)return;if(re.has(x.code))throw Error(x.reason||`core closed the socket (${x.code})`);if(Date.now()-w>k)h=I;i.log(`disconnected (${x.reason||x.code}), reconnecting in ${Math.round(h/1000)}s`),await se(h,i.signal),h=Math.min(h*2,k)}}finally{m?.stop(),await f?.stop()}}class E{#o=[];#e;#t=0;truncated=!1;constructor(i){this.#e=i}append(i){if(this.#t>=this.#e){this.truncated=!0;return}let c=this.#e-this.#t;if(i.byteLength>c){this.#o.push(i.subarray(0,c)),this.#t=this.#e,this.truncated=!0;return}this.#o.push(i),this.#t+=i.byteLength}text(){let i=Buffer.concat(this.#o).toString("utf8");return this.truncated?`${i}
3
3
  [output truncated]`:i}}function ie(i){let c=[i.action];if(i.coordinate)c.push(`at ${i.coordinate.join(",")}`);if(i.text!==void 0)c.push(JSON.stringify(j(i.text)));if(i.region)c.push(`region ${i.region.join(",")}`);return c.join(" ")}function j(i){let c=i.trim().split(`
4
- `)[0]??"";return c.length>z?`${c.slice(0,z)}…`:c}async function ae(i){let{startDesktop:c}=await import("./chunk-5tnnqapc.js"),{display:u,driver:f,permissions:m}=await c(!1);if(i(`computer use on, ${u.width}x${u.height} screenshots`),!m.screenRecording||!m.accessibility)i(" screen recording or accessibility is missing, run `broods machine --doctor --request`");return f}async function ce(i,c){let{McpHost:u,readMcpServersFile:f}=await import("./chunk-f3e652yr.js"),m=new u(f(i),c);return c(`mcp servers from ${i}: ${m.names().join(", ")}`),m}async function le(i,c,u){try{if(i.type==="mcp-list"){let m=await c.listTools(i.server);return u(` mcp ${i.server}: ${m.length} tools`),{type:"mcp-tools",id:i.id,tools:m}}u(` mcp ${i.server}.${i.tool}`);let f=await c.callTool(i.server,i.tool,i.args);return{type:"mcp-result",id:i.id,result:f}}catch(f){let m=f instanceof Error?f.message:String(f);return u(` mcp ${i.server}: ${m}`),{type:i.type==="mcp-call"?"mcp-result":"mcp-tools",id:i.id,error:m}}}function pe(i,c,u,f,m,h){return new Promise((w)=>{let b=new f(T(i.baseUrl),E(c)),x=new AbortController,M=()=>b.close(1000,"daemon stopped"),F=(v)=>{if(b.readyState===b.OPEN)b.send(JSON.stringify(v))},S=(v,g)=>{i.signal.removeEventListener("abort",M),x.abort(),w({code:v,reason:g})};i.signal.addEventListener("abort",M,{once:!0}),b.onopen=()=>F({type:"hello",sandbox:i.sandbox,hostname:oe(),platform:process.platform,computer:m!==null,mcp:h?.names(),instance:u,force:i.force}),b.onmessage=(v)=>{let g=D(v.data);if(g?.type==="ready"){i.log(`connected as ${i.sandbox} (${g.sandboxId})`);return}if(g?.type==="computer"&&m){i.log(` ${ie(g)}`),m.run(g).then((y)=>{if(y.error)i.log(` error: ${y.error}`);F(y)});return}if((g?.type==="mcp-call"||g?.type==="mcp-list")&&h){le(g,h,i.log).then(F);return}if(g?.type!=="exec")return;i.log(`$ ${j(g.code)}`),ne(g,i.cwd,x.signal).then((y)=>{i.log(` exit ${y.exitCode??"none"} in ${y.durationMs}ms${y.timedOut?" (timed out)":""}`),F(y)})},b.onerror=()=>S(1006,"connection failed"),b.onclose=(v)=>S(v.code,v.reason)})}export{we as runMachineDaemon};
4
+ `)[0]??"";return c.length>A?`${c.slice(0,A)}…`:c}async function ae(i){let{startDesktop:c}=await import("./chunk-5tnnqapc.js"),{display:u,driver:f,permissions:m}=await c(!1);if(i(`computer use on, ${u.width}x${u.height} screenshots`),!m.screenRecording||!m.accessibility)i(" screen recording or accessibility is missing, run `broods machine --doctor --request`");return f}async function ce(i,c){let{McpHost:u,readMcpServersFile:f}=await import("./chunk-ee92fs0x.js"),m=new u(f(i),c);return c(`mcp servers from ${i}: ${m.names().join(", ")}`),m}async function le(i,c,u){try{if(i.type==="mcp-list"){let m=await c.listTools(i.server);return u(` mcp ${i.server}: ${m.length} tools`),{type:"mcp-tools",id:i.id,tools:m}}u(` mcp ${i.server}.${i.tool}`);let f=await c.callTool(i.server,i.tool,i.args);return{type:"mcp-result",id:i.id,result:f}}catch(f){let m=f instanceof Error?f.message:String(f);return u(` mcp ${i.server}: ${m}`),{type:i.type==="mcp-call"?"mcp-result":"mcp-tools",id:i.id,error:m}}}function pe(i,c,u,f,m,h){return new Promise((w)=>{let b=new f(T(i.baseUrl),z(c)),x=new AbortController,M=()=>b.close(1000,"daemon stopped"),F=(v)=>{if(b.readyState===b.OPEN)b.send(JSON.stringify(v))},S=(v,g)=>{i.signal.removeEventListener("abort",M),x.abort(),w({code:v,reason:g})};i.signal.addEventListener("abort",M,{once:!0}),b.onopen=()=>F({type:"hello",sandbox:i.sandbox,hostname:oe(),platform:process.platform,computer:m!==null,mcp:h?.names(),instance:u,force:i.force}),b.onmessage=(v)=>{let g=R(v.data);if(g?.type==="ready"){i.log(`connected as ${i.sandbox} (${g.sandboxId})`);return}if(g?.type==="computer"&&m){i.log(` ${ie(g)}`),m.run(g).then((y)=>{if(y.error)i.log(` error: ${y.error}`);F(y)});return}if((g?.type==="mcp-call"||g?.type==="mcp-list")&&h){le(g,h,i.log).then(F);return}if(g?.type!=="exec")return;i.log(`$ ${j(g.code)}`),ne(g,i.cwd,x.signal).then((y)=>{i.log(` exit ${y.exitCode??"none"} in ${y.durationMs}ms${y.timedOut?" (timed out)":""}`),F(y)})},b.onerror=()=>S(1006,"connection failed"),b.onclose=(v)=>S(v.code,v.reason)})}export{we as runMachineDaemon};
@@ -1 +1 @@
1
- import{L}from"./chunk-8h6ctjyq.js";import{Oe,e,n,t,s}from"./chunk-44z8fx25.js";import{readFileSync as m}from"node:fs";import{dirname as d,resolve as p}from"node:path";import{Client as g}from"@modelcontextprotocol/client";import{StdioClientTransport as h}from"@modelcontextprotocol/client/stdio";var f={name:"broods-machine",version:"1.0.0"},u=t({command:e().min(1),args:n(e()).default([]),env:s(e(),e()).optional(),cwd:e().optional()}),w=t({mcpServers:s(e(),u).refine((r)=>Object.keys(r).length>0,"lists no MCP servers")});class y{#t=new Map;#e;#r;constructor(r,o){this.#r=r,this.#e=o}async callTool(r,o,i){return await(await this.#n(r)).callTool({name:o,arguments:i})}async listTools(r){return(await(await this.#n(r)).listTools()).tools}names(){return[...this.#r.keys()]}async stop(){let r=[...this.#t.values()];this.#t.clear(),await Promise.all(r.map((o)=>o.then((i)=>i.close()).catch(()=>{})))}#n(r){let o=this.#r.get(r);if(!o)return Promise.reject(Error(`no MCP server named "${r}" in the --mcp file`));let i=this.#t.get(r);if(i)return i;let c=(async()=>{this.#e(`mcp ${r}: ${[o.command,...o.args].join(" ")}`);let a=new h({...o,env:{...L(),...o.env},stderr:"inherit"});a.onclose=()=>{if(this.#e(`mcp ${r}: exited`),this.#t.get(r)===c)this.#t.delete(r)};let l=new g(f);return await l.connect(a),l})();return c.catch(()=>{if(this.#t.get(r)===c)this.#t.delete(r)}),this.#t.set(r,c),c}}function b(r){let o=p(r),i=w.safeParse(v(o));if(!i.success)throw Error(`${o}: ${Oe(i.error)}`);return new Map(Object.entries(i.data.mcpServers).map(([c,a])=>[c,a.cwd?{...a,cwd:p(d(o),a.cwd)}:a]))}function v(r){try{return JSON.parse(m(r,"utf8"))}catch(o){throw Error(`could not read ${r}: ${o instanceof Error?o.message:String(o)}`)}}export{y as McpHost,b as readMcpServersFile};
1
+ import{U}from"./chunk-t0fvmbkd.js";import{Oe,e,n,t,s}from"./chunk-naxtmb6t.js";import{readFileSync as m}from"node:fs";import{dirname as d,resolve as p}from"node:path";import{Client as g}from"@modelcontextprotocol/client";import{StdioClientTransport as h}from"@modelcontextprotocol/client/stdio";var f={name:"broods-machine",version:"1.0.0"},u=t({command:e().min(1),args:n(e()).default([]),env:s(e(),e()).optional(),cwd:e().optional()}),w=t({mcpServers:s(e(),u).refine((r)=>Object.keys(r).length>0,"lists no MCP servers")});class y{#t=new Map;#e;#r;constructor(r,o){this.#r=r,this.#e=o}async callTool(r,o,i){return await(await this.#n(r)).callTool({name:o,arguments:i})}async listTools(r){return(await(await this.#n(r)).listTools()).tools}names(){return[...this.#r.keys()]}async stop(){let r=[...this.#t.values()];this.#t.clear(),await Promise.all(r.map((o)=>o.then((i)=>i.close()).catch(()=>{})))}#n(r){let o=this.#r.get(r);if(!o)return Promise.reject(Error(`no MCP server named "${r}" in the --mcp file`));let i=this.#t.get(r);if(i)return i;let c=(async()=>{this.#e(`mcp ${r}: ${[o.command,...o.args].join(" ")}`);let a=new h({...o,env:{...U(),...o.env},stderr:"inherit"});a.onclose=()=>{if(this.#e(`mcp ${r}: exited`),this.#t.get(r)===c)this.#t.delete(r)};let l=new g(f);return await l.connect(a),l})();return c.catch(()=>{if(this.#t.get(r)===c)this.#t.delete(r)}),this.#t.set(r,c),c}}function b(r){let o=p(r),i=w.safeParse(v(o));if(!i.success)throw Error(`${o}: ${Oe(i.error)}`);return new Map(Object.entries(i.data.mcpServers).map(([c,a])=>[c,a.cwd?{...a,cwd:p(d(o),a.cwd)}:a]))}function v(r){try{return JSON.parse(m(r,"utf8"))}catch(o){throw Error(`could not read ${r}: ${o instanceof Error?o.message:String(o)}`)}}export{y as McpHost,b as readMcpServersFile};
@@ -1 +1 @@
1
- import{T,i,F,M,X,Q,ee,b,P,te,ae,ce,Se,be,ve,_e,le,ue,we,Re,$e,N}from"./chunk-43d2rmnt.js";var z=class{_readBuffer;_started=!1;_closed=!1;constructor(r=le.stdin,s=le.stdout,c){this._stdin=r,this._stdout=s,this._readBuffer=new ve({maxBufferSize:c?.maxBufferSize})}onclose;onerror;onmessage;_ondata=(r)=>{try{this._readBuffer.append(r),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}};_onerror=(r)=>{this.onerror?.(r)};_onstdouterror=(r)=>{this.onerror?.(r),this.close().catch(()=>{})};async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror),this._stdout.on("error",this._onstdouterror)}processReadBuffer(){while(!0)try{let r=this._readBuffer.readMessage();if(r===null)break;this.onmessage?.(r)}catch(r){this.onerror?.(r)}}async close(){if(this._closed)return;if(this._closed=!0,this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdout.off("error",this._onstdouterror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(r){if(this._closed)return Promise.reject(Error("StdioServerTransport is closed"));return new Promise((s,c)=>{let l=_e(r),t=!1,f=(_)=>{if(t)return;t=!0,this._stdout.off("error",f),this._stdout.off("drain",p),c(_)},p=()=>{if(t)return;t=!0,this._stdout.off("error",f),this._stdout.off("drain",p),s()};if(this._stdout.once("error",f),this._stdout.write(l)){if(t)return;t=!0,this._stdout.off("error",f),s()}else if(!t)this._stdout.once("drain",p)})}},j=3000,A=class{onclose;onerror;onmessage;_closed=!1;_pendingRequests=new Set;_drainWaiters=[];constructor(r,s,c){this._wire=r,this._onInstanceClose=s,this._outboundIntercept=c}async start(){}async send(r,s){if(te(r)||ae(r)){let{id:c}=r;if(c!==void 0)this._settle(c)}if(this._closed)return;if(this._outboundIntercept?.(r)==="handled")return;return this._wire.send(r,s)}setProtocolVersion=(r)=>{this._wire.setProtocolVersion?.(r)};deliver(r,s){if(this._closed)return;if(b(r))this._pendingRequests.add(r.id);else if(P(r)&&r.method==="notifications/cancelled"){let c=r.params?.requestId;if(c!==void 0)this._settle(c)}this.onmessage?.(r,s)}async whenRequestsAnswered(r){if(this._closed||this._pendingRequests.size===0)return!0;return await new Promise((s)=>{let c=()=>{clearTimeout(l),s(!0)},l=setTimeout(()=>{this._drainWaiters=this._drainWaiters.filter((t)=>t!==c),s(!1)},r);this._drainWaiters.push(c)})}async close(){if(this._closed)return;this._closed=!0,this._pendingRequests.clear(),this._releaseDrainWaiters();try{this._onInstanceClose()}finally{this.onclose?.()}}_settle(r){if(this._pendingRequests.delete(r),this._pendingRequests.size===0)this._releaseDrainWaiters()}_releaseDrainWaiters(){let r=this._drainWaiters;this._drainWaiters=[];for(let s of r)s()}};function J(r){let s=r.params;if(r.method==="initialize"&&!ce(s)){let f=s!==null&&typeof s==="object"&&typeof s.protocolVersion==="string"?s.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...f!==void 0&&{requestedVersion:f}}}if(!X(s))return{kind:"legacy",reason:"no-claim"};let c=M(s),l=(c===void 0?[]:ee(c))[0];if(l!==void 0)return{kind:"invalid-envelope",issue:l};let t=Q(s);if(t===void 0||!T.includes(t))return{kind:"unsupported-revision",requested:t??"unknown"};return{kind:"modern",revision:t,classification:{era:"modern",revision:t}}}function g(r,s={}){let c=s.legacy??"serve",l=s.transport??new z,t={phase:"opening"},f,p=!1,_=()=>p||t.phase==="closed",d=(e)=>{try{s.onerror?.(e)}catch{}},y=(e,n,o,a)=>l.send({jsonrpc:"2.0",id:e,error:{code:n,message:o,...a!==void 0&&{data:a}}}).catch((u)=>d(h(u))),w=new we(s.maxSubscriptions??ue),k=(e)=>{if(!P(e))return;let n=w.routeOutbound(e);if(n==="passthrough")return;for(let o of n)l.send({jsonrpc:"2.0",...o}).catch((a)=>d(h(a)));return"handled"},I=async(e)=>{if(b(e)&&e.method==="subscriptions/listen"){let n=M(e.params),o=X(e.params)?(n===void 0?[]:ee(n))[0]:{key:"_meta",problem:"the per-request envelope is required on protocol revision 2026-07-28"},a=Q(e.params),u;if(o!==void 0)u={jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid _meta envelope: ${o.key}: ${o.problem}`}};else if(a===void 0||!T.includes(a)){let v=new F({supported:[...T],requested:a??"unknown"});u={jsonrpc:"2.0",id:e.id,error:{code:v.code,message:v.message,data:v.data}}}else u=w.serve(e);return await l.send("error"in u?u:{jsonrpc:"2.0",method:u.method,params:u.params}).catch((v)=>d(h(v))),!0}if(P(e)&&e.method==="notifications/cancelled"){let n=e.params?.requestId;if(n!==void 0&&w.cancel(n))return!0}return!1},q=(e,n,o)=>{let a=Se({kind:"legacy",reason:n,...o!==void 0&&{requestedVersion:o}},T);if(a===void 0)return Promise.resolve();return d(Error(`Rejected 2025-era request on a modern-only stdio connection (${a.cell}): ${a.message}`)),y(e.id,a.code,a.message,a.data)},D=(e)=>{if(p||e===f)return;C()},m=async(e,n)=>{let o=await r({era:e}),a=o instanceof N?o.server:o;if(e==="modern")be(a,n),Re(a,T),w.setServerCapabilities(a.getCapabilities(),$e(a));let u=new A(l,()=>D(u),e==="modern"?k:void 0);return await o.connect(u),{product:o,channel:u}},R=(e)=>e.product.close().catch((n)=>d(h(n))),V=async(e)=>{f=e.channel;try{if(!await e.channel.whenRequestsAnswered(j))d(Error(`Discarded the probe instance with requests still unanswered after ${j}ms; continuing with the fallback`));await e.product.close()}catch(n){d(h(n))}finally{f=void 0}},B=async(e)=>{if(t.phase==="closed")return;if(t.phase==="pinned"){if(t.era==="modern"&&b(e)&&e.method==="initialize"&&!ce(e.params)){await q(e,"initialize",e.params!==null&&typeof e.params==="object"&&typeof e.params.protocolVersion==="string"?e.params.protocolVersion:void 0);return}if(t.era==="modern"&&await I(e))return;t.instance.channel.deliver(e);return}if(!b(e)&&!P(e)){d(Error("Discarded a JSON-RPC response received before the connection negotiated an era"));return}let n=J(e);switch(n.kind){case"invalid-envelope":{let o=`Invalid _meta envelope for protocol revision 2026-07-28: ${n.issue.key}: ${n.issue.problem}`;if(b(e))await y(e.id,i.InvalidParams,o,{envelope:n.issue});else d(Error(`Discarded a notification with a malformed envelope: ${o}`));return}case"unsupported-revision":if(b(e)){let o=new F({supported:[...T],requested:n.requested});d(o),await y(e.id,o.code,o.message,o.data)}else d(Error(`Discarded a notification claiming unsupported protocol revision ${n.requested}`));return;case"modern":if(b(e)&&e.method==="server/discover"){if(t.phase==="probe"){t.instance.channel.deliver(e,{classification:n.classification});return}let o=await m("modern",n.revision);if(_()){await R(o);return}t={phase:"probe",instance:o},o.channel.deliver(e,{classification:n.classification});return}if(t.phase==="probe"){if(P(e)){t.instance.channel.deliver(e,{classification:n.classification});return}t={phase:"pinned",era:"modern",instance:t.instance}}else{let o=await m("modern",n.revision);if(_()){await R(o);return}t={phase:"pinned",era:"modern",instance:o}}if(await I(e))return;t.instance.channel.deliver(e,{classification:n.classification});return;case"legacy":{if(c==="reject"){if(b(e))await q(e,n.reason,n.requestedVersion);return}if(t.phase==="probe"){if(await V(t.instance),_())return;t={phase:"opening"}}let o=await m("legacy");if(_()){await R(o);return}t={phase:"pinned",era:"legacy",instance:o},t.instance.channel.deliver(e);return}}},S=[],E=!1,W=async()=>{if(E)return;E=!0;try{while(S.length>0){let e=S.shift();try{await B(e)}catch(n){if(b(e))await y(e.id,i.InternalError,"Internal server error");d(h(n))}}}finally{E=!1}},C=async()=>{if(p||t.phase==="closed")return;p=!0;let e=t;t={phase:"closed"};for(let n of w.teardownAll())await l.send(n).catch((o)=>d(h(o)));if(e.phase==="probe"||e.phase==="pinned")await e.instance.product.close().catch((n)=>d(h(n)));await l.close().catch((n)=>d(h(n)))};l.onmessage=(e)=>{S.push(e),W()},l.onerror=(e)=>{if(d(e),t.phase==="probe"||t.phase==="pinned")t.instance.channel.onerror?.(e)},l.onclose=()=>{if(p||t.phase==="closed")return;p=!0;let e=t;if(t={phase:"closed"},e.phase==="probe"||e.phase==="pinned")e.instance.product.close().catch((n)=>d(h(n)))};let O=l.start().catch((e)=>{throw d(h(e)),e});return O.catch(()=>{}),{close:async()=>{await O.catch(()=>{}),await C()}}}function h(r){return r instanceof Error?r:Error(String(r))}export{g as serveStdio};
1
+ import{P,i,B,N,X,Q,ee,b,I,te,ae,ce,Se,be,ve,_e,le,ue,we,Re,$e,j}from"./chunk-dcjq5a2g.js";var A=class{_readBuffer;_started=!1;_closed=!1;constructor(r=le.stdin,s=le.stdout,c){this._stdin=r,this._stdout=s,this._readBuffer=new ve({maxBufferSize:c?.maxBufferSize})}onclose;onerror;onmessage;_ondata=(r)=>{try{this._readBuffer.append(r),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}};_onerror=(r)=>{this.onerror?.(r)};_onstdouterror=(r)=>{this.onerror?.(r),this.close().catch(()=>{})};async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror),this._stdout.on("error",this._onstdouterror)}processReadBuffer(){while(!0)try{let r=this._readBuffer.readMessage();if(r===null)break;this.onmessage?.(r)}catch(r){this.onerror?.(r)}}async close(){if(this._closed)return;if(this._closed=!0,this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdout.off("error",this._onstdouterror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(r){if(this._closed)return Promise.reject(Error("StdioServerTransport is closed"));return new Promise((s,c)=>{let l=_e(r),t=!1,f=(_)=>{if(t)return;t=!0,this._stdout.off("error",f),this._stdout.off("drain",p),c(_)},p=()=>{if(t)return;t=!0,this._stdout.off("error",f),this._stdout.off("drain",p),s()};if(this._stdout.once("error",f),this._stdout.write(l)){if(t)return;t=!0,this._stdout.off("error",f),s()}else if(!t)this._stdout.once("drain",p)})}},D=3000,J=class{onclose;onerror;onmessage;_closed=!1;_pendingRequests=new Set;_drainWaiters=[];constructor(r,s,c){this._wire=r,this._onInstanceClose=s,this._outboundIntercept=c}async start(){}async send(r,s){if(te(r)||ae(r)){let{id:c}=r;if(c!==void 0)this._settle(c)}if(this._closed)return;if(this._outboundIntercept?.(r)==="handled")return;return this._wire.send(r,s)}setProtocolVersion=(r)=>{this._wire.setProtocolVersion?.(r)};deliver(r,s){if(this._closed)return;if(b(r))this._pendingRequests.add(r.id);else if(I(r)&&r.method==="notifications/cancelled"){let c=r.params?.requestId;if(c!==void 0)this._settle(c)}this.onmessage?.(r,s)}async whenRequestsAnswered(r){if(this._closed||this._pendingRequests.size===0)return!0;return await new Promise((s)=>{let c=()=>{clearTimeout(l),s(!0)},l=setTimeout(()=>{this._drainWaiters=this._drainWaiters.filter((t)=>t!==c),s(!1)},r);this._drainWaiters.push(c)})}async close(){if(this._closed)return;this._closed=!0,this._pendingRequests.clear(),this._releaseDrainWaiters();try{this._onInstanceClose()}finally{this.onclose?.()}}_settle(r){if(this._pendingRequests.delete(r),this._pendingRequests.size===0)this._releaseDrainWaiters()}_releaseDrainWaiters(){let r=this._drainWaiters;this._drainWaiters=[];for(let s of r)s()}};function L(r){let s=r.params;if(r.method==="initialize"&&!ce(s)){let f=s!==null&&typeof s==="object"&&typeof s.protocolVersion==="string"?s.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...f!==void 0&&{requestedVersion:f}}}if(!X(s))return{kind:"legacy",reason:"no-claim"};let c=N(s),l=(c===void 0?[]:ee(c))[0];if(l!==void 0)return{kind:"invalid-envelope",issue:l};let t=Q(s);if(t===void 0||!P.includes(t))return{kind:"unsupported-revision",requested:t??"unknown"};return{kind:"modern",revision:t,classification:{era:"modern",revision:t}}}function F(r,s={}){let c=s.legacy??"serve",l=s.transport??new A,t={phase:"opening"},f,p=!1,_=()=>p||t.phase==="closed",d=(e)=>{try{s.onerror?.(e)}catch{}},y=(e,n,o,a)=>l.send({jsonrpc:"2.0",id:e,error:{code:n,message:o,...a!==void 0&&{data:a}}}).catch((u)=>d(h(u))),w=new we(s.maxSubscriptions??ue),M=(e)=>{if(!I(e))return;let n=w.routeOutbound(e);if(n==="passthrough")return;for(let o of n)l.send({jsonrpc:"2.0",...o}).catch((a)=>d(h(a)));return"handled"},q=async(e)=>{if(b(e)&&e.method==="subscriptions/listen"){let n=N(e.params),o=X(e.params)?(n===void 0?[]:ee(n))[0]:{key:"_meta",problem:"the per-request envelope is required on protocol revision 2026-07-28"},a=Q(e.params),u;if(o!==void 0)u={jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid _meta envelope: ${o.key}: ${o.problem}`}};else if(a===void 0||!P.includes(a)){let v=new B({supported:[...P],requested:a??"unknown"});u={jsonrpc:"2.0",id:e.id,error:{code:v.code,message:v.message,data:v.data}}}else u=w.serve(e);return await l.send("error"in u?u:{jsonrpc:"2.0",method:u.method,params:u.params}).catch((v)=>d(h(v))),!0}if(I(e)&&e.method==="notifications/cancelled"){let n=e.params?.requestId;if(n!==void 0&&w.cancel(n))return!0}return!1},C=(e,n,o)=>{let a=Se({kind:"legacy",reason:n,...o!==void 0&&{requestedVersion:o}},P);if(a===void 0)return Promise.resolve();return d(Error(`Rejected 2025-era request on a modern-only stdio connection (${a.cell}): ${a.message}`)),y(e.id,a.code,a.message,a.data)},V=(e)=>{if(p||e===f)return;O()},m=async(e,n)=>{let o=await r({era:e}),a=o instanceof j?o.server:o;if(e==="modern")be(a,n),Re(a,P),w.setServerCapabilities(a.getCapabilities(),$e(a));let u=new J(l,()=>V(u),e==="modern"?M:void 0);return await o.connect(u),{product:o,channel:u}},R=(e)=>e.product.close().catch((n)=>d(h(n))),T=async(e)=>{f=e.channel;try{if(!await e.channel.whenRequestsAnswered(D))d(Error(`Discarded the probe instance with requests still unanswered after ${D}ms; continuing with the fallback`));await e.product.close()}catch(n){d(h(n))}finally{f=void 0}},W=async(e)=>{if(t.phase==="closed")return;if(t.phase==="pinned"){if(t.era==="modern"&&b(e)&&e.method==="initialize"&&!ce(e.params)){await C(e,"initialize",e.params!==null&&typeof e.params==="object"&&typeof e.params.protocolVersion==="string"?e.params.protocolVersion:void 0);return}if(t.era==="modern"&&await q(e))return;t.instance.channel.deliver(e);return}if(!b(e)&&!I(e)){d(Error("Discarded a JSON-RPC response received before the connection negotiated an era"));return}let n=L(e);switch(n.kind){case"invalid-envelope":{let o=`Invalid _meta envelope for protocol revision 2026-07-28: ${n.issue.key}: ${n.issue.problem}`;if(b(e))await y(e.id,i.InvalidParams,o,{envelope:n.issue});else d(Error(`Discarded a notification with a malformed envelope: ${o}`));return}case"unsupported-revision":if(b(e)){let o=new B({supported:[...P],requested:n.requested});d(o),await y(e.id,o.code,o.message,o.data)}else d(Error(`Discarded a notification claiming unsupported protocol revision ${n.requested}`));return;case"modern":if(b(e)&&e.method==="server/discover"){if(t.phase==="probe"){t.instance.channel.deliver(e,{classification:n.classification});return}let o=await m("modern",n.revision);if(_()){await R(o);return}t={phase:"probe",instance:o},o.channel.deliver(e,{classification:n.classification});return}if(t.phase==="probe"){if(I(e)){t.instance.channel.deliver(e,{classification:n.classification});return}t={phase:"pinned",era:"modern",instance:t.instance}}else{let o=await m("modern",n.revision);if(_()){await R(o);return}t={phase:"pinned",era:"modern",instance:o}}if(await q(e))return;t.instance.channel.deliver(e,{classification:n.classification});return;case"legacy":{if(c==="reject"){if(b(e))await C(e,n.reason,n.requestedVersion);return}if(t.phase==="probe"){if(await T(t.instance),_())return;t={phase:"opening"}}let o=await m("legacy");if(_()){await R(o);return}t={phase:"pinned",era:"legacy",instance:o},t.instance.channel.deliver(e);return}}},S=[],E=!1,z=async()=>{if(E)return;E=!0;try{while(S.length>0){let e=S.shift();try{await W(e)}catch(n){if(b(e))await y(e.id,i.InternalError,"Internal server error");d(h(n))}}}finally{E=!1}},O=async()=>{if(p||t.phase==="closed")return;p=!0;let e=t;t={phase:"closed"};for(let n of w.teardownAll())await l.send(n).catch((o)=>d(h(o)));if(e.phase==="probe"||e.phase==="pinned")await e.instance.product.close().catch((n)=>d(h(n)));await l.close().catch((n)=>d(h(n)))};l.onmessage=(e)=>{S.push(e),z()},l.onerror=(e)=>{if(d(e),t.phase==="probe"||t.phase==="pinned")t.instance.channel.onerror?.(e)},l.onclose=()=>{if(p||t.phase==="closed")return;p=!0;let e=t;if(t={phase:"closed"},e.phase==="probe"||e.phase==="pinned")e.instance.product.close().catch((n)=>d(h(n)))};let k=l.start().catch((e)=>{throw d(h(e)),e});return k.catch(()=>{}),{close:async()=>{await k.catch(()=>{}),await O()}}}function h(r){return r instanceof Error?r:Error(String(r))}export{F as serveStdio};
@@ -0,0 +1,19 @@
1
+ import{convertToModelMessages as et,generateId as rt,getToolName as H,isToolUIPart as x,readUIMessageStream as st}from"ai";var K=String.fromCharCode(27);new RegExp(`${K}\\[[0-?]*[ -/]*[@-~]`,"g");var w=new RegExp(`^${K}\\[[0-?]*[ -/]*[@-~]`);function h(t){let e=0,r=0;while(r<t.length){let s=t.slice(r).match(w);if(s){r+=s[0].length;continue}let n=t.codePointAt(r);if(n==null)break;let i=String.fromCodePoint(n);e+=j(n),r+=i.length}return e}function g(t,e){if(e<=0)return"";let r="",s=0,n=0;while(n<t.length&&s<e){let i=t.slice(n).match(w);if(i){r+=i[0],n+=i[0].length;continue}let o=t.codePointAt(n);if(o==null)break;let u=String.fromCodePoint(o),l=j(o);if(l>0&&s+l>e)break;r+=u,n+=u.length,s+=l}while(n<t.length){let i=t.slice(n).match(w);if(!i)break;r+=i[0],n+=i[0].length}return r}function j(t){if(t===9)return 4;if(t<32||t>=127&&t<160)return 0;if(nt(t))return 0;return at(t)?2:1}function nt(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 at(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)}function m(t,{multiline:e=!1}={}){let r="";for(let s of t){let n=s.charCodeAt(0);if(s===`
2
+ `&&e)r+=`
3
+ `;else if(s==="\t")r+=" ";else if(n<32||n>=127&&n<=159)r+=`\\u${n.toString(16).padStart(4,"0")}`;else r+=s}return r}var d={bold:"\x1B[1m",boldOff:"\x1B[22m",italic:"\x1B[3m",italicOff:"\x1B[23m"},it="─";function ot(t){let e=m(t,{multiline:!0}).split(`
4
+ `),r=[];for(let s=0;s<e.length;s+=1){let n=ut(e,s);if(n!=null){r.push(...pt(n)),s=n.endIndex-1;continue}r.push(lt(e[s]??""))}return r.join(`
5
+ `)}function lt(t){if(t.startsWith("### "))return p(`▶ ${t.slice(4)}`);if(t.startsWith("## "))return p(`■ ${t.slice(3)}`);if(t.startsWith("# "))return p(`█ ${t.slice(2)}`);let e=t.match(/^(\s*)[-+*]\s+(.*)$/);if(e){let[,r,s=""]=e;return p(`${r}•${s.length>0?` ${s}`:""}`)}if(/^\d+\. /.test(t))return p(t.replace(/^(\d+)\. /,"$1. "));if(t.startsWith("> "))return p(`│ ${t.slice(2)}`);return p(t)}function p(t){return t.replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*\n]+)\*\*/g,`${d.bold}$1${d.boldOff}`).replace(/__([^_\n]+)__/g,`${d.bold}$1${d.boldOff}`).replace(/\*([^*\n]+)\*/g,`${d.italic}$1${d.italicOff}`).replace(/_([^_\n]+)_/g,`${d.italic}$1${d.italicOff}`)}function ut(t,e){let r=T(t[e]??"");if(r==null||r.length<2)return;let s=T(t[e+1]??"");if(s==null||s.length!==r.length)return;let n=ct(s);if(n==null)return;let i=[],o=e+2;while(o<t.length){let u=T(t[o]??"");if(u==null)break;i.push(dt(u,r.length)),o+=1}return{alignments:n,endIndex:o,header:r,rows:i}}function T(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 r=[],s="";for(let n=0;n<e.length;n+=1){let i=e[n],o=e[n+1];if(i==="\\"&&o==="|"){s+="|",n+=1;continue}if(i==="|"){r.push(s.trim()),s="";continue}s+=i}return r.push(s.trim()),r}function ct(t){let e=[];for(let r of t){let s=r.match(/^(:)?-{3,}(:)?$/);if(s==null)return;let[,n,i]=s;e.push(n!=null&&i!=null?"center":i!=null?"right":"left")}return e}function dt(t,e){return Array.from({length:e},(r,s)=>t[s]??"")}function pt(t){let e=t.header.map((i)=>`${d.bold}${p(i)}${d.boldOff}`),r=t.rows.map((i)=>i.map(p)),s=[e,...r],n=t.alignments.map((i,o)=>Math.max(3,...s.map((u)=>h(u[o]??""))));return[R(e,n,t.alignments),n.map((i)=>it.repeat(i)).join(" "),...r.map((i)=>R(i,n,t.alignments))]}function R(t,e,r){return t.map((s,n)=>ht(s,e[n]??0,r[n]??"left")).join(" ")}function ht(t,e,r){let s=Math.max(0,e-h(t));if(r==="right")return`${" ".repeat(s)}${t}`;if(r==="center"){let n=Math.floor(s/2),i=s-n;return`${" ".repeat(n)}${t}${" ".repeat(i)}`}return`${t}${" ".repeat(s)}`}var J="─";function ft(t){let e=Math.max(20,t.width),r=Math.max(8,t.height)-3-2,s=t.visibleBodyLines.slice(0,r);while(s.length<r)s.push("");return[A(e,t.title,t.rightTitle),...s.map((n)=>U(n,e)),B(e),A(e,t.inputActive?"Input":"Status"),U(t.inputActive?`> ${m(t.input)}${t.inputCursorVisible===!1?" ":"█"}`:m(t.status??"Streaming... ↑/↓ scroll · Ctrl+C quit"),e),B(e)].join(`
6
+ `)}function A(t,e,r){e=m(e),r=r==null?void 0:m(r);let s=Math.max(0,t-2),n=e?g(` ${e} `,s):"",i=r?g(` ${r} `,Math.max(0,s-h(n))):"",o=Math.max(0,s-h(n)-h(i));return`┌${n}${J.repeat(o)}${i}┐`}function B(t){return`└${J.repeat(t-2)}┘`}function U(t,e){let r=e-4,s=g(t,r);return`│ ${s}${" ".repeat(Math.max(0,r-h(s)))} │`}var y="\x1B",mt=`${y}[H`,gt=`${y}[2J`,yt=`${y}[2K`,vt=`${y}[?2026h`,bt=`${y}[?2026l`,xt=class{#e;#r;#i;#c=!1;#d=!1;constructor(t,e){this.#r=t.write.bind(t),this.#e=e?.useSynchronizedUpdates??!0,t.write=(r,s,n)=>{if(!this.#c)this.#d=!0;return this.#r(r,s,n)}}present(t){let e=Tt(t),r=this.#i&&!this.#d?St(this.#i,e):`${mt}${gt}${t}`;if(this.#i=e,this.#d=!1,r.length===0)return;this.#k(r)}reset(){this.#i=void 0}#k(t){this.#c=!0;try{if(!this.#e){this.#r(t);return}this.#r(`${vt}${t}${bt}`)}finally{this.#c=!1}}};function Tt(t){return{lines:t.split(`
7
+ `)}}function St(t,e){let r="",s=Math.max(t.lines.length,e.lines.length);for(let n=0;n<s;n++){let i=e.lines[n];if(t.lines[n]===i)continue;r+=`${y}[${n+1};1H${yt}${i??""}`}return r}var kt="outputTokensPerSecond",c={reset:"\x1B[0m",dim:"\x1B[2m",user:"\x1B[96m",assistant:"\x1B[92m",reasoning:"\x1B[94m",tool:"\x1B[95m",error:"\x1B[91m"},wt={user:{color:c.user,border:"─"},assistant:{color:c.assistant,border:"─"},reasoning:{color:c.reasoning,border:"·"},tool:{color:c.tool,border:"─"},error:{color:c.error,border:"─"}},Mt=500,$t=new Intl.Segmenter(void 0,{granularity:"grapheme"}),f="↑/↓ · PgUp/PgDn · Esc/Ctrl+C",Ct="↑/↓ · PgUp/PgDn · q/Esc/Ctrl+C",v=`Processing input... ${f}`,L=`Processing tool results... ${f}`,S=`Streaming... ${f}`,O=`Executing tools... ${f}`,M=class{#e;#r;#i;#c;#d;#k;#N;#n=[];#u="";#g=!1;#p=0;#I="";#s=S;#w=!1;#a=!1;#h;#E;#f;#y;#v=!0;#b;#o;#x;#R;constructor(t){this.#e=t?.input??process.stdin,this.#r=t?.output??process.stdout,this.#i=t?.frameBuffer??new xt(this.#r),this.#c=t?.tools??"auto-collapsed",this.#d=t?.reasoning??"auto-collapsed",this.#k=t?.responseStatistics??kt,this.#N=t?.contextSize,this.#E=t?.contextSize}async readPrompt(t){return this.#A(t),this.#g=!0,this.#u=t?.initialPrompt??"",this.#s=`Type a prompt and press Enter · ${f}`,this.#K(),this.#t(),await new Promise((e,r)=>{this.#o=(s)=>{let n=b(s);switch(n.type){case"character":this.#u+=n.value,this.#U(),this.#t();break;case"backspace":this.#u=Qt(this.#u),this.#U(),this.#t();break;case"enter":{let i=this.#u;this.#g=!1,this.#C(),this.#s=v,this.#F(i),this.#u="",this.#t(),this.#l(),e(i);break}case"up":case"down":this.#T(n.type);break;case"page-up":case"page-down":this.#$(n.type);break;case"ctrl-l":this.#S();break;case"escape":case"ctrl-c":this.#C(),this.#B(),r(k())}},this.#M()})}async renderStream(t,e){this.#A(e),this.#g=!1,this.#s=v,this.#j(e?.submittedPrompt),this.#a=!1,this.#h=void 0,this.#f=void 0,this.#y=void 0;let r={tools:e?.tools??this.#c,reasoning:e?.reasoning??this.#d,responseStatistics:e?.responseStatistics??this.#k};this.#t();let s=new Promise((o)=>{this.#R=o});this.#o=(o)=>this.#H(o),this.#M();let n,i=Nt(this.#G(t.uiMessageStream));try{let o=st({message:t.message,stream:i,onError:(u)=>this.#q("Error",Et(u))});for await(let u of It(o,s)){if(this.#a)break;n=u,this.#D(u,r)}if(!this.#a&&n&&this.#f!=null)this.#D(n,r)}finally{if(this.#R=void 0,this.#a)t.abort?.();if(this.#l(),this.#s=this.#a?"Interrupted":e?.continueSession?`Done · Enter another prompt · ${f}`:`Done · ${Ct}`,this.#t(),await this.#Z(e),this.#a||!e?.continueSession)this.#B()}if(this.#a)throw k();return n}async readToolApproval(t,e){return this.#A(e),this.#g=!1,this.#s=`Approve ${Wt(t)}? y/n · ${f}`,this.#a=!1,this.#t(),await new Promise((r,s)=>{this.#o=(n)=>{let i=b(n);switch(i.type){case"character":{let o=i.value.toLowerCase();if(o==="y")this.#s=`Approved · ${v}`,this.#l(),this.#t(),r({approved:!0});else if(o==="n")this.#s=`Denied · ${v}`,this.#l(),this.#t(),r({approved:!1,reason:"Denied by user."});break}case"up":case"down":this.#T(i.type);break;case"page-up":case"page-down":this.#$(i.type);break;case"ctrl-l":this.#S();break;case"escape":case"ctrl-c":this.#a=!0,this.#B(),s(k())}},this.#M()})}#A(t){if(this.#I=t?.title??this.#I,this.#E=t?.contextSize??this.#N,this.#w)return;if(this.#w=!0,this.#i.reset(),this.#r.write("\x1B[?1049h\x1B[?25l"),this.#e.isTTY)this.#e.setRawMode?.(!0),this.#e.resume();this.#x=()=>this.#S(),this.#r.on("resize",this.#x)}#B(){if(this.#l(),this.#C(),!this.#w)return;if(this.#e.isTTY)this.#e.setRawMode?.(!1),this.#e.pause();if(this.#x)this.#r.off("resize",this.#x),this.#x=void 0;this.#r.write("\x1B[?25h\x1B[?1049l"),this.#i.reset(),this.#w=!1}#M(){if(this.#o)this.#e.on("data",this.#o)}#l(){if(this.#o)this.#e.off("data",this.#o),this.#o=void 0}#H(t){let e=b(t);switch(e.type){case"up":case"down":this.#T(e.type);break;case"page-up":case"page-down":this.#$(e.type);break;case"ctrl-l":this.#S();break;case"escape":case"ctrl-c":this.#a=!0,this.#R?.()}}#T(t,e=1){let r=t==="up"?e:-e;this.#p=this.#_(this.#p+r),this.#t()}#$(t){this.#T(t==="page-up"?"up":"down",this.#W())}#K(){this.#C(),this.#U(),this.#b=setInterval(()=>{this.#v=!this.#v,this.#t()},Mt),this.#b.unref?.()}#C(){if(this.#b)clearInterval(this.#b),this.#b=void 0;this.#v=!0}#U(){this.#v=!0}#j(t){if(t==null)return;let e=this.#n.at(-1);if(e?.kind==="user"&&e.content===t)return;this.#F(t)}#F(t){let e=this.#m();this.#n.push({kind:"user",title:"User",content:t}),this.#O(e)}#D(t,e){let r=this.#m(),s=new Set,n=Kt(t.metadata);this.#h=n.totalTokens??this.#h,this.#f=n.outputTokens??this.#f,this.#y=n.outputTokensPerSecond??this.#y;for(let[i,o]of t.parts.entries()){let u=zt(t.id,i);switch(o.type){case"text":{let l=o.text.trim();if(l.length===0)break;s.add(u),this.#L({id:u,kind:"assistant",title:"Assistant",rightTitle:Gt({totalTokens:this.#h,outputTokens:this.#f,outputTokensPerSecond:this.#y},e.responseStatistics),content:l});break}case"reasoning":{let l=o.text.trim();if(e.reasoning==="hidden"||l.length===0)break;s.add(u),this.#L({id:u,kind:"reasoning",title:"Reasoning",content:l,collapsed:W(t,i,e.reasoning,e)});break}default:if(x(o)){if(e.tools==="hidden")break;s.add(u),this.#L({id:u,...Rt(o,{mode:e.tools,collapsed:W(t,i,e.tools,e)})})}}}this.#J(t.id,s),this.#O(r)}#L(t){let e=t.id?this.#n.find((r)=>r.id===t.id):void 0;if(e){let r=e.cache;e.kind=t.kind,e.title=t.title,e.rightTitle=t.rightTitle,e.content=t.content,e.collapsed=t.collapsed,e.cache=r&&G(t,r)?r:void 0;return}this.#n.push(t)}#J(t,e){let r=`${t}:`;this.#n=this.#n.filter((s)=>s.id==null||!s.id.startsWith(r)||e.has(s.id))}async*#G(t){let e=!1;for await(let r of Ft(t)){let s=Ut(r,{hasPendingToolResults:e});if(r.type==="start-step")e=!1;else if(Lt(r))e=!0;if(s&&this.#s!==s)this.#s=s,this.#t();else if(Bt(r)&&this.#s!==S)this.#s=S,this.#t();if(r.type==="error")this.#q("Error",r.errorText);if(r.type==="finish"){let n=Ht(r);this.#h=n.totalTokens,this.#f=n.outputTokens,this.#y=n.outputTokensPerSecond}yield r}}#q(t,e){let r=this.#m();this.#n.push({kind:"error",title:t,content:e}),this.#O(r)}#O(t){if(this.#p!==0){let e=this.#m()-t;this.#p=this.#_(this.#p+e)}this.#t()}#t(){let t=ft({width:this.#z(),height:this.#V(),title:this.#I,rightTitle:Z(this.#h,this.#E),visibleBodyLines:this.#Y(),input:this.#u,inputActive:this.#g,inputCursorVisible:this.#v,status:this.#s});this.#i.present(t)}#S(){this.#i.reset(),this.#t()}#Y(){if(this.#n.length===0)return["Waiting for input..."];let t=this.#W(),e=this.#m(),r=Math.max(0,e-t-this.#p),s=r+t,n=[],i=0;for(let o of this.#n){let u=N(o,this.#z()-4),l=i+u.length;if(l>r&&i<s)n.push(...u.slice(Math.max(0,r-i),s-i));if(n.length>=t)break;i=l}return n}#_(t){let e=Math.max(0,this.#m()-this.#W());return Math.min(Math.max(0,t),e)}#m(){if(this.#n.length===0)return 1;let t=0;for(let e of this.#n)t+=N(e,this.#z()-4).length;return t}#W(){return Math.max(1,this.#V()-5)}#z(){return Math.max(20,this.#r.columns??80)}#V(){return Math.max(8,this.#r.rows??24)}async#Z(t){if(t?.waitForExit===!1||!this.#e.isTTY||this.#a)return;await new Promise((e)=>{this.#o=(r)=>{let s=b(r);switch(s.type){case"up":case"down":this.#T(s.type);break;case"page-up":case"page-down":this.#$(s.type);break;case"ctrl-l":this.#S();break;case"escape":this.#l(),e();break;case"character":if(s.value==="q")this.#l(),e();break;case"ctrl-c":this.#l(),process.exitCode=130,e()}},this.#M()})}};function k(){return Error("Interrupted")}async function*It(t,e){let r=t[Symbol.asyncIterator](),s=e.then(()=>({done:!0,value:void 0}));while(!0){let n=await Promise.race([r.next(),s]);if(n.done)break;yield n.value}}function Et(t){if(t instanceof Error)return t.message;if(typeof t==="string")return t;return JSON.stringify(t)}function Rt(t,e){let r=H(t),s=`Tool · ${t.title??r}`,n="input"in t?t.input:void 0,i=n===void 0?"Input: (streaming...)":`Input:
8
+ ${z(n)}`,o=Ot(t);if(e.collapsed)return{kind:"tool",title:s,rightTitle:o,content:"",collapsed:!0};switch(t.state){case"input-streaming":return{kind:"tool",title:s,rightTitle:o,content:i};case"input-available":return{kind:"tool",title:s,rightTitle:o,content:i};case"approval-requested":return{kind:"tool",title:s,rightTitle:o,content:i};case"approval-responded":return{kind:"tool",title:s,rightTitle:o,content:i};case"output-available":return{kind:"tool",title:s,rightTitle:o,content:`${i}
9
+
10
+ Output:
11
+ ${z(t.output)}`};case"output-error":return{kind:"error",title:`Tool Error · ${t.title??r}`,rightTitle:o,content:`${i}
12
+
13
+ Error:
14
+ ${t.errorText}`};case"output-denied":return{kind:"error",title:`Tool Denied · ${t.title??r}`,rightTitle:o,content:`${i}
15
+
16
+ Reason: ${t.approval.reason??"denied"}`}}}function W(t,e,r,s){switch(r){case"collapsed":return!0;case"auto-collapsed":return t.parts.slice(e+1).some((n)=>At(n,s));case"full":case"hidden":return!1}}function At(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 x(t)&&e.tools!=="hidden"}}function Bt(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 Ut(t,{hasPendingToolResults:e}){switch(t.type){case"start-step":return e?L:v;case"tool-output-available":case"tool-output-error":case"tool-output-denied":return L;case"tool-input-available":return O;case"tool-approval-response":return t.approved?O:void 0;default:return}}function Lt(t){switch(t.type){case"tool-output-available":case"tool-output-error":case"tool-output-denied":return!0;default:return!1}}function Ot(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 z(t){if(typeof t==="string")return t;return JSON.stringify(t,null,2)}function Wt(t){return`tool ${t.title??t.toolName}`}function zt(t,e){return`${t}:${e}`}function Nt(t){if(t instanceof ReadableStream)return t;return new ReadableStream({async start(e){try{for await(let r of t)e.enqueue(r);e.close()}catch(r){e.error(r)}}})}async function*Ft(t){if(t instanceof ReadableStream){let e=t.getReader();try{while(!0){let{done:r,value:s}=await e.read();if(r)return;yield s}}finally{e.releaseLock()}return}yield*t}function N(t,e){if(t.cache&&G(t,t.cache,e))return t.cache.lines;let r=Dt(t,e);return t.cache={width:e,kind:t.kind,title:t.title,rightTitle:t.rightTitle,content:t.content,collapsed:t.collapsed===!0,lines:r},r}function G(t,e,r=e.width){return e.width===r&&e.kind===t.kind&&e.title===t.title&&e.rightTitle===t.rightTitle&&e.content===t.content&&e.collapsed===(t.collapsed===!0)}function Dt(t,e){let r=wt[t.kind],s=Math.max(1,e-4),n=` ${m(t.title)} `,i=t.rightTitle?` ${m(t.rightTitle)} `:"";if(t.collapsed){let a=Math.max(0,e-2-n.length-i.length);return[`${r.color}╭${n}${r.border.repeat(a)}${i}╮${c.reset}`,`${r.color}╰${r.border.repeat(Math.max(0,e-2))}╯${c.reset}`]}let o=Math.max(0,e-2-n.length-i.length),u=`${r.color}╭${n}${r.border.repeat(o)}${i}╮${c.reset}`,l=`${r.color}╰${r.border.repeat(Math.max(0,e-2))}╯${c.reset}`;return[u,...(t.content.length>0?ot(t.content):c.dim+"(streaming...)"+c.reset).split(`
17
+ `).flatMap((a)=>_t(a,s)).map((a)=>qt(a,s,r.color)),l]}function qt(t,e,r){let s=g(t,e),n=" ".repeat(Math.max(0,e-h(s)));return`${r}│${c.reset} ${s}${n} ${r}│${c.reset}`}function _t(t,e){if(t.length===0)return[""];let r=[],s=t;while(h(s)>e){let n=Vt(s,e);r.push(s.slice(0,n).trimEnd()),s=s.slice(n).trimStart()}return r.push(s),r}function Vt(t,e){let r=g(t,e+1).lastIndexOf(" ");if(r>0)return r;return g(t,e).length}function Ht(t){let e="usage"in t?t.usage:void 0,r="messageMetadata"in t?t.messageMetadata?.usage:void 0,s="messageMetadata"in t?t.messageMetadata?.performance:void 0;return{totalTokens:Y(e??r),outputTokens:I(e??r),outputTokensPerSecond:s?.outputTokensPerSecond}}function Kt(t){let e=t;return{totalTokens:Y(e?.usage),outputTokens:I(e?.usage),outputTokensPerSecond:e?.performance?.outputTokensPerSecond}}function Y(t){let e=t?.totalTokens;if(typeof e==="number")return e;if(typeof e?.total==="number")return e.total;let r=jt(t),s=I(t);if(r!=null&&s!=null)return r+s}function jt(t){let e=t?.inputTokens;if(typeof e==="number")return e;if(typeof e?.total==="number")return e.total;return t?.promptTokens}function I(t){let e=t?.outputTokens;if(typeof e==="number")return e;if(typeof e?.total==="number")return e.total;return t?.completionTokens}function Z(t,e){if(t==null)return;let r=`${t.toLocaleString()} ${t===1?"token":"tokens"}`,s=Jt(t,e);return s==null?r:`${r} ${s}`}function Jt(t,e){if(e==null||e<=0||!Number.isFinite(e))return;return`${Math.round(t/e*100).toLocaleString()}%`}function Gt(t,e){if(e==="outputTokensPerSecond")return Yt(t.outputTokensPerSecond);return Z(t.outputTokens)}function Yt(t){if(t==null)return;return`${Zt(t)} tok/s`}function Zt(t){return Number.isInteger(t)?t.toLocaleString():t.toLocaleString(void 0,{maximumFractionDigits:1})}function Qt(t){let e=0;for(let{index:r}of $t.segment(t))e=r;return t.slice(0,e)}function b(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`
18
+ `: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 Xt="outputTokensPerSecond",Pt=class{constructor(t){this.chatId=rt(),this.agent=t.agent,this.transport=t.transport,this.renderer=ee(t)??te(t),this.title=t.title,this.tools=t.tools??"auto-collapsed",this.reasoning=t.reasoning??"auto-collapsed",this.responseStatistics=t.responseStatistics??Xt,this.contextSize=t.contextSize,this.sandbox=t.sandbox}async run(){let t=this.title,e=[],r=0,s=()=>`message-${++r}`,n,i=!1,o=!1;while(!0){if(!o){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(l){if(V(l))return;throw l}if(n==null)return}e.push(ne(s(),n)),i=!0}let u=await this.streamMessages([...e],s);try{let l=await this.renderer.renderStream(u,{title:t,submittedPrompt:n,continueSession:Boolean(this.renderer.readPrompt),tools:this.tools,reasoning:this.reasoning,responseStatistics:this.responseStatistics,contextSize:this.contextSize,waitForExit:!1});if(l&&l.parts.length>0){let a=ae(l);if(a.length>0){if(!this.renderer.readToolApproval)throw Error("Tool approval was requested, but the renderer does not support tool approval input.");for(let E of a)ie(l,E,await this.renderer.readToolApproval(E,{title:t}));D(e,l,o),o=!0,n=void 0;continue}D(e,l,o)}}catch(l){if(V(l))return;throw l}o=!1,n=void 0}}async streamMessages(t,e){let r=new AbortController,s=()=>r.abort();if(this.transport)return{uiMessageStream:await this.transport.sendMessages({trigger:"submit-message",chatId:this.chatId,messageId:void 0,messages:t,abortSignal:r.signal}),message:C(t),abort:s};let n=this.agent;return{uiMessageStream:re((await n.stream({prompt:await et(t,{tools:n.tools}),abortSignal:r.signal,options:void 0,experimental_sandbox:this.sandbox})).fullStream,e,t),message:C(t),abort:s}}};function te(t){return t.tools===void 0&&t.reasoning===void 0&&t.responseStatistics===void 0&&t.contextSize===void 0?new M:new M({tools:t.tools,reasoning:t.reasoning,responseStatistics:t.responseStatistics,contextSize:t.contextSize})}function ee(t){if(t.renderer)return t.renderer;if(!t.screen&&!t.userInput)return;return new M({tools:t.tools,reasoning:t.reasoning,responseStatistics:t.responseStatistics,contextSize:t.contextSize,input:t.userInput,output:t.screen})}async function*re(t,e,r=[]){let s=new Set,n=new Set,i=new Set,o,u,l=!1;yield{type:"start",messageId:C(r)?.id??e()};for await(let a of t)switch(a.type){case"text-start":s.add(a.id),yield{type:"text-start",id:a.id,providerMetadata:a.providerMetadata};break;case"text-delta":if(!s.has(a.id))s.add(a.id),yield{type:"text-start",id:a.id,providerMetadata:a.providerMetadata};yield{type:"text-delta",id:a.id,delta:a.text,providerMetadata:a.providerMetadata};break;case"text-end":s.delete(a.id),yield{type:"text-end",id:a.id,providerMetadata:a.providerMetadata};break;case"reasoning-start":n.add(a.id),yield{type:"reasoning-start",id:a.id,providerMetadata:a.providerMetadata};break;case"reasoning-delta":if(!n.has(a.id))n.add(a.id),yield{type:"reasoning-start",id:a.id,providerMetadata:a.providerMetadata};yield{type:"reasoning-delta",id:a.id,delta:a.text,providerMetadata:a.providerMetadata};break;case"reasoning-end":n.delete(a.id),yield{type:"reasoning-end",id:a.id,providerMetadata:a.providerMetadata};break;case"tool-input-start":yield{type:"tool-input-start",toolCallId:a.id,toolName:a.toolName,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,toolMetadata:a.toolMetadata,dynamic:a.dynamic,title:a.title};break;case"tool-input-delta":yield{type:"tool-input-delta",toolCallId:a.id,inputTextDelta:a.delta};break;case"tool-call":i.add(a.toolCallId),yield{type:"tool-input-available",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,toolMetadata:a.toolMetadata,dynamic:a.dynamic,title:a.title};break;case"tool-approval-request":if(!i.has(a.toolCall.toolCallId))i.add(a.toolCall.toolCallId),yield{type:"tool-input-available",toolCallId:a.toolCall.toolCallId,toolName:a.toolCall.toolName,input:a.toolCall.input,providerExecuted:a.toolCall.providerExecuted,providerMetadata:a.toolCall.providerMetadata,toolMetadata:a.toolCall.toolMetadata,dynamic:a.toolCall.dynamic,title:a.toolCall.title};yield{type:"tool-approval-request",approvalId:a.approvalId,toolCallId:a.toolCall.toolCallId,isAutomatic:a.isAutomatic};break;case"tool-approval-response":yield{type:"tool-approval-response",approvalId:a.approvalId,approved:a.approved,reason:a.reason,providerExecuted:a.providerExecuted};break;case"tool-result":yield{type:"tool-output-available",toolCallId:a.toolCallId,output:a.output,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,toolMetadata:a.toolMetadata,dynamic:a.dynamic,preliminary:a.preliminary};break;case"tool-error":yield{type:"tool-output-error",toolCallId:a.toolCallId,errorText:q(a.error),providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,toolMetadata:a.toolMetadata,dynamic:a.dynamic};break;case"tool-output-denied":yield{type:"tool-output-denied",toolCallId:a.toolCallId};break;case"source":if(a.sourceType==="url")yield{type:"source-url",sourceId:a.id,url:a.url,title:a.title,providerMetadata:a.providerMetadata};else yield{type:"source-document",sourceId:a.id,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata};break;case"file":yield{type:"file",url:_(a.file.mediaType,a.file.base64),mediaType:a.file.mediaType,providerMetadata:a.providerMetadata};break;case"reasoning-file":yield{type:"reasoning-file",url:_(a.file.mediaType,a.file.base64),mediaType:a.file.mediaType,providerMetadata:a.providerMetadata};break;case"start-step":yield{type:"start-step"};break;case"finish-step":o=a.usage,u=a.performance,yield{type:"finish-step"};break;case"finish":yield*F(s,n),l=!0,yield{type:"finish",finishReason:a.finishReason,messageMetadata:se(o??a.totalUsage,u)};break;case"abort":yield{type:"abort",reason:a.reason};break;case"error":yield{type:"error",errorText:q(a.error)}}if(!l)yield*F(s,n),yield{type:"finish"}}function se(t,e){if(t?.totalTokens==null&&t?.outputTokens==null&&e?.outputTokensPerSecond==null)return;return{...t?.totalTokens==null&&t?.outputTokens==null?{}:{usage:{...t.totalTokens==null?{}:{totalTokens:t.totalTokens},...t.outputTokens==null?{}:{outputTokens:t.outputTokens}}},...e?.outputTokensPerSecond==null?{}:{performance:{outputTokensPerSecond:e.outputTokensPerSecond}}}}function*F(t,e){for(let r of t)yield{type:"text-end",id:r};t.clear();for(let r of e)yield{type:"reasoning-end",id:r};e.clear()}function ne(t,e){return{id:t,role:"user",parts:[{type:"text",text:e}]}}function D(t,e,r){if(r&&t.at(-1)?.role==="assistant"){t[t.length-1]=e;return}t.push(e)}function C(t){let e=t.at(-1);return e?.role==="assistant"?e:void 0}function ae(t){let e=[];for(let[r,s]of t.parts.entries()){if(!x(s)||s.state!=="approval-requested"||s.approval.isAutomatic===!0)continue;e.push({approvalId:s.approval.id,toolCallId:s.toolCallId,toolName:H(s),title:s.title,input:s.input,providerExecuted:s.providerExecuted,messageId:t.id,partIndex:r})}return e}function ie(t,e,r){let s=t.parts[e.partIndex];if(!s||!x(s)||s.toolCallId!==e.toolCallId)throw Error(`Could not find tool approval request ${e.approvalId}.`);s.state="approval-responded",s.approval={id:e.approvalId,approved:r.approved,...r.reason?{reason:r.reason}:{}}}function q(t){if(t instanceof Error)return t.message;if(typeof t==="string")return t;return JSON.stringify(t)}function _(t,e){return`data:${t};base64,${e}`}function V(t){return t instanceof Error&&t.message==="Interrupted"}async function Q(t){await new Pt(t).run()}import{convertToModelMessages as oe,generateId as X,toTextStream as le,toUIMessageStream as ue}from"ai";async function be(t){if(t.prompt!==void 0)ce(t.prompt);await Q({title:`broods · ${t.agent.name}`,tools:"full",transport:new P(t.client,t.agent)})}async function xe(t){let e=le({stream:tt(t.client.stream(t.agent,{input:t.prompt}),void 0,()=>{})});for await(let r of e)process.stdout.write(r);process.stdout.write(`
19
+ `)}async function ce(t){let e=process.stdin.listenerCount("data"),r=Date.now()+1e4;while(process.stdin.listenerCount("data")<=e){if(Date.now()>r)return;await new Promise((s)=>setTimeout(s,20))}process.stdin.emit("data",Buffer.from(t)),process.stdin.emit("data",Buffer.from("\r"))}class P{client;agent;conversationKey=`tui-${X()}`;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 oe(t.messages));if(e.events.length===0)throw Error("Nothing new to send: the agent already saw this turn.");let r=this.client.stream(this.agent,{conversationKey:this.conversationKey,events:e.events});return ue({stream:tt(r,t.abortSignal,e.commit),originalMessages:t.messages,generateMessageId:X,sendSources:!0})}pendingEvents(t){let e=[],r=[],s=0;for(let n of t){if(n.role==="user"){if(s+=1,s>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))r.push(i)}if(r.length>0)e.push({role:"tool",content:r});return{events:e,commit:()=>{this.sentUserTurns=s;for(let n of r)this.sentApprovals.add(n.approvalId)}}}}function de(t){return new Promise((e)=>{if(!t)return;let r=()=>e({done:!0,value:void 0});if(t.aborted)r();else t.addEventListener("abort",r,{once:!0})})}function tt(t,e,r){let s=!1,n=()=>void t.return(void 0);return new ReadableStream({pull:async function(i){let o=await Promise.race([t.next(),de(e)]);if(e?.aborted){n(),i.close();return}if(!s)s=!0,r();if(o.done)i.close();else i.enqueue(o.value)},cancel:n})}export{be as runAgentTui,xe as streamAgentText};