broods 0.37.0 → 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.
package/dist/index.d.ts CHANGED
@@ -227,7 +227,7 @@ interface AgentSubagentConfig {
227
227
  visibility?: "full" | "result" | "none";
228
228
  [key: string]: unknown;
229
229
  }
230
- interface AgentModelConfig extends LanguageModelCallOptions, Pick<RequestOptions, "maxRetries" | "timeout"> {
230
+ interface AgentModelConfig extends LanguageModelCallOptions, Partial<Pick<RequestOptions, "maxRetries" | "timeout">> {
231
231
  provider?: AccountModelProviderName;
232
232
  modelId?: string;
233
233
  /**
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{W,Se,Me,xe,Ae,ze,K,$e,P,we,F,Y,ke,X,I,Oe,Ne,je,qe,De,Le,Ue,Fe,Be,Ve,Ze,He,We,Ke,Ge,Je,Ye,Xe,Qe,et,tt,rt,ie,R,g}from"./chunk-pxzdwb6g.js";import{m,Ce,L,U}from"./chunk-mqsvqhkj.js";export{m as BroodsAccountApiError,U as BroodsAccountClient,F as BroodsClient,ke as BroodsWebSocketClient,P as DEFAULT_CORE_BASE_URL,we as IngressAcceptedError,Me as MAX_OBSERVABILITY_BACKFILL,ke as WebSocketClient,ke as WebsocketClient,Ne as defineAgent,je as defineBroods,qe as defineCron,Ye as defineDiscordChannel,Ze as defineDiscordConnection,Xe as defineGitHubChannel,He as defineGitHubConnection,De as defineHarness,Le as defineMcp,Qe as definePancakeChannel,We as definePancakeConnection,Ue as definePolicy,Fe as defineSandbox,Be as defineSkill,et as defineSlackChannel,Ke as defineSlackConnection,tt as defineTelegramChannel,Ge as defineTelegramConnection,Ve as defineWorkspace,rt as defineZaloChannel,Je as defineZaloConnection,Oe as env,Ce as envPlaceholder,ie as isBroodsConfig,R as isConnectionDefinition,xe as isLogLevel,Ae as isObservabilityClientMessage,g as isResource,ze as isRootSpanKind,K as isSandboxLogId,$e as isTraceId,Y as normalizeHttpServiceUrl,Se as readSseStream,L as resolveEnvCredential,W as resolveRunEvents,X as toWebSocketBaseUrl,I as webSocketSubprotocols};
1
+ import{B,me,xe,Ce,Oe,Ae,F,ze,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}from"./chunk-tgqhxn4k.js";import{m,Te,L,D}from"./chunk-9m85p3e3.js";export{m as BroodsAccountApiError,D as BroodsAccountClient,j as BroodsClient,Pe as BroodsWebSocketClient,z as DEFAULT_CORE_BASE_URL,he as IngressAcceptedError,xe as MAX_OBSERVABILITY_BACKFILL,Pe as WebSocketClient,Pe as WebsocketClient,Ne as defineAgent,je as defineBroods,qe as defineCron,Ye as defineDiscordChannel,He as defineDiscordConnection,Xe as defineGitHubChannel,Ve as defineGitHubConnection,Le as defineHarness,De as defineMcp,Qe as definePancakeChannel,Ke as definePancakeConnection,Ue as definePolicy,Be as defineSandbox,Fe as defineSkill,et as defineSlackChannel,We as defineSlackConnection,tt as defineTelegramChannel,Ge as defineTelegramConnection,Ze as defineWorkspace,nt as defineZaloChannel,Je as defineZaloConnection,Me as env,Te as envPlaceholder,ne as isBroodsConfig,w as isConnectionDefinition,Ce as isLogLevel,Oe as isObservabilityClientMessage,g as isResource,Ae as isRootSpanKind,F as isSandboxLogId,ze as isTraceId,V as normalizeHttpServiceUrl,me as readSseStream,L as resolveEnvCredential,B as resolveRunEvents,K as toWebSocketBaseUrl,E as webSocketSubprotocols};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "broods",
3
- "version": "0.37.0",
3
+ "version": "0.37.1",
4
4
  "description": "CLI + TypeScript SDK for the broods agent platform.",
5
5
  "keywords": [
6
6
  "agents",
@@ -77,11 +77,6 @@
77
77
  "peerDependencies": {
78
78
  "ai": "^7.0.99"
79
79
  },
80
- "peerDependenciesMeta": {
81
- "ai": {
82
- "optional": true
83
- }
84
- },
85
80
  "engines": {
86
81
  "node": ">=22.15"
87
82
  }
@@ -1,4 +0,0 @@
1
- import{I}from"./chunk-pxzdwb6g.js";import{ce,le,e,o,i,l,r,t,u,S,s,p,n}from"./cli/index.js";import{spawn as V}from"node:child_process";import{hostname as ee}from"node:os";import{performance as T}from"node:perf_hooks";var j=["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 k={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; check BROODS_API_KEY"},unknownSandbox:{code:4404,reason:"No machine sandbox with that name in this account"}},N="/v1/machines/ws",H=t({action:p(j),coordinate:r(o().int()).length(2).optional().describe("[x, y] in screenshot pixels for mouse actions."),start_coordinate:r(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:r(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.")}),P=H.extend({type:n("computer"),id:e()}),U=t({type:n("computer-result"),id:e(),text:e().optional(),image:t({data:e(),mediaType:e()}).optional(),app:e().optional(),error:e().optional()}),B=t({type:n("exec"),id:e(),code:e(),cwd:e().optional(),env:s(e(),e()).optional(),timeoutSeconds:o().positive(),outputLimitBytes:o().positive()}),K=t({type:n("hello"),sandbox:e().min(1),hostname:e().optional(),platform:e().optional(),computer:i().optional(),mcp:r(e()).optional(),instance:e().optional(),force:i().optional()}),W=t({type:n("mcp-call"),id:e(),server:e(),tool:e(),args:s(e(),l())}),G=t({type:n("mcp-list"),id:e(),server:e()}),J=t({type:n("mcp-result"),id:e(),result:u({content:r(l())}).optional(),error:e().optional()}),X=t({type:n("mcp-tools"),id:e(),tools:r(u({name:e(),inputSchema:s(e(),l())})).optional(),error:e().optional()}),Y=t({type:n("ready"),sandboxId:e()}),q=t({type:n("result"),id:e(),exitCode:o().nullable(),stdout:e(),stderr:e(),durationMs:o(),timedOut:i(),truncated:i()}),Z=S("type",[P,B,W,G,Y]),me=S("type",[U,K,J,X,q]);function O(c){let a=new URL(N,c);return a.protocol=a.protocol==="https:"?"wss:":"ws:",a.toString()}function D(c){return Q(Z,c)}function Q(c,a){if(typeof a!=="string")return null;try{let m=c.safeParse(JSON.parse(a));return m.success?m.data:null}catch{return null}}var te=new Set([k.occupied.code,k.replaced.code,k.unauthorized.code,k.unknownSandbox.code]),R=72,L=30000,z=1000;function oe(c,a,m){return new Promise((y)=>{let d=T.now(),b=new C(c.outputLimitBytes),h=new C(c.outputLimitBytes),M=!1,_=!1,w=(v,E)=>{if(_)return;if(_=!0,clearTimeout(g),m?.removeEventListener("abort",f),E)h.append(Buffer.from(`${E}
2
- `));y({type:"result",id:c.id,exitCode:v,stdout:b.text(),stderr:h.text(),durationMs:Math.round(T.now()-d),timedOut:M,truncated:b.truncated||h.truncated})},x=V("bash",["-lc",c.code],{cwd:c.cwd??a,env:{...process.env,...c.env},detached:!0,stdio:["ignore","pipe","pipe"]}),F=()=>{if(!x.pid)return;try{process.kill(-x.pid,"SIGKILL")}catch{x.kill("SIGKILL")}},g=setTimeout(()=>{M=!0,F()},c.timeoutSeconds*1000),f=()=>{F(),w(null,"stopped: the daemon closed its socket")};if(m?.addEventListener("abort",f,{once:!0}),x.stdout.on("data",(v)=>b.append(v)),x.stderr.on("data",(v)=>h.append(v)),x.on("error",(v)=>w(null,v.message)),x.on("close",(v)=>w(v)),m?.aborted)f()})}async function Fe(c){let a=le(),m=crypto.randomUUID(),y=c.mcpFile?await ie(c.mcpFile,c.log):null,d=c.computer?await ne(c.log):null,b=z;try{while(!c.signal.aborted){let h=Date.now(),M=await ae(c,m,a,d,y);if(c.signal.aborted)return;if(te.has(M.code))throw Error(M.reason||`core closed the socket (${M.code})`);if(Date.now()-h>L)b=z;c.log(`disconnected (${M.reason||M.code}), reconnecting in ${Math.round(b/1000)}s`),await ce(b,c.signal),b=Math.min(b*2,L)}}finally{d?.stop(),await y?.stop()}}class C{#o=[];#e;#t=0;truncated=!1;constructor(c){this.#e=c}append(c){if(this.#t>=this.#e){this.truncated=!0;return}let a=this.#e-this.#t;if(c.byteLength>a){this.#o.push(c.subarray(0,a)),this.#t=this.#e,this.truncated=!0;return}this.#o.push(c),this.#t+=c.byteLength}text(){let c=Buffer.concat(this.#o).toString("utf8");return this.truncated?`${c}
3
- [output truncated]`:c}}function re(c){let a=[c.action];if(c.coordinate)a.push(`at ${c.coordinate.join(",")}`);if(c.text!==void 0)a.push(JSON.stringify(A(c.text)));if(c.region)a.push(`region ${c.region.join(",")}`);return a.join(" ")}function A(c){let a=c.trim().split(`
4
- `)[0]??"";return a.length>R?`${a.slice(0,R)}…`:a}async function ne(c){let{startDesktop:a}=await import("./chunk-5tnnqapc.js"),{display:m,driver:y,permissions:d}=await a(!1);if(c(`computer use on, ${m.width}x${m.height} screenshots`),!d.screenRecording||!d.accessibility)c(" screen recording or accessibility is missing, run `broods machine --doctor --request`");return y}async function ie(c,a){let{McpHost:m,readMcpServersFile:y}=await import("./chunk-794tw7dm.js"),d=new m(y(c),a);return a(`mcp servers from ${c}: ${d.names().join(", ")}`),d}async function se(c,a,m){try{if(c.type==="mcp-list"){let d=await a.listTools(c.server);return m(` mcp ${c.server}: ${d.length} tools`),{type:"mcp-tools",id:c.id,tools:d}}m(` mcp ${c.server}.${c.tool}`);let y=await a.callTool(c.server,c.tool,c.args);return{type:"mcp-result",id:c.id,result:y}}catch(y){let d=y instanceof Error?y.message:String(y);return m(` mcp ${c.server}: ${d}`),{type:c.type==="mcp-call"?"mcp-result":"mcp-tools",id:c.id,error:d}}}function ae(c,a,m,y,d){return new Promise((b)=>{let h=new m(O(c.baseUrl),I(c.apiKey)),M=new AbortController,_=()=>h.close(1000,"daemon stopped"),w=(F)=>{if(h.readyState===h.OPEN)h.send(JSON.stringify(F))},x=(F,g)=>{c.signal.removeEventListener("abort",_),M.abort(),b({code:F,reason:g})};c.signal.addEventListener("abort",_,{once:!0}),h.onopen=()=>w({type:"hello",sandbox:c.sandbox,hostname:ee(),platform:process.platform,computer:y!==null,mcp:d?.names(),instance:a,force:c.force}),h.onmessage=(F)=>{let g=D(F.data);if(g?.type==="ready"){c.log(`connected as ${c.sandbox} (${g.sandboxId})`);return}if(g?.type==="computer"&&y){c.log(` ${re(g)}`),y.run(g).then((f)=>{if(f.error)c.log(` error: ${f.error}`);w(f)});return}if((g?.type==="mcp-call"||g?.type==="mcp-list")&&d){se(g,d,c.log).then(w);return}if(g?.type!=="exec")return;c.log(`$ ${A(g.code)}`),oe(g,c.cwd,M.signal).then((f)=>{c.log(` exit ${f.exitCode??"none"} in ${f.durationMs}ms${f.timedOut?" (timed out)":""}`),w(f)})},h.onerror=()=>x(1006,"connection failed"),h.onclose=(F)=>x(F.code,F.reason)})}export{Fe as runMachineDaemon};
@@ -1 +0,0 @@
1
- import"./chunk-txsgyj2d.js";import{Pe,e,r,t,s}from"./cli/index.js";import{readFileSync as d}from"node:fs";import{dirname as m,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:r(e()).default([]),env:s(e(),e()).optional(),cwd:e().optional()}),w=t({mcpServers:s(e(),u).refine((n)=>Object.keys(n).length>0,"lists no MCP servers")});class y{#t=new Map;#e;#r;constructor(n,i){this.#r=n,this.#e=i}async callTool(n,i,o){return await(await this.#n(n)).callTool({name:i,arguments:o})}async listTools(n){return(await(await this.#n(n)).listTools()).tools}names(){return[...this.#r.keys()]}async stop(){let n=[...this.#t.values()];this.#t.clear(),await Promise.all(n.map((i)=>i.then((o)=>o.close()).catch(()=>{})))}#n(n){let i=this.#r.get(n);if(!i)return Promise.reject(Error(`no MCP server named "${n}" in the --mcp file`));let o=this.#t.get(n);if(o)return o;let c=(async()=>{this.#e(`mcp ${n}: ${[i.command,...i.args].join(" ")}`);let a=new h({...i,env:{...v(),...i.env},stderr:"inherit"});a.onclose=()=>{if(this.#e(`mcp ${n}: exited`),this.#t.get(n)===c)this.#t.delete(n)};let l=new g(f);return await l.connect(a),l})();return c.catch(()=>{if(this.#t.get(n)===c)this.#t.delete(n)}),this.#t.set(n,c),c}}function R(n){let i=p(n),o=w.safeParse(S(i));if(!o.success)throw Error(`${i}: ${Pe(o.error)}`);return new Map(Object.entries(o.data.mcpServers).map(([c,a])=>[c,a.cwd?{...a,cwd:p(m(i),a.cwd)}:a]))}function v(){let n={};for(let[i,o]of Object.entries(process.env))if(typeof o==="string")n[i]=o;return n}function S(n){try{return JSON.parse(d(n,"utf8"))}catch(i){throw Error(`could not read ${n}: ${i instanceof Error?i.message:String(i)}`)}}export{y as McpHost,R as readMcpServersFile};
@@ -1 +0,0 @@
1
- import{C,a,D,z,B,V,Z,b,x,H,re,ne,me,fe,he,ge,oe,se,ye,ve,be,O}from"./chunk-gcm6m7md.js";import"./chunk-txsgyj2d.js";var J=class{_readBuffer;_started=!1;_closed=!1;constructor(r=oe.stdin,o=oe.stdout,c){this._stdin=r,this._stdout=o,this._readBuffer=new he({maxBufferSize:c?.maxBufferSize})}onclose;onerror;onmessage;_ondata=(r)=>{try{this._readBuffer.append(r),this.processReadBuffer()}catch(o){this.onerror?.(o),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((o,c)=>{let l=ge(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),o()};if(this._stdout.once("error",f),this._stdout.write(l)){if(t)return;t=!0,this._stdout.off("error",f),o()}else if(!t)this._stdout.once("drain",p)})}},k=3000,L=class{onclose;onerror;onmessage;_closed=!1;_pendingRequests=new Set;_drainWaiters=[];constructor(r,o,c){this._wire=r,this._onInstanceClose=o,this._outboundIntercept=c}async start(){}async send(r,o){if(H(r)||re(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,o)}setProtocolVersion=(r)=>{this._wire.setProtocolVersion?.(r)};deliver(r,o){if(this._closed)return;if(b(r))this._pendingRequests.add(r.id);else if(x(r)&&r.method==="notifications/cancelled"){let c=r.params?.requestId;if(c!==void 0)this._settle(c)}this.onmessage?.(r,o)}async whenRequestsAnswered(r){if(this._closed||this._pendingRequests.size===0)return!0;return await new Promise((o)=>{let c=()=>{clearTimeout(l),o(!0)},l=setTimeout(()=>{this._drainWaiters=this._drainWaiters.filter((t)=>t!==c),o(!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 o of r)o()}};function U(r){let o=r.params;if(r.method==="initialize"&&!ne(o)){let f=o!==null&&typeof o==="object"&&typeof o.protocolVersion==="string"?o.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...f!==void 0&&{requestedVersion:f}}}if(!B(o))return{kind:"legacy",reason:"no-claim"};let c=z(o),l=(c===void 0?[]:Z(c))[0];if(l!==void 0)return{kind:"invalid-envelope",issue:l};let t=V(o);if(t===void 0||!C.includes(t))return{kind:"unsupported-revision",requested:t??"unknown"};return{kind:"modern",revision:t,classification:{era:"modern",revision:t}}}function Q(r,o={}){let c=o.legacy??"serve",l=o.transport??new J,t={phase:"opening"},f,p=!1,_=()=>p||t.phase==="closed",d=(e)=>{try{o.onerror?.(e)}catch{}},y=(e,n,i,s)=>l.send({jsonrpc:"2.0",id:e,error:{code:n,message:i,...s!==void 0&&{data:s}}}).catch((u)=>d(h(u))),w=new ye(o.maxSubscriptions??se),M=(e)=>{if(!x(e))return;let n=w.routeOutbound(e);if(n==="passthrough")return;for(let i of n)l.send({jsonrpc:"2.0",...i}).catch((s)=>d(h(s)));return"handled"},I=async(e)=>{if(b(e)&&e.method==="subscriptions/listen"){let n=z(e.params),i=B(e.params)?(n===void 0?[]:Z(n))[0]:{key:"_meta",problem:"the per-request envelope is required on protocol revision 2026-07-28"},s=V(e.params),u;if(i!==void 0)u={jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid _meta envelope: ${i.key}: ${i.problem}`}};else if(s===void 0||!C.includes(s)){let v=new D({supported:[...C],requested:s??"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(x(e)&&e.method==="notifications/cancelled"){let n=e.params?.requestId;if(n!==void 0&&w.cancel(n))return!0}return!1},q=(e,n,i)=>{let s=me({kind:"legacy",reason:n,...i!==void 0&&{requestedVersion:i}},C);if(s===void 0)return Promise.resolve();return d(Error(`Rejected 2025-era request on a modern-only stdio connection (${s.cell}): ${s.message}`)),y(e.id,s.code,s.message,s.data)},T=(e)=>{if(p||e===f)return;P()},m=async(e,n)=>{let i=await r({era:e}),s=i instanceof O?i.server:i;if(e==="modern")fe(s,n),ve(s,C),w.setServerCapabilities(s.getCapabilities(),be(s));let u=new L(l,()=>T(u),e==="modern"?M:void 0);return await i.connect(u),{product:i,channel:u}},R=(e)=>e.product.close().catch((n)=>d(h(n))),N=async(e)=>{f=e.channel;try{if(!await e.channel.whenRequestsAnswered(k))d(Error(`Discarded the probe instance with requests still unanswered after ${k}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"&&!ne(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)&&!x(e)){d(Error("Discarded a JSON-RPC response received before the connection negotiated an era"));return}let n=U(e);switch(n.kind){case"invalid-envelope":{let i=`Invalid _meta envelope for protocol revision 2026-07-28: ${n.issue.key}: ${n.issue.problem}`;if(b(e))await y(e.id,a.InvalidParams,i,{envelope:n.issue});else d(Error(`Discarded a notification with a malformed envelope: ${i}`));return}case"unsupported-revision":if(b(e)){let i=new D({supported:[...C],requested:n.requested});d(i),await y(e.id,i.code,i.message,i.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 i=await m("modern",n.revision);if(_()){await R(i);return}t={phase:"probe",instance:i},i.channel.deliver(e,{classification:n.classification});return}if(t.phase==="probe"){if(x(e)){t.instance.channel.deliver(e,{classification:n.classification});return}t={phase:"pinned",era:"modern",instance:t.instance}}else{let i=await m("modern",n.revision);if(_()){await R(i);return}t={phase:"pinned",era:"modern",instance:i}}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 N(t.instance),_())return;t={phase:"opening"}}let i=await m("legacy");if(_()){await R(i);return}t={phase:"pinned",era:"legacy",instance:i},t.instance.channel.deliver(e);return}}},S=[],E=!1,A=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,a.InternalError,"Internal server error");d(h(n))}}}finally{E=!1}},P=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((i)=>d(h(i)));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),A()},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 j=l.start().catch((e)=>{throw d(h(e)),e});return j.catch(()=>{}),{close:async()=>{await j.catch(()=>{}),await P()}}}function h(r){return r instanceof Error?r:Error(String(r))}export{Q as serveStdio};